##// END OF EJS Templates
Merge with stable
Wagner Bruna -
r11721:0b8d17bb merge stable
parent child Browse files
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,42 +1,47 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 #
2 #
3 # runrst - register custom roles and run correct writer
3 # runrst - register custom roles and run correct writer
4 #
4 #
5 # Copyright 2010 Matt Mackall <mpm@selenic.com> and others
5 # Copyright 2010 Matt Mackall <mpm@selenic.com> and others
6 #
6 #
7 # This software may be used and distributed according to the terms of the
7 # This software may be used and distributed according to the terms of the
8 # GNU General Public License version 2 or any later version.
8 # GNU General Public License version 2 or any later version.
9
9
10 """usage: %s WRITER args...
10 """usage: %s WRITER args...
11
11
12 where WRITER is the name of a Docutils writer such as 'html' or 'manpage'
12 where WRITER is the name of a Docutils writer such as 'html' or 'manpage'
13 """
13 """
14
14
15 import sys
15 import sys
16 try:
16 from docutils.parsers.rst import roles
17 from docutils.parsers.rst import roles
17 from docutils.core import publish_cmdline
18 from docutils.core import publish_cmdline
18 from docutils import nodes, utils
19 from docutils import nodes, utils
20 except ImportError:
21 sys.stderr.write("abort: couldn't generate documentation: docutils "
22 "module is missing\n")
23 sys.exit(-1)
19
24
20 def role_hg(name, rawtext, text, lineno, inliner,
25 def role_hg(name, rawtext, text, lineno, inliner,
21 options={}, content=[]):
26 options={}, content=[]):
22 text = "hg " + utils.unescape(text)
27 text = "hg " + utils.unescape(text)
23 linktext = nodes.literal(rawtext, text)
28 linktext = nodes.literal(rawtext, text)
24 parts = text.split()
29 parts = text.split()
25 cmd, args = parts[1], parts[2:]
30 cmd, args = parts[1], parts[2:]
26 if cmd == 'help' and args:
31 if cmd == 'help' and args:
27 cmd = args[0] # link to 'dates' for 'hg help dates'
32 cmd = args[0] # link to 'dates' for 'hg help dates'
28 node = nodes.reference(rawtext, '', linktext,
33 node = nodes.reference(rawtext, '', linktext,
29 refuri="hg.1.html#%s" % cmd)
34 refuri="hg.1.html#%s" % cmd)
30 return [node], []
35 return [node], []
31
36
32 roles.register_local_role("hg", role_hg)
37 roles.register_local_role("hg", role_hg)
33
38
34 if __name__ == "__main__":
39 if __name__ == "__main__":
35 if len(sys.argv) < 2:
40 if len(sys.argv) < 2:
36 sys.stderr.write(__doc__ % sys.argv[0])
41 sys.stderr.write(__doc__ % sys.argv[0])
37 sys.exit(1)
42 sys.exit(1)
38
43
39 writer = sys.argv[1]
44 writer = sys.argv[1]
40 del sys.argv[1]
45 del sys.argv[1]
41
46
42 publish_cmdline(writer_name=writer)
47 publish_cmdline(writer_name=writer)
@@ -1,531 +1,534 b''
1 # Mercurial extension to provide the 'hg bookmark' command
1 # Mercurial extension to provide the 'hg bookmark' command
2 #
2 #
3 # Copyright 2008 David Soria Parra <dsp@php.net>
3 # Copyright 2008 David Soria Parra <dsp@php.net>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 '''track a line of development with movable markers
8 '''track a line of development with movable markers
9
9
10 Bookmarks are local movable markers to changesets. Every bookmark
10 Bookmarks are local movable markers to changesets. Every bookmark
11 points to a changeset identified by its hash. If you commit a
11 points to a changeset identified by its hash. If you commit a
12 changeset that is based on a changeset that has a bookmark on it, the
12 changeset that is based on a changeset that has a bookmark on it, the
13 bookmark shifts to the new changeset.
13 bookmark shifts to the new changeset.
14
14
15 It is possible to use bookmark names in every revision lookup (e.g.
15 It is possible to use bookmark names in every revision lookup (e.g.
16 :hg:`merge`, :hg:`update`).
16 :hg:`merge`, :hg:`update`).
17
17
18 By default, when several bookmarks point to the same changeset, they
18 By default, when several bookmarks point to the same changeset, they
19 will all move forward together. It is possible to obtain a more
19 will all move forward together. It is possible to obtain a more
20 git-like experience by adding the following configuration option to
20 git-like experience by adding the following configuration option to
21 your .hgrc::
21 your .hgrc::
22
22
23 [bookmarks]
23 [bookmarks]
24 track.current = True
24 track.current = True
25
25
26 This will cause Mercurial to track the bookmark that you are currently
26 This will cause Mercurial to track the bookmark that you are currently
27 using, and only update it. This is similar to git's approach to
27 using, and only update it. This is similar to git's approach to
28 branching.
28 branching.
29 '''
29 '''
30
30
31 from mercurial.i18n import _
31 from mercurial.i18n import _
32 from mercurial.node import nullid, nullrev, hex, short
32 from mercurial.node import nullid, nullrev, hex, short
33 from mercurial import util, commands, repair, extensions, pushkey, hg, url
33 from mercurial import util, commands, repair, extensions, pushkey, hg, url
34 import os
34 import os
35
35
36 def write(repo):
36 def write(repo):
37 '''Write bookmarks
37 '''Write bookmarks
38
38
39 Write the given bookmark => hash dictionary to the .hg/bookmarks file
39 Write the given bookmark => hash dictionary to the .hg/bookmarks file
40 in a format equal to those of localtags.
40 in a format equal to those of localtags.
41
41
42 We also store a backup of the previous state in undo.bookmarks that
42 We also store a backup of the previous state in undo.bookmarks that
43 can be copied back on rollback.
43 can be copied back on rollback.
44 '''
44 '''
45 refs = repo._bookmarks
45 refs = repo._bookmarks
46 if os.path.exists(repo.join('bookmarks')):
46 if os.path.exists(repo.join('bookmarks')):
47 util.copyfile(repo.join('bookmarks'), repo.join('undo.bookmarks'))
47 util.copyfile(repo.join('bookmarks'), repo.join('undo.bookmarks'))
48 if repo._bookmarkcurrent not in refs:
48 if repo._bookmarkcurrent not in refs:
49 setcurrent(repo, None)
49 setcurrent(repo, None)
50 wlock = repo.wlock()
50 wlock = repo.wlock()
51 try:
51 try:
52 file = repo.opener('bookmarks', 'w', atomictemp=True)
52 file = repo.opener('bookmarks', 'w', atomictemp=True)
53 for refspec, node in refs.iteritems():
53 for refspec, node in refs.iteritems():
54 file.write("%s %s\n" % (hex(node), refspec))
54 file.write("%s %s\n" % (hex(node), refspec))
55 file.rename()
55 file.rename()
56
56
57 # touch 00changelog.i so hgweb reloads bookmarks (no lock needed)
57 # touch 00changelog.i so hgweb reloads bookmarks (no lock needed)
58 try:
58 try:
59 os.utime(repo.sjoin('00changelog.i'), None)
59 os.utime(repo.sjoin('00changelog.i'), None)
60 except OSError:
60 except OSError:
61 pass
61 pass
62
62
63 finally:
63 finally:
64 wlock.release()
64 wlock.release()
65
65
66 def setcurrent(repo, mark):
66 def setcurrent(repo, mark):
67 '''Set the name of the bookmark that we are currently on
67 '''Set the name of the bookmark that we are currently on
68
68
69 Set the name of the bookmark that we are on (hg update <bookmark>).
69 Set the name of the bookmark that we are on (hg update <bookmark>).
70 The name is recorded in .hg/bookmarks.current
70 The name is recorded in .hg/bookmarks.current
71 '''
71 '''
72 current = repo._bookmarkcurrent
72 current = repo._bookmarkcurrent
73 if current == mark:
73 if current == mark:
74 return
74 return
75
75
76 refs = repo._bookmarks
76 refs = repo._bookmarks
77
77
78 # do not update if we do update to a rev equal to the current bookmark
78 # do not update if we do update to a rev equal to the current bookmark
79 if (mark and mark not in refs and
79 if (mark and mark not in refs and
80 current and refs[current] == repo.changectx('.').node()):
80 current and refs[current] == repo.changectx('.').node()):
81 return
81 return
82 if mark not in refs:
82 if mark not in refs:
83 mark = ''
83 mark = ''
84 wlock = repo.wlock()
84 wlock = repo.wlock()
85 try:
85 try:
86 file = repo.opener('bookmarks.current', 'w', atomictemp=True)
86 file = repo.opener('bookmarks.current', 'w', atomictemp=True)
87 file.write(mark)
87 file.write(mark)
88 file.rename()
88 file.rename()
89 finally:
89 finally:
90 wlock.release()
90 wlock.release()
91 repo._bookmarkcurrent = mark
91 repo._bookmarkcurrent = mark
92
92
93 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False, rename=None):
93 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False, rename=None):
94 '''track a line of development with movable markers
94 '''track a line of development with movable markers
95
95
96 Bookmarks are pointers to certain commits that move when
96 Bookmarks are pointers to certain commits that move when
97 committing. Bookmarks are local. They can be renamed, copied and
97 committing. Bookmarks are local. They can be renamed, copied and
98 deleted. It is possible to use bookmark names in :hg:`merge` and
98 deleted. It is possible to use bookmark names in :hg:`merge` and
99 :hg:`update` to merge and update respectively to a given bookmark.
99 :hg:`update` to merge and update respectively to a given bookmark.
100
100
101 You can use :hg:`bookmark NAME` to set a bookmark on the working
101 You can use :hg:`bookmark NAME` to set a bookmark on the working
102 directory's parent revision with the given name. If you specify
102 directory's parent revision with the given name. If you specify
103 a revision using -r REV (where REV may be an existing bookmark),
103 a revision using -r REV (where REV may be an existing bookmark),
104 the bookmark is assigned to that revision.
104 the bookmark is assigned to that revision.
105 '''
105 '''
106 hexfn = ui.debugflag and hex or short
106 hexfn = ui.debugflag and hex or short
107 marks = repo._bookmarks
107 marks = repo._bookmarks
108 cur = repo.changectx('.').node()
108 cur = repo.changectx('.').node()
109
109
110 if rename:
110 if rename:
111 if rename not in marks:
111 if rename not in marks:
112 raise util.Abort(_("a bookmark of this name does not exist"))
112 raise util.Abort(_("a bookmark of this name does not exist"))
113 if mark in marks and not force:
113 if mark in marks and not force:
114 raise util.Abort(_("a bookmark of the same name already exists"))
114 raise util.Abort(_("a bookmark of the same name already exists"))
115 if mark is None:
115 if mark is None:
116 raise util.Abort(_("new bookmark name required"))
116 raise util.Abort(_("new bookmark name required"))
117 marks[mark] = marks[rename]
117 marks[mark] = marks[rename]
118 del marks[rename]
118 del marks[rename]
119 if repo._bookmarkcurrent == rename:
119 if repo._bookmarkcurrent == rename:
120 setcurrent(repo, mark)
120 setcurrent(repo, mark)
121 write(repo)
121 write(repo)
122 return
122 return
123
123
124 if delete:
124 if delete:
125 if mark is None:
125 if mark is None:
126 raise util.Abort(_("bookmark name required"))
126 raise util.Abort(_("bookmark name required"))
127 if mark not in marks:
127 if mark not in marks:
128 raise util.Abort(_("a bookmark of this name does not exist"))
128 raise util.Abort(_("a bookmark of this name does not exist"))
129 if mark == repo._bookmarkcurrent:
129 if mark == repo._bookmarkcurrent:
130 setcurrent(repo, None)
130 setcurrent(repo, None)
131 del marks[mark]
131 del marks[mark]
132 write(repo)
132 write(repo)
133 return
133 return
134
134
135 if mark != None:
135 if mark != None:
136 if "\n" in mark:
136 if "\n" in mark:
137 raise util.Abort(_("bookmark name cannot contain newlines"))
137 raise util.Abort(_("bookmark name cannot contain newlines"))
138 mark = mark.strip()
138 mark = mark.strip()
139 if not mark:
140 raise util.Abort(_("bookmark names cannot consist entirely of "
141 "whitespace"))
139 if mark in marks and not force:
142 if mark in marks and not force:
140 raise util.Abort(_("a bookmark of the same name already exists"))
143 raise util.Abort(_("a bookmark of the same name already exists"))
141 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
144 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
142 and not force):
145 and not force):
143 raise util.Abort(
146 raise util.Abort(
144 _("a bookmark cannot have the name of an existing branch"))
147 _("a bookmark cannot have the name of an existing branch"))
145 if rev:
148 if rev:
146 marks[mark] = repo.lookup(rev)
149 marks[mark] = repo.lookup(rev)
147 else:
150 else:
148 marks[mark] = repo.changectx('.').node()
151 marks[mark] = repo.changectx('.').node()
149 setcurrent(repo, mark)
152 setcurrent(repo, mark)
150 write(repo)
153 write(repo)
151 return
154 return
152
155
153 if mark is None:
156 if mark is None:
154 if rev:
157 if rev:
155 raise util.Abort(_("bookmark name required"))
158 raise util.Abort(_("bookmark name required"))
156 if len(marks) == 0:
159 if len(marks) == 0:
157 ui.status(_("no bookmarks set\n"))
160 ui.status(_("no bookmarks set\n"))
158 else:
161 else:
159 for bmark, n in marks.iteritems():
162 for bmark, n in marks.iteritems():
160 if ui.configbool('bookmarks', 'track.current'):
163 if ui.configbool('bookmarks', 'track.current'):
161 current = repo._bookmarkcurrent
164 current = repo._bookmarkcurrent
162 if bmark == current and n == cur:
165 if bmark == current and n == cur:
163 prefix, label = '*', 'bookmarks.current'
166 prefix, label = '*', 'bookmarks.current'
164 else:
167 else:
165 prefix, label = ' ', ''
168 prefix, label = ' ', ''
166 else:
169 else:
167 if n == cur:
170 if n == cur:
168 prefix, label = '*', 'bookmarks.current'
171 prefix, label = '*', 'bookmarks.current'
169 else:
172 else:
170 prefix, label = ' ', ''
173 prefix, label = ' ', ''
171
174
172 if ui.quiet:
175 if ui.quiet:
173 ui.write("%s\n" % bmark, label=label)
176 ui.write("%s\n" % bmark, label=label)
174 else:
177 else:
175 ui.write(" %s %-25s %d:%s\n" % (
178 ui.write(" %s %-25s %d:%s\n" % (
176 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
179 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
177 label=label)
180 label=label)
178 return
181 return
179
182
180 def _revstostrip(changelog, node):
183 def _revstostrip(changelog, node):
181 srev = changelog.rev(node)
184 srev = changelog.rev(node)
182 tostrip = [srev]
185 tostrip = [srev]
183 saveheads = []
186 saveheads = []
184 for r in xrange(srev, len(changelog)):
187 for r in xrange(srev, len(changelog)):
185 parents = changelog.parentrevs(r)
188 parents = changelog.parentrevs(r)
186 if parents[0] in tostrip or parents[1] in tostrip:
189 if parents[0] in tostrip or parents[1] in tostrip:
187 tostrip.append(r)
190 tostrip.append(r)
188 if parents[1] != nullrev:
191 if parents[1] != nullrev:
189 for p in parents:
192 for p in parents:
190 if p not in tostrip and p > srev:
193 if p not in tostrip and p > srev:
191 saveheads.append(p)
194 saveheads.append(p)
192 return [r for r in tostrip if r not in saveheads]
195 return [r for r in tostrip if r not in saveheads]
193
196
194 def strip(oldstrip, ui, repo, node, backup="all"):
197 def strip(oldstrip, ui, repo, node, backup="all"):
195 """Strip bookmarks if revisions are stripped using
198 """Strip bookmarks if revisions are stripped using
196 the mercurial.strip method. This usually happens during
199 the mercurial.strip method. This usually happens during
197 qpush and qpop"""
200 qpush and qpop"""
198 revisions = _revstostrip(repo.changelog, node)
201 revisions = _revstostrip(repo.changelog, node)
199 marks = repo._bookmarks
202 marks = repo._bookmarks
200 update = []
203 update = []
201 for mark, n in marks.iteritems():
204 for mark, n in marks.iteritems():
202 if repo.changelog.rev(n) in revisions:
205 if repo.changelog.rev(n) in revisions:
203 update.append(mark)
206 update.append(mark)
204 oldstrip(ui, repo, node, backup)
207 oldstrip(ui, repo, node, backup)
205 if len(update) > 0:
208 if len(update) > 0:
206 for m in update:
209 for m in update:
207 marks[m] = repo.changectx('.').node()
210 marks[m] = repo.changectx('.').node()
208 write(repo)
211 write(repo)
209
212
210 def reposetup(ui, repo):
213 def reposetup(ui, repo):
211 if not repo.local():
214 if not repo.local():
212 return
215 return
213
216
214 class bookmark_repo(repo.__class__):
217 class bookmark_repo(repo.__class__):
215
218
216 @util.propertycache
219 @util.propertycache
217 def _bookmarks(self):
220 def _bookmarks(self):
218 '''Parse .hg/bookmarks file and return a dictionary
221 '''Parse .hg/bookmarks file and return a dictionary
219
222
220 Bookmarks are stored as {HASH}\\s{NAME}\\n (localtags format) values
223 Bookmarks are stored as {HASH}\\s{NAME}\\n (localtags format) values
221 in the .hg/bookmarks file.
224 in the .hg/bookmarks file.
222 Read the file and return a (name=>nodeid) dictionary
225 Read the file and return a (name=>nodeid) dictionary
223 '''
226 '''
224 try:
227 try:
225 bookmarks = {}
228 bookmarks = {}
226 for line in self.opener('bookmarks'):
229 for line in self.opener('bookmarks'):
227 sha, refspec = line.strip().split(' ', 1)
230 sha, refspec = line.strip().split(' ', 1)
228 bookmarks[refspec] = super(bookmark_repo, self).lookup(sha)
231 bookmarks[refspec] = super(bookmark_repo, self).lookup(sha)
229 except:
232 except:
230 pass
233 pass
231 return bookmarks
234 return bookmarks
232
235
233 @util.propertycache
236 @util.propertycache
234 def _bookmarkcurrent(self):
237 def _bookmarkcurrent(self):
235 '''Get the current bookmark
238 '''Get the current bookmark
236
239
237 If we use gittishsh branches we have a current bookmark that
240 If we use gittishsh branches we have a current bookmark that
238 we are on. This function returns the name of the bookmark. It
241 we are on. This function returns the name of the bookmark. It
239 is stored in .hg/bookmarks.current
242 is stored in .hg/bookmarks.current
240 '''
243 '''
241 mark = None
244 mark = None
242 if os.path.exists(self.join('bookmarks.current')):
245 if os.path.exists(self.join('bookmarks.current')):
243 file = self.opener('bookmarks.current')
246 file = self.opener('bookmarks.current')
244 # No readline() in posixfile_nt, reading everything is cheap
247 # No readline() in posixfile_nt, reading everything is cheap
245 mark = (file.readlines() or [''])[0]
248 mark = (file.readlines() or [''])[0]
246 if mark == '':
249 if mark == '':
247 mark = None
250 mark = None
248 file.close()
251 file.close()
249 return mark
252 return mark
250
253
251 def rollback(self, *args):
254 def rollback(self, *args):
252 if os.path.exists(self.join('undo.bookmarks')):
255 if os.path.exists(self.join('undo.bookmarks')):
253 util.rename(self.join('undo.bookmarks'), self.join('bookmarks'))
256 util.rename(self.join('undo.bookmarks'), self.join('bookmarks'))
254 return super(bookmark_repo, self).rollback(*args)
257 return super(bookmark_repo, self).rollback(*args)
255
258
256 def lookup(self, key):
259 def lookup(self, key):
257 if key in self._bookmarks:
260 if key in self._bookmarks:
258 key = self._bookmarks[key]
261 key = self._bookmarks[key]
259 return super(bookmark_repo, self).lookup(key)
262 return super(bookmark_repo, self).lookup(key)
260
263
261 def _bookmarksupdate(self, parents, node):
264 def _bookmarksupdate(self, parents, node):
262 marks = self._bookmarks
265 marks = self._bookmarks
263 update = False
266 update = False
264 if ui.configbool('bookmarks', 'track.current'):
267 if ui.configbool('bookmarks', 'track.current'):
265 mark = self._bookmarkcurrent
268 mark = self._bookmarkcurrent
266 if mark and marks[mark] in parents:
269 if mark and marks[mark] in parents:
267 marks[mark] = node
270 marks[mark] = node
268 update = True
271 update = True
269 else:
272 else:
270 for mark, n in marks.items():
273 for mark, n in marks.items():
271 if n in parents:
274 if n in parents:
272 marks[mark] = node
275 marks[mark] = node
273 update = True
276 update = True
274 if update:
277 if update:
275 write(self)
278 write(self)
276
279
277 def commitctx(self, ctx, error=False):
280 def commitctx(self, ctx, error=False):
278 """Add a revision to the repository and
281 """Add a revision to the repository and
279 move the bookmark"""
282 move the bookmark"""
280 wlock = self.wlock() # do both commit and bookmark with lock held
283 wlock = self.wlock() # do both commit and bookmark with lock held
281 try:
284 try:
282 node = super(bookmark_repo, self).commitctx(ctx, error)
285 node = super(bookmark_repo, self).commitctx(ctx, error)
283 if node is None:
286 if node is None:
284 return None
287 return None
285 parents = self.changelog.parents(node)
288 parents = self.changelog.parents(node)
286 if parents[1] == nullid:
289 if parents[1] == nullid:
287 parents = (parents[0],)
290 parents = (parents[0],)
288
291
289 self._bookmarksupdate(parents, node)
292 self._bookmarksupdate(parents, node)
290 return node
293 return node
291 finally:
294 finally:
292 wlock.release()
295 wlock.release()
293
296
294 def pull(self, remote, heads=None, force=False):
297 def pull(self, remote, heads=None, force=False):
295 result = super(bookmark_repo, self).pull(remote, heads, force)
298 result = super(bookmark_repo, self).pull(remote, heads, force)
296
299
297 self.ui.debug("checking for updated bookmarks\n")
300 self.ui.debug("checking for updated bookmarks\n")
298 rb = remote.listkeys('bookmarks')
301 rb = remote.listkeys('bookmarks')
299 changes = 0
302 changes = 0
300 for k in rb.keys():
303 for k in rb.keys():
301 if k in self._bookmarks:
304 if k in self._bookmarks:
302 nr, nl = rb[k], self._bookmarks[k]
305 nr, nl = rb[k], self._bookmarks[k]
303 if nr in self:
306 if nr in self:
304 cr = self[nr]
307 cr = self[nr]
305 cl = self[nl]
308 cl = self[nl]
306 if cl.rev() >= cr.rev():
309 if cl.rev() >= cr.rev():
307 continue
310 continue
308 if cr in cl.descendants():
311 if cr in cl.descendants():
309 self._bookmarks[k] = cr.node()
312 self._bookmarks[k] = cr.node()
310 changes += 1
313 changes += 1
311 self.ui.status(_("updating bookmark %s\n") % k)
314 self.ui.status(_("updating bookmark %s\n") % k)
312 else:
315 else:
313 self.ui.warn(_("not updating divergent"
316 self.ui.warn(_("not updating divergent"
314 " bookmark %s\n") % k)
317 " bookmark %s\n") % k)
315 if changes:
318 if changes:
316 write(repo)
319 write(repo)
317
320
318 return result
321 return result
319
322
320 def push(self, remote, force=False, revs=None, newbranch=False):
323 def push(self, remote, force=False, revs=None, newbranch=False):
321 result = super(bookmark_repo, self).push(remote, force, revs,
324 result = super(bookmark_repo, self).push(remote, force, revs,
322 newbranch)
325 newbranch)
323
326
324 self.ui.debug("checking for updated bookmarks\n")
327 self.ui.debug("checking for updated bookmarks\n")
325 rb = remote.listkeys('bookmarks')
328 rb = remote.listkeys('bookmarks')
326 for k in rb.keys():
329 for k in rb.keys():
327 if k in self._bookmarks:
330 if k in self._bookmarks:
328 nr, nl = rb[k], self._bookmarks[k]
331 nr, nl = rb[k], self._bookmarks[k]
329 if nr in self:
332 if nr in self:
330 cr = self[nr]
333 cr = self[nr]
331 cl = self[nl]
334 cl = self[nl]
332 if cl in cr.descendants():
335 if cl in cr.descendants():
333 r = remote.pushkey('bookmarks', k, nr, nl)
336 r = remote.pushkey('bookmarks', k, nr, nl)
334 if r:
337 if r:
335 self.ui.status(_("updating bookmark %s\n") % k)
338 self.ui.status(_("updating bookmark %s\n") % k)
336 else:
339 else:
337 self.ui.warn(_('updating bookmark %s'
340 self.ui.warn(_('updating bookmark %s'
338 ' failed!\n') % k)
341 ' failed!\n') % k)
339
342
340 return result
343 return result
341
344
342 def addchangegroup(self, *args, **kwargs):
345 def addchangegroup(self, *args, **kwargs):
343 parents = self.dirstate.parents()
346 parents = self.dirstate.parents()
344
347
345 result = super(bookmark_repo, self).addchangegroup(*args, **kwargs)
348 result = super(bookmark_repo, self).addchangegroup(*args, **kwargs)
346 if result > 1:
349 if result > 1:
347 # We have more heads than before
350 # We have more heads than before
348 return result
351 return result
349 node = self.changelog.tip()
352 node = self.changelog.tip()
350
353
351 self._bookmarksupdate(parents, node)
354 self._bookmarksupdate(parents, node)
352 return result
355 return result
353
356
354 def _findtags(self):
357 def _findtags(self):
355 """Merge bookmarks with normal tags"""
358 """Merge bookmarks with normal tags"""
356 (tags, tagtypes) = super(bookmark_repo, self)._findtags()
359 (tags, tagtypes) = super(bookmark_repo, self)._findtags()
357 tags.update(self._bookmarks)
360 tags.update(self._bookmarks)
358 return (tags, tagtypes)
361 return (tags, tagtypes)
359
362
360 if hasattr(repo, 'invalidate'):
363 if hasattr(repo, 'invalidate'):
361 def invalidate(self):
364 def invalidate(self):
362 super(bookmark_repo, self).invalidate()
365 super(bookmark_repo, self).invalidate()
363 for attr in ('_bookmarks', '_bookmarkcurrent'):
366 for attr in ('_bookmarks', '_bookmarkcurrent'):
364 if attr in self.__dict__:
367 if attr in self.__dict__:
365 delattr(self, attr)
368 delattr(self, attr)
366
369
367 repo.__class__ = bookmark_repo
370 repo.__class__ = bookmark_repo
368
371
369 def listbookmarks(repo):
372 def listbookmarks(repo):
370 d = {}
373 d = {}
371 for k, v in repo._bookmarks.iteritems():
374 for k, v in repo._bookmarks.iteritems():
372 d[k] = hex(v)
375 d[k] = hex(v)
373 return d
376 return d
374
377
375 def pushbookmark(repo, key, old, new):
378 def pushbookmark(repo, key, old, new):
376 w = repo.wlock()
379 w = repo.wlock()
377 try:
380 try:
378 marks = repo._bookmarks
381 marks = repo._bookmarks
379 if hex(marks.get(key, '')) != old:
382 if hex(marks.get(key, '')) != old:
380 return False
383 return False
381 if new == '':
384 if new == '':
382 del marks[key]
385 del marks[key]
383 else:
386 else:
384 if new not in repo:
387 if new not in repo:
385 return False
388 return False
386 marks[key] = repo[new].node()
389 marks[key] = repo[new].node()
387 write(repo)
390 write(repo)
388 return True
391 return True
389 finally:
392 finally:
390 w.release()
393 w.release()
391
394
392 def pull(oldpull, ui, repo, source="default", **opts):
395 def pull(oldpull, ui, repo, source="default", **opts):
393 # translate bookmark args to rev args for actual pull
396 # translate bookmark args to rev args for actual pull
394 if opts.get('bookmark'):
397 if opts.get('bookmark'):
395 # this is an unpleasant hack as pull will do this internally
398 # this is an unpleasant hack as pull will do this internally
396 source, branches = hg.parseurl(ui.expandpath(source),
399 source, branches = hg.parseurl(ui.expandpath(source),
397 opts.get('branch'))
400 opts.get('branch'))
398 other = hg.repository(hg.remoteui(repo, opts), source)
401 other = hg.repository(hg.remoteui(repo, opts), source)
399 rb = other.listkeys('bookmarks')
402 rb = other.listkeys('bookmarks')
400
403
401 for b in opts['bookmark']:
404 for b in opts['bookmark']:
402 if b not in rb:
405 if b not in rb:
403 raise util.Abort(_('remote bookmark %s not found!') % b)
406 raise util.Abort(_('remote bookmark %s not found!') % b)
404 opts.setdefault('rev', []).append(b)
407 opts.setdefault('rev', []).append(b)
405
408
406 result = oldpull(ui, repo, source, **opts)
409 result = oldpull(ui, repo, source, **opts)
407
410
408 # update specified bookmarks
411 # update specified bookmarks
409 if opts.get('bookmark'):
412 if opts.get('bookmark'):
410 for b in opts['bookmark']:
413 for b in opts['bookmark']:
411 # explicit pull overrides local bookmark if any
414 # explicit pull overrides local bookmark if any
412 ui.status(_("importing bookmark %s\n") % b)
415 ui.status(_("importing bookmark %s\n") % b)
413 repo._bookmarks[b] = repo[rb[b]].node()
416 repo._bookmarks[b] = repo[rb[b]].node()
414 write(repo)
417 write(repo)
415
418
416 return result
419 return result
417
420
418 def push(oldpush, ui, repo, dest=None, **opts):
421 def push(oldpush, ui, repo, dest=None, **opts):
419 dopush = True
422 dopush = True
420 if opts.get('bookmark'):
423 if opts.get('bookmark'):
421 dopush = False
424 dopush = False
422 for b in opts['bookmark']:
425 for b in opts['bookmark']:
423 if b in repo._bookmarks:
426 if b in repo._bookmarks:
424 dopush = True
427 dopush = True
425 opts.setdefault('rev', []).append(b)
428 opts.setdefault('rev', []).append(b)
426
429
427 result = 0
430 result = 0
428 if dopush:
431 if dopush:
429 result = oldpush(ui, repo, dest, **opts)
432 result = oldpush(ui, repo, dest, **opts)
430
433
431 if opts.get('bookmark'):
434 if opts.get('bookmark'):
432 # this is an unpleasant hack as push will do this internally
435 # this is an unpleasant hack as push will do this internally
433 dest = ui.expandpath(dest or 'default-push', dest or 'default')
436 dest = ui.expandpath(dest or 'default-push', dest or 'default')
434 dest, branches = hg.parseurl(dest, opts.get('branch'))
437 dest, branches = hg.parseurl(dest, opts.get('branch'))
435 other = hg.repository(hg.remoteui(repo, opts), dest)
438 other = hg.repository(hg.remoteui(repo, opts), dest)
436 rb = other.listkeys('bookmarks')
439 rb = other.listkeys('bookmarks')
437 for b in opts['bookmark']:
440 for b in opts['bookmark']:
438 # explicit push overrides remote bookmark if any
441 # explicit push overrides remote bookmark if any
439 if b in repo._bookmarks:
442 if b in repo._bookmarks:
440 ui.status(_("exporting bookmark %s\n") % b)
443 ui.status(_("exporting bookmark %s\n") % b)
441 new = repo[b].hex()
444 new = repo[b].hex()
442 else:
445 else:
443 ui.status(_("deleting remote bookmark %s\n") % b)
446 ui.status(_("deleting remote bookmark %s\n") % b)
444 new = '' # delete
447 new = '' # delete
445 old = rb.get(b, '')
448 old = rb.get(b, '')
446 r = other.pushkey('bookmarks', b, old, new)
449 r = other.pushkey('bookmarks', b, old, new)
447 if not r:
450 if not r:
448 ui.warn(_('updating bookmark %s failed!\n') % b)
451 ui.warn(_('updating bookmark %s failed!\n') % b)
449 if not result:
452 if not result:
450 result = 2
453 result = 2
451
454
452 return result
455 return result
453
456
454 def diffbookmarks(ui, repo, remote):
457 def diffbookmarks(ui, repo, remote):
455 ui.status(_("searching for changes\n"))
458 ui.status(_("searching for changes\n"))
456
459
457 lmarks = repo.listkeys('bookmarks')
460 lmarks = repo.listkeys('bookmarks')
458 rmarks = remote.listkeys('bookmarks')
461 rmarks = remote.listkeys('bookmarks')
459
462
460 diff = set(rmarks) - set(lmarks)
463 diff = set(rmarks) - set(lmarks)
461 for k in diff:
464 for k in diff:
462 ui.write(" %-25s %s\n" % (k, rmarks[k][:12]))
465 ui.write(" %-25s %s\n" % (k, rmarks[k][:12]))
463
466
464 if len(diff) <= 0:
467 if len(diff) <= 0:
465 ui.status(_("no changes found\n"))
468 ui.status(_("no changes found\n"))
466 return 1
469 return 1
467 return 0
470 return 0
468
471
469 def incoming(oldincoming, ui, repo, source="default", **opts):
472 def incoming(oldincoming, ui, repo, source="default", **opts):
470 if opts.get('bookmarks'):
473 if opts.get('bookmarks'):
471 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
474 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
472 other = hg.repository(hg.remoteui(repo, opts), source)
475 other = hg.repository(hg.remoteui(repo, opts), source)
473 ui.status(_('comparing with %s\n') % url.hidepassword(source))
476 ui.status(_('comparing with %s\n') % url.hidepassword(source))
474 return diffbookmarks(ui, repo, other)
477 return diffbookmarks(ui, repo, other)
475 else:
478 else:
476 return oldincoming(ui, repo, source, **opts)
479 return oldincoming(ui, repo, source, **opts)
477
480
478 def outgoing(oldoutgoing, ui, repo, dest=None, **opts):
481 def outgoing(oldoutgoing, ui, repo, dest=None, **opts):
479 if opts.get('bookmarks'):
482 if opts.get('bookmarks'):
480 dest = ui.expandpath(dest or 'default-push', dest or 'default')
483 dest = ui.expandpath(dest or 'default-push', dest or 'default')
481 dest, branches = hg.parseurl(dest, opts.get('branch'))
484 dest, branches = hg.parseurl(dest, opts.get('branch'))
482 other = hg.repository(hg.remoteui(repo, opts), dest)
485 other = hg.repository(hg.remoteui(repo, opts), dest)
483 ui.status(_('comparing with %s\n') % url.hidepassword(dest))
486 ui.status(_('comparing with %s\n') % url.hidepassword(dest))
484 return diffbookmarks(ui, other, repo)
487 return diffbookmarks(ui, other, repo)
485 else:
488 else:
486 return oldoutgoing(ui, repo, dest, **opts)
489 return oldoutgoing(ui, repo, dest, **opts)
487
490
488 def uisetup(ui):
491 def uisetup(ui):
489 extensions.wrapfunction(repair, "strip", strip)
492 extensions.wrapfunction(repair, "strip", strip)
490 if ui.configbool('bookmarks', 'track.current'):
493 if ui.configbool('bookmarks', 'track.current'):
491 extensions.wrapcommand(commands.table, 'update', updatecurbookmark)
494 extensions.wrapcommand(commands.table, 'update', updatecurbookmark)
492
495
493 entry = extensions.wrapcommand(commands.table, 'pull', pull)
496 entry = extensions.wrapcommand(commands.table, 'pull', pull)
494 entry[1].append(('B', 'bookmark', [],
497 entry[1].append(('B', 'bookmark', [],
495 _("bookmark to import")))
498 _("bookmark to import")))
496 entry = extensions.wrapcommand(commands.table, 'push', push)
499 entry = extensions.wrapcommand(commands.table, 'push', push)
497 entry[1].append(('B', 'bookmark', [],
500 entry[1].append(('B', 'bookmark', [],
498 _("bookmark to export")))
501 _("bookmark to export")))
499 entry = extensions.wrapcommand(commands.table, 'incoming', incoming)
502 entry = extensions.wrapcommand(commands.table, 'incoming', incoming)
500 entry[1].append(('B', 'bookmarks', False,
503 entry[1].append(('B', 'bookmarks', False,
501 _("compare bookmark")))
504 _("compare bookmark")))
502 entry = extensions.wrapcommand(commands.table, 'outgoing', outgoing)
505 entry = extensions.wrapcommand(commands.table, 'outgoing', outgoing)
503 entry[1].append(('B', 'bookmarks', False,
506 entry[1].append(('B', 'bookmarks', False,
504 _("compare bookmark")))
507 _("compare bookmark")))
505
508
506 pushkey.register('bookmarks', pushbookmark, listbookmarks)
509 pushkey.register('bookmarks', pushbookmark, listbookmarks)
507
510
508 def updatecurbookmark(orig, ui, repo, *args, **opts):
511 def updatecurbookmark(orig, ui, repo, *args, **opts):
509 '''Set the current bookmark
512 '''Set the current bookmark
510
513
511 If the user updates to a bookmark we update the .hg/bookmarks.current
514 If the user updates to a bookmark we update the .hg/bookmarks.current
512 file.
515 file.
513 '''
516 '''
514 res = orig(ui, repo, *args, **opts)
517 res = orig(ui, repo, *args, **opts)
515 rev = opts['rev']
518 rev = opts['rev']
516 if not rev and len(args) > 0:
519 if not rev and len(args) > 0:
517 rev = args[0]
520 rev = args[0]
518 setcurrent(repo, rev)
521 setcurrent(repo, rev)
519 return res
522 return res
520
523
521 cmdtable = {
524 cmdtable = {
522 "bookmarks":
525 "bookmarks":
523 (bookmark,
526 (bookmark,
524 [('f', 'force', False, _('force')),
527 [('f', 'force', False, _('force')),
525 ('r', 'rev', '', _('revision'), _('REV')),
528 ('r', 'rev', '', _('revision'), _('REV')),
526 ('d', 'delete', False, _('delete a given bookmark')),
529 ('d', 'delete', False, _('delete a given bookmark')),
527 ('m', 'rename', '', _('rename a given bookmark'), _('NAME'))],
530 ('m', 'rename', '', _('rename a given bookmark'), _('NAME'))],
528 _('hg bookmarks [-f] [-d] [-m NAME] [-r REV] [NAME]')),
531 _('hg bookmarks [-f] [-d] [-m NAME] [-r REV] [NAME]')),
529 }
532 }
530
533
531 colortable = {'bookmarks.current': 'green'}
534 colortable = {'bookmarks.current': 'green'}
@@ -1,576 +1,575 b''
1 # keyword.py - $Keyword$ expansion for Mercurial
1 # keyword.py - $Keyword$ expansion for Mercurial
2 #
2 #
3 # Copyright 2007-2010 Christian Ebert <blacktrash@gmx.net>
3 # Copyright 2007-2010 Christian Ebert <blacktrash@gmx.net>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7 #
7 #
8 # $Id$
8 # $Id$
9 #
9 #
10 # Keyword expansion hack against the grain of a DSCM
10 # Keyword expansion hack against the grain of a DSCM
11 #
11 #
12 # There are many good reasons why this is not needed in a distributed
12 # There are many good reasons why this is not needed in a distributed
13 # SCM, still it may be useful in very small projects based on single
13 # SCM, still it may be useful in very small projects based on single
14 # files (like LaTeX packages), that are mostly addressed to an
14 # files (like LaTeX packages), that are mostly addressed to an
15 # audience not running a version control system.
15 # audience not running a version control system.
16 #
16 #
17 # For in-depth discussion refer to
17 # For in-depth discussion refer to
18 # <http://mercurial.selenic.com/wiki/KeywordPlan>.
18 # <http://mercurial.selenic.com/wiki/KeywordPlan>.
19 #
19 #
20 # Keyword expansion is based on Mercurial's changeset template mappings.
20 # Keyword expansion is based on Mercurial's changeset template mappings.
21 #
21 #
22 # Binary files are not touched.
22 # Binary files are not touched.
23 #
23 #
24 # Files to act upon/ignore are specified in the [keyword] section.
24 # Files to act upon/ignore are specified in the [keyword] section.
25 # Customized keyword template mappings in the [keywordmaps] section.
25 # Customized keyword template mappings in the [keywordmaps] section.
26 #
26 #
27 # Run "hg help keyword" and "hg kwdemo" to get info on configuration.
27 # Run "hg help keyword" and "hg kwdemo" to get info on configuration.
28
28
29 '''expand keywords in tracked files
29 '''expand keywords in tracked files
30
30
31 This extension expands RCS/CVS-like or self-customized $Keywords$ in
31 This extension expands RCS/CVS-like or self-customized $Keywords$ in
32 tracked text files selected by your configuration.
32 tracked text files selected by your configuration.
33
33
34 Keywords are only expanded in local repositories and not stored in the
34 Keywords are only expanded in local repositories and not stored in the
35 change history. The mechanism can be regarded as a convenience for the
35 change history. The mechanism can be regarded as a convenience for the
36 current user or for archive distribution.
36 current user or for archive distribution.
37
37
38 Configuration is done in the [keyword], [keywordset] and [keywordmaps]
38 Configuration is done in the [keyword], [keywordset] and [keywordmaps]
39 sections of hgrc files.
39 sections of hgrc files.
40
40
41 Example::
41 Example::
42
42
43 [keyword]
43 [keyword]
44 # expand keywords in every python file except those matching "x*"
44 # expand keywords in every python file except those matching "x*"
45 **.py =
45 **.py =
46 x* = ignore
46 x* = ignore
47
47
48 [keywordset]
48 [keywordset]
49 # prefer svn- over cvs-like default keywordmaps
49 # prefer svn- over cvs-like default keywordmaps
50 svn = True
50 svn = True
51
51
52 NOTE: the more specific you are in your filename patterns the less you
52 NOTE: the more specific you are in your filename patterns the less you
53 lose speed in huge repositories.
53 lose speed in huge repositories.
54
54
55 For [keywordmaps] template mapping and expansion demonstration and
55 For [keywordmaps] template mapping and expansion demonstration and
56 control run :hg:`kwdemo`. See :hg:`help templates` for a list of
56 control run :hg:`kwdemo`. See :hg:`help templates` for a list of
57 available templates and filters.
57 available templates and filters.
58
58
59 Three additional date template filters are provided::
59 Three additional date template filters are provided::
60
60
61 utcdate "2006/09/18 15:13:13"
61 utcdate "2006/09/18 15:13:13"
62 svnutcdate "2006-09-18 15:13:13Z"
62 svnutcdate "2006-09-18 15:13:13Z"
63 svnisodate "2006-09-18 08:13:13 -700 (Mon, 18 Sep 2006)"
63 svnisodate "2006-09-18 08:13:13 -700 (Mon, 18 Sep 2006)"
64
64
65 The default template mappings (view with :hg:`kwdemo -d`) can be
65 The default template mappings (view with :hg:`kwdemo -d`) can be
66 replaced with customized keywords and templates. Again, run
66 replaced with customized keywords and templates. Again, run
67 :hg:`kwdemo` to control the results of your config changes.
67 :hg:`kwdemo` to control the results of your config changes.
68
68
69 Before changing/disabling active keywords, run :hg:`kwshrink` to avoid
69 Before changing/disabling active keywords, run :hg:`kwshrink` to avoid
70 the risk of inadvertently storing expanded keywords in the change
70 the risk of inadvertently storing expanded keywords in the change
71 history.
71 history.
72
72
73 To force expansion after enabling it, or a configuration change, run
73 To force expansion after enabling it, or a configuration change, run
74 :hg:`kwexpand`.
74 :hg:`kwexpand`.
75
75
76 Expansions spanning more than one line and incremental expansions,
76 Expansions spanning more than one line and incremental expansions,
77 like CVS' $Log$, are not supported. A keyword template map "Log =
77 like CVS' $Log$, are not supported. A keyword template map "Log =
78 {desc}" expands to the first line of the changeset description.
78 {desc}" expands to the first line of the changeset description.
79 '''
79 '''
80
80
81 from mercurial import commands, cmdutil, dispatch, filelog, revlog, extensions
81 from mercurial import commands, cmdutil, dispatch, filelog, revlog, extensions
82 from mercurial import patch, localrepo, templater, templatefilters, util, match
82 from mercurial import patch, localrepo, templater, templatefilters, util, match
83 from mercurial.hgweb import webcommands
83 from mercurial.hgweb import webcommands
84 from mercurial.i18n import _
84 from mercurial.i18n import _
85 import re, shutil, tempfile
85 import re, shutil, tempfile
86
86
87 commands.optionalrepo += ' kwdemo'
87 commands.optionalrepo += ' kwdemo'
88
88
89 # hg commands that do not act on keywords
89 # hg commands that do not act on keywords
90 nokwcommands = ('add addremove annotate bundle copy export grep incoming init'
90 nokwcommands = ('add addremove annotate bundle copy export grep incoming init'
91 ' log outgoing push rename rollback tip verify'
91 ' log outgoing push rename rollback tip verify'
92 ' convert email glog')
92 ' convert email glog')
93
93
94 # hg commands that trigger expansion only when writing to working dir,
94 # hg commands that trigger expansion only when writing to working dir,
95 # not when reading filelog, and unexpand when reading from working dir
95 # not when reading filelog, and unexpand when reading from working dir
96 restricted = 'merge record qrecord resolve transplant'
96 restricted = 'merge record qrecord resolve transplant'
97
97
98 # commands using dorecord
98 # commands using dorecord
99 recordcommands = 'record qrecord'
99 recordcommands = 'record qrecord'
100 # names of extensions using dorecord
100 # names of extensions using dorecord
101 recordextensions = 'record'
101 recordextensions = 'record'
102
102
103 # date like in cvs' $Date
103 # date like in cvs' $Date
104 utcdate = lambda x: util.datestr((x[0], 0), '%Y/%m/%d %H:%M:%S')
104 utcdate = lambda x: util.datestr((x[0], 0), '%Y/%m/%d %H:%M:%S')
105 # date like in svn's $Date
105 # date like in svn's $Date
106 svnisodate = lambda x: util.datestr(x, '%Y-%m-%d %H:%M:%S %1%2 (%a, %d %b %Y)')
106 svnisodate = lambda x: util.datestr(x, '%Y-%m-%d %H:%M:%S %1%2 (%a, %d %b %Y)')
107 # date like in svn's $Id
107 # date like in svn's $Id
108 svnutcdate = lambda x: util.datestr((x[0], 0), '%Y-%m-%d %H:%M:%SZ')
108 svnutcdate = lambda x: util.datestr((x[0], 0), '%Y-%m-%d %H:%M:%SZ')
109
109
110 # make keyword tools accessible
110 # make keyword tools accessible
111 kwtools = {'templater': None, 'hgcmd': '', 'inc': [], 'exc': ['.hg*']}
111 kwtools = {'templater': None, 'hgcmd': ''}
112
112
113
113
114 def _defaultkwmaps(ui):
114 def _defaultkwmaps(ui):
115 '''Returns default keywordmaps according to keywordset configuration.'''
115 '''Returns default keywordmaps according to keywordset configuration.'''
116 templates = {
116 templates = {
117 'Revision': '{node|short}',
117 'Revision': '{node|short}',
118 'Author': '{author|user}',
118 'Author': '{author|user}',
119 }
119 }
120 kwsets = ({
120 kwsets = ({
121 'Date': '{date|utcdate}',
121 'Date': '{date|utcdate}',
122 'RCSfile': '{file|basename},v',
122 'RCSfile': '{file|basename},v',
123 'RCSFile': '{file|basename},v', # kept for backwards compatibility
123 'RCSFile': '{file|basename},v', # kept for backwards compatibility
124 # with hg-keyword
124 # with hg-keyword
125 'Source': '{root}/{file},v',
125 'Source': '{root}/{file},v',
126 'Id': '{file|basename},v {node|short} {date|utcdate} {author|user}',
126 'Id': '{file|basename},v {node|short} {date|utcdate} {author|user}',
127 'Header': '{root}/{file},v {node|short} {date|utcdate} {author|user}',
127 'Header': '{root}/{file},v {node|short} {date|utcdate} {author|user}',
128 }, {
128 }, {
129 'Date': '{date|svnisodate}',
129 'Date': '{date|svnisodate}',
130 'Id': '{file|basename},v {node|short} {date|svnutcdate} {author|user}',
130 'Id': '{file|basename},v {node|short} {date|svnutcdate} {author|user}',
131 'LastChangedRevision': '{node|short}',
131 'LastChangedRevision': '{node|short}',
132 'LastChangedBy': '{author|user}',
132 'LastChangedBy': '{author|user}',
133 'LastChangedDate': '{date|svnisodate}',
133 'LastChangedDate': '{date|svnisodate}',
134 })
134 })
135 templates.update(kwsets[ui.configbool('keywordset', 'svn')])
135 templates.update(kwsets[ui.configbool('keywordset', 'svn')])
136 return templates
136 return templates
137
137
138 class kwtemplater(object):
138 class kwtemplater(object):
139 '''
139 '''
140 Sets up keyword templates, corresponding keyword regex, and
140 Sets up keyword templates, corresponding keyword regex, and
141 provides keyword substitution functions.
141 provides keyword substitution functions.
142 '''
142 '''
143
143
144 def __init__(self, ui, repo):
144 def __init__(self, ui, repo, inc, exc):
145 self.ui = ui
145 self.ui = ui
146 self.repo = repo
146 self.repo = repo
147 self.match = match.match(repo.root, '', [],
147 self.match = match.match(repo.root, '', [], inc, exc)
148 kwtools['inc'], kwtools['exc'])
149 self.restrict = kwtools['hgcmd'] in restricted.split()
148 self.restrict = kwtools['hgcmd'] in restricted.split()
150 self.record = kwtools['hgcmd'] in recordcommands.split()
149 self.record = kwtools['hgcmd'] in recordcommands.split()
151
150
152 kwmaps = self.ui.configitems('keywordmaps')
151 kwmaps = self.ui.configitems('keywordmaps')
153 if kwmaps: # override default templates
152 if kwmaps: # override default templates
154 self.templates = dict((k, templater.parsestring(v, False))
153 self.templates = dict((k, templater.parsestring(v, False))
155 for k, v in kwmaps)
154 for k, v in kwmaps)
156 else:
155 else:
157 self.templates = _defaultkwmaps(self.ui)
156 self.templates = _defaultkwmaps(self.ui)
158 escaped = map(re.escape, self.templates.keys())
157 escaped = map(re.escape, self.templates.keys())
159 kwpat = r'\$(%s)(: [^$\n\r]*? )??\$' % '|'.join(escaped)
158 kwpat = r'\$(%s)(: [^$\n\r]*? )??\$' % '|'.join(escaped)
160 self.re_kw = re.compile(kwpat)
159 self.re_kw = re.compile(kwpat)
161
160
162 templatefilters.filters['utcdate'] = utcdate
161 templatefilters.filters['utcdate'] = utcdate
163 templatefilters.filters['svnisodate'] = svnisodate
162 templatefilters.filters['svnisodate'] = svnisodate
164 templatefilters.filters['svnutcdate'] = svnutcdate
163 templatefilters.filters['svnutcdate'] = svnutcdate
165
164
166 def substitute(self, data, path, ctx, subfunc):
165 def substitute(self, data, path, ctx, subfunc):
167 '''Replaces keywords in data with expanded template.'''
166 '''Replaces keywords in data with expanded template.'''
168 def kwsub(mobj):
167 def kwsub(mobj):
169 kw = mobj.group(1)
168 kw = mobj.group(1)
170 ct = cmdutil.changeset_templater(self.ui, self.repo,
169 ct = cmdutil.changeset_templater(self.ui, self.repo,
171 False, None, '', False)
170 False, None, '', False)
172 ct.use_template(self.templates[kw])
171 ct.use_template(self.templates[kw])
173 self.ui.pushbuffer()
172 self.ui.pushbuffer()
174 ct.show(ctx, root=self.repo.root, file=path)
173 ct.show(ctx, root=self.repo.root, file=path)
175 ekw = templatefilters.firstline(self.ui.popbuffer())
174 ekw = templatefilters.firstline(self.ui.popbuffer())
176 return '$%s: %s $' % (kw, ekw)
175 return '$%s: %s $' % (kw, ekw)
177 return subfunc(kwsub, data)
176 return subfunc(kwsub, data)
178
177
179 def expand(self, path, node, data):
178 def expand(self, path, node, data):
180 '''Returns data with keywords expanded.'''
179 '''Returns data with keywords expanded.'''
181 if not self.restrict and self.match(path) and not util.binary(data):
180 if not self.restrict and self.match(path) and not util.binary(data):
182 ctx = self.repo.filectx(path, fileid=node).changectx()
181 ctx = self.repo.filectx(path, fileid=node).changectx()
183 return self.substitute(data, path, ctx, self.re_kw.sub)
182 return self.substitute(data, path, ctx, self.re_kw.sub)
184 return data
183 return data
185
184
186 def iskwfile(self, path, flagfunc):
185 def iskwfile(self, path, flagfunc):
187 '''Returns true if path matches [keyword] pattern
186 '''Returns true if path matches [keyword] pattern
188 and is not a symbolic link.
187 and is not a symbolic link.
189 Caveat: localrepository._link fails on Windows.'''
188 Caveat: localrepository._link fails on Windows.'''
190 return self.match(path) and not 'l' in flagfunc(path)
189 return self.match(path) and not 'l' in flagfunc(path)
191
190
192 def overwrite(self, ctx, candidates, iswctx, expand):
191 def overwrite(self, ctx, candidates, iswctx, expand):
193 '''Overwrites selected files expanding/shrinking keywords.'''
192 '''Overwrites selected files expanding/shrinking keywords.'''
194 if self.record:
193 if self.record:
195 candidates = [f for f in ctx.files() if f in ctx]
194 candidates = [f for f in ctx.files() if f in ctx]
196 candidates = [f for f in candidates if self.iskwfile(f, ctx.flags)]
195 candidates = [f for f in candidates if self.iskwfile(f, ctx.flags)]
197 if candidates:
196 if candidates:
198 self.restrict = True # do not expand when reading
197 self.restrict = True # do not expand when reading
199 mf = ctx.manifest()
198 mf = ctx.manifest()
200 msg = (expand and _('overwriting %s expanding keywords\n')
199 msg = (expand and _('overwriting %s expanding keywords\n')
201 or _('overwriting %s shrinking keywords\n'))
200 or _('overwriting %s shrinking keywords\n'))
202 for f in candidates:
201 for f in candidates:
203 if not self.record:
202 if not self.record:
204 data = self.repo.file(f).read(mf[f])
203 data = self.repo.file(f).read(mf[f])
205 else:
204 else:
206 data = self.repo.wread(f)
205 data = self.repo.wread(f)
207 if util.binary(data):
206 if util.binary(data):
208 continue
207 continue
209 if expand:
208 if expand:
210 if iswctx:
209 if iswctx:
211 ctx = self.repo.filectx(f, fileid=mf[f]).changectx()
210 ctx = self.repo.filectx(f, fileid=mf[f]).changectx()
212 data, found = self.substitute(data, f, ctx,
211 data, found = self.substitute(data, f, ctx,
213 self.re_kw.subn)
212 self.re_kw.subn)
214 else:
213 else:
215 found = self.re_kw.search(data)
214 found = self.re_kw.search(data)
216 if found:
215 if found:
217 self.ui.note(msg % f)
216 self.ui.note(msg % f)
218 self.repo.wwrite(f, data, mf.flags(f))
217 self.repo.wwrite(f, data, mf.flags(f))
219 if iswctx:
218 if iswctx:
220 self.repo.dirstate.normal(f)
219 self.repo.dirstate.normal(f)
221 elif self.record:
220 elif self.record:
222 self.repo.dirstate.normallookup(f)
221 self.repo.dirstate.normallookup(f)
223 self.restrict = False
222 self.restrict = False
224
223
225 def shrinktext(self, text):
224 def shrinktext(self, text):
226 '''Unconditionally removes all keyword substitutions from text.'''
225 '''Unconditionally removes all keyword substitutions from text.'''
227 return self.re_kw.sub(r'$\1$', text)
226 return self.re_kw.sub(r'$\1$', text)
228
227
229 def shrink(self, fname, text):
228 def shrink(self, fname, text):
230 '''Returns text with all keyword substitutions removed.'''
229 '''Returns text with all keyword substitutions removed.'''
231 if self.match(fname) and not util.binary(text):
230 if self.match(fname) and not util.binary(text):
232 return self.shrinktext(text)
231 return self.shrinktext(text)
233 return text
232 return text
234
233
235 def shrinklines(self, fname, lines):
234 def shrinklines(self, fname, lines):
236 '''Returns lines with keyword substitutions removed.'''
235 '''Returns lines with keyword substitutions removed.'''
237 if self.match(fname):
236 if self.match(fname):
238 text = ''.join(lines)
237 text = ''.join(lines)
239 if not util.binary(text):
238 if not util.binary(text):
240 return self.shrinktext(text).splitlines(True)
239 return self.shrinktext(text).splitlines(True)
241 return lines
240 return lines
242
241
243 def wread(self, fname, data):
242 def wread(self, fname, data):
244 '''If in restricted mode returns data read from wdir with
243 '''If in restricted mode returns data read from wdir with
245 keyword substitutions removed.'''
244 keyword substitutions removed.'''
246 return self.restrict and self.shrink(fname, data) or data
245 return self.restrict and self.shrink(fname, data) or data
247
246
248 class kwfilelog(filelog.filelog):
247 class kwfilelog(filelog.filelog):
249 '''
248 '''
250 Subclass of filelog to hook into its read, add, cmp methods.
249 Subclass of filelog to hook into its read, add, cmp methods.
251 Keywords are "stored" unexpanded, and processed on reading.
250 Keywords are "stored" unexpanded, and processed on reading.
252 '''
251 '''
253 def __init__(self, opener, kwt, path):
252 def __init__(self, opener, kwt, path):
254 super(kwfilelog, self).__init__(opener, path)
253 super(kwfilelog, self).__init__(opener, path)
255 self.kwt = kwt
254 self.kwt = kwt
256 self.path = path
255 self.path = path
257
256
258 def read(self, node):
257 def read(self, node):
259 '''Expands keywords when reading filelog.'''
258 '''Expands keywords when reading filelog.'''
260 data = super(kwfilelog, self).read(node)
259 data = super(kwfilelog, self).read(node)
261 return self.kwt.expand(self.path, node, data)
260 return self.kwt.expand(self.path, node, data)
262
261
263 def add(self, text, meta, tr, link, p1=None, p2=None):
262 def add(self, text, meta, tr, link, p1=None, p2=None):
264 '''Removes keyword substitutions when adding to filelog.'''
263 '''Removes keyword substitutions when adding to filelog.'''
265 text = self.kwt.shrink(self.path, text)
264 text = self.kwt.shrink(self.path, text)
266 return super(kwfilelog, self).add(text, meta, tr, link, p1, p2)
265 return super(kwfilelog, self).add(text, meta, tr, link, p1, p2)
267
266
268 def cmp(self, node, text):
267 def cmp(self, node, text):
269 '''Removes keyword substitutions for comparison.'''
268 '''Removes keyword substitutions for comparison.'''
270 text = self.kwt.shrink(self.path, text)
269 text = self.kwt.shrink(self.path, text)
271 if self.renamed(node):
270 if self.renamed(node):
272 t2 = super(kwfilelog, self).read(node)
271 t2 = super(kwfilelog, self).read(node)
273 return t2 != text
272 return t2 != text
274 return revlog.revlog.cmp(self, node, text)
273 return revlog.revlog.cmp(self, node, text)
275
274
276 def _status(ui, repo, kwt, *pats, **opts):
275 def _status(ui, repo, kwt, *pats, **opts):
277 '''Bails out if [keyword] configuration is not active.
276 '''Bails out if [keyword] configuration is not active.
278 Returns status of working directory.'''
277 Returns status of working directory.'''
279 if kwt:
278 if kwt:
280 return repo.status(match=cmdutil.match(repo, pats, opts), clean=True,
279 return repo.status(match=cmdutil.match(repo, pats, opts), clean=True,
281 unknown=opts.get('unknown') or opts.get('all'))
280 unknown=opts.get('unknown') or opts.get('all'))
282 if ui.configitems('keyword'):
281 if ui.configitems('keyword'):
283 raise util.Abort(_('[keyword] patterns cannot match'))
282 raise util.Abort(_('[keyword] patterns cannot match'))
284 raise util.Abort(_('no [keyword] patterns configured'))
283 raise util.Abort(_('no [keyword] patterns configured'))
285
284
286 def _kwfwrite(ui, repo, expand, *pats, **opts):
285 def _kwfwrite(ui, repo, expand, *pats, **opts):
287 '''Selects files and passes them to kwtemplater.overwrite.'''
286 '''Selects files and passes them to kwtemplater.overwrite.'''
288 wctx = repo[None]
287 wctx = repo[None]
289 if len(wctx.parents()) > 1:
288 if len(wctx.parents()) > 1:
290 raise util.Abort(_('outstanding uncommitted merge'))
289 raise util.Abort(_('outstanding uncommitted merge'))
291 kwt = kwtools['templater']
290 kwt = kwtools['templater']
292 wlock = repo.wlock()
291 wlock = repo.wlock()
293 try:
292 try:
294 status = _status(ui, repo, kwt, *pats, **opts)
293 status = _status(ui, repo, kwt, *pats, **opts)
295 modified, added, removed, deleted, unknown, ignored, clean = status
294 modified, added, removed, deleted, unknown, ignored, clean = status
296 if modified or added or removed or deleted:
295 if modified or added or removed or deleted:
297 raise util.Abort(_('outstanding uncommitted changes'))
296 raise util.Abort(_('outstanding uncommitted changes'))
298 kwt.overwrite(wctx, clean, True, expand)
297 kwt.overwrite(wctx, clean, True, expand)
299 finally:
298 finally:
300 wlock.release()
299 wlock.release()
301
300
302 def demo(ui, repo, *args, **opts):
301 def demo(ui, repo, *args, **opts):
303 '''print [keywordmaps] configuration and an expansion example
302 '''print [keywordmaps] configuration and an expansion example
304
303
305 Show current, custom, or default keyword template maps and their
304 Show current, custom, or default keyword template maps and their
306 expansions.
305 expansions.
307
306
308 Extend the current configuration by specifying maps as arguments
307 Extend the current configuration by specifying maps as arguments
309 and using -f/--rcfile to source an external hgrc file.
308 and using -f/--rcfile to source an external hgrc file.
310
309
311 Use -d/--default to disable current configuration.
310 Use -d/--default to disable current configuration.
312
311
313 See :hg:`help templates` for information on templates and filters.
312 See :hg:`help templates` for information on templates and filters.
314 '''
313 '''
315 def demoitems(section, items):
314 def demoitems(section, items):
316 ui.write('[%s]\n' % section)
315 ui.write('[%s]\n' % section)
317 for k, v in sorted(items):
316 for k, v in sorted(items):
318 ui.write('%s = %s\n' % (k, v))
317 ui.write('%s = %s\n' % (k, v))
319
318
320 fn = 'demo.txt'
319 fn = 'demo.txt'
321 tmpdir = tempfile.mkdtemp('', 'kwdemo.')
320 tmpdir = tempfile.mkdtemp('', 'kwdemo.')
322 ui.note(_('creating temporary repository at %s\n') % tmpdir)
321 ui.note(_('creating temporary repository at %s\n') % tmpdir)
323 repo = localrepo.localrepository(ui, tmpdir, True)
322 repo = localrepo.localrepository(ui, tmpdir, True)
324 ui.setconfig('keyword', fn, '')
323 ui.setconfig('keyword', fn, '')
325
324
326 uikwmaps = ui.configitems('keywordmaps')
325 uikwmaps = ui.configitems('keywordmaps')
327 if args or opts.get('rcfile'):
326 if args or opts.get('rcfile'):
328 ui.status(_('\n\tconfiguration using custom keyword template maps\n'))
327 ui.status(_('\n\tconfiguration using custom keyword template maps\n'))
329 if uikwmaps:
328 if uikwmaps:
330 ui.status(_('\textending current template maps\n'))
329 ui.status(_('\textending current template maps\n'))
331 if opts.get('default') or not uikwmaps:
330 if opts.get('default') or not uikwmaps:
332 ui.status(_('\toverriding default template maps\n'))
331 ui.status(_('\toverriding default template maps\n'))
333 if opts.get('rcfile'):
332 if opts.get('rcfile'):
334 ui.readconfig(opts.get('rcfile'))
333 ui.readconfig(opts.get('rcfile'))
335 if args:
334 if args:
336 # simulate hgrc parsing
335 # simulate hgrc parsing
337 rcmaps = ['[keywordmaps]\n'] + [a + '\n' for a in args]
336 rcmaps = ['[keywordmaps]\n'] + [a + '\n' for a in args]
338 fp = repo.opener('hgrc', 'w')
337 fp = repo.opener('hgrc', 'w')
339 fp.writelines(rcmaps)
338 fp.writelines(rcmaps)
340 fp.close()
339 fp.close()
341 ui.readconfig(repo.join('hgrc'))
340 ui.readconfig(repo.join('hgrc'))
342 kwmaps = dict(ui.configitems('keywordmaps'))
341 kwmaps = dict(ui.configitems('keywordmaps'))
343 elif opts.get('default'):
342 elif opts.get('default'):
344 ui.status(_('\n\tconfiguration using default keyword template maps\n'))
343 ui.status(_('\n\tconfiguration using default keyword template maps\n'))
345 kwmaps = _defaultkwmaps(ui)
344 kwmaps = _defaultkwmaps(ui)
346 if uikwmaps:
345 if uikwmaps:
347 ui.status(_('\tdisabling current template maps\n'))
346 ui.status(_('\tdisabling current template maps\n'))
348 for k, v in kwmaps.iteritems():
347 for k, v in kwmaps.iteritems():
349 ui.setconfig('keywordmaps', k, v)
348 ui.setconfig('keywordmaps', k, v)
350 else:
349 else:
351 ui.status(_('\n\tconfiguration using current keyword template maps\n'))
350 ui.status(_('\n\tconfiguration using current keyword template maps\n'))
352 kwmaps = dict(uikwmaps) or _defaultkwmaps(ui)
351 kwmaps = dict(uikwmaps) or _defaultkwmaps(ui)
353
352
354 uisetup(ui)
353 uisetup(ui)
355 reposetup(ui, repo)
354 reposetup(ui, repo)
356 ui.write('[extensions]\nkeyword =\n')
355 ui.write('[extensions]\nkeyword =\n')
357 demoitems('keyword', ui.configitems('keyword'))
356 demoitems('keyword', ui.configitems('keyword'))
358 demoitems('keywordmaps', kwmaps.iteritems())
357 demoitems('keywordmaps', kwmaps.iteritems())
359 keywords = '$' + '$\n$'.join(sorted(kwmaps.keys())) + '$\n'
358 keywords = '$' + '$\n$'.join(sorted(kwmaps.keys())) + '$\n'
360 repo.wopener(fn, 'w').write(keywords)
359 repo.wopener(fn, 'w').write(keywords)
361 repo[None].add([fn])
360 repo[None].add([fn])
362 ui.note(_('\nkeywords written to %s:\n') % fn)
361 ui.note(_('\nkeywords written to %s:\n') % fn)
363 ui.note(keywords)
362 ui.note(keywords)
364 repo.dirstate.setbranch('demobranch')
363 repo.dirstate.setbranch('demobranch')
365 for name, cmd in ui.configitems('hooks'):
364 for name, cmd in ui.configitems('hooks'):
366 if name.split('.', 1)[0].find('commit') > -1:
365 if name.split('.', 1)[0].find('commit') > -1:
367 repo.ui.setconfig('hooks', name, '')
366 repo.ui.setconfig('hooks', name, '')
368 msg = _('hg keyword configuration and expansion example')
367 msg = _('hg keyword configuration and expansion example')
369 ui.note("hg ci -m '%s'\n" % msg)
368 ui.note("hg ci -m '%s'\n" % msg)
370 repo.commit(text=msg)
369 repo.commit(text=msg)
371 ui.status(_('\n\tkeywords expanded\n'))
370 ui.status(_('\n\tkeywords expanded\n'))
372 ui.write(repo.wread(fn))
371 ui.write(repo.wread(fn))
373 shutil.rmtree(tmpdir, ignore_errors=True)
372 shutil.rmtree(tmpdir, ignore_errors=True)
374
373
375 def expand(ui, repo, *pats, **opts):
374 def expand(ui, repo, *pats, **opts):
376 '''expand keywords in the working directory
375 '''expand keywords in the working directory
377
376
378 Run after (re)enabling keyword expansion.
377 Run after (re)enabling keyword expansion.
379
378
380 kwexpand refuses to run if given files contain local changes.
379 kwexpand refuses to run if given files contain local changes.
381 '''
380 '''
382 # 3rd argument sets expansion to True
381 # 3rd argument sets expansion to True
383 _kwfwrite(ui, repo, True, *pats, **opts)
382 _kwfwrite(ui, repo, True, *pats, **opts)
384
383
385 def files(ui, repo, *pats, **opts):
384 def files(ui, repo, *pats, **opts):
386 '''show files configured for keyword expansion
385 '''show files configured for keyword expansion
387
386
388 List which files in the working directory are matched by the
387 List which files in the working directory are matched by the
389 [keyword] configuration patterns.
388 [keyword] configuration patterns.
390
389
391 Useful to prevent inadvertent keyword expansion and to speed up
390 Useful to prevent inadvertent keyword expansion and to speed up
392 execution by including only files that are actual candidates for
391 execution by including only files that are actual candidates for
393 expansion.
392 expansion.
394
393
395 See :hg:`help keyword` on how to construct patterns both for
394 See :hg:`help keyword` on how to construct patterns both for
396 inclusion and exclusion of files.
395 inclusion and exclusion of files.
397
396
398 With -A/--all and -v/--verbose the codes used to show the status
397 With -A/--all and -v/--verbose the codes used to show the status
399 of files are::
398 of files are::
400
399
401 K = keyword expansion candidate
400 K = keyword expansion candidate
402 k = keyword expansion candidate (not tracked)
401 k = keyword expansion candidate (not tracked)
403 I = ignored
402 I = ignored
404 i = ignored (not tracked)
403 i = ignored (not tracked)
405 '''
404 '''
406 kwt = kwtools['templater']
405 kwt = kwtools['templater']
407 status = _status(ui, repo, kwt, *pats, **opts)
406 status = _status(ui, repo, kwt, *pats, **opts)
408 cwd = pats and repo.getcwd() or ''
407 cwd = pats and repo.getcwd() or ''
409 modified, added, removed, deleted, unknown, ignored, clean = status
408 modified, added, removed, deleted, unknown, ignored, clean = status
410 files = []
409 files = []
411 if not opts.get('unknown') or opts.get('all'):
410 if not opts.get('unknown') or opts.get('all'):
412 files = sorted(modified + added + clean)
411 files = sorted(modified + added + clean)
413 wctx = repo[None]
412 wctx = repo[None]
414 kwfiles = [f for f in files if kwt.iskwfile(f, wctx.flags)]
413 kwfiles = [f for f in files if kwt.iskwfile(f, wctx.flags)]
415 kwunknown = [f for f in unknown if kwt.iskwfile(f, wctx.flags)]
414 kwunknown = [f for f in unknown if kwt.iskwfile(f, wctx.flags)]
416 if not opts.get('ignore') or opts.get('all'):
415 if not opts.get('ignore') or opts.get('all'):
417 showfiles = kwfiles, kwunknown
416 showfiles = kwfiles, kwunknown
418 else:
417 else:
419 showfiles = [], []
418 showfiles = [], []
420 if opts.get('all') or opts.get('ignore'):
419 if opts.get('all') or opts.get('ignore'):
421 showfiles += ([f for f in files if f not in kwfiles],
420 showfiles += ([f for f in files if f not in kwfiles],
422 [f for f in unknown if f not in kwunknown])
421 [f for f in unknown if f not in kwunknown])
423 for char, filenames in zip('KkIi', showfiles):
422 for char, filenames in zip('KkIi', showfiles):
424 fmt = (opts.get('all') or ui.verbose) and '%s %%s\n' % char or '%s\n'
423 fmt = (opts.get('all') or ui.verbose) and '%s %%s\n' % char or '%s\n'
425 for f in filenames:
424 for f in filenames:
426 ui.write(fmt % repo.pathto(f, cwd))
425 ui.write(fmt % repo.pathto(f, cwd))
427
426
428 def shrink(ui, repo, *pats, **opts):
427 def shrink(ui, repo, *pats, **opts):
429 '''revert expanded keywords in the working directory
428 '''revert expanded keywords in the working directory
430
429
431 Run before changing/disabling active keywords or if you experience
430 Run before changing/disabling active keywords or if you experience
432 problems with :hg:`import` or :hg:`merge`.
431 problems with :hg:`import` or :hg:`merge`.
433
432
434 kwshrink refuses to run if given files contain local changes.
433 kwshrink refuses to run if given files contain local changes.
435 '''
434 '''
436 # 3rd argument sets expansion to False
435 # 3rd argument sets expansion to False
437 _kwfwrite(ui, repo, False, *pats, **opts)
436 _kwfwrite(ui, repo, False, *pats, **opts)
438
437
439
438
440 def uisetup(ui):
439 def uisetup(ui):
441 '''Collects [keyword] config in kwtools.
440 ''' Monkeypatches dispatch._parse to retrieve user command.'''
442 Monkeypatches dispatch._parse if needed.'''
443
441
444 for pat, opt in ui.configitems('keyword'):
445 if opt != 'ignore':
446 kwtools['inc'].append(pat)
447 else:
448 kwtools['exc'].append(pat)
449
450 if kwtools['inc']:
451 def kwdispatch_parse(orig, ui, args):
442 def kwdispatch_parse(orig, ui, args):
452 '''Monkeypatch dispatch._parse to obtain running hg command.'''
443 '''Monkeypatch dispatch._parse to obtain running hg command.'''
453 cmd, func, args, options, cmdoptions = orig(ui, args)
444 cmd, func, args, options, cmdoptions = orig(ui, args)
454 kwtools['hgcmd'] = cmd
445 kwtools['hgcmd'] = cmd
455 return cmd, func, args, options, cmdoptions
446 return cmd, func, args, options, cmdoptions
456
447
457 extensions.wrapfunction(dispatch, '_parse', kwdispatch_parse)
448 extensions.wrapfunction(dispatch, '_parse', kwdispatch_parse)
458
449
459 def reposetup(ui, repo):
450 def reposetup(ui, repo):
460 '''Sets up repo as kwrepo for keyword substitution.
451 '''Sets up repo as kwrepo for keyword substitution.
461 Overrides file method to return kwfilelog instead of filelog
452 Overrides file method to return kwfilelog instead of filelog
462 if file matches user configuration.
453 if file matches user configuration.
463 Wraps commit to overwrite configured files with updated
454 Wraps commit to overwrite configured files with updated
464 keyword substitutions.
455 keyword substitutions.
465 Monkeypatches patch and webcommands.'''
456 Monkeypatches patch and webcommands.'''
466
457
467 try:
458 try:
468 if (not repo.local() or not kwtools['inc']
459 if (not repo.local() or kwtools['hgcmd'] in nokwcommands.split()
469 or kwtools['hgcmd'] in nokwcommands.split()
470 or '.hg' in util.splitpath(repo.root)
460 or '.hg' in util.splitpath(repo.root)
471 or repo._url.startswith('bundle:')):
461 or repo._url.startswith('bundle:')):
472 return
462 return
473 except AttributeError:
463 except AttributeError:
474 pass
464 pass
475
465
476 kwtools['templater'] = kwt = kwtemplater(ui, repo)
466 inc, exc = [], ['.hg*']
467 for pat, opt in ui.configitems('keyword'):
468 if opt != 'ignore':
469 inc.append(pat)
470 else:
471 exc.append(pat)
472 if not inc:
473 return
474
475 kwtools['templater'] = kwt = kwtemplater(ui, repo, inc, exc)
477
476
478 class kwrepo(repo.__class__):
477 class kwrepo(repo.__class__):
479 def file(self, f):
478 def file(self, f):
480 if f[0] == '/':
479 if f[0] == '/':
481 f = f[1:]
480 f = f[1:]
482 return kwfilelog(self.sopener, kwt, f)
481 return kwfilelog(self.sopener, kwt, f)
483
482
484 def wread(self, filename):
483 def wread(self, filename):
485 data = super(kwrepo, self).wread(filename)
484 data = super(kwrepo, self).wread(filename)
486 return kwt.wread(filename, data)
485 return kwt.wread(filename, data)
487
486
488 def commit(self, *args, **opts):
487 def commit(self, *args, **opts):
489 # use custom commitctx for user commands
488 # use custom commitctx for user commands
490 # other extensions can still wrap repo.commitctx directly
489 # other extensions can still wrap repo.commitctx directly
491 self.commitctx = self.kwcommitctx
490 self.commitctx = self.kwcommitctx
492 try:
491 try:
493 return super(kwrepo, self).commit(*args, **opts)
492 return super(kwrepo, self).commit(*args, **opts)
494 finally:
493 finally:
495 del self.commitctx
494 del self.commitctx
496
495
497 def kwcommitctx(self, ctx, error=False):
496 def kwcommitctx(self, ctx, error=False):
498 n = super(kwrepo, self).commitctx(ctx, error)
497 n = super(kwrepo, self).commitctx(ctx, error)
499 # no lock needed, only called from repo.commit() which already locks
498 # no lock needed, only called from repo.commit() which already locks
500 if not kwt.record:
499 if not kwt.record:
501 kwt.overwrite(self[n], sorted(ctx.added() + ctx.modified()),
500 kwt.overwrite(self[n], sorted(ctx.added() + ctx.modified()),
502 False, True)
501 False, True)
503 return n
502 return n
504
503
505 # monkeypatches
504 # monkeypatches
506 def kwpatchfile_init(orig, self, ui, fname, opener,
505 def kwpatchfile_init(orig, self, ui, fname, opener,
507 missing=False, eolmode=None):
506 missing=False, eolmode=None):
508 '''Monkeypatch/wrap patch.patchfile.__init__ to avoid
507 '''Monkeypatch/wrap patch.patchfile.__init__ to avoid
509 rejects or conflicts due to expanded keywords in working dir.'''
508 rejects or conflicts due to expanded keywords in working dir.'''
510 orig(self, ui, fname, opener, missing, eolmode)
509 orig(self, ui, fname, opener, missing, eolmode)
511 # shrink keywords read from working dir
510 # shrink keywords read from working dir
512 self.lines = kwt.shrinklines(self.fname, self.lines)
511 self.lines = kwt.shrinklines(self.fname, self.lines)
513
512
514 def kw_diff(orig, repo, node1=None, node2=None, match=None, changes=None,
513 def kw_diff(orig, repo, node1=None, node2=None, match=None, changes=None,
515 opts=None):
514 opts=None):
516 '''Monkeypatch patch.diff to avoid expansion except when
515 '''Monkeypatch patch.diff to avoid expansion except when
517 comparing against working dir.'''
516 comparing against working dir.'''
518 if node2 is not None:
517 if node2 is not None:
519 kwt.match = util.never
518 kwt.match = util.never
520 elif node1 is not None and node1 != repo['.'].node():
519 elif node1 is not None and node1 != repo['.'].node():
521 kwt.restrict = True
520 kwt.restrict = True
522 return orig(repo, node1, node2, match, changes, opts)
521 return orig(repo, node1, node2, match, changes, opts)
523
522
524 def kwweb_skip(orig, web, req, tmpl):
523 def kwweb_skip(orig, web, req, tmpl):
525 '''Wraps webcommands.x turning off keyword expansion.'''
524 '''Wraps webcommands.x turning off keyword expansion.'''
526 kwt.match = util.never
525 kwt.match = util.never
527 return orig(web, req, tmpl)
526 return orig(web, req, tmpl)
528
527
529 def kw_dorecord(orig, ui, repo, commitfunc, *pats, **opts):
528 def kw_dorecord(orig, ui, repo, commitfunc, *pats, **opts):
530 '''Wraps record.dorecord expanding keywords after recording.'''
529 '''Wraps record.dorecord expanding keywords after recording.'''
531 wlock = repo.wlock()
530 wlock = repo.wlock()
532 try:
531 try:
533 # record returns 0 even when nothing has changed
532 # record returns 0 even when nothing has changed
534 # therefore compare nodes before and after
533 # therefore compare nodes before and after
535 ctx = repo['.']
534 ctx = repo['.']
536 ret = orig(ui, repo, commitfunc, *pats, **opts)
535 ret = orig(ui, repo, commitfunc, *pats, **opts)
537 recordctx = repo['.']
536 recordctx = repo['.']
538 if ctx != recordctx:
537 if ctx != recordctx:
539 kwt.overwrite(recordctx, None, False, True)
538 kwt.overwrite(recordctx, None, False, True)
540 return ret
539 return ret
541 finally:
540 finally:
542 wlock.release()
541 wlock.release()
543
542
544 repo.__class__ = kwrepo
543 repo.__class__ = kwrepo
545
544
546 extensions.wrapfunction(patch.patchfile, '__init__', kwpatchfile_init)
545 extensions.wrapfunction(patch.patchfile, '__init__', kwpatchfile_init)
547 if not kwt.restrict:
546 if not kwt.restrict:
548 extensions.wrapfunction(patch, 'diff', kw_diff)
547 extensions.wrapfunction(patch, 'diff', kw_diff)
549 for c in 'annotate changeset rev filediff diff'.split():
548 for c in 'annotate changeset rev filediff diff'.split():
550 extensions.wrapfunction(webcommands, c, kwweb_skip)
549 extensions.wrapfunction(webcommands, c, kwweb_skip)
551 for name in recordextensions.split():
550 for name in recordextensions.split():
552 try:
551 try:
553 record = extensions.find(name)
552 record = extensions.find(name)
554 extensions.wrapfunction(record, 'dorecord', kw_dorecord)
553 extensions.wrapfunction(record, 'dorecord', kw_dorecord)
555 except KeyError:
554 except KeyError:
556 pass
555 pass
557
556
558 cmdtable = {
557 cmdtable = {
559 'kwdemo':
558 'kwdemo':
560 (demo,
559 (demo,
561 [('d', 'default', None, _('show default keyword template maps')),
560 [('d', 'default', None, _('show default keyword template maps')),
562 ('f', 'rcfile', '',
561 ('f', 'rcfile', '',
563 _('read maps from rcfile'), _('FILE'))],
562 _('read maps from rcfile'), _('FILE'))],
564 _('hg kwdemo [-d] [-f RCFILE] [TEMPLATEMAP]...')),
563 _('hg kwdemo [-d] [-f RCFILE] [TEMPLATEMAP]...')),
565 'kwexpand': (expand, commands.walkopts,
564 'kwexpand': (expand, commands.walkopts,
566 _('hg kwexpand [OPTION]... [FILE]...')),
565 _('hg kwexpand [OPTION]... [FILE]...')),
567 'kwfiles':
566 'kwfiles':
568 (files,
567 (files,
569 [('A', 'all', None, _('show keyword status flags of all files')),
568 [('A', 'all', None, _('show keyword status flags of all files')),
570 ('i', 'ignore', None, _('show files excluded from expansion')),
569 ('i', 'ignore', None, _('show files excluded from expansion')),
571 ('u', 'unknown', None, _('only show unknown (not tracked) files')),
570 ('u', 'unknown', None, _('only show unknown (not tracked) files')),
572 ] + commands.walkopts,
571 ] + commands.walkopts,
573 _('hg kwfiles [OPTION]... [FILE]...')),
572 _('hg kwfiles [OPTION]... [FILE]...')),
574 'kwshrink': (shrink, commands.walkopts,
573 'kwshrink': (shrink, commands.walkopts,
575 _('hg kwshrink [OPTION]... [FILE]...')),
574 _('hg kwshrink [OPTION]... [FILE]...')),
576 }
575 }
@@ -1,3018 +1,3022 b''
1 # mq.py - patch queues for mercurial
1 # mq.py - patch queues for mercurial
2 #
2 #
3 # Copyright 2005, 2006 Chris Mason <mason@suse.com>
3 # Copyright 2005, 2006 Chris Mason <mason@suse.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 '''manage a stack of patches
8 '''manage a stack of patches
9
9
10 This extension lets you work with a stack of patches in a Mercurial
10 This extension lets you work with a stack of patches in a Mercurial
11 repository. It manages two stacks of patches - all known patches, and
11 repository. It manages two stacks of patches - all known patches, and
12 applied patches (subset of known patches).
12 applied patches (subset of known patches).
13
13
14 Known patches are represented as patch files in the .hg/patches
14 Known patches are represented as patch files in the .hg/patches
15 directory. Applied patches are both patch files and changesets.
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 create new patch qnew
19 create new patch qnew
20 import existing patch qimport
20 import existing patch qimport
21
21
22 print patch series qseries
22 print patch series qseries
23 print applied patches qapplied
23 print applied patches qapplied
24
24
25 add known patch to applied stack qpush
25 add known patch to applied stack qpush
26 remove patch from applied stack qpop
26 remove patch from applied stack qpop
27 refresh contents of top applied patch qrefresh
27 refresh contents of top applied patch qrefresh
28
28
29 By default, mq will automatically use git patches when required to
29 By default, mq will automatically use git patches when required to
30 avoid losing file mode changes, copy records, binary files or empty
30 avoid losing file mode changes, copy records, binary files or empty
31 files creations or deletions. This behaviour can be configured with::
31 files creations or deletions. This behaviour can be configured with::
32
32
33 [mq]
33 [mq]
34 git = auto/keep/yes/no
34 git = auto/keep/yes/no
35
35
36 If set to 'keep', mq will obey the [diff] section configuration while
36 If set to 'keep', mq will obey the [diff] section configuration while
37 preserving existing git patches upon qrefresh. If set to 'yes' or
37 preserving existing git patches upon qrefresh. If set to 'yes' or
38 'no', mq will override the [diff] section and always generate git or
38 'no', mq will override the [diff] section and always generate git or
39 regular patches, possibly losing data in the second case.
39 regular patches, possibly losing data in the second case.
40
40
41 You will by default be managing a patch queue named "patches". You can
41 You will by default be managing a patch queue named "patches". You can
42 create other, independent patch queues with the :hg:`qqueue` command.
42 create other, independent patch queues with the :hg:`qqueue` command.
43 '''
43 '''
44
44
45 from mercurial.i18n import _
45 from mercurial.i18n import _
46 from mercurial.node import bin, hex, short, nullid, nullrev
46 from mercurial.node import bin, hex, short, nullid, nullrev
47 from mercurial.lock import release
47 from mercurial.lock import release
48 from mercurial import commands, cmdutil, hg, patch, util
48 from mercurial import commands, cmdutil, hg, patch, util
49 from mercurial import repair, extensions, url, error
49 from mercurial import repair, extensions, url, error
50 import os, sys, re, errno
50 import os, sys, re, errno
51
51
52 commands.norepo += " qclone"
52 commands.norepo += " qclone"
53
53
54 # Patch names looks like unix-file names.
54 # Patch names looks like unix-file names.
55 # They must be joinable with queue directory and result in the patch path.
55 # They must be joinable with queue directory and result in the patch path.
56 normname = util.normpath
56 normname = util.normpath
57
57
58 class statusentry(object):
58 class statusentry(object):
59 def __init__(self, node, name):
59 def __init__(self, node, name):
60 self.node, self.name = node, name
60 self.node, self.name = node, name
61 def __repr__(self):
61 def __repr__(self):
62 return hex(self.node) + ':' + self.name
62 return hex(self.node) + ':' + self.name
63
63
64 class patchheader(object):
64 class patchheader(object):
65 def __init__(self, pf, plainmode=False):
65 def __init__(self, pf, plainmode=False):
66 def eatdiff(lines):
66 def eatdiff(lines):
67 while lines:
67 while lines:
68 l = lines[-1]
68 l = lines[-1]
69 if (l.startswith("diff -") or
69 if (l.startswith("diff -") or
70 l.startswith("Index:") or
70 l.startswith("Index:") or
71 l.startswith("===========")):
71 l.startswith("===========")):
72 del lines[-1]
72 del lines[-1]
73 else:
73 else:
74 break
74 break
75 def eatempty(lines):
75 def eatempty(lines):
76 while lines:
76 while lines:
77 if not lines[-1].strip():
77 if not lines[-1].strip():
78 del lines[-1]
78 del lines[-1]
79 else:
79 else:
80 break
80 break
81
81
82 message = []
82 message = []
83 comments = []
83 comments = []
84 user = None
84 user = None
85 date = None
85 date = None
86 parent = None
86 parent = None
87 format = None
87 format = None
88 subject = None
88 subject = None
89 diffstart = 0
89 diffstart = 0
90
90
91 for line in file(pf):
91 for line in file(pf):
92 line = line.rstrip()
92 line = line.rstrip()
93 if (line.startswith('diff --git')
93 if (line.startswith('diff --git')
94 or (diffstart and line.startswith('+++ '))):
94 or (diffstart and line.startswith('+++ '))):
95 diffstart = 2
95 diffstart = 2
96 break
96 break
97 diffstart = 0 # reset
97 diffstart = 0 # reset
98 if line.startswith("--- "):
98 if line.startswith("--- "):
99 diffstart = 1
99 diffstart = 1
100 continue
100 continue
101 elif format == "hgpatch":
101 elif format == "hgpatch":
102 # parse values when importing the result of an hg export
102 # parse values when importing the result of an hg export
103 if line.startswith("# User "):
103 if line.startswith("# User "):
104 user = line[7:]
104 user = line[7:]
105 elif line.startswith("# Date "):
105 elif line.startswith("# Date "):
106 date = line[7:]
106 date = line[7:]
107 elif line.startswith("# Parent "):
107 elif line.startswith("# Parent "):
108 parent = line[9:]
108 parent = line[9:]
109 elif not line.startswith("# ") and line:
109 elif not line.startswith("# ") and line:
110 message.append(line)
110 message.append(line)
111 format = None
111 format = None
112 elif line == '# HG changeset patch':
112 elif line == '# HG changeset patch':
113 message = []
113 message = []
114 format = "hgpatch"
114 format = "hgpatch"
115 elif (format != "tagdone" and (line.startswith("Subject: ") or
115 elif (format != "tagdone" and (line.startswith("Subject: ") or
116 line.startswith("subject: "))):
116 line.startswith("subject: "))):
117 subject = line[9:]
117 subject = line[9:]
118 format = "tag"
118 format = "tag"
119 elif (format != "tagdone" and (line.startswith("From: ") or
119 elif (format != "tagdone" and (line.startswith("From: ") or
120 line.startswith("from: "))):
120 line.startswith("from: "))):
121 user = line[6:]
121 user = line[6:]
122 format = "tag"
122 format = "tag"
123 elif (format != "tagdone" and (line.startswith("Date: ") or
123 elif (format != "tagdone" and (line.startswith("Date: ") or
124 line.startswith("date: "))):
124 line.startswith("date: "))):
125 date = line[6:]
125 date = line[6:]
126 format = "tag"
126 format = "tag"
127 elif format == "tag" and line == "":
127 elif format == "tag" and line == "":
128 # when looking for tags (subject: from: etc) they
128 # when looking for tags (subject: from: etc) they
129 # end once you find a blank line in the source
129 # end once you find a blank line in the source
130 format = "tagdone"
130 format = "tagdone"
131 elif message or line:
131 elif message or line:
132 message.append(line)
132 message.append(line)
133 comments.append(line)
133 comments.append(line)
134
134
135 eatdiff(message)
135 eatdiff(message)
136 eatdiff(comments)
136 eatdiff(comments)
137 eatempty(message)
137 eatempty(message)
138 eatempty(comments)
138 eatempty(comments)
139
139
140 # make sure message isn't empty
140 # make sure message isn't empty
141 if format and format.startswith("tag") and subject:
141 if format and format.startswith("tag") and subject:
142 message.insert(0, "")
142 message.insert(0, "")
143 message.insert(0, subject)
143 message.insert(0, subject)
144
144
145 self.message = message
145 self.message = message
146 self.comments = comments
146 self.comments = comments
147 self.user = user
147 self.user = user
148 self.date = date
148 self.date = date
149 self.parent = parent
149 self.parent = parent
150 self.haspatch = diffstart > 1
150 self.haspatch = diffstart > 1
151 self.plainmode = plainmode
151 self.plainmode = plainmode
152
152
153 def setuser(self, user):
153 def setuser(self, user):
154 if not self.updateheader(['From: ', '# User '], user):
154 if not self.updateheader(['From: ', '# User '], user):
155 try:
155 try:
156 patchheaderat = self.comments.index('# HG changeset patch')
156 patchheaderat = self.comments.index('# HG changeset patch')
157 self.comments.insert(patchheaderat + 1, '# User ' + user)
157 self.comments.insert(patchheaderat + 1, '# User ' + user)
158 except ValueError:
158 except ValueError:
159 if self.plainmode or self._hasheader(['Date: ']):
159 if self.plainmode or self._hasheader(['Date: ']):
160 self.comments = ['From: ' + user] + self.comments
160 self.comments = ['From: ' + user] + self.comments
161 else:
161 else:
162 tmp = ['# HG changeset patch', '# User ' + user, '']
162 tmp = ['# HG changeset patch', '# User ' + user, '']
163 self.comments = tmp + self.comments
163 self.comments = tmp + self.comments
164 self.user = user
164 self.user = user
165
165
166 def setdate(self, date):
166 def setdate(self, date):
167 if not self.updateheader(['Date: ', '# Date '], date):
167 if not self.updateheader(['Date: ', '# Date '], date):
168 try:
168 try:
169 patchheaderat = self.comments.index('# HG changeset patch')
169 patchheaderat = self.comments.index('# HG changeset patch')
170 self.comments.insert(patchheaderat + 1, '# Date ' + date)
170 self.comments.insert(patchheaderat + 1, '# Date ' + date)
171 except ValueError:
171 except ValueError:
172 if self.plainmode or self._hasheader(['From: ']):
172 if self.plainmode or self._hasheader(['From: ']):
173 self.comments = ['Date: ' + date] + self.comments
173 self.comments = ['Date: ' + date] + self.comments
174 else:
174 else:
175 tmp = ['# HG changeset patch', '# Date ' + date, '']
175 tmp = ['# HG changeset patch', '# Date ' + date, '']
176 self.comments = tmp + self.comments
176 self.comments = tmp + self.comments
177 self.date = date
177 self.date = date
178
178
179 def setparent(self, parent):
179 def setparent(self, parent):
180 if not self.updateheader(['# Parent '], parent):
180 if not self.updateheader(['# Parent '], parent):
181 try:
181 try:
182 patchheaderat = self.comments.index('# HG changeset patch')
182 patchheaderat = self.comments.index('# HG changeset patch')
183 self.comments.insert(patchheaderat + 1, '# Parent ' + parent)
183 self.comments.insert(patchheaderat + 1, '# Parent ' + parent)
184 except ValueError:
184 except ValueError:
185 pass
185 pass
186 self.parent = parent
186 self.parent = parent
187
187
188 def setmessage(self, message):
188 def setmessage(self, message):
189 if self.comments:
189 if self.comments:
190 self._delmsg()
190 self._delmsg()
191 self.message = [message]
191 self.message = [message]
192 self.comments += self.message
192 self.comments += self.message
193
193
194 def updateheader(self, prefixes, new):
194 def updateheader(self, prefixes, new):
195 '''Update all references to a field in the patch header.
195 '''Update all references to a field in the patch header.
196 Return whether the field is present.'''
196 Return whether the field is present.'''
197 res = False
197 res = False
198 for prefix in prefixes:
198 for prefix in prefixes:
199 for i in xrange(len(self.comments)):
199 for i in xrange(len(self.comments)):
200 if self.comments[i].startswith(prefix):
200 if self.comments[i].startswith(prefix):
201 self.comments[i] = prefix + new
201 self.comments[i] = prefix + new
202 res = True
202 res = True
203 break
203 break
204 return res
204 return res
205
205
206 def _hasheader(self, prefixes):
206 def _hasheader(self, prefixes):
207 '''Check if a header starts with any of the given prefixes.'''
207 '''Check if a header starts with any of the given prefixes.'''
208 for prefix in prefixes:
208 for prefix in prefixes:
209 for comment in self.comments:
209 for comment in self.comments:
210 if comment.startswith(prefix):
210 if comment.startswith(prefix):
211 return True
211 return True
212 return False
212 return False
213
213
214 def __str__(self):
214 def __str__(self):
215 if not self.comments:
215 if not self.comments:
216 return ''
216 return ''
217 return '\n'.join(self.comments) + '\n\n'
217 return '\n'.join(self.comments) + '\n\n'
218
218
219 def _delmsg(self):
219 def _delmsg(self):
220 '''Remove existing message, keeping the rest of the comments fields.
220 '''Remove existing message, keeping the rest of the comments fields.
221 If comments contains 'subject: ', message will prepend
221 If comments contains 'subject: ', message will prepend
222 the field and a blank line.'''
222 the field and a blank line.'''
223 if self.message:
223 if self.message:
224 subj = 'subject: ' + self.message[0].lower()
224 subj = 'subject: ' + self.message[0].lower()
225 for i in xrange(len(self.comments)):
225 for i in xrange(len(self.comments)):
226 if subj == self.comments[i].lower():
226 if subj == self.comments[i].lower():
227 del self.comments[i]
227 del self.comments[i]
228 self.message = self.message[2:]
228 self.message = self.message[2:]
229 break
229 break
230 ci = 0
230 ci = 0
231 for mi in self.message:
231 for mi in self.message:
232 while mi != self.comments[ci]:
232 while mi != self.comments[ci]:
233 ci += 1
233 ci += 1
234 del self.comments[ci]
234 del self.comments[ci]
235
235
236 class queue(object):
236 class queue(object):
237 def __init__(self, ui, path, patchdir=None):
237 def __init__(self, ui, path, patchdir=None):
238 self.basepath = path
238 self.basepath = path
239 try:
239 try:
240 fh = open(os.path.join(path, 'patches.queue'))
240 fh = open(os.path.join(path, 'patches.queue'))
241 cur = fh.read().rstrip()
241 cur = fh.read().rstrip()
242 if not cur:
242 if not cur:
243 curpath = os.path.join(path, 'patches')
243 curpath = os.path.join(path, 'patches')
244 else:
244 else:
245 curpath = os.path.join(path, 'patches-' + cur)
245 curpath = os.path.join(path, 'patches-' + cur)
246 except IOError:
246 except IOError:
247 curpath = os.path.join(path, 'patches')
247 curpath = os.path.join(path, 'patches')
248 self.path = patchdir or curpath
248 self.path = patchdir or curpath
249 self.opener = util.opener(self.path)
249 self.opener = util.opener(self.path)
250 self.ui = ui
250 self.ui = ui
251 self.applied_dirty = 0
251 self.applied_dirty = 0
252 self.series_dirty = 0
252 self.series_dirty = 0
253 self.added = []
253 self.added = []
254 self.series_path = "series"
254 self.series_path = "series"
255 self.status_path = "status"
255 self.status_path = "status"
256 self.guards_path = "guards"
256 self.guards_path = "guards"
257 self.active_guards = None
257 self.active_guards = None
258 self.guards_dirty = False
258 self.guards_dirty = False
259 # Handle mq.git as a bool with extended values
259 # Handle mq.git as a bool with extended values
260 try:
260 try:
261 gitmode = ui.configbool('mq', 'git', None)
261 gitmode = ui.configbool('mq', 'git', None)
262 if gitmode is None:
262 if gitmode is None:
263 raise error.ConfigError()
263 raise error.ConfigError()
264 self.gitmode = gitmode and 'yes' or 'no'
264 self.gitmode = gitmode and 'yes' or 'no'
265 except error.ConfigError:
265 except error.ConfigError:
266 self.gitmode = ui.config('mq', 'git', 'auto').lower()
266 self.gitmode = ui.config('mq', 'git', 'auto').lower()
267 self.plainmode = ui.configbool('mq', 'plain', False)
267 self.plainmode = ui.configbool('mq', 'plain', False)
268
268
269 @util.propertycache
269 @util.propertycache
270 def applied(self):
270 def applied(self):
271 if os.path.exists(self.join(self.status_path)):
271 if os.path.exists(self.join(self.status_path)):
272 def parse(l):
272 def parse(l):
273 n, name = l.split(':', 1)
273 n, name = l.split(':', 1)
274 return statusentry(bin(n), name)
274 return statusentry(bin(n), name)
275 lines = self.opener(self.status_path).read().splitlines()
275 lines = self.opener(self.status_path).read().splitlines()
276 return [parse(l) for l in lines]
276 return [parse(l) for l in lines]
277 return []
277 return []
278
278
279 @util.propertycache
279 @util.propertycache
280 def full_series(self):
280 def full_series(self):
281 if os.path.exists(self.join(self.series_path)):
281 if os.path.exists(self.join(self.series_path)):
282 return self.opener(self.series_path).read().splitlines()
282 return self.opener(self.series_path).read().splitlines()
283 return []
283 return []
284
284
285 @util.propertycache
285 @util.propertycache
286 def series(self):
286 def series(self):
287 self.parse_series()
287 self.parse_series()
288 return self.series
288 return self.series
289
289
290 @util.propertycache
290 @util.propertycache
291 def series_guards(self):
291 def series_guards(self):
292 self.parse_series()
292 self.parse_series()
293 return self.series_guards
293 return self.series_guards
294
294
295 def invalidate(self):
295 def invalidate(self):
296 for a in 'applied full_series series series_guards'.split():
296 for a in 'applied full_series series series_guards'.split():
297 if a in self.__dict__:
297 if a in self.__dict__:
298 delattr(self, a)
298 delattr(self, a)
299 self.applied_dirty = 0
299 self.applied_dirty = 0
300 self.series_dirty = 0
300 self.series_dirty = 0
301 self.guards_dirty = False
301 self.guards_dirty = False
302 self.active_guards = None
302 self.active_guards = None
303
303
304 def diffopts(self, opts={}, patchfn=None):
304 def diffopts(self, opts={}, patchfn=None):
305 diffopts = patch.diffopts(self.ui, opts)
305 diffopts = patch.diffopts(self.ui, opts)
306 if self.gitmode == 'auto':
306 if self.gitmode == 'auto':
307 diffopts.upgrade = True
307 diffopts.upgrade = True
308 elif self.gitmode == 'keep':
308 elif self.gitmode == 'keep':
309 pass
309 pass
310 elif self.gitmode in ('yes', 'no'):
310 elif self.gitmode in ('yes', 'no'):
311 diffopts.git = self.gitmode == 'yes'
311 diffopts.git = self.gitmode == 'yes'
312 else:
312 else:
313 raise util.Abort(_('mq.git option can be auto/keep/yes/no'
313 raise util.Abort(_('mq.git option can be auto/keep/yes/no'
314 ' got %s') % self.gitmode)
314 ' got %s') % self.gitmode)
315 if patchfn:
315 if patchfn:
316 diffopts = self.patchopts(diffopts, patchfn)
316 diffopts = self.patchopts(diffopts, patchfn)
317 return diffopts
317 return diffopts
318
318
319 def patchopts(self, diffopts, *patches):
319 def patchopts(self, diffopts, *patches):
320 """Return a copy of input diff options with git set to true if
320 """Return a copy of input diff options with git set to true if
321 referenced patch is a git patch and should be preserved as such.
321 referenced patch is a git patch and should be preserved as such.
322 """
322 """
323 diffopts = diffopts.copy()
323 diffopts = diffopts.copy()
324 if not diffopts.git and self.gitmode == 'keep':
324 if not diffopts.git and self.gitmode == 'keep':
325 for patchfn in patches:
325 for patchfn in patches:
326 patchf = self.opener(patchfn, 'r')
326 patchf = self.opener(patchfn, 'r')
327 # if the patch was a git patch, refresh it as a git patch
327 # if the patch was a git patch, refresh it as a git patch
328 for line in patchf:
328 for line in patchf:
329 if line.startswith('diff --git'):
329 if line.startswith('diff --git'):
330 diffopts.git = True
330 diffopts.git = True
331 break
331 break
332 patchf.close()
332 patchf.close()
333 return diffopts
333 return diffopts
334
334
335 def join(self, *p):
335 def join(self, *p):
336 return os.path.join(self.path, *p)
336 return os.path.join(self.path, *p)
337
337
338 def find_series(self, patch):
338 def find_series(self, patch):
339 def matchpatch(l):
339 def matchpatch(l):
340 l = l.split('#', 1)[0]
340 l = l.split('#', 1)[0]
341 return l.strip() == patch
341 return l.strip() == patch
342 for index, l in enumerate(self.full_series):
342 for index, l in enumerate(self.full_series):
343 if matchpatch(l):
343 if matchpatch(l):
344 return index
344 return index
345 return None
345 return None
346
346
347 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
347 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
348
348
349 def parse_series(self):
349 def parse_series(self):
350 self.series = []
350 self.series = []
351 self.series_guards = []
351 self.series_guards = []
352 for l in self.full_series:
352 for l in self.full_series:
353 h = l.find('#')
353 h = l.find('#')
354 if h == -1:
354 if h == -1:
355 patch = l
355 patch = l
356 comment = ''
356 comment = ''
357 elif h == 0:
357 elif h == 0:
358 continue
358 continue
359 else:
359 else:
360 patch = l[:h]
360 patch = l[:h]
361 comment = l[h:]
361 comment = l[h:]
362 patch = patch.strip()
362 patch = patch.strip()
363 if patch:
363 if patch:
364 if patch in self.series:
364 if patch in self.series:
365 raise util.Abort(_('%s appears more than once in %s') %
365 raise util.Abort(_('%s appears more than once in %s') %
366 (patch, self.join(self.series_path)))
366 (patch, self.join(self.series_path)))
367 self.series.append(patch)
367 self.series.append(patch)
368 self.series_guards.append(self.guard_re.findall(comment))
368 self.series_guards.append(self.guard_re.findall(comment))
369
369
370 def check_guard(self, guard):
370 def check_guard(self, guard):
371 if not guard:
371 if not guard:
372 return _('guard cannot be an empty string')
372 return _('guard cannot be an empty string')
373 bad_chars = '# \t\r\n\f'
373 bad_chars = '# \t\r\n\f'
374 first = guard[0]
374 first = guard[0]
375 if first in '-+':
375 if first in '-+':
376 return (_('guard %r starts with invalid character: %r') %
376 return (_('guard %r starts with invalid character: %r') %
377 (guard, first))
377 (guard, first))
378 for c in bad_chars:
378 for c in bad_chars:
379 if c in guard:
379 if c in guard:
380 return _('invalid character in guard %r: %r') % (guard, c)
380 return _('invalid character in guard %r: %r') % (guard, c)
381
381
382 def set_active(self, guards):
382 def set_active(self, guards):
383 for guard in guards:
383 for guard in guards:
384 bad = self.check_guard(guard)
384 bad = self.check_guard(guard)
385 if bad:
385 if bad:
386 raise util.Abort(bad)
386 raise util.Abort(bad)
387 guards = sorted(set(guards))
387 guards = sorted(set(guards))
388 self.ui.debug('active guards: %s\n' % ' '.join(guards))
388 self.ui.debug('active guards: %s\n' % ' '.join(guards))
389 self.active_guards = guards
389 self.active_guards = guards
390 self.guards_dirty = True
390 self.guards_dirty = True
391
391
392 def active(self):
392 def active(self):
393 if self.active_guards is None:
393 if self.active_guards is None:
394 self.active_guards = []
394 self.active_guards = []
395 try:
395 try:
396 guards = self.opener(self.guards_path).read().split()
396 guards = self.opener(self.guards_path).read().split()
397 except IOError, err:
397 except IOError, err:
398 if err.errno != errno.ENOENT:
398 if err.errno != errno.ENOENT:
399 raise
399 raise
400 guards = []
400 guards = []
401 for i, guard in enumerate(guards):
401 for i, guard in enumerate(guards):
402 bad = self.check_guard(guard)
402 bad = self.check_guard(guard)
403 if bad:
403 if bad:
404 self.ui.warn('%s:%d: %s\n' %
404 self.ui.warn('%s:%d: %s\n' %
405 (self.join(self.guards_path), i + 1, bad))
405 (self.join(self.guards_path), i + 1, bad))
406 else:
406 else:
407 self.active_guards.append(guard)
407 self.active_guards.append(guard)
408 return self.active_guards
408 return self.active_guards
409
409
410 def set_guards(self, idx, guards):
410 def set_guards(self, idx, guards):
411 for g in guards:
411 for g in guards:
412 if len(g) < 2:
412 if len(g) < 2:
413 raise util.Abort(_('guard %r too short') % g)
413 raise util.Abort(_('guard %r too short') % g)
414 if g[0] not in '-+':
414 if g[0] not in '-+':
415 raise util.Abort(_('guard %r starts with invalid char') % g)
415 raise util.Abort(_('guard %r starts with invalid char') % g)
416 bad = self.check_guard(g[1:])
416 bad = self.check_guard(g[1:])
417 if bad:
417 if bad:
418 raise util.Abort(bad)
418 raise util.Abort(bad)
419 drop = self.guard_re.sub('', self.full_series[idx])
419 drop = self.guard_re.sub('', self.full_series[idx])
420 self.full_series[idx] = drop + ''.join([' #' + g for g in guards])
420 self.full_series[idx] = drop + ''.join([' #' + g for g in guards])
421 self.parse_series()
421 self.parse_series()
422 self.series_dirty = True
422 self.series_dirty = True
423
423
424 def pushable(self, idx):
424 def pushable(self, idx):
425 if isinstance(idx, str):
425 if isinstance(idx, str):
426 idx = self.series.index(idx)
426 idx = self.series.index(idx)
427 patchguards = self.series_guards[idx]
427 patchguards = self.series_guards[idx]
428 if not patchguards:
428 if not patchguards:
429 return True, None
429 return True, None
430 guards = self.active()
430 guards = self.active()
431 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
431 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
432 if exactneg:
432 if exactneg:
433 return False, exactneg[0]
433 return False, exactneg[0]
434 pos = [g for g in patchguards if g[0] == '+']
434 pos = [g for g in patchguards if g[0] == '+']
435 exactpos = [g for g in pos if g[1:] in guards]
435 exactpos = [g for g in pos if g[1:] in guards]
436 if pos:
436 if pos:
437 if exactpos:
437 if exactpos:
438 return True, exactpos[0]
438 return True, exactpos[0]
439 return False, pos
439 return False, pos
440 return True, ''
440 return True, ''
441
441
442 def explain_pushable(self, idx, all_patches=False):
442 def explain_pushable(self, idx, all_patches=False):
443 write = all_patches and self.ui.write or self.ui.warn
443 write = all_patches and self.ui.write or self.ui.warn
444 if all_patches or self.ui.verbose:
444 if all_patches or self.ui.verbose:
445 if isinstance(idx, str):
445 if isinstance(idx, str):
446 idx = self.series.index(idx)
446 idx = self.series.index(idx)
447 pushable, why = self.pushable(idx)
447 pushable, why = self.pushable(idx)
448 if all_patches and pushable:
448 if all_patches and pushable:
449 if why is None:
449 if why is None:
450 write(_('allowing %s - no guards in effect\n') %
450 write(_('allowing %s - no guards in effect\n') %
451 self.series[idx])
451 self.series[idx])
452 else:
452 else:
453 if not why:
453 if not why:
454 write(_('allowing %s - no matching negative guards\n') %
454 write(_('allowing %s - no matching negative guards\n') %
455 self.series[idx])
455 self.series[idx])
456 else:
456 else:
457 write(_('allowing %s - guarded by %r\n') %
457 write(_('allowing %s - guarded by %r\n') %
458 (self.series[idx], why))
458 (self.series[idx], why))
459 if not pushable:
459 if not pushable:
460 if why:
460 if why:
461 write(_('skipping %s - guarded by %r\n') %
461 write(_('skipping %s - guarded by %r\n') %
462 (self.series[idx], why))
462 (self.series[idx], why))
463 else:
463 else:
464 write(_('skipping %s - no matching guards\n') %
464 write(_('skipping %s - no matching guards\n') %
465 self.series[idx])
465 self.series[idx])
466
466
467 def save_dirty(self):
467 def save_dirty(self):
468 def write_list(items, path):
468 def write_list(items, path):
469 fp = self.opener(path, 'w')
469 fp = self.opener(path, 'w')
470 for i in items:
470 for i in items:
471 fp.write("%s\n" % i)
471 fp.write("%s\n" % i)
472 fp.close()
472 fp.close()
473 if self.applied_dirty:
473 if self.applied_dirty:
474 write_list(map(str, self.applied), self.status_path)
474 write_list(map(str, self.applied), self.status_path)
475 if self.series_dirty:
475 if self.series_dirty:
476 write_list(self.full_series, self.series_path)
476 write_list(self.full_series, self.series_path)
477 if self.guards_dirty:
477 if self.guards_dirty:
478 write_list(self.active_guards, self.guards_path)
478 write_list(self.active_guards, self.guards_path)
479 if self.added:
479 if self.added:
480 qrepo = self.qrepo()
480 qrepo = self.qrepo()
481 if qrepo:
481 if qrepo:
482 qrepo[None].add(self.added)
482 qrepo[None].add(self.added)
483 self.added = []
483 self.added = []
484
484
485 def removeundo(self, repo):
485 def removeundo(self, repo):
486 undo = repo.sjoin('undo')
486 undo = repo.sjoin('undo')
487 if not os.path.exists(undo):
487 if not os.path.exists(undo):
488 return
488 return
489 try:
489 try:
490 os.unlink(undo)
490 os.unlink(undo)
491 except OSError, inst:
491 except OSError, inst:
492 self.ui.warn(_('error removing undo: %s\n') % str(inst))
492 self.ui.warn(_('error removing undo: %s\n') % str(inst))
493
493
494 def printdiff(self, repo, diffopts, node1, node2=None, files=None,
494 def printdiff(self, repo, diffopts, node1, node2=None, files=None,
495 fp=None, changes=None, opts={}):
495 fp=None, changes=None, opts={}):
496 stat = opts.get('stat')
496 stat = opts.get('stat')
497 m = cmdutil.match(repo, files, opts)
497 m = cmdutil.match(repo, files, opts)
498 cmdutil.diffordiffstat(self.ui, repo, diffopts, node1, node2, m,
498 cmdutil.diffordiffstat(self.ui, repo, diffopts, node1, node2, m,
499 changes, stat, fp)
499 changes, stat, fp)
500
500
501 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
501 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
502 # first try just applying the patch
502 # first try just applying the patch
503 (err, n) = self.apply(repo, [patch], update_status=False,
503 (err, n) = self.apply(repo, [patch], update_status=False,
504 strict=True, merge=rev)
504 strict=True, merge=rev)
505
505
506 if err == 0:
506 if err == 0:
507 return (err, n)
507 return (err, n)
508
508
509 if n is None:
509 if n is None:
510 raise util.Abort(_("apply failed for patch %s") % patch)
510 raise util.Abort(_("apply failed for patch %s") % patch)
511
511
512 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
512 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
513
513
514 # apply failed, strip away that rev and merge.
514 # apply failed, strip away that rev and merge.
515 hg.clean(repo, head)
515 hg.clean(repo, head)
516 self.strip(repo, n, update=False, backup='strip')
516 self.strip(repo, n, update=False, backup='strip')
517
517
518 ctx = repo[rev]
518 ctx = repo[rev]
519 ret = hg.merge(repo, rev)
519 ret = hg.merge(repo, rev)
520 if ret:
520 if ret:
521 raise util.Abort(_("update returned %d") % ret)
521 raise util.Abort(_("update returned %d") % ret)
522 n = repo.commit(ctx.description(), ctx.user(), force=True)
522 n = repo.commit(ctx.description(), ctx.user(), force=True)
523 if n is None:
523 if n is None:
524 raise util.Abort(_("repo commit failed"))
524 raise util.Abort(_("repo commit failed"))
525 try:
525 try:
526 ph = patchheader(mergeq.join(patch), self.plainmode)
526 ph = patchheader(mergeq.join(patch), self.plainmode)
527 except:
527 except:
528 raise util.Abort(_("unable to read %s") % patch)
528 raise util.Abort(_("unable to read %s") % patch)
529
529
530 diffopts = self.patchopts(diffopts, patch)
530 diffopts = self.patchopts(diffopts, patch)
531 patchf = self.opener(patch, "w")
531 patchf = self.opener(patch, "w")
532 comments = str(ph)
532 comments = str(ph)
533 if comments:
533 if comments:
534 patchf.write(comments)
534 patchf.write(comments)
535 self.printdiff(repo, diffopts, head, n, fp=patchf)
535 self.printdiff(repo, diffopts, head, n, fp=patchf)
536 patchf.close()
536 patchf.close()
537 self.removeundo(repo)
537 self.removeundo(repo)
538 return (0, n)
538 return (0, n)
539
539
540 def qparents(self, repo, rev=None):
540 def qparents(self, repo, rev=None):
541 if rev is None:
541 if rev is None:
542 (p1, p2) = repo.dirstate.parents()
542 (p1, p2) = repo.dirstate.parents()
543 if p2 == nullid:
543 if p2 == nullid:
544 return p1
544 return p1
545 if not self.applied:
545 if not self.applied:
546 return None
546 return None
547 return self.applied[-1].node
547 return self.applied[-1].node
548 p1, p2 = repo.changelog.parents(rev)
548 p1, p2 = repo.changelog.parents(rev)
549 if p2 != nullid and p2 in [x.node for x in self.applied]:
549 if p2 != nullid and p2 in [x.node for x in self.applied]:
550 return p2
550 return p2
551 return p1
551 return p1
552
552
553 def mergepatch(self, repo, mergeq, series, diffopts):
553 def mergepatch(self, repo, mergeq, series, diffopts):
554 if not self.applied:
554 if not self.applied:
555 # each of the patches merged in will have two parents. This
555 # each of the patches merged in will have two parents. This
556 # can confuse the qrefresh, qdiff, and strip code because it
556 # can confuse the qrefresh, qdiff, and strip code because it
557 # needs to know which parent is actually in the patch queue.
557 # needs to know which parent is actually in the patch queue.
558 # so, we insert a merge marker with only one parent. This way
558 # so, we insert a merge marker with only one parent. This way
559 # the first patch in the queue is never a merge patch
559 # the first patch in the queue is never a merge patch
560 #
560 #
561 pname = ".hg.patches.merge.marker"
561 pname = ".hg.patches.merge.marker"
562 n = repo.commit('[mq]: merge marker', force=True)
562 n = repo.commit('[mq]: merge marker', force=True)
563 self.removeundo(repo)
563 self.removeundo(repo)
564 self.applied.append(statusentry(n, pname))
564 self.applied.append(statusentry(n, pname))
565 self.applied_dirty = 1
565 self.applied_dirty = 1
566
566
567 head = self.qparents(repo)
567 head = self.qparents(repo)
568
568
569 for patch in series:
569 for patch in series:
570 patch = mergeq.lookup(patch, strict=True)
570 patch = mergeq.lookup(patch, strict=True)
571 if not patch:
571 if not patch:
572 self.ui.warn(_("patch %s does not exist\n") % patch)
572 self.ui.warn(_("patch %s does not exist\n") % patch)
573 return (1, None)
573 return (1, None)
574 pushable, reason = self.pushable(patch)
574 pushable, reason = self.pushable(patch)
575 if not pushable:
575 if not pushable:
576 self.explain_pushable(patch, all_patches=True)
576 self.explain_pushable(patch, all_patches=True)
577 continue
577 continue
578 info = mergeq.isapplied(patch)
578 info = mergeq.isapplied(patch)
579 if not info:
579 if not info:
580 self.ui.warn(_("patch %s is not applied\n") % patch)
580 self.ui.warn(_("patch %s is not applied\n") % patch)
581 return (1, None)
581 return (1, None)
582 rev = info[1]
582 rev = info[1]
583 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
583 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
584 if head:
584 if head:
585 self.applied.append(statusentry(head, patch))
585 self.applied.append(statusentry(head, patch))
586 self.applied_dirty = 1
586 self.applied_dirty = 1
587 if err:
587 if err:
588 return (err, head)
588 return (err, head)
589 self.save_dirty()
589 self.save_dirty()
590 return (0, head)
590 return (0, head)
591
591
592 def patch(self, repo, patchfile):
592 def patch(self, repo, patchfile):
593 '''Apply patchfile to the working directory.
593 '''Apply patchfile to the working directory.
594 patchfile: name of patch file'''
594 patchfile: name of patch file'''
595 files = {}
595 files = {}
596 try:
596 try:
597 fuzz = patch.patch(patchfile, self.ui, strip=1, cwd=repo.root,
597 fuzz = patch.patch(patchfile, self.ui, strip=1, cwd=repo.root,
598 files=files, eolmode=None)
598 files=files, eolmode=None)
599 except Exception, inst:
599 except Exception, inst:
600 self.ui.note(str(inst) + '\n')
600 self.ui.note(str(inst) + '\n')
601 if not self.ui.verbose:
601 if not self.ui.verbose:
602 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
602 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
603 return (False, files, False)
603 return (False, files, False)
604
604
605 return (True, files, fuzz)
605 return (True, files, fuzz)
606
606
607 def apply(self, repo, series, list=False, update_status=True,
607 def apply(self, repo, series, list=False, update_status=True,
608 strict=False, patchdir=None, merge=None, all_files=None):
608 strict=False, patchdir=None, merge=None, all_files=None):
609 wlock = lock = tr = None
609 wlock = lock = tr = None
610 try:
610 try:
611 wlock = repo.wlock()
611 wlock = repo.wlock()
612 lock = repo.lock()
612 lock = repo.lock()
613 tr = repo.transaction("qpush")
613 tr = repo.transaction("qpush")
614 try:
614 try:
615 ret = self._apply(repo, series, list, update_status,
615 ret = self._apply(repo, series, list, update_status,
616 strict, patchdir, merge, all_files=all_files)
616 strict, patchdir, merge, all_files=all_files)
617 tr.close()
617 tr.close()
618 self.save_dirty()
618 self.save_dirty()
619 return ret
619 return ret
620 except:
620 except:
621 try:
621 try:
622 tr.abort()
622 tr.abort()
623 finally:
623 finally:
624 repo.invalidate()
624 repo.invalidate()
625 repo.dirstate.invalidate()
625 repo.dirstate.invalidate()
626 raise
626 raise
627 finally:
627 finally:
628 release(tr, lock, wlock)
628 release(tr, lock, wlock)
629 self.removeundo(repo)
629 self.removeundo(repo)
630
630
631 def _apply(self, repo, series, list=False, update_status=True,
631 def _apply(self, repo, series, list=False, update_status=True,
632 strict=False, patchdir=None, merge=None, all_files=None):
632 strict=False, patchdir=None, merge=None, all_files=None):
633 '''returns (error, hash)
633 '''returns (error, hash)
634 error = 1 for unable to read, 2 for patch failed, 3 for patch fuzz'''
634 error = 1 for unable to read, 2 for patch failed, 3 for patch fuzz'''
635 # TODO unify with commands.py
635 # TODO unify with commands.py
636 if not patchdir:
636 if not patchdir:
637 patchdir = self.path
637 patchdir = self.path
638 err = 0
638 err = 0
639 n = None
639 n = None
640 for patchname in series:
640 for patchname in series:
641 pushable, reason = self.pushable(patchname)
641 pushable, reason = self.pushable(patchname)
642 if not pushable:
642 if not pushable:
643 self.explain_pushable(patchname, all_patches=True)
643 self.explain_pushable(patchname, all_patches=True)
644 continue
644 continue
645 self.ui.status(_("applying %s\n") % patchname)
645 self.ui.status(_("applying %s\n") % patchname)
646 pf = os.path.join(patchdir, patchname)
646 pf = os.path.join(patchdir, patchname)
647
647
648 try:
648 try:
649 ph = patchheader(self.join(patchname), self.plainmode)
649 ph = patchheader(self.join(patchname), self.plainmode)
650 except:
650 except:
651 self.ui.warn(_("unable to read %s\n") % patchname)
651 self.ui.warn(_("unable to read %s\n") % patchname)
652 err = 1
652 err = 1
653 break
653 break
654
654
655 message = ph.message
655 message = ph.message
656 if not message:
656 if not message:
657 message = "imported patch %s\n" % patchname
657 message = "imported patch %s\n" % patchname
658 else:
658 else:
659 if list:
659 if list:
660 message.append("\nimported patch %s" % patchname)
660 message.append("\nimported patch %s" % patchname)
661 message = '\n'.join(message)
661 message = '\n'.join(message)
662
662
663 if ph.haspatch:
663 if ph.haspatch:
664 (patcherr, files, fuzz) = self.patch(repo, pf)
664 (patcherr, files, fuzz) = self.patch(repo, pf)
665 if all_files is not None:
665 if all_files is not None:
666 all_files.update(files)
666 all_files.update(files)
667 patcherr = not patcherr
667 patcherr = not patcherr
668 else:
668 else:
669 self.ui.warn(_("patch %s is empty\n") % patchname)
669 self.ui.warn(_("patch %s is empty\n") % patchname)
670 patcherr, files, fuzz = 0, [], 0
670 patcherr, files, fuzz = 0, [], 0
671
671
672 if merge and files:
672 if merge and files:
673 # Mark as removed/merged and update dirstate parent info
673 # Mark as removed/merged and update dirstate parent info
674 removed = []
674 removed = []
675 merged = []
675 merged = []
676 for f in files:
676 for f in files:
677 if os.path.exists(repo.wjoin(f)):
677 if os.path.exists(repo.wjoin(f)):
678 merged.append(f)
678 merged.append(f)
679 else:
679 else:
680 removed.append(f)
680 removed.append(f)
681 for f in removed:
681 for f in removed:
682 repo.dirstate.remove(f)
682 repo.dirstate.remove(f)
683 for f in merged:
683 for f in merged:
684 repo.dirstate.merge(f)
684 repo.dirstate.merge(f)
685 p1, p2 = repo.dirstate.parents()
685 p1, p2 = repo.dirstate.parents()
686 repo.dirstate.setparents(p1, merge)
686 repo.dirstate.setparents(p1, merge)
687
687
688 files = patch.updatedir(self.ui, repo, files)
688 files = patch.updatedir(self.ui, repo, files)
689 match = cmdutil.matchfiles(repo, files or [])
689 match = cmdutil.matchfiles(repo, files or [])
690 n = repo.commit(message, ph.user, ph.date, match=match, force=True)
690 n = repo.commit(message, ph.user, ph.date, match=match, force=True)
691
691
692 if n is None:
692 if n is None:
693 raise util.Abort(_("repo commit failed"))
693 raise util.Abort(_("repo commit failed"))
694
694
695 if update_status:
695 if update_status:
696 self.applied.append(statusentry(n, patchname))
696 self.applied.append(statusentry(n, patchname))
697
697
698 if patcherr:
698 if patcherr:
699 self.ui.warn(_("patch failed, rejects left in working dir\n"))
699 self.ui.warn(_("patch failed, rejects left in working dir\n"))
700 err = 2
700 err = 2
701 break
701 break
702
702
703 if fuzz and strict:
703 if fuzz and strict:
704 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
704 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
705 err = 3
705 err = 3
706 break
706 break
707 return (err, n)
707 return (err, n)
708
708
709 def _cleanup(self, patches, numrevs, keep=False):
709 def _cleanup(self, patches, numrevs, keep=False):
710 if not keep:
710 if not keep:
711 r = self.qrepo()
711 r = self.qrepo()
712 if r:
712 if r:
713 r[None].remove(patches, True)
713 r[None].remove(patches, True)
714 else:
714 else:
715 for p in patches:
715 for p in patches:
716 os.unlink(self.join(p))
716 os.unlink(self.join(p))
717
717
718 if numrevs:
718 if numrevs:
719 del self.applied[:numrevs]
719 del self.applied[:numrevs]
720 self.applied_dirty = 1
720 self.applied_dirty = 1
721
721
722 for i in sorted([self.find_series(p) for p in patches], reverse=True):
722 for i in sorted([self.find_series(p) for p in patches], reverse=True):
723 del self.full_series[i]
723 del self.full_series[i]
724 self.parse_series()
724 self.parse_series()
725 self.series_dirty = 1
725 self.series_dirty = 1
726
726
727 def _revpatches(self, repo, revs):
727 def _revpatches(self, repo, revs):
728 firstrev = repo[self.applied[0].node].rev()
728 firstrev = repo[self.applied[0].node].rev()
729 patches = []
729 patches = []
730 for i, rev in enumerate(revs):
730 for i, rev in enumerate(revs):
731
731
732 if rev < firstrev:
732 if rev < firstrev:
733 raise util.Abort(_('revision %d is not managed') % rev)
733 raise util.Abort(_('revision %d is not managed') % rev)
734
734
735 ctx = repo[rev]
735 ctx = repo[rev]
736 base = self.applied[i].node
736 base = self.applied[i].node
737 if ctx.node() != base:
737 if ctx.node() != base:
738 msg = _('cannot delete revision %d above applied patches')
738 msg = _('cannot delete revision %d above applied patches')
739 raise util.Abort(msg % rev)
739 raise util.Abort(msg % rev)
740
740
741 patch = self.applied[i].name
741 patch = self.applied[i].name
742 for fmt in ('[mq]: %s', 'imported patch %s'):
742 for fmt in ('[mq]: %s', 'imported patch %s'):
743 if ctx.description() == fmt % patch:
743 if ctx.description() == fmt % patch:
744 msg = _('patch %s finalized without changeset message\n')
744 msg = _('patch %s finalized without changeset message\n')
745 repo.ui.status(msg % patch)
745 repo.ui.status(msg % patch)
746 break
746 break
747
747
748 patches.append(patch)
748 patches.append(patch)
749 return patches
749 return patches
750
750
751 def finish(self, repo, revs):
751 def finish(self, repo, revs):
752 patches = self._revpatches(repo, sorted(revs))
752 patches = self._revpatches(repo, sorted(revs))
753 self._cleanup(patches, len(patches))
753 self._cleanup(patches, len(patches))
754
754
755 def delete(self, repo, patches, opts):
755 def delete(self, repo, patches, opts):
756 if not patches and not opts.get('rev'):
756 if not patches and not opts.get('rev'):
757 raise util.Abort(_('qdelete requires at least one revision or '
757 raise util.Abort(_('qdelete requires at least one revision or '
758 'patch name'))
758 'patch name'))
759
759
760 realpatches = []
760 realpatches = []
761 for patch in patches:
761 for patch in patches:
762 patch = self.lookup(patch, strict=True)
762 patch = self.lookup(patch, strict=True)
763 info = self.isapplied(patch)
763 info = self.isapplied(patch)
764 if info:
764 if info:
765 raise util.Abort(_("cannot delete applied patch %s") % patch)
765 raise util.Abort(_("cannot delete applied patch %s") % patch)
766 if patch not in self.series:
766 if patch not in self.series:
767 raise util.Abort(_("patch %s not in series file") % patch)
767 raise util.Abort(_("patch %s not in series file") % patch)
768 realpatches.append(patch)
768 realpatches.append(patch)
769
769
770 numrevs = 0
770 numrevs = 0
771 if opts.get('rev'):
771 if opts.get('rev'):
772 if not self.applied:
772 if not self.applied:
773 raise util.Abort(_('no patches applied'))
773 raise util.Abort(_('no patches applied'))
774 revs = cmdutil.revrange(repo, opts['rev'])
774 revs = cmdutil.revrange(repo, opts['rev'])
775 if len(revs) > 1 and revs[0] > revs[1]:
775 if len(revs) > 1 and revs[0] > revs[1]:
776 revs.reverse()
776 revs.reverse()
777 revpatches = self._revpatches(repo, revs)
777 revpatches = self._revpatches(repo, revs)
778 realpatches += revpatches
778 realpatches += revpatches
779 numrevs = len(revpatches)
779 numrevs = len(revpatches)
780
780
781 self._cleanup(realpatches, numrevs, opts.get('keep'))
781 self._cleanup(realpatches, numrevs, opts.get('keep'))
782
782
783 def check_toppatch(self, repo):
783 def check_toppatch(self, repo):
784 if self.applied:
784 if self.applied:
785 top = self.applied[-1].node
785 top = self.applied[-1].node
786 patch = self.applied[-1].name
786 patch = self.applied[-1].name
787 pp = repo.dirstate.parents()
787 pp = repo.dirstate.parents()
788 if top not in pp:
788 if top not in pp:
789 raise util.Abort(_("working directory revision is not qtip"))
789 raise util.Abort(_("working directory revision is not qtip"))
790 return top, patch
790 return top, patch
791 return None, None
791 return None, None
792
792
793 def check_localchanges(self, repo, force=False, refresh=True):
793 def check_localchanges(self, repo, force=False, refresh=True):
794 m, a, r, d = repo.status()[:4]
794 m, a, r, d = repo.status()[:4]
795 if (m or a or r or d) and not force:
795 if (m or a or r or d) and not force:
796 if refresh:
796 if refresh:
797 raise util.Abort(_("local changes found, refresh first"))
797 raise util.Abort(_("local changes found, refresh first"))
798 else:
798 else:
799 raise util.Abort(_("local changes found"))
799 raise util.Abort(_("local changes found"))
800 return m, a, r, d
800 return m, a, r, d
801
801
802 _reserved = ('series', 'status', 'guards')
802 _reserved = ('series', 'status', 'guards')
803 def check_reserved_name(self, name):
803 def check_reserved_name(self, name):
804 if (name in self._reserved or name.startswith('.hg')
804 if (name in self._reserved or name.startswith('.hg')
805 or name.startswith('.mq') or '#' in name or ':' in name):
805 or name.startswith('.mq') or '#' in name or ':' in name):
806 raise util.Abort(_('"%s" cannot be used as the name of a patch')
806 raise util.Abort(_('"%s" cannot be used as the name of a patch')
807 % name)
807 % name)
808
808
809 def new(self, repo, patchfn, *pats, **opts):
809 def new(self, repo, patchfn, *pats, **opts):
810 """options:
810 """options:
811 msg: a string or a no-argument function returning a string
811 msg: a string or a no-argument function returning a string
812 """
812 """
813 msg = opts.get('msg')
813 msg = opts.get('msg')
814 user = opts.get('user')
814 user = opts.get('user')
815 date = opts.get('date')
815 date = opts.get('date')
816 if date:
816 if date:
817 date = util.parsedate(date)
817 date = util.parsedate(date)
818 diffopts = self.diffopts({'git': opts.get('git')})
818 diffopts = self.diffopts({'git': opts.get('git')})
819 self.check_reserved_name(patchfn)
819 self.check_reserved_name(patchfn)
820 if os.path.exists(self.join(patchfn)):
820 if os.path.exists(self.join(patchfn)):
821 raise util.Abort(_('patch "%s" already exists') % patchfn)
821 raise util.Abort(_('patch "%s" already exists') % patchfn)
822 if opts.get('include') or opts.get('exclude') or pats:
822 if opts.get('include') or opts.get('exclude') or pats:
823 match = cmdutil.match(repo, pats, opts)
823 match = cmdutil.match(repo, pats, opts)
824 # detect missing files in pats
824 # detect missing files in pats
825 def badfn(f, msg):
825 def badfn(f, msg):
826 raise util.Abort('%s: %s' % (f, msg))
826 raise util.Abort('%s: %s' % (f, msg))
827 match.bad = badfn
827 match.bad = badfn
828 m, a, r, d = repo.status(match=match)[:4]
828 m, a, r, d = repo.status(match=match)[:4]
829 else:
829 else:
830 m, a, r, d = self.check_localchanges(repo, force=True)
830 m, a, r, d = self.check_localchanges(repo, force=True)
831 match = cmdutil.matchfiles(repo, m + a + r)
831 match = cmdutil.matchfiles(repo, m + a + r)
832 if len(repo[None].parents()) > 1:
832 if len(repo[None].parents()) > 1:
833 raise util.Abort(_('cannot manage merge changesets'))
833 raise util.Abort(_('cannot manage merge changesets'))
834 commitfiles = m + a + r
834 commitfiles = m + a + r
835 self.check_toppatch(repo)
835 self.check_toppatch(repo)
836 insert = self.full_series_end()
836 insert = self.full_series_end()
837 wlock = repo.wlock()
837 wlock = repo.wlock()
838 try:
838 try:
839 # if patch file write fails, abort early
839 # if patch file write fails, abort early
840 p = self.opener(patchfn, "w")
840 p = self.opener(patchfn, "w")
841 try:
841 try:
842 if self.plainmode:
842 if self.plainmode:
843 if user:
843 if user:
844 p.write("From: " + user + "\n")
844 p.write("From: " + user + "\n")
845 if not date:
845 if not date:
846 p.write("\n")
846 p.write("\n")
847 if date:
847 if date:
848 p.write("Date: %d %d\n\n" % date)
848 p.write("Date: %d %d\n\n" % date)
849 else:
849 else:
850 p.write("# HG changeset patch\n")
850 p.write("# HG changeset patch\n")
851 p.write("# Parent "
851 p.write("# Parent "
852 + hex(repo[None].parents()[0].node()) + "\n")
852 + hex(repo[None].parents()[0].node()) + "\n")
853 if user:
853 if user:
854 p.write("# User " + user + "\n")
854 p.write("# User " + user + "\n")
855 if date:
855 if date:
856 p.write("# Date %s %s\n\n" % date)
856 p.write("# Date %s %s\n\n" % date)
857 if hasattr(msg, '__call__'):
857 if hasattr(msg, '__call__'):
858 msg = msg()
858 msg = msg()
859 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
859 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
860 n = repo.commit(commitmsg, user, date, match=match, force=True)
860 n = repo.commit(commitmsg, user, date, match=match, force=True)
861 if n is None:
861 if n is None:
862 raise util.Abort(_("repo commit failed"))
862 raise util.Abort(_("repo commit failed"))
863 try:
863 try:
864 self.full_series[insert:insert] = [patchfn]
864 self.full_series[insert:insert] = [patchfn]
865 self.applied.append(statusentry(n, patchfn))
865 self.applied.append(statusentry(n, patchfn))
866 self.parse_series()
866 self.parse_series()
867 self.series_dirty = 1
867 self.series_dirty = 1
868 self.applied_dirty = 1
868 self.applied_dirty = 1
869 if msg:
869 if msg:
870 msg = msg + "\n\n"
870 msg = msg + "\n\n"
871 p.write(msg)
871 p.write(msg)
872 if commitfiles:
872 if commitfiles:
873 parent = self.qparents(repo, n)
873 parent = self.qparents(repo, n)
874 chunks = patch.diff(repo, node1=parent, node2=n,
874 chunks = patch.diff(repo, node1=parent, node2=n,
875 match=match, opts=diffopts)
875 match=match, opts=diffopts)
876 for chunk in chunks:
876 for chunk in chunks:
877 p.write(chunk)
877 p.write(chunk)
878 p.close()
878 p.close()
879 wlock.release()
879 wlock.release()
880 wlock = None
880 wlock = None
881 r = self.qrepo()
881 r = self.qrepo()
882 if r:
882 if r:
883 r[None].add([patchfn])
883 r[None].add([patchfn])
884 except:
884 except:
885 repo.rollback()
885 repo.rollback()
886 raise
886 raise
887 except Exception:
887 except Exception:
888 patchpath = self.join(patchfn)
888 patchpath = self.join(patchfn)
889 try:
889 try:
890 os.unlink(patchpath)
890 os.unlink(patchpath)
891 except:
891 except:
892 self.ui.warn(_('error unlinking %s\n') % patchpath)
892 self.ui.warn(_('error unlinking %s\n') % patchpath)
893 raise
893 raise
894 self.removeundo(repo)
894 self.removeundo(repo)
895 finally:
895 finally:
896 release(wlock)
896 release(wlock)
897
897
898 def strip(self, repo, rev, update=True, backup="all", force=None):
898 def strip(self, repo, rev, update=True, backup="all", force=None):
899 wlock = lock = None
899 wlock = lock = None
900 try:
900 try:
901 wlock = repo.wlock()
901 wlock = repo.wlock()
902 lock = repo.lock()
902 lock = repo.lock()
903
903
904 if update:
904 if update:
905 self.check_localchanges(repo, force=force, refresh=False)
905 self.check_localchanges(repo, force=force, refresh=False)
906 urev = self.qparents(repo, rev)
906 urev = self.qparents(repo, rev)
907 hg.clean(repo, urev)
907 hg.clean(repo, urev)
908 repo.dirstate.write()
908 repo.dirstate.write()
909
909
910 self.removeundo(repo)
910 self.removeundo(repo)
911 repair.strip(self.ui, repo, rev, backup)
911 repair.strip(self.ui, repo, rev, backup)
912 # strip may have unbundled a set of backed up revisions after
912 # strip may have unbundled a set of backed up revisions after
913 # the actual strip
913 # the actual strip
914 self.removeundo(repo)
914 self.removeundo(repo)
915 finally:
915 finally:
916 release(lock, wlock)
916 release(lock, wlock)
917
917
918 def isapplied(self, patch):
918 def isapplied(self, patch):
919 """returns (index, rev, patch)"""
919 """returns (index, rev, patch)"""
920 for i, a in enumerate(self.applied):
920 for i, a in enumerate(self.applied):
921 if a.name == patch:
921 if a.name == patch:
922 return (i, a.node, a.name)
922 return (i, a.node, a.name)
923 return None
923 return None
924
924
925 # if the exact patch name does not exist, we try a few
925 # if the exact patch name does not exist, we try a few
926 # variations. If strict is passed, we try only #1
926 # variations. If strict is passed, we try only #1
927 #
927 #
928 # 1) a number to indicate an offset in the series file
928 # 1) a number to indicate an offset in the series file
929 # 2) a unique substring of the patch name was given
929 # 2) a unique substring of the patch name was given
930 # 3) patchname[-+]num to indicate an offset in the series file
930 # 3) patchname[-+]num to indicate an offset in the series file
931 def lookup(self, patch, strict=False):
931 def lookup(self, patch, strict=False):
932 patch = patch and str(patch)
932 patch = patch and str(patch)
933
933
934 def partial_name(s):
934 def partial_name(s):
935 if s in self.series:
935 if s in self.series:
936 return s
936 return s
937 matches = [x for x in self.series if s in x]
937 matches = [x for x in self.series if s in x]
938 if len(matches) > 1:
938 if len(matches) > 1:
939 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
939 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
940 for m in matches:
940 for m in matches:
941 self.ui.warn(' %s\n' % m)
941 self.ui.warn(' %s\n' % m)
942 return None
942 return None
943 if matches:
943 if matches:
944 return matches[0]
944 return matches[0]
945 if self.series and self.applied:
945 if self.series and self.applied:
946 if s == 'qtip':
946 if s == 'qtip':
947 return self.series[self.series_end(True)-1]
947 return self.series[self.series_end(True)-1]
948 if s == 'qbase':
948 if s == 'qbase':
949 return self.series[0]
949 return self.series[0]
950 return None
950 return None
951
951
952 if patch is None:
952 if patch is None:
953 return None
953 return None
954 if patch in self.series:
954 if patch in self.series:
955 return patch
955 return patch
956
956
957 if not os.path.isfile(self.join(patch)):
957 if not os.path.isfile(self.join(patch)):
958 try:
958 try:
959 sno = int(patch)
959 sno = int(patch)
960 except (ValueError, OverflowError):
960 except (ValueError, OverflowError):
961 pass
961 pass
962 else:
962 else:
963 if -len(self.series) <= sno < len(self.series):
963 if -len(self.series) <= sno < len(self.series):
964 return self.series[sno]
964 return self.series[sno]
965
965
966 if not strict:
966 if not strict:
967 res = partial_name(patch)
967 res = partial_name(patch)
968 if res:
968 if res:
969 return res
969 return res
970 minus = patch.rfind('-')
970 minus = patch.rfind('-')
971 if minus >= 0:
971 if minus >= 0:
972 res = partial_name(patch[:minus])
972 res = partial_name(patch[:minus])
973 if res:
973 if res:
974 i = self.series.index(res)
974 i = self.series.index(res)
975 try:
975 try:
976 off = int(patch[minus + 1:] or 1)
976 off = int(patch[minus + 1:] or 1)
977 except (ValueError, OverflowError):
977 except (ValueError, OverflowError):
978 pass
978 pass
979 else:
979 else:
980 if i - off >= 0:
980 if i - off >= 0:
981 return self.series[i - off]
981 return self.series[i - off]
982 plus = patch.rfind('+')
982 plus = patch.rfind('+')
983 if plus >= 0:
983 if plus >= 0:
984 res = partial_name(patch[:plus])
984 res = partial_name(patch[:plus])
985 if res:
985 if res:
986 i = self.series.index(res)
986 i = self.series.index(res)
987 try:
987 try:
988 off = int(patch[plus + 1:] or 1)
988 off = int(patch[plus + 1:] or 1)
989 except (ValueError, OverflowError):
989 except (ValueError, OverflowError):
990 pass
990 pass
991 else:
991 else:
992 if i + off < len(self.series):
992 if i + off < len(self.series):
993 return self.series[i + off]
993 return self.series[i + off]
994 raise util.Abort(_("patch %s not in series") % patch)
994 raise util.Abort(_("patch %s not in series") % patch)
995
995
996 def push(self, repo, patch=None, force=False, list=False,
996 def push(self, repo, patch=None, force=False, list=False,
997 mergeq=None, all=False, move=False):
997 mergeq=None, all=False, move=False):
998 diffopts = self.diffopts()
998 diffopts = self.diffopts()
999 wlock = repo.wlock()
999 wlock = repo.wlock()
1000 try:
1000 try:
1001 heads = []
1001 heads = []
1002 for b, ls in repo.branchmap().iteritems():
1002 for b, ls in repo.branchmap().iteritems():
1003 heads += ls
1003 heads += ls
1004 if not heads:
1004 if not heads:
1005 heads = [nullid]
1005 heads = [nullid]
1006 if repo.dirstate.parents()[0] not in heads:
1006 if repo.dirstate.parents()[0] not in heads:
1007 self.ui.status(_("(working directory not at a head)\n"))
1007 self.ui.status(_("(working directory not at a head)\n"))
1008
1008
1009 if not self.series:
1009 if not self.series:
1010 self.ui.warn(_('no patches in series\n'))
1010 self.ui.warn(_('no patches in series\n'))
1011 return 0
1011 return 0
1012
1012
1013 patch = self.lookup(patch)
1013 patch = self.lookup(patch)
1014 # Suppose our series file is: A B C and the current 'top'
1014 # Suppose our series file is: A B C and the current 'top'
1015 # patch is B. qpush C should be performed (moving forward)
1015 # patch is B. qpush C should be performed (moving forward)
1016 # qpush B is a NOP (no change) qpush A is an error (can't
1016 # qpush B is a NOP (no change) qpush A is an error (can't
1017 # go backwards with qpush)
1017 # go backwards with qpush)
1018 if patch:
1018 if patch:
1019 info = self.isapplied(patch)
1019 info = self.isapplied(patch)
1020 if info:
1020 if info:
1021 if info[0] < len(self.applied) - 1:
1021 if info[0] < len(self.applied) - 1:
1022 raise util.Abort(
1022 raise util.Abort(
1023 _("cannot push to a previous patch: %s") % patch)
1023 _("cannot push to a previous patch: %s") % patch)
1024 self.ui.warn(
1024 self.ui.warn(
1025 _('qpush: %s is already at the top\n') % patch)
1025 _('qpush: %s is already at the top\n') % patch)
1026 return 0
1026 return 0
1027 pushable, reason = self.pushable(patch)
1027 pushable, reason = self.pushable(patch)
1028 if not pushable:
1028 if not pushable:
1029 if reason:
1029 if reason:
1030 reason = _('guarded by %r') % reason
1030 reason = _('guarded by %r') % reason
1031 else:
1031 else:
1032 reason = _('no matching guards')
1032 reason = _('no matching guards')
1033 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1033 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1034 return 1
1034 return 1
1035 elif all:
1035 elif all:
1036 patch = self.series[-1]
1036 patch = self.series[-1]
1037 if self.isapplied(patch):
1037 if self.isapplied(patch):
1038 self.ui.warn(_('all patches are currently applied\n'))
1038 self.ui.warn(_('all patches are currently applied\n'))
1039 return 0
1039 return 0
1040
1040
1041 # Following the above example, starting at 'top' of B:
1041 # Following the above example, starting at 'top' of B:
1042 # qpush should be performed (pushes C), but a subsequent
1042 # qpush should be performed (pushes C), but a subsequent
1043 # qpush without an argument is an error (nothing to
1043 # qpush without an argument is an error (nothing to
1044 # apply). This allows a loop of "...while hg qpush..." to
1044 # apply). This allows a loop of "...while hg qpush..." to
1045 # work as it detects an error when done
1045 # work as it detects an error when done
1046 start = self.series_end()
1046 start = self.series_end()
1047 if start == len(self.series):
1047 if start == len(self.series):
1048 self.ui.warn(_('patch series already fully applied\n'))
1048 self.ui.warn(_('patch series already fully applied\n'))
1049 return 1
1049 return 1
1050 if not force:
1050 if not force:
1051 self.check_localchanges(repo)
1051 self.check_localchanges(repo)
1052
1052
1053 if move:
1053 if move:
1054 try:
1054 if not patch:
1055 index = self.series.index(patch, start)
1055 raise util.Abort(_("please specify the patch to move"))
1056 for i, rpn in enumerate(self.full_series[start:]):
1057 # strip markers for patch guards
1058 if self.guard_re.split(rpn, 1)[0] == patch:
1059 break
1060 index = start + i
1061 assert index < len(self.full_series)
1056 fullpatch = self.full_series[index]
1062 fullpatch = self.full_series[index]
1057 del self.full_series[index]
1063 del self.full_series[index]
1058 except ValueError:
1059 raise util.Abort(_("patch '%s' not found") % patch)
1060 self.full_series.insert(start, fullpatch)
1064 self.full_series.insert(start, fullpatch)
1061 self.parse_series()
1065 self.parse_series()
1062 self.series_dirty = 1
1066 self.series_dirty = 1
1063
1067
1064 self.applied_dirty = 1
1068 self.applied_dirty = 1
1065 if start > 0:
1069 if start > 0:
1066 self.check_toppatch(repo)
1070 self.check_toppatch(repo)
1067 if not patch:
1071 if not patch:
1068 patch = self.series[start]
1072 patch = self.series[start]
1069 end = start + 1
1073 end = start + 1
1070 else:
1074 else:
1071 end = self.series.index(patch, start) + 1
1075 end = self.series.index(patch, start) + 1
1072
1076
1073 s = self.series[start:end]
1077 s = self.series[start:end]
1074 all_files = set()
1078 all_files = set()
1075 try:
1079 try:
1076 if mergeq:
1080 if mergeq:
1077 ret = self.mergepatch(repo, mergeq, s, diffopts)
1081 ret = self.mergepatch(repo, mergeq, s, diffopts)
1078 else:
1082 else:
1079 ret = self.apply(repo, s, list, all_files=all_files)
1083 ret = self.apply(repo, s, list, all_files=all_files)
1080 except:
1084 except:
1081 self.ui.warn(_('cleaning up working directory...'))
1085 self.ui.warn(_('cleaning up working directory...'))
1082 node = repo.dirstate.parents()[0]
1086 node = repo.dirstate.parents()[0]
1083 hg.revert(repo, node, None)
1087 hg.revert(repo, node, None)
1084 # only remove unknown files that we know we touched or
1088 # only remove unknown files that we know we touched or
1085 # created while patching
1089 # created while patching
1086 for f in all_files:
1090 for f in all_files:
1087 if f not in repo.dirstate:
1091 if f not in repo.dirstate:
1088 try:
1092 try:
1089 util.unlink(repo.wjoin(f))
1093 util.unlink(repo.wjoin(f))
1090 except OSError, inst:
1094 except OSError, inst:
1091 if inst.errno != errno.ENOENT:
1095 if inst.errno != errno.ENOENT:
1092 raise
1096 raise
1093 self.ui.warn(_('done\n'))
1097 self.ui.warn(_('done\n'))
1094 raise
1098 raise
1095
1099
1096 if not self.applied:
1100 if not self.applied:
1097 return ret[0]
1101 return ret[0]
1098 top = self.applied[-1].name
1102 top = self.applied[-1].name
1099 if ret[0] and ret[0] > 1:
1103 if ret[0] and ret[0] > 1:
1100 msg = _("errors during apply, please fix and refresh %s\n")
1104 msg = _("errors during apply, please fix and refresh %s\n")
1101 self.ui.write(msg % top)
1105 self.ui.write(msg % top)
1102 else:
1106 else:
1103 self.ui.write(_("now at: %s\n") % top)
1107 self.ui.write(_("now at: %s\n") % top)
1104 return ret[0]
1108 return ret[0]
1105
1109
1106 finally:
1110 finally:
1107 wlock.release()
1111 wlock.release()
1108
1112
1109 def pop(self, repo, patch=None, force=False, update=True, all=False):
1113 def pop(self, repo, patch=None, force=False, update=True, all=False):
1110 wlock = repo.wlock()
1114 wlock = repo.wlock()
1111 try:
1115 try:
1112 if patch:
1116 if patch:
1113 # index, rev, patch
1117 # index, rev, patch
1114 info = self.isapplied(patch)
1118 info = self.isapplied(patch)
1115 if not info:
1119 if not info:
1116 patch = self.lookup(patch)
1120 patch = self.lookup(patch)
1117 info = self.isapplied(patch)
1121 info = self.isapplied(patch)
1118 if not info:
1122 if not info:
1119 raise util.Abort(_("patch %s is not applied") % patch)
1123 raise util.Abort(_("patch %s is not applied") % patch)
1120
1124
1121 if not self.applied:
1125 if not self.applied:
1122 # Allow qpop -a to work repeatedly,
1126 # Allow qpop -a to work repeatedly,
1123 # but not qpop without an argument
1127 # but not qpop without an argument
1124 self.ui.warn(_("no patches applied\n"))
1128 self.ui.warn(_("no patches applied\n"))
1125 return not all
1129 return not all
1126
1130
1127 if all:
1131 if all:
1128 start = 0
1132 start = 0
1129 elif patch:
1133 elif patch:
1130 start = info[0] + 1
1134 start = info[0] + 1
1131 else:
1135 else:
1132 start = len(self.applied) - 1
1136 start = len(self.applied) - 1
1133
1137
1134 if start >= len(self.applied):
1138 if start >= len(self.applied):
1135 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1139 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1136 return
1140 return
1137
1141
1138 if not update:
1142 if not update:
1139 parents = repo.dirstate.parents()
1143 parents = repo.dirstate.parents()
1140 rr = [x.node for x in self.applied]
1144 rr = [x.node for x in self.applied]
1141 for p in parents:
1145 for p in parents:
1142 if p in rr:
1146 if p in rr:
1143 self.ui.warn(_("qpop: forcing dirstate update\n"))
1147 self.ui.warn(_("qpop: forcing dirstate update\n"))
1144 update = True
1148 update = True
1145 else:
1149 else:
1146 parents = [p.node() for p in repo[None].parents()]
1150 parents = [p.node() for p in repo[None].parents()]
1147 needupdate = False
1151 needupdate = False
1148 for entry in self.applied[start:]:
1152 for entry in self.applied[start:]:
1149 if entry.node in parents:
1153 if entry.node in parents:
1150 needupdate = True
1154 needupdate = True
1151 break
1155 break
1152 update = needupdate
1156 update = needupdate
1153
1157
1154 if not force and update:
1158 if not force and update:
1155 self.check_localchanges(repo)
1159 self.check_localchanges(repo)
1156
1160
1157 self.applied_dirty = 1
1161 self.applied_dirty = 1
1158 end = len(self.applied)
1162 end = len(self.applied)
1159 rev = self.applied[start].node
1163 rev = self.applied[start].node
1160 if update:
1164 if update:
1161 top = self.check_toppatch(repo)[0]
1165 top = self.check_toppatch(repo)[0]
1162
1166
1163 try:
1167 try:
1164 heads = repo.changelog.heads(rev)
1168 heads = repo.changelog.heads(rev)
1165 except error.LookupError:
1169 except error.LookupError:
1166 node = short(rev)
1170 node = short(rev)
1167 raise util.Abort(_('trying to pop unknown node %s') % node)
1171 raise util.Abort(_('trying to pop unknown node %s') % node)
1168
1172
1169 if heads != [self.applied[-1].node]:
1173 if heads != [self.applied[-1].node]:
1170 raise util.Abort(_("popping would remove a revision not "
1174 raise util.Abort(_("popping would remove a revision not "
1171 "managed by this patch queue"))
1175 "managed by this patch queue"))
1172
1176
1173 # we know there are no local changes, so we can make a simplified
1177 # we know there are no local changes, so we can make a simplified
1174 # form of hg.update.
1178 # form of hg.update.
1175 if update:
1179 if update:
1176 qp = self.qparents(repo, rev)
1180 qp = self.qparents(repo, rev)
1177 ctx = repo[qp]
1181 ctx = repo[qp]
1178 m, a, r, d = repo.status(qp, top)[:4]
1182 m, a, r, d = repo.status(qp, top)[:4]
1179 if d:
1183 if d:
1180 raise util.Abort(_("deletions found between repo revs"))
1184 raise util.Abort(_("deletions found between repo revs"))
1181 for f in a:
1185 for f in a:
1182 try:
1186 try:
1183 util.unlink(repo.wjoin(f))
1187 util.unlink(repo.wjoin(f))
1184 except OSError, e:
1188 except OSError, e:
1185 if e.errno != errno.ENOENT:
1189 if e.errno != errno.ENOENT:
1186 raise
1190 raise
1187 repo.dirstate.forget(f)
1191 repo.dirstate.forget(f)
1188 for f in m + r:
1192 for f in m + r:
1189 fctx = ctx[f]
1193 fctx = ctx[f]
1190 repo.wwrite(f, fctx.data(), fctx.flags())
1194 repo.wwrite(f, fctx.data(), fctx.flags())
1191 repo.dirstate.normal(f)
1195 repo.dirstate.normal(f)
1192 repo.dirstate.setparents(qp, nullid)
1196 repo.dirstate.setparents(qp, nullid)
1193 for patch in reversed(self.applied[start:end]):
1197 for patch in reversed(self.applied[start:end]):
1194 self.ui.status(_("popping %s\n") % patch.name)
1198 self.ui.status(_("popping %s\n") % patch.name)
1195 del self.applied[start:end]
1199 del self.applied[start:end]
1196 self.strip(repo, rev, update=False, backup='strip')
1200 self.strip(repo, rev, update=False, backup='strip')
1197 if self.applied:
1201 if self.applied:
1198 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1202 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1199 else:
1203 else:
1200 self.ui.write(_("patch queue now empty\n"))
1204 self.ui.write(_("patch queue now empty\n"))
1201 finally:
1205 finally:
1202 wlock.release()
1206 wlock.release()
1203
1207
1204 def diff(self, repo, pats, opts):
1208 def diff(self, repo, pats, opts):
1205 top, patch = self.check_toppatch(repo)
1209 top, patch = self.check_toppatch(repo)
1206 if not top:
1210 if not top:
1207 self.ui.write(_("no patches applied\n"))
1211 self.ui.write(_("no patches applied\n"))
1208 return
1212 return
1209 qp = self.qparents(repo, top)
1213 qp = self.qparents(repo, top)
1210 if opts.get('reverse'):
1214 if opts.get('reverse'):
1211 node1, node2 = None, qp
1215 node1, node2 = None, qp
1212 else:
1216 else:
1213 node1, node2 = qp, None
1217 node1, node2 = qp, None
1214 diffopts = self.diffopts(opts, patch)
1218 diffopts = self.diffopts(opts, patch)
1215 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1219 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1216
1220
1217 def refresh(self, repo, pats=None, **opts):
1221 def refresh(self, repo, pats=None, **opts):
1218 if not self.applied:
1222 if not self.applied:
1219 self.ui.write(_("no patches applied\n"))
1223 self.ui.write(_("no patches applied\n"))
1220 return 1
1224 return 1
1221 msg = opts.get('msg', '').rstrip()
1225 msg = opts.get('msg', '').rstrip()
1222 newuser = opts.get('user')
1226 newuser = opts.get('user')
1223 newdate = opts.get('date')
1227 newdate = opts.get('date')
1224 if newdate:
1228 if newdate:
1225 newdate = '%d %d' % util.parsedate(newdate)
1229 newdate = '%d %d' % util.parsedate(newdate)
1226 wlock = repo.wlock()
1230 wlock = repo.wlock()
1227
1231
1228 try:
1232 try:
1229 self.check_toppatch(repo)
1233 self.check_toppatch(repo)
1230 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1234 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1231 if repo.changelog.heads(top) != [top]:
1235 if repo.changelog.heads(top) != [top]:
1232 raise util.Abort(_("cannot refresh a revision with children"))
1236 raise util.Abort(_("cannot refresh a revision with children"))
1233
1237
1234 cparents = repo.changelog.parents(top)
1238 cparents = repo.changelog.parents(top)
1235 patchparent = self.qparents(repo, top)
1239 patchparent = self.qparents(repo, top)
1236 ph = patchheader(self.join(patchfn), self.plainmode)
1240 ph = patchheader(self.join(patchfn), self.plainmode)
1237 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1241 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1238 if msg:
1242 if msg:
1239 ph.setmessage(msg)
1243 ph.setmessage(msg)
1240 if newuser:
1244 if newuser:
1241 ph.setuser(newuser)
1245 ph.setuser(newuser)
1242 if newdate:
1246 if newdate:
1243 ph.setdate(newdate)
1247 ph.setdate(newdate)
1244 ph.setparent(hex(patchparent))
1248 ph.setparent(hex(patchparent))
1245
1249
1246 # only commit new patch when write is complete
1250 # only commit new patch when write is complete
1247 patchf = self.opener(patchfn, 'w', atomictemp=True)
1251 patchf = self.opener(patchfn, 'w', atomictemp=True)
1248
1252
1249 comments = str(ph)
1253 comments = str(ph)
1250 if comments:
1254 if comments:
1251 patchf.write(comments)
1255 patchf.write(comments)
1252
1256
1253 # update the dirstate in place, strip off the qtip commit
1257 # update the dirstate in place, strip off the qtip commit
1254 # and then commit.
1258 # and then commit.
1255 #
1259 #
1256 # this should really read:
1260 # this should really read:
1257 # mm, dd, aa, aa2 = repo.status(tip, patchparent)[:4]
1261 # mm, dd, aa, aa2 = repo.status(tip, patchparent)[:4]
1258 # but we do it backwards to take advantage of manifest/chlog
1262 # but we do it backwards to take advantage of manifest/chlog
1259 # caching against the next repo.status call
1263 # caching against the next repo.status call
1260 mm, aa, dd, aa2 = repo.status(patchparent, top)[:4]
1264 mm, aa, dd, aa2 = repo.status(patchparent, top)[:4]
1261 changes = repo.changelog.read(top)
1265 changes = repo.changelog.read(top)
1262 man = repo.manifest.read(changes[0])
1266 man = repo.manifest.read(changes[0])
1263 aaa = aa[:]
1267 aaa = aa[:]
1264 matchfn = cmdutil.match(repo, pats, opts)
1268 matchfn = cmdutil.match(repo, pats, opts)
1265 # in short mode, we only diff the files included in the
1269 # in short mode, we only diff the files included in the
1266 # patch already plus specified files
1270 # patch already plus specified files
1267 if opts.get('short'):
1271 if opts.get('short'):
1268 # if amending a patch, we start with existing
1272 # if amending a patch, we start with existing
1269 # files plus specified files - unfiltered
1273 # files plus specified files - unfiltered
1270 match = cmdutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1274 match = cmdutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1271 # filter with inc/exl options
1275 # filter with inc/exl options
1272 matchfn = cmdutil.match(repo, opts=opts)
1276 matchfn = cmdutil.match(repo, opts=opts)
1273 else:
1277 else:
1274 match = cmdutil.matchall(repo)
1278 match = cmdutil.matchall(repo)
1275 m, a, r, d = repo.status(match=match)[:4]
1279 m, a, r, d = repo.status(match=match)[:4]
1276
1280
1277 # we might end up with files that were added between
1281 # we might end up with files that were added between
1278 # qtip and the dirstate parent, but then changed in the
1282 # qtip and the dirstate parent, but then changed in the
1279 # local dirstate. in this case, we want them to only
1283 # local dirstate. in this case, we want them to only
1280 # show up in the added section
1284 # show up in the added section
1281 for x in m:
1285 for x in m:
1282 if x not in aa:
1286 if x not in aa:
1283 mm.append(x)
1287 mm.append(x)
1284 # we might end up with files added by the local dirstate that
1288 # we might end up with files added by the local dirstate that
1285 # were deleted by the patch. In this case, they should only
1289 # were deleted by the patch. In this case, they should only
1286 # show up in the changed section.
1290 # show up in the changed section.
1287 for x in a:
1291 for x in a:
1288 if x in dd:
1292 if x in dd:
1289 del dd[dd.index(x)]
1293 del dd[dd.index(x)]
1290 mm.append(x)
1294 mm.append(x)
1291 else:
1295 else:
1292 aa.append(x)
1296 aa.append(x)
1293 # make sure any files deleted in the local dirstate
1297 # make sure any files deleted in the local dirstate
1294 # are not in the add or change column of the patch
1298 # are not in the add or change column of the patch
1295 forget = []
1299 forget = []
1296 for x in d + r:
1300 for x in d + r:
1297 if x in aa:
1301 if x in aa:
1298 del aa[aa.index(x)]
1302 del aa[aa.index(x)]
1299 forget.append(x)
1303 forget.append(x)
1300 continue
1304 continue
1301 elif x in mm:
1305 elif x in mm:
1302 del mm[mm.index(x)]
1306 del mm[mm.index(x)]
1303 dd.append(x)
1307 dd.append(x)
1304
1308
1305 m = list(set(mm))
1309 m = list(set(mm))
1306 r = list(set(dd))
1310 r = list(set(dd))
1307 a = list(set(aa))
1311 a = list(set(aa))
1308 c = [filter(matchfn, l) for l in (m, a, r)]
1312 c = [filter(matchfn, l) for l in (m, a, r)]
1309 match = cmdutil.matchfiles(repo, set(c[0] + c[1] + c[2]))
1313 match = cmdutil.matchfiles(repo, set(c[0] + c[1] + c[2]))
1310 chunks = patch.diff(repo, patchparent, match=match,
1314 chunks = patch.diff(repo, patchparent, match=match,
1311 changes=c, opts=diffopts)
1315 changes=c, opts=diffopts)
1312 for chunk in chunks:
1316 for chunk in chunks:
1313 patchf.write(chunk)
1317 patchf.write(chunk)
1314
1318
1315 try:
1319 try:
1316 if diffopts.git or diffopts.upgrade:
1320 if diffopts.git or diffopts.upgrade:
1317 copies = {}
1321 copies = {}
1318 for dst in a:
1322 for dst in a:
1319 src = repo.dirstate.copied(dst)
1323 src = repo.dirstate.copied(dst)
1320 # during qfold, the source file for copies may
1324 # during qfold, the source file for copies may
1321 # be removed. Treat this as a simple add.
1325 # be removed. Treat this as a simple add.
1322 if src is not None and src in repo.dirstate:
1326 if src is not None and src in repo.dirstate:
1323 copies.setdefault(src, []).append(dst)
1327 copies.setdefault(src, []).append(dst)
1324 repo.dirstate.add(dst)
1328 repo.dirstate.add(dst)
1325 # remember the copies between patchparent and qtip
1329 # remember the copies between patchparent and qtip
1326 for dst in aaa:
1330 for dst in aaa:
1327 f = repo.file(dst)
1331 f = repo.file(dst)
1328 src = f.renamed(man[dst])
1332 src = f.renamed(man[dst])
1329 if src:
1333 if src:
1330 copies.setdefault(src[0], []).extend(
1334 copies.setdefault(src[0], []).extend(
1331 copies.get(dst, []))
1335 copies.get(dst, []))
1332 if dst in a:
1336 if dst in a:
1333 copies[src[0]].append(dst)
1337 copies[src[0]].append(dst)
1334 # we can't copy a file created by the patch itself
1338 # we can't copy a file created by the patch itself
1335 if dst in copies:
1339 if dst in copies:
1336 del copies[dst]
1340 del copies[dst]
1337 for src, dsts in copies.iteritems():
1341 for src, dsts in copies.iteritems():
1338 for dst in dsts:
1342 for dst in dsts:
1339 repo.dirstate.copy(src, dst)
1343 repo.dirstate.copy(src, dst)
1340 else:
1344 else:
1341 for dst in a:
1345 for dst in a:
1342 repo.dirstate.add(dst)
1346 repo.dirstate.add(dst)
1343 # Drop useless copy information
1347 # Drop useless copy information
1344 for f in list(repo.dirstate.copies()):
1348 for f in list(repo.dirstate.copies()):
1345 repo.dirstate.copy(None, f)
1349 repo.dirstate.copy(None, f)
1346 for f in r:
1350 for f in r:
1347 repo.dirstate.remove(f)
1351 repo.dirstate.remove(f)
1348 # if the patch excludes a modified file, mark that
1352 # if the patch excludes a modified file, mark that
1349 # file with mtime=0 so status can see it.
1353 # file with mtime=0 so status can see it.
1350 mm = []
1354 mm = []
1351 for i in xrange(len(m)-1, -1, -1):
1355 for i in xrange(len(m)-1, -1, -1):
1352 if not matchfn(m[i]):
1356 if not matchfn(m[i]):
1353 mm.append(m[i])
1357 mm.append(m[i])
1354 del m[i]
1358 del m[i]
1355 for f in m:
1359 for f in m:
1356 repo.dirstate.normal(f)
1360 repo.dirstate.normal(f)
1357 for f in mm:
1361 for f in mm:
1358 repo.dirstate.normallookup(f)
1362 repo.dirstate.normallookup(f)
1359 for f in forget:
1363 for f in forget:
1360 repo.dirstate.forget(f)
1364 repo.dirstate.forget(f)
1361
1365
1362 if not msg:
1366 if not msg:
1363 if not ph.message:
1367 if not ph.message:
1364 message = "[mq]: %s\n" % patchfn
1368 message = "[mq]: %s\n" % patchfn
1365 else:
1369 else:
1366 message = "\n".join(ph.message)
1370 message = "\n".join(ph.message)
1367 else:
1371 else:
1368 message = msg
1372 message = msg
1369
1373
1370 user = ph.user or changes[1]
1374 user = ph.user or changes[1]
1371
1375
1372 # assumes strip can roll itself back if interrupted
1376 # assumes strip can roll itself back if interrupted
1373 repo.dirstate.setparents(*cparents)
1377 repo.dirstate.setparents(*cparents)
1374 self.applied.pop()
1378 self.applied.pop()
1375 self.applied_dirty = 1
1379 self.applied_dirty = 1
1376 self.strip(repo, top, update=False,
1380 self.strip(repo, top, update=False,
1377 backup='strip')
1381 backup='strip')
1378 except:
1382 except:
1379 repo.dirstate.invalidate()
1383 repo.dirstate.invalidate()
1380 raise
1384 raise
1381
1385
1382 try:
1386 try:
1383 # might be nice to attempt to roll back strip after this
1387 # might be nice to attempt to roll back strip after this
1384 patchf.rename()
1388 patchf.rename()
1385 n = repo.commit(message, user, ph.date, match=match,
1389 n = repo.commit(message, user, ph.date, match=match,
1386 force=True)
1390 force=True)
1387 self.applied.append(statusentry(n, patchfn))
1391 self.applied.append(statusentry(n, patchfn))
1388 except:
1392 except:
1389 ctx = repo[cparents[0]]
1393 ctx = repo[cparents[0]]
1390 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1394 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1391 self.save_dirty()
1395 self.save_dirty()
1392 self.ui.warn(_('refresh interrupted while patch was popped! '
1396 self.ui.warn(_('refresh interrupted while patch was popped! '
1393 '(revert --all, qpush to recover)\n'))
1397 '(revert --all, qpush to recover)\n'))
1394 raise
1398 raise
1395 finally:
1399 finally:
1396 wlock.release()
1400 wlock.release()
1397 self.removeundo(repo)
1401 self.removeundo(repo)
1398
1402
1399 def init(self, repo, create=False):
1403 def init(self, repo, create=False):
1400 if not create and os.path.isdir(self.path):
1404 if not create and os.path.isdir(self.path):
1401 raise util.Abort(_("patch queue directory already exists"))
1405 raise util.Abort(_("patch queue directory already exists"))
1402 try:
1406 try:
1403 os.mkdir(self.path)
1407 os.mkdir(self.path)
1404 except OSError, inst:
1408 except OSError, inst:
1405 if inst.errno != errno.EEXIST or not create:
1409 if inst.errno != errno.EEXIST or not create:
1406 raise
1410 raise
1407 if create:
1411 if create:
1408 return self.qrepo(create=True)
1412 return self.qrepo(create=True)
1409
1413
1410 def unapplied(self, repo, patch=None):
1414 def unapplied(self, repo, patch=None):
1411 if patch and patch not in self.series:
1415 if patch and patch not in self.series:
1412 raise util.Abort(_("patch %s is not in series file") % patch)
1416 raise util.Abort(_("patch %s is not in series file") % patch)
1413 if not patch:
1417 if not patch:
1414 start = self.series_end()
1418 start = self.series_end()
1415 else:
1419 else:
1416 start = self.series.index(patch) + 1
1420 start = self.series.index(patch) + 1
1417 unapplied = []
1421 unapplied = []
1418 for i in xrange(start, len(self.series)):
1422 for i in xrange(start, len(self.series)):
1419 pushable, reason = self.pushable(i)
1423 pushable, reason = self.pushable(i)
1420 if pushable:
1424 if pushable:
1421 unapplied.append((i, self.series[i]))
1425 unapplied.append((i, self.series[i]))
1422 self.explain_pushable(i)
1426 self.explain_pushable(i)
1423 return unapplied
1427 return unapplied
1424
1428
1425 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1429 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1426 summary=False):
1430 summary=False):
1427 def displayname(pfx, patchname, state):
1431 def displayname(pfx, patchname, state):
1428 if pfx:
1432 if pfx:
1429 self.ui.write(pfx)
1433 self.ui.write(pfx)
1430 if summary:
1434 if summary:
1431 ph = patchheader(self.join(patchname), self.plainmode)
1435 ph = patchheader(self.join(patchname), self.plainmode)
1432 msg = ph.message and ph.message[0] or ''
1436 msg = ph.message and ph.message[0] or ''
1433 if self.ui.formatted():
1437 if self.ui.formatted():
1434 width = util.termwidth() - len(pfx) - len(patchname) - 2
1438 width = util.termwidth() - len(pfx) - len(patchname) - 2
1435 if width > 0:
1439 if width > 0:
1436 msg = util.ellipsis(msg, width)
1440 msg = util.ellipsis(msg, width)
1437 else:
1441 else:
1438 msg = ''
1442 msg = ''
1439 self.ui.write(patchname, label='qseries.' + state)
1443 self.ui.write(patchname, label='qseries.' + state)
1440 self.ui.write(': ')
1444 self.ui.write(': ')
1441 self.ui.write(msg, label='qseries.message.' + state)
1445 self.ui.write(msg, label='qseries.message.' + state)
1442 else:
1446 else:
1443 self.ui.write(patchname, label='qseries.' + state)
1447 self.ui.write(patchname, label='qseries.' + state)
1444 self.ui.write('\n')
1448 self.ui.write('\n')
1445
1449
1446 applied = set([p.name for p in self.applied])
1450 applied = set([p.name for p in self.applied])
1447 if length is None:
1451 if length is None:
1448 length = len(self.series) - start
1452 length = len(self.series) - start
1449 if not missing:
1453 if not missing:
1450 if self.ui.verbose:
1454 if self.ui.verbose:
1451 idxwidth = len(str(start + length - 1))
1455 idxwidth = len(str(start + length - 1))
1452 for i in xrange(start, start + length):
1456 for i in xrange(start, start + length):
1453 patch = self.series[i]
1457 patch = self.series[i]
1454 if patch in applied:
1458 if patch in applied:
1455 char, state = 'A', 'applied'
1459 char, state = 'A', 'applied'
1456 elif self.pushable(i)[0]:
1460 elif self.pushable(i)[0]:
1457 char, state = 'U', 'unapplied'
1461 char, state = 'U', 'unapplied'
1458 else:
1462 else:
1459 char, state = 'G', 'guarded'
1463 char, state = 'G', 'guarded'
1460 pfx = ''
1464 pfx = ''
1461 if self.ui.verbose:
1465 if self.ui.verbose:
1462 pfx = '%*d %s ' % (idxwidth, i, char)
1466 pfx = '%*d %s ' % (idxwidth, i, char)
1463 elif status and status != char:
1467 elif status and status != char:
1464 continue
1468 continue
1465 displayname(pfx, patch, state)
1469 displayname(pfx, patch, state)
1466 else:
1470 else:
1467 msng_list = []
1471 msng_list = []
1468 for root, dirs, files in os.walk(self.path):
1472 for root, dirs, files in os.walk(self.path):
1469 d = root[len(self.path) + 1:]
1473 d = root[len(self.path) + 1:]
1470 for f in files:
1474 for f in files:
1471 fl = os.path.join(d, f)
1475 fl = os.path.join(d, f)
1472 if (fl not in self.series and
1476 if (fl not in self.series and
1473 fl not in (self.status_path, self.series_path,
1477 fl not in (self.status_path, self.series_path,
1474 self.guards_path)
1478 self.guards_path)
1475 and not fl.startswith('.')):
1479 and not fl.startswith('.')):
1476 msng_list.append(fl)
1480 msng_list.append(fl)
1477 for x in sorted(msng_list):
1481 for x in sorted(msng_list):
1478 pfx = self.ui.verbose and ('D ') or ''
1482 pfx = self.ui.verbose and ('D ') or ''
1479 displayname(pfx, x, 'missing')
1483 displayname(pfx, x, 'missing')
1480
1484
1481 def issaveline(self, l):
1485 def issaveline(self, l):
1482 if l.name == '.hg.patches.save.line':
1486 if l.name == '.hg.patches.save.line':
1483 return True
1487 return True
1484
1488
1485 def qrepo(self, create=False):
1489 def qrepo(self, create=False):
1486 if create or os.path.isdir(self.join(".hg")):
1490 if create or os.path.isdir(self.join(".hg")):
1487 return hg.repository(self.ui, path=self.path, create=create)
1491 return hg.repository(self.ui, path=self.path, create=create)
1488
1492
1489 def restore(self, repo, rev, delete=None, qupdate=None):
1493 def restore(self, repo, rev, delete=None, qupdate=None):
1490 desc = repo[rev].description().strip()
1494 desc = repo[rev].description().strip()
1491 lines = desc.splitlines()
1495 lines = desc.splitlines()
1492 i = 0
1496 i = 0
1493 datastart = None
1497 datastart = None
1494 series = []
1498 series = []
1495 applied = []
1499 applied = []
1496 qpp = None
1500 qpp = None
1497 for i, line in enumerate(lines):
1501 for i, line in enumerate(lines):
1498 if line == 'Patch Data:':
1502 if line == 'Patch Data:':
1499 datastart = i + 1
1503 datastart = i + 1
1500 elif line.startswith('Dirstate:'):
1504 elif line.startswith('Dirstate:'):
1501 l = line.rstrip()
1505 l = line.rstrip()
1502 l = l[10:].split(' ')
1506 l = l[10:].split(' ')
1503 qpp = [bin(x) for x in l]
1507 qpp = [bin(x) for x in l]
1504 elif datastart != None:
1508 elif datastart != None:
1505 l = line.rstrip()
1509 l = line.rstrip()
1506 n, name = l.split(':', 1)
1510 n, name = l.split(':', 1)
1507 if n:
1511 if n:
1508 applied.append(statusentry(bin(n), name))
1512 applied.append(statusentry(bin(n), name))
1509 else:
1513 else:
1510 series.append(l)
1514 series.append(l)
1511 if datastart is None:
1515 if datastart is None:
1512 self.ui.warn(_("No saved patch data found\n"))
1516 self.ui.warn(_("No saved patch data found\n"))
1513 return 1
1517 return 1
1514 self.ui.warn(_("restoring status: %s\n") % lines[0])
1518 self.ui.warn(_("restoring status: %s\n") % lines[0])
1515 self.full_series = series
1519 self.full_series = series
1516 self.applied = applied
1520 self.applied = applied
1517 self.parse_series()
1521 self.parse_series()
1518 self.series_dirty = 1
1522 self.series_dirty = 1
1519 self.applied_dirty = 1
1523 self.applied_dirty = 1
1520 heads = repo.changelog.heads()
1524 heads = repo.changelog.heads()
1521 if delete:
1525 if delete:
1522 if rev not in heads:
1526 if rev not in heads:
1523 self.ui.warn(_("save entry has children, leaving it alone\n"))
1527 self.ui.warn(_("save entry has children, leaving it alone\n"))
1524 else:
1528 else:
1525 self.ui.warn(_("removing save entry %s\n") % short(rev))
1529 self.ui.warn(_("removing save entry %s\n") % short(rev))
1526 pp = repo.dirstate.parents()
1530 pp = repo.dirstate.parents()
1527 if rev in pp:
1531 if rev in pp:
1528 update = True
1532 update = True
1529 else:
1533 else:
1530 update = False
1534 update = False
1531 self.strip(repo, rev, update=update, backup='strip')
1535 self.strip(repo, rev, update=update, backup='strip')
1532 if qpp:
1536 if qpp:
1533 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1537 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1534 (short(qpp[0]), short(qpp[1])))
1538 (short(qpp[0]), short(qpp[1])))
1535 if qupdate:
1539 if qupdate:
1536 self.ui.status(_("queue directory updating\n"))
1540 self.ui.status(_("queue directory updating\n"))
1537 r = self.qrepo()
1541 r = self.qrepo()
1538 if not r:
1542 if not r:
1539 self.ui.warn(_("Unable to load queue repository\n"))
1543 self.ui.warn(_("Unable to load queue repository\n"))
1540 return 1
1544 return 1
1541 hg.clean(r, qpp[0])
1545 hg.clean(r, qpp[0])
1542
1546
1543 def save(self, repo, msg=None):
1547 def save(self, repo, msg=None):
1544 if not self.applied:
1548 if not self.applied:
1545 self.ui.warn(_("save: no patches applied, exiting\n"))
1549 self.ui.warn(_("save: no patches applied, exiting\n"))
1546 return 1
1550 return 1
1547 if self.issaveline(self.applied[-1]):
1551 if self.issaveline(self.applied[-1]):
1548 self.ui.warn(_("status is already saved\n"))
1552 self.ui.warn(_("status is already saved\n"))
1549 return 1
1553 return 1
1550
1554
1551 if not msg:
1555 if not msg:
1552 msg = _("hg patches saved state")
1556 msg = _("hg patches saved state")
1553 else:
1557 else:
1554 msg = "hg patches: " + msg.rstrip('\r\n')
1558 msg = "hg patches: " + msg.rstrip('\r\n')
1555 r = self.qrepo()
1559 r = self.qrepo()
1556 if r:
1560 if r:
1557 pp = r.dirstate.parents()
1561 pp = r.dirstate.parents()
1558 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1562 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1559 msg += "\n\nPatch Data:\n"
1563 msg += "\n\nPatch Data:\n"
1560 msg += ''.join('%s\n' % x for x in self.applied)
1564 msg += ''.join('%s\n' % x for x in self.applied)
1561 msg += ''.join(':%s\n' % x for x in self.full_series)
1565 msg += ''.join(':%s\n' % x for x in self.full_series)
1562 n = repo.commit(msg, force=True)
1566 n = repo.commit(msg, force=True)
1563 if not n:
1567 if not n:
1564 self.ui.warn(_("repo commit failed\n"))
1568 self.ui.warn(_("repo commit failed\n"))
1565 return 1
1569 return 1
1566 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1570 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1567 self.applied_dirty = 1
1571 self.applied_dirty = 1
1568 self.removeundo(repo)
1572 self.removeundo(repo)
1569
1573
1570 def full_series_end(self):
1574 def full_series_end(self):
1571 if self.applied:
1575 if self.applied:
1572 p = self.applied[-1].name
1576 p = self.applied[-1].name
1573 end = self.find_series(p)
1577 end = self.find_series(p)
1574 if end is None:
1578 if end is None:
1575 return len(self.full_series)
1579 return len(self.full_series)
1576 return end + 1
1580 return end + 1
1577 return 0
1581 return 0
1578
1582
1579 def series_end(self, all_patches=False):
1583 def series_end(self, all_patches=False):
1580 """If all_patches is False, return the index of the next pushable patch
1584 """If all_patches is False, return the index of the next pushable patch
1581 in the series, or the series length. If all_patches is True, return the
1585 in the series, or the series length. If all_patches is True, return the
1582 index of the first patch past the last applied one.
1586 index of the first patch past the last applied one.
1583 """
1587 """
1584 end = 0
1588 end = 0
1585 def next(start):
1589 def next(start):
1586 if all_patches or start >= len(self.series):
1590 if all_patches or start >= len(self.series):
1587 return start
1591 return start
1588 for i in xrange(start, len(self.series)):
1592 for i in xrange(start, len(self.series)):
1589 p, reason = self.pushable(i)
1593 p, reason = self.pushable(i)
1590 if p:
1594 if p:
1591 break
1595 break
1592 self.explain_pushable(i)
1596 self.explain_pushable(i)
1593 return i
1597 return i
1594 if self.applied:
1598 if self.applied:
1595 p = self.applied[-1].name
1599 p = self.applied[-1].name
1596 try:
1600 try:
1597 end = self.series.index(p)
1601 end = self.series.index(p)
1598 except ValueError:
1602 except ValueError:
1599 return 0
1603 return 0
1600 return next(end + 1)
1604 return next(end + 1)
1601 return next(end)
1605 return next(end)
1602
1606
1603 def appliedname(self, index):
1607 def appliedname(self, index):
1604 pname = self.applied[index].name
1608 pname = self.applied[index].name
1605 if not self.ui.verbose:
1609 if not self.ui.verbose:
1606 p = pname
1610 p = pname
1607 else:
1611 else:
1608 p = str(self.series.index(pname)) + " " + pname
1612 p = str(self.series.index(pname)) + " " + pname
1609 return p
1613 return p
1610
1614
1611 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1615 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1612 force=None, git=False):
1616 force=None, git=False):
1613 def checkseries(patchname):
1617 def checkseries(patchname):
1614 if patchname in self.series:
1618 if patchname in self.series:
1615 raise util.Abort(_('patch %s is already in the series file')
1619 raise util.Abort(_('patch %s is already in the series file')
1616 % patchname)
1620 % patchname)
1617 def checkfile(patchname):
1621 def checkfile(patchname):
1618 if not force and os.path.exists(self.join(patchname)):
1622 if not force and os.path.exists(self.join(patchname)):
1619 raise util.Abort(_('patch "%s" already exists')
1623 raise util.Abort(_('patch "%s" already exists')
1620 % patchname)
1624 % patchname)
1621
1625
1622 if rev:
1626 if rev:
1623 if files:
1627 if files:
1624 raise util.Abort(_('option "-r" not valid when importing '
1628 raise util.Abort(_('option "-r" not valid when importing '
1625 'files'))
1629 'files'))
1626 rev = cmdutil.revrange(repo, rev)
1630 rev = cmdutil.revrange(repo, rev)
1627 rev.sort(reverse=True)
1631 rev.sort(reverse=True)
1628 if (len(files) > 1 or len(rev) > 1) and patchname:
1632 if (len(files) > 1 or len(rev) > 1) and patchname:
1629 raise util.Abort(_('option "-n" not valid when importing multiple '
1633 raise util.Abort(_('option "-n" not valid when importing multiple '
1630 'patches'))
1634 'patches'))
1631 if rev:
1635 if rev:
1632 # If mq patches are applied, we can only import revisions
1636 # If mq patches are applied, we can only import revisions
1633 # that form a linear path to qbase.
1637 # that form a linear path to qbase.
1634 # Otherwise, they should form a linear path to a head.
1638 # Otherwise, they should form a linear path to a head.
1635 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1639 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1636 if len(heads) > 1:
1640 if len(heads) > 1:
1637 raise util.Abort(_('revision %d is the root of more than one '
1641 raise util.Abort(_('revision %d is the root of more than one '
1638 'branch') % rev[-1])
1642 'branch') % rev[-1])
1639 if self.applied:
1643 if self.applied:
1640 base = repo.changelog.node(rev[0])
1644 base = repo.changelog.node(rev[0])
1641 if base in [n.node for n in self.applied]:
1645 if base in [n.node for n in self.applied]:
1642 raise util.Abort(_('revision %d is already managed')
1646 raise util.Abort(_('revision %d is already managed')
1643 % rev[0])
1647 % rev[0])
1644 if heads != [self.applied[-1].node]:
1648 if heads != [self.applied[-1].node]:
1645 raise util.Abort(_('revision %d is not the parent of '
1649 raise util.Abort(_('revision %d is not the parent of '
1646 'the queue') % rev[0])
1650 'the queue') % rev[0])
1647 base = repo.changelog.rev(self.applied[0].node)
1651 base = repo.changelog.rev(self.applied[0].node)
1648 lastparent = repo.changelog.parentrevs(base)[0]
1652 lastparent = repo.changelog.parentrevs(base)[0]
1649 else:
1653 else:
1650 if heads != [repo.changelog.node(rev[0])]:
1654 if heads != [repo.changelog.node(rev[0])]:
1651 raise util.Abort(_('revision %d has unmanaged children')
1655 raise util.Abort(_('revision %d has unmanaged children')
1652 % rev[0])
1656 % rev[0])
1653 lastparent = None
1657 lastparent = None
1654
1658
1655 diffopts = self.diffopts({'git': git})
1659 diffopts = self.diffopts({'git': git})
1656 for r in rev:
1660 for r in rev:
1657 p1, p2 = repo.changelog.parentrevs(r)
1661 p1, p2 = repo.changelog.parentrevs(r)
1658 n = repo.changelog.node(r)
1662 n = repo.changelog.node(r)
1659 if p2 != nullrev:
1663 if p2 != nullrev:
1660 raise util.Abort(_('cannot import merge revision %d') % r)
1664 raise util.Abort(_('cannot import merge revision %d') % r)
1661 if lastparent and lastparent != r:
1665 if lastparent and lastparent != r:
1662 raise util.Abort(_('revision %d is not the parent of %d')
1666 raise util.Abort(_('revision %d is not the parent of %d')
1663 % (r, lastparent))
1667 % (r, lastparent))
1664 lastparent = p1
1668 lastparent = p1
1665
1669
1666 if not patchname:
1670 if not patchname:
1667 patchname = normname('%d.diff' % r)
1671 patchname = normname('%d.diff' % r)
1668 self.check_reserved_name(patchname)
1672 self.check_reserved_name(patchname)
1669 checkseries(patchname)
1673 checkseries(patchname)
1670 checkfile(patchname)
1674 checkfile(patchname)
1671 self.full_series.insert(0, patchname)
1675 self.full_series.insert(0, patchname)
1672
1676
1673 patchf = self.opener(patchname, "w")
1677 patchf = self.opener(patchname, "w")
1674 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1678 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1675 patchf.close()
1679 patchf.close()
1676
1680
1677 se = statusentry(n, patchname)
1681 se = statusentry(n, patchname)
1678 self.applied.insert(0, se)
1682 self.applied.insert(0, se)
1679
1683
1680 self.added.append(patchname)
1684 self.added.append(patchname)
1681 patchname = None
1685 patchname = None
1682 self.parse_series()
1686 self.parse_series()
1683 self.applied_dirty = 1
1687 self.applied_dirty = 1
1684 self.series_dirty = True
1688 self.series_dirty = True
1685
1689
1686 for i, filename in enumerate(files):
1690 for i, filename in enumerate(files):
1687 if existing:
1691 if existing:
1688 if filename == '-':
1692 if filename == '-':
1689 raise util.Abort(_('-e is incompatible with import from -'))
1693 raise util.Abort(_('-e is incompatible with import from -'))
1690 if not patchname:
1694 if not patchname:
1691 patchname = normname(filename)
1695 patchname = normname(filename)
1692 self.check_reserved_name(patchname)
1696 self.check_reserved_name(patchname)
1693 if not os.path.isfile(self.join(patchname)):
1697 if not os.path.isfile(self.join(patchname)):
1694 raise util.Abort(_("patch %s does not exist") % patchname)
1698 raise util.Abort(_("patch %s does not exist") % patchname)
1695 else:
1699 else:
1696 try:
1700 try:
1697 if filename == '-':
1701 if filename == '-':
1698 if not patchname:
1702 if not patchname:
1699 raise util.Abort(
1703 raise util.Abort(
1700 _('need --name to import a patch from -'))
1704 _('need --name to import a patch from -'))
1701 text = sys.stdin.read()
1705 text = sys.stdin.read()
1702 else:
1706 else:
1703 text = url.open(self.ui, filename).read()
1707 text = url.open(self.ui, filename).read()
1704 except (OSError, IOError):
1708 except (OSError, IOError):
1705 raise util.Abort(_("unable to read %s") % filename)
1709 raise util.Abort(_("unable to read file %s") % filename)
1706 if not patchname:
1710 if not patchname:
1707 patchname = normname(os.path.basename(filename))
1711 patchname = normname(os.path.basename(filename))
1708 self.check_reserved_name(patchname)
1712 self.check_reserved_name(patchname)
1709 checkfile(patchname)
1713 checkfile(patchname)
1710 patchf = self.opener(patchname, "w")
1714 patchf = self.opener(patchname, "w")
1711 patchf.write(text)
1715 patchf.write(text)
1712 if not force:
1716 if not force:
1713 checkseries(patchname)
1717 checkseries(patchname)
1714 if patchname not in self.series:
1718 if patchname not in self.series:
1715 index = self.full_series_end() + i
1719 index = self.full_series_end() + i
1716 self.full_series[index:index] = [patchname]
1720 self.full_series[index:index] = [patchname]
1717 self.parse_series()
1721 self.parse_series()
1718 self.series_dirty = True
1722 self.series_dirty = True
1719 self.ui.warn(_("adding %s to series file\n") % patchname)
1723 self.ui.warn(_("adding %s to series file\n") % patchname)
1720 self.added.append(patchname)
1724 self.added.append(patchname)
1721 patchname = None
1725 patchname = None
1722
1726
1723 def delete(ui, repo, *patches, **opts):
1727 def delete(ui, repo, *patches, **opts):
1724 """remove patches from queue
1728 """remove patches from queue
1725
1729
1726 The patches must not be applied, and at least one patch is required. With
1730 The patches must not be applied, and at least one patch is required. With
1727 -k/--keep, the patch files are preserved in the patch directory.
1731 -k/--keep, the patch files are preserved in the patch directory.
1728
1732
1729 To stop managing a patch and move it into permanent history,
1733 To stop managing a patch and move it into permanent history,
1730 use the :hg:`qfinish` command."""
1734 use the :hg:`qfinish` command."""
1731 q = repo.mq
1735 q = repo.mq
1732 q.delete(repo, patches, opts)
1736 q.delete(repo, patches, opts)
1733 q.save_dirty()
1737 q.save_dirty()
1734 return 0
1738 return 0
1735
1739
1736 def applied(ui, repo, patch=None, **opts):
1740 def applied(ui, repo, patch=None, **opts):
1737 """print the patches already applied"""
1741 """print the patches already applied"""
1738
1742
1739 q = repo.mq
1743 q = repo.mq
1740 l = len(q.applied)
1744 l = len(q.applied)
1741
1745
1742 if patch:
1746 if patch:
1743 if patch not in q.series:
1747 if patch not in q.series:
1744 raise util.Abort(_("patch %s is not in series file") % patch)
1748 raise util.Abort(_("patch %s is not in series file") % patch)
1745 end = q.series.index(patch) + 1
1749 end = q.series.index(patch) + 1
1746 else:
1750 else:
1747 end = q.series_end(True)
1751 end = q.series_end(True)
1748
1752
1749 if opts.get('last') and not end:
1753 if opts.get('last') and not end:
1750 ui.write(_("no patches applied\n"))
1754 ui.write(_("no patches applied\n"))
1751 return 1
1755 return 1
1752 elif opts.get('last') and end == 1:
1756 elif opts.get('last') and end == 1:
1753 ui.write(_("only one patch applied\n"))
1757 ui.write(_("only one patch applied\n"))
1754 return 1
1758 return 1
1755 elif opts.get('last'):
1759 elif opts.get('last'):
1756 start = end - 2
1760 start = end - 2
1757 end = 1
1761 end = 1
1758 else:
1762 else:
1759 start = 0
1763 start = 0
1760
1764
1761 return q.qseries(repo, length=end, start=start, status='A',
1765 return q.qseries(repo, length=end, start=start, status='A',
1762 summary=opts.get('summary'))
1766 summary=opts.get('summary'))
1763
1767
1764 def unapplied(ui, repo, patch=None, **opts):
1768 def unapplied(ui, repo, patch=None, **opts):
1765 """print the patches not yet applied"""
1769 """print the patches not yet applied"""
1766
1770
1767 q = repo.mq
1771 q = repo.mq
1768 if patch:
1772 if patch:
1769 if patch not in q.series:
1773 if patch not in q.series:
1770 raise util.Abort(_("patch %s is not in series file") % patch)
1774 raise util.Abort(_("patch %s is not in series file") % patch)
1771 start = q.series.index(patch) + 1
1775 start = q.series.index(patch) + 1
1772 else:
1776 else:
1773 start = q.series_end(True)
1777 start = q.series_end(True)
1774
1778
1775 if start == len(q.series) and opts.get('first'):
1779 if start == len(q.series) and opts.get('first'):
1776 ui.write(_("all patches applied\n"))
1780 ui.write(_("all patches applied\n"))
1777 return 1
1781 return 1
1778
1782
1779 length = opts.get('first') and 1 or None
1783 length = opts.get('first') and 1 or None
1780 return q.qseries(repo, start=start, length=length, status='U',
1784 return q.qseries(repo, start=start, length=length, status='U',
1781 summary=opts.get('summary'))
1785 summary=opts.get('summary'))
1782
1786
1783 def qimport(ui, repo, *filename, **opts):
1787 def qimport(ui, repo, *filename, **opts):
1784 """import a patch
1788 """import a patch
1785
1789
1786 The patch is inserted into the series after the last applied
1790 The patch is inserted into the series after the last applied
1787 patch. If no patches have been applied, qimport prepends the patch
1791 patch. If no patches have been applied, qimport prepends the patch
1788 to the series.
1792 to the series.
1789
1793
1790 The patch will have the same name as its source file unless you
1794 The patch will have the same name as its source file unless you
1791 give it a new one with -n/--name.
1795 give it a new one with -n/--name.
1792
1796
1793 You can register an existing patch inside the patch directory with
1797 You can register an existing patch inside the patch directory with
1794 the -e/--existing flag.
1798 the -e/--existing flag.
1795
1799
1796 With -f/--force, an existing patch of the same name will be
1800 With -f/--force, an existing patch of the same name will be
1797 overwritten.
1801 overwritten.
1798
1802
1799 An existing changeset may be placed under mq control with -r/--rev
1803 An existing changeset may be placed under mq control with -r/--rev
1800 (e.g. qimport --rev tip -n patch will place tip under mq control).
1804 (e.g. qimport --rev tip -n patch will place tip under mq control).
1801 With -g/--git, patches imported with --rev will use the git diff
1805 With -g/--git, patches imported with --rev will use the git diff
1802 format. See the diffs help topic for information on why this is
1806 format. See the diffs help topic for information on why this is
1803 important for preserving rename/copy information and permission
1807 important for preserving rename/copy information and permission
1804 changes.
1808 changes.
1805
1809
1806 To import a patch from standard input, pass - as the patch file.
1810 To import a patch from standard input, pass - as the patch file.
1807 When importing from standard input, a patch name must be specified
1811 When importing from standard input, a patch name must be specified
1808 using the --name flag.
1812 using the --name flag.
1809 """
1813 """
1810 q = repo.mq
1814 q = repo.mq
1811 try:
1815 try:
1812 q.qimport(repo, filename, patchname=opts['name'],
1816 q.qimport(repo, filename, patchname=opts['name'],
1813 existing=opts['existing'], force=opts['force'], rev=opts['rev'],
1817 existing=opts['existing'], force=opts['force'], rev=opts['rev'],
1814 git=opts['git'])
1818 git=opts['git'])
1815 finally:
1819 finally:
1816 q.save_dirty()
1820 q.save_dirty()
1817
1821
1818 if opts.get('push') and not opts.get('rev'):
1822 if opts.get('push') and not opts.get('rev'):
1819 return q.push(repo, None)
1823 return q.push(repo, None)
1820 return 0
1824 return 0
1821
1825
1822 def qinit(ui, repo, create):
1826 def qinit(ui, repo, create):
1823 """initialize a new queue repository
1827 """initialize a new queue repository
1824
1828
1825 This command also creates a series file for ordering patches, and
1829 This command also creates a series file for ordering patches, and
1826 an mq-specific .hgignore file in the queue repository, to exclude
1830 an mq-specific .hgignore file in the queue repository, to exclude
1827 the status and guards files (these contain mostly transient state)."""
1831 the status and guards files (these contain mostly transient state)."""
1828 q = repo.mq
1832 q = repo.mq
1829 r = q.init(repo, create)
1833 r = q.init(repo, create)
1830 q.save_dirty()
1834 q.save_dirty()
1831 if r:
1835 if r:
1832 if not os.path.exists(r.wjoin('.hgignore')):
1836 if not os.path.exists(r.wjoin('.hgignore')):
1833 fp = r.wopener('.hgignore', 'w')
1837 fp = r.wopener('.hgignore', 'w')
1834 fp.write('^\\.hg\n')
1838 fp.write('^\\.hg\n')
1835 fp.write('^\\.mq\n')
1839 fp.write('^\\.mq\n')
1836 fp.write('syntax: glob\n')
1840 fp.write('syntax: glob\n')
1837 fp.write('status\n')
1841 fp.write('status\n')
1838 fp.write('guards\n')
1842 fp.write('guards\n')
1839 fp.close()
1843 fp.close()
1840 if not os.path.exists(r.wjoin('series')):
1844 if not os.path.exists(r.wjoin('series')):
1841 r.wopener('series', 'w').close()
1845 r.wopener('series', 'w').close()
1842 r[None].add(['.hgignore', 'series'])
1846 r[None].add(['.hgignore', 'series'])
1843 commands.add(ui, r)
1847 commands.add(ui, r)
1844 return 0
1848 return 0
1845
1849
1846 def init(ui, repo, **opts):
1850 def init(ui, repo, **opts):
1847 """init a new queue repository (DEPRECATED)
1851 """init a new queue repository (DEPRECATED)
1848
1852
1849 The queue repository is unversioned by default. If
1853 The queue repository is unversioned by default. If
1850 -c/--create-repo is specified, qinit will create a separate nested
1854 -c/--create-repo is specified, qinit will create a separate nested
1851 repository for patches (qinit -c may also be run later to convert
1855 repository for patches (qinit -c may also be run later to convert
1852 an unversioned patch repository into a versioned one). You can use
1856 an unversioned patch repository into a versioned one). You can use
1853 qcommit to commit changes to this queue repository.
1857 qcommit to commit changes to this queue repository.
1854
1858
1855 This command is deprecated. Without -c, it's implied by other relevant
1859 This command is deprecated. Without -c, it's implied by other relevant
1856 commands. With -c, use :hg:`init --mq` instead."""
1860 commands. With -c, use :hg:`init --mq` instead."""
1857 return qinit(ui, repo, create=opts['create_repo'])
1861 return qinit(ui, repo, create=opts['create_repo'])
1858
1862
1859 def clone(ui, source, dest=None, **opts):
1863 def clone(ui, source, dest=None, **opts):
1860 '''clone main and patch repository at same time
1864 '''clone main and patch repository at same time
1861
1865
1862 If source is local, destination will have no patches applied. If
1866 If source is local, destination will have no patches applied. If
1863 source is remote, this command can not check if patches are
1867 source is remote, this command can not check if patches are
1864 applied in source, so cannot guarantee that patches are not
1868 applied in source, so cannot guarantee that patches are not
1865 applied in destination. If you clone remote repository, be sure
1869 applied in destination. If you clone remote repository, be sure
1866 before that it has no patches applied.
1870 before that it has no patches applied.
1867
1871
1868 Source patch repository is looked for in <src>/.hg/patches by
1872 Source patch repository is looked for in <src>/.hg/patches by
1869 default. Use -p <url> to change.
1873 default. Use -p <url> to change.
1870
1874
1871 The patch directory must be a nested Mercurial repository, as
1875 The patch directory must be a nested Mercurial repository, as
1872 would be created by :hg:`init --mq`.
1876 would be created by :hg:`init --mq`.
1873 '''
1877 '''
1874 def patchdir(repo):
1878 def patchdir(repo):
1875 url = repo.url()
1879 url = repo.url()
1876 if url.endswith('/'):
1880 if url.endswith('/'):
1877 url = url[:-1]
1881 url = url[:-1]
1878 return url + '/.hg/patches'
1882 return url + '/.hg/patches'
1879 if dest is None:
1883 if dest is None:
1880 dest = hg.defaultdest(source)
1884 dest = hg.defaultdest(source)
1881 sr = hg.repository(hg.remoteui(ui, opts), ui.expandpath(source))
1885 sr = hg.repository(hg.remoteui(ui, opts), ui.expandpath(source))
1882 if opts['patches']:
1886 if opts['patches']:
1883 patchespath = ui.expandpath(opts['patches'])
1887 patchespath = ui.expandpath(opts['patches'])
1884 else:
1888 else:
1885 patchespath = patchdir(sr)
1889 patchespath = patchdir(sr)
1886 try:
1890 try:
1887 hg.repository(ui, patchespath)
1891 hg.repository(ui, patchespath)
1888 except error.RepoError:
1892 except error.RepoError:
1889 raise util.Abort(_('versioned patch repository not found'
1893 raise util.Abort(_('versioned patch repository not found'
1890 ' (see init --mq)'))
1894 ' (see init --mq)'))
1891 qbase, destrev = None, None
1895 qbase, destrev = None, None
1892 if sr.local():
1896 if sr.local():
1893 if sr.mq.applied:
1897 if sr.mq.applied:
1894 qbase = sr.mq.applied[0].node
1898 qbase = sr.mq.applied[0].node
1895 if not hg.islocal(dest):
1899 if not hg.islocal(dest):
1896 heads = set(sr.heads())
1900 heads = set(sr.heads())
1897 destrev = list(heads.difference(sr.heads(qbase)))
1901 destrev = list(heads.difference(sr.heads(qbase)))
1898 destrev.append(sr.changelog.parents(qbase)[0])
1902 destrev.append(sr.changelog.parents(qbase)[0])
1899 elif sr.capable('lookup'):
1903 elif sr.capable('lookup'):
1900 try:
1904 try:
1901 qbase = sr.lookup('qbase')
1905 qbase = sr.lookup('qbase')
1902 except error.RepoError:
1906 except error.RepoError:
1903 pass
1907 pass
1904 ui.note(_('cloning main repository\n'))
1908 ui.note(_('cloning main repository\n'))
1905 sr, dr = hg.clone(ui, sr.url(), dest,
1909 sr, dr = hg.clone(ui, sr.url(), dest,
1906 pull=opts['pull'],
1910 pull=opts['pull'],
1907 rev=destrev,
1911 rev=destrev,
1908 update=False,
1912 update=False,
1909 stream=opts['uncompressed'])
1913 stream=opts['uncompressed'])
1910 ui.note(_('cloning patch repository\n'))
1914 ui.note(_('cloning patch repository\n'))
1911 hg.clone(ui, opts['patches'] or patchdir(sr), patchdir(dr),
1915 hg.clone(ui, opts['patches'] or patchdir(sr), patchdir(dr),
1912 pull=opts['pull'], update=not opts['noupdate'],
1916 pull=opts['pull'], update=not opts['noupdate'],
1913 stream=opts['uncompressed'])
1917 stream=opts['uncompressed'])
1914 if dr.local():
1918 if dr.local():
1915 if qbase:
1919 if qbase:
1916 ui.note(_('stripping applied patches from destination '
1920 ui.note(_('stripping applied patches from destination '
1917 'repository\n'))
1921 'repository\n'))
1918 dr.mq.strip(dr, qbase, update=False, backup=None)
1922 dr.mq.strip(dr, qbase, update=False, backup=None)
1919 if not opts['noupdate']:
1923 if not opts['noupdate']:
1920 ui.note(_('updating destination repository\n'))
1924 ui.note(_('updating destination repository\n'))
1921 hg.update(dr, dr.changelog.tip())
1925 hg.update(dr, dr.changelog.tip())
1922
1926
1923 def commit(ui, repo, *pats, **opts):
1927 def commit(ui, repo, *pats, **opts):
1924 """commit changes in the queue repository (DEPRECATED)
1928 """commit changes in the queue repository (DEPRECATED)
1925
1929
1926 This command is deprecated; use :hg:`commit --mq` instead."""
1930 This command is deprecated; use :hg:`commit --mq` instead."""
1927 q = repo.mq
1931 q = repo.mq
1928 r = q.qrepo()
1932 r = q.qrepo()
1929 if not r:
1933 if not r:
1930 raise util.Abort('no queue repository')
1934 raise util.Abort('no queue repository')
1931 commands.commit(r.ui, r, *pats, **opts)
1935 commands.commit(r.ui, r, *pats, **opts)
1932
1936
1933 def series(ui, repo, **opts):
1937 def series(ui, repo, **opts):
1934 """print the entire series file"""
1938 """print the entire series file"""
1935 repo.mq.qseries(repo, missing=opts['missing'], summary=opts['summary'])
1939 repo.mq.qseries(repo, missing=opts['missing'], summary=opts['summary'])
1936 return 0
1940 return 0
1937
1941
1938 def top(ui, repo, **opts):
1942 def top(ui, repo, **opts):
1939 """print the name of the current patch"""
1943 """print the name of the current patch"""
1940 q = repo.mq
1944 q = repo.mq
1941 t = q.applied and q.series_end(True) or 0
1945 t = q.applied and q.series_end(True) or 0
1942 if t:
1946 if t:
1943 return q.qseries(repo, start=t - 1, length=1, status='A',
1947 return q.qseries(repo, start=t - 1, length=1, status='A',
1944 summary=opts.get('summary'))
1948 summary=opts.get('summary'))
1945 else:
1949 else:
1946 ui.write(_("no patches applied\n"))
1950 ui.write(_("no patches applied\n"))
1947 return 1
1951 return 1
1948
1952
1949 def next(ui, repo, **opts):
1953 def next(ui, repo, **opts):
1950 """print the name of the next patch"""
1954 """print the name of the next patch"""
1951 q = repo.mq
1955 q = repo.mq
1952 end = q.series_end()
1956 end = q.series_end()
1953 if end == len(q.series):
1957 if end == len(q.series):
1954 ui.write(_("all patches applied\n"))
1958 ui.write(_("all patches applied\n"))
1955 return 1
1959 return 1
1956 return q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
1960 return q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
1957
1961
1958 def prev(ui, repo, **opts):
1962 def prev(ui, repo, **opts):
1959 """print the name of the previous patch"""
1963 """print the name of the previous patch"""
1960 q = repo.mq
1964 q = repo.mq
1961 l = len(q.applied)
1965 l = len(q.applied)
1962 if l == 1:
1966 if l == 1:
1963 ui.write(_("only one patch applied\n"))
1967 ui.write(_("only one patch applied\n"))
1964 return 1
1968 return 1
1965 if not l:
1969 if not l:
1966 ui.write(_("no patches applied\n"))
1970 ui.write(_("no patches applied\n"))
1967 return 1
1971 return 1
1968 return q.qseries(repo, start=l - 2, length=1, status='A',
1972 return q.qseries(repo, start=l - 2, length=1, status='A',
1969 summary=opts.get('summary'))
1973 summary=opts.get('summary'))
1970
1974
1971 def setupheaderopts(ui, opts):
1975 def setupheaderopts(ui, opts):
1972 if not opts.get('user') and opts.get('currentuser'):
1976 if not opts.get('user') and opts.get('currentuser'):
1973 opts['user'] = ui.username()
1977 opts['user'] = ui.username()
1974 if not opts.get('date') and opts.get('currentdate'):
1978 if not opts.get('date') and opts.get('currentdate'):
1975 opts['date'] = "%d %d" % util.makedate()
1979 opts['date'] = "%d %d" % util.makedate()
1976
1980
1977 def new(ui, repo, patch, *args, **opts):
1981 def new(ui, repo, patch, *args, **opts):
1978 """create a new patch
1982 """create a new patch
1979
1983
1980 qnew creates a new patch on top of the currently-applied patch (if
1984 qnew creates a new patch on top of the currently-applied patch (if
1981 any). The patch will be initialized with any outstanding changes
1985 any). The patch will be initialized with any outstanding changes
1982 in the working directory. You may also use -I/--include,
1986 in the working directory. You may also use -I/--include,
1983 -X/--exclude, and/or a list of files after the patch name to add
1987 -X/--exclude, and/or a list of files after the patch name to add
1984 only changes to matching files to the new patch, leaving the rest
1988 only changes to matching files to the new patch, leaving the rest
1985 as uncommitted modifications.
1989 as uncommitted modifications.
1986
1990
1987 -u/--user and -d/--date can be used to set the (given) user and
1991 -u/--user and -d/--date can be used to set the (given) user and
1988 date, respectively. -U/--currentuser and -D/--currentdate set user
1992 date, respectively. -U/--currentuser and -D/--currentdate set user
1989 to current user and date to current date.
1993 to current user and date to current date.
1990
1994
1991 -e/--edit, -m/--message or -l/--logfile set the patch header as
1995 -e/--edit, -m/--message or -l/--logfile set the patch header as
1992 well as the commit message. If none is specified, the header is
1996 well as the commit message. If none is specified, the header is
1993 empty and the commit message is '[mq]: PATCH'.
1997 empty and the commit message is '[mq]: PATCH'.
1994
1998
1995 Use the -g/--git option to keep the patch in the git extended diff
1999 Use the -g/--git option to keep the patch in the git extended diff
1996 format. Read the diffs help topic for more information on why this
2000 format. Read the diffs help topic for more information on why this
1997 is important for preserving permission changes and copy/rename
2001 is important for preserving permission changes and copy/rename
1998 information.
2002 information.
1999 """
2003 """
2000 msg = cmdutil.logmessage(opts)
2004 msg = cmdutil.logmessage(opts)
2001 def getmsg():
2005 def getmsg():
2002 return ui.edit(msg, ui.username())
2006 return ui.edit(msg, ui.username())
2003 q = repo.mq
2007 q = repo.mq
2004 opts['msg'] = msg
2008 opts['msg'] = msg
2005 if opts.get('edit'):
2009 if opts.get('edit'):
2006 opts['msg'] = getmsg
2010 opts['msg'] = getmsg
2007 else:
2011 else:
2008 opts['msg'] = msg
2012 opts['msg'] = msg
2009 setupheaderopts(ui, opts)
2013 setupheaderopts(ui, opts)
2010 q.new(repo, patch, *args, **opts)
2014 q.new(repo, patch, *args, **opts)
2011 q.save_dirty()
2015 q.save_dirty()
2012 return 0
2016 return 0
2013
2017
2014 def refresh(ui, repo, *pats, **opts):
2018 def refresh(ui, repo, *pats, **opts):
2015 """update the current patch
2019 """update the current patch
2016
2020
2017 If any file patterns are provided, the refreshed patch will
2021 If any file patterns are provided, the refreshed patch will
2018 contain only the modifications that match those patterns; the
2022 contain only the modifications that match those patterns; the
2019 remaining modifications will remain in the working directory.
2023 remaining modifications will remain in the working directory.
2020
2024
2021 If -s/--short is specified, files currently included in the patch
2025 If -s/--short is specified, files currently included in the patch
2022 will be refreshed just like matched files and remain in the patch.
2026 will be refreshed just like matched files and remain in the patch.
2023
2027
2024 hg add/remove/copy/rename work as usual, though you might want to
2028 hg add/remove/copy/rename work as usual, though you might want to
2025 use git-style patches (-g/--git or [diff] git=1) to track copies
2029 use git-style patches (-g/--git or [diff] git=1) to track copies
2026 and renames. See the diffs help topic for more information on the
2030 and renames. See the diffs help topic for more information on the
2027 git diff format.
2031 git diff format.
2028 """
2032 """
2029 q = repo.mq
2033 q = repo.mq
2030 message = cmdutil.logmessage(opts)
2034 message = cmdutil.logmessage(opts)
2031 if opts['edit']:
2035 if opts['edit']:
2032 if not q.applied:
2036 if not q.applied:
2033 ui.write(_("no patches applied\n"))
2037 ui.write(_("no patches applied\n"))
2034 return 1
2038 return 1
2035 if message:
2039 if message:
2036 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2040 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2037 patch = q.applied[-1].name
2041 patch = q.applied[-1].name
2038 ph = patchheader(q.join(patch), q.plainmode)
2042 ph = patchheader(q.join(patch), q.plainmode)
2039 message = ui.edit('\n'.join(ph.message), ph.user or ui.username())
2043 message = ui.edit('\n'.join(ph.message), ph.user or ui.username())
2040 setupheaderopts(ui, opts)
2044 setupheaderopts(ui, opts)
2041 ret = q.refresh(repo, pats, msg=message, **opts)
2045 ret = q.refresh(repo, pats, msg=message, **opts)
2042 q.save_dirty()
2046 q.save_dirty()
2043 return ret
2047 return ret
2044
2048
2045 def diff(ui, repo, *pats, **opts):
2049 def diff(ui, repo, *pats, **opts):
2046 """diff of the current patch and subsequent modifications
2050 """diff of the current patch and subsequent modifications
2047
2051
2048 Shows a diff which includes the current patch as well as any
2052 Shows a diff which includes the current patch as well as any
2049 changes which have been made in the working directory since the
2053 changes which have been made in the working directory since the
2050 last refresh (thus showing what the current patch would become
2054 last refresh (thus showing what the current patch would become
2051 after a qrefresh).
2055 after a qrefresh).
2052
2056
2053 Use :hg:`diff` if you only want to see the changes made since the
2057 Use :hg:`diff` if you only want to see the changes made since the
2054 last qrefresh, or :hg:`export qtip` if you want to see changes
2058 last qrefresh, or :hg:`export qtip` if you want to see changes
2055 made by the current patch without including changes made since the
2059 made by the current patch without including changes made since the
2056 qrefresh.
2060 qrefresh.
2057 """
2061 """
2058 repo.mq.diff(repo, pats, opts)
2062 repo.mq.diff(repo, pats, opts)
2059 return 0
2063 return 0
2060
2064
2061 def fold(ui, repo, *files, **opts):
2065 def fold(ui, repo, *files, **opts):
2062 """fold the named patches into the current patch
2066 """fold the named patches into the current patch
2063
2067
2064 Patches must not yet be applied. Each patch will be successively
2068 Patches must not yet be applied. Each patch will be successively
2065 applied to the current patch in the order given. If all the
2069 applied to the current patch in the order given. If all the
2066 patches apply successfully, the current patch will be refreshed
2070 patches apply successfully, the current patch will be refreshed
2067 with the new cumulative patch, and the folded patches will be
2071 with the new cumulative patch, and the folded patches will be
2068 deleted. With -k/--keep, the folded patch files will not be
2072 deleted. With -k/--keep, the folded patch files will not be
2069 removed afterwards.
2073 removed afterwards.
2070
2074
2071 The header for each folded patch will be concatenated with the
2075 The header for each folded patch will be concatenated with the
2072 current patch header, separated by a line of '* * *'."""
2076 current patch header, separated by a line of '* * *'."""
2073
2077
2074 q = repo.mq
2078 q = repo.mq
2075
2079
2076 if not files:
2080 if not files:
2077 raise util.Abort(_('qfold requires at least one patch name'))
2081 raise util.Abort(_('qfold requires at least one patch name'))
2078 if not q.check_toppatch(repo)[0]:
2082 if not q.check_toppatch(repo)[0]:
2079 raise util.Abort(_('No patches applied'))
2083 raise util.Abort(_('No patches applied'))
2080 q.check_localchanges(repo)
2084 q.check_localchanges(repo)
2081
2085
2082 message = cmdutil.logmessage(opts)
2086 message = cmdutil.logmessage(opts)
2083 if opts['edit']:
2087 if opts['edit']:
2084 if message:
2088 if message:
2085 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2089 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2086
2090
2087 parent = q.lookup('qtip')
2091 parent = q.lookup('qtip')
2088 patches = []
2092 patches = []
2089 messages = []
2093 messages = []
2090 for f in files:
2094 for f in files:
2091 p = q.lookup(f)
2095 p = q.lookup(f)
2092 if p in patches or p == parent:
2096 if p in patches or p == parent:
2093 ui.warn(_('Skipping already folded patch %s') % p)
2097 ui.warn(_('Skipping already folded patch %s') % p)
2094 if q.isapplied(p):
2098 if q.isapplied(p):
2095 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
2099 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
2096 patches.append(p)
2100 patches.append(p)
2097
2101
2098 for p in patches:
2102 for p in patches:
2099 if not message:
2103 if not message:
2100 ph = patchheader(q.join(p), q.plainmode)
2104 ph = patchheader(q.join(p), q.plainmode)
2101 if ph.message:
2105 if ph.message:
2102 messages.append(ph.message)
2106 messages.append(ph.message)
2103 pf = q.join(p)
2107 pf = q.join(p)
2104 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2108 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2105 if not patchsuccess:
2109 if not patchsuccess:
2106 raise util.Abort(_('Error folding patch %s') % p)
2110 raise util.Abort(_('Error folding patch %s') % p)
2107 patch.updatedir(ui, repo, files)
2111 patch.updatedir(ui, repo, files)
2108
2112
2109 if not message:
2113 if not message:
2110 ph = patchheader(q.join(parent), q.plainmode)
2114 ph = patchheader(q.join(parent), q.plainmode)
2111 message, user = ph.message, ph.user
2115 message, user = ph.message, ph.user
2112 for msg in messages:
2116 for msg in messages:
2113 message.append('* * *')
2117 message.append('* * *')
2114 message.extend(msg)
2118 message.extend(msg)
2115 message = '\n'.join(message)
2119 message = '\n'.join(message)
2116
2120
2117 if opts['edit']:
2121 if opts['edit']:
2118 message = ui.edit(message, user or ui.username())
2122 message = ui.edit(message, user or ui.username())
2119
2123
2120 diffopts = q.patchopts(q.diffopts(), *patches)
2124 diffopts = q.patchopts(q.diffopts(), *patches)
2121 q.refresh(repo, msg=message, git=diffopts.git)
2125 q.refresh(repo, msg=message, git=diffopts.git)
2122 q.delete(repo, patches, opts)
2126 q.delete(repo, patches, opts)
2123 q.save_dirty()
2127 q.save_dirty()
2124
2128
2125 def goto(ui, repo, patch, **opts):
2129 def goto(ui, repo, patch, **opts):
2126 '''push or pop patches until named patch is at top of stack'''
2130 '''push or pop patches until named patch is at top of stack'''
2127 q = repo.mq
2131 q = repo.mq
2128 patch = q.lookup(patch)
2132 patch = q.lookup(patch)
2129 if q.isapplied(patch):
2133 if q.isapplied(patch):
2130 ret = q.pop(repo, patch, force=opts['force'])
2134 ret = q.pop(repo, patch, force=opts['force'])
2131 else:
2135 else:
2132 ret = q.push(repo, patch, force=opts['force'])
2136 ret = q.push(repo, patch, force=opts['force'])
2133 q.save_dirty()
2137 q.save_dirty()
2134 return ret
2138 return ret
2135
2139
2136 def guard(ui, repo, *args, **opts):
2140 def guard(ui, repo, *args, **opts):
2137 '''set or print guards for a patch
2141 '''set or print guards for a patch
2138
2142
2139 Guards control whether a patch can be pushed. A patch with no
2143 Guards control whether a patch can be pushed. A patch with no
2140 guards is always pushed. A patch with a positive guard ("+foo") is
2144 guards is always pushed. A patch with a positive guard ("+foo") is
2141 pushed only if the :hg:`qselect` command has activated it. A patch with
2145 pushed only if the :hg:`qselect` command has activated it. A patch with
2142 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
2146 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
2143 has activated it.
2147 has activated it.
2144
2148
2145 With no arguments, print the currently active guards.
2149 With no arguments, print the currently active guards.
2146 With arguments, set guards for the named patch.
2150 With arguments, set guards for the named patch.
2147 NOTE: Specifying negative guards now requires '--'.
2151 NOTE: Specifying negative guards now requires '--'.
2148
2152
2149 To set guards on another patch::
2153 To set guards on another patch::
2150
2154
2151 hg qguard other.patch -- +2.6.17 -stable
2155 hg qguard other.patch -- +2.6.17 -stable
2152 '''
2156 '''
2153 def status(idx):
2157 def status(idx):
2154 guards = q.series_guards[idx] or ['unguarded']
2158 guards = q.series_guards[idx] or ['unguarded']
2155 ui.write('%s: ' % ui.label(q.series[idx], 'qguard.patch'))
2159 ui.write('%s: ' % ui.label(q.series[idx], 'qguard.patch'))
2156 for i, guard in enumerate(guards):
2160 for i, guard in enumerate(guards):
2157 if guard.startswith('+'):
2161 if guard.startswith('+'):
2158 ui.write(guard, label='qguard.positive')
2162 ui.write(guard, label='qguard.positive')
2159 elif guard.startswith('-'):
2163 elif guard.startswith('-'):
2160 ui.write(guard, label='qguard.negative')
2164 ui.write(guard, label='qguard.negative')
2161 else:
2165 else:
2162 ui.write(guard, label='qguard.unguarded')
2166 ui.write(guard, label='qguard.unguarded')
2163 if i != len(guards) - 1:
2167 if i != len(guards) - 1:
2164 ui.write(' ')
2168 ui.write(' ')
2165 ui.write('\n')
2169 ui.write('\n')
2166 q = repo.mq
2170 q = repo.mq
2167 patch = None
2171 patch = None
2168 args = list(args)
2172 args = list(args)
2169 if opts['list']:
2173 if opts['list']:
2170 if args or opts['none']:
2174 if args or opts['none']:
2171 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
2175 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
2172 for i in xrange(len(q.series)):
2176 for i in xrange(len(q.series)):
2173 status(i)
2177 status(i)
2174 return
2178 return
2175 if not args or args[0][0:1] in '-+':
2179 if not args or args[0][0:1] in '-+':
2176 if not q.applied:
2180 if not q.applied:
2177 raise util.Abort(_('no patches applied'))
2181 raise util.Abort(_('no patches applied'))
2178 patch = q.applied[-1].name
2182 patch = q.applied[-1].name
2179 if patch is None and args[0][0:1] not in '-+':
2183 if patch is None and args[0][0:1] not in '-+':
2180 patch = args.pop(0)
2184 patch = args.pop(0)
2181 if patch is None:
2185 if patch is None:
2182 raise util.Abort(_('no patch to work with'))
2186 raise util.Abort(_('no patch to work with'))
2183 if args or opts['none']:
2187 if args or opts['none']:
2184 idx = q.find_series(patch)
2188 idx = q.find_series(patch)
2185 if idx is None:
2189 if idx is None:
2186 raise util.Abort(_('no patch named %s') % patch)
2190 raise util.Abort(_('no patch named %s') % patch)
2187 q.set_guards(idx, args)
2191 q.set_guards(idx, args)
2188 q.save_dirty()
2192 q.save_dirty()
2189 else:
2193 else:
2190 status(q.series.index(q.lookup(patch)))
2194 status(q.series.index(q.lookup(patch)))
2191
2195
2192 def header(ui, repo, patch=None):
2196 def header(ui, repo, patch=None):
2193 """print the header of the topmost or specified patch"""
2197 """print the header of the topmost or specified patch"""
2194 q = repo.mq
2198 q = repo.mq
2195
2199
2196 if patch:
2200 if patch:
2197 patch = q.lookup(patch)
2201 patch = q.lookup(patch)
2198 else:
2202 else:
2199 if not q.applied:
2203 if not q.applied:
2200 ui.write(_('no patches applied\n'))
2204 ui.write(_('no patches applied\n'))
2201 return 1
2205 return 1
2202 patch = q.lookup('qtip')
2206 patch = q.lookup('qtip')
2203 ph = patchheader(q.join(patch), q.plainmode)
2207 ph = patchheader(q.join(patch), q.plainmode)
2204
2208
2205 ui.write('\n'.join(ph.message) + '\n')
2209 ui.write('\n'.join(ph.message) + '\n')
2206
2210
2207 def lastsavename(path):
2211 def lastsavename(path):
2208 (directory, base) = os.path.split(path)
2212 (directory, base) = os.path.split(path)
2209 names = os.listdir(directory)
2213 names = os.listdir(directory)
2210 namere = re.compile("%s.([0-9]+)" % base)
2214 namere = re.compile("%s.([0-9]+)" % base)
2211 maxindex = None
2215 maxindex = None
2212 maxname = None
2216 maxname = None
2213 for f in names:
2217 for f in names:
2214 m = namere.match(f)
2218 m = namere.match(f)
2215 if m:
2219 if m:
2216 index = int(m.group(1))
2220 index = int(m.group(1))
2217 if maxindex is None or index > maxindex:
2221 if maxindex is None or index > maxindex:
2218 maxindex = index
2222 maxindex = index
2219 maxname = f
2223 maxname = f
2220 if maxname:
2224 if maxname:
2221 return (os.path.join(directory, maxname), maxindex)
2225 return (os.path.join(directory, maxname), maxindex)
2222 return (None, None)
2226 return (None, None)
2223
2227
2224 def savename(path):
2228 def savename(path):
2225 (last, index) = lastsavename(path)
2229 (last, index) = lastsavename(path)
2226 if last is None:
2230 if last is None:
2227 index = 0
2231 index = 0
2228 newpath = path + ".%d" % (index + 1)
2232 newpath = path + ".%d" % (index + 1)
2229 return newpath
2233 return newpath
2230
2234
2231 def push(ui, repo, patch=None, **opts):
2235 def push(ui, repo, patch=None, **opts):
2232 """push the next patch onto the stack
2236 """push the next patch onto the stack
2233
2237
2234 When -f/--force is applied, all local changes in patched files
2238 When -f/--force is applied, all local changes in patched files
2235 will be lost.
2239 will be lost.
2236 """
2240 """
2237 q = repo.mq
2241 q = repo.mq
2238 mergeq = None
2242 mergeq = None
2239
2243
2240 if opts['merge']:
2244 if opts['merge']:
2241 if opts['name']:
2245 if opts['name']:
2242 newpath = repo.join(opts['name'])
2246 newpath = repo.join(opts['name'])
2243 else:
2247 else:
2244 newpath, i = lastsavename(q.path)
2248 newpath, i = lastsavename(q.path)
2245 if not newpath:
2249 if not newpath:
2246 ui.warn(_("no saved queues found, please use -n\n"))
2250 ui.warn(_("no saved queues found, please use -n\n"))
2247 return 1
2251 return 1
2248 mergeq = queue(ui, repo.join(""), newpath)
2252 mergeq = queue(ui, repo.join(""), newpath)
2249 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2253 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2250 ret = q.push(repo, patch, force=opts['force'], list=opts['list'],
2254 ret = q.push(repo, patch, force=opts['force'], list=opts['list'],
2251 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'))
2255 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'))
2252 return ret
2256 return ret
2253
2257
2254 def pop(ui, repo, patch=None, **opts):
2258 def pop(ui, repo, patch=None, **opts):
2255 """pop the current patch off the stack
2259 """pop the current patch off the stack
2256
2260
2257 By default, pops off the top of the patch stack. If given a patch
2261 By default, pops off the top of the patch stack. If given a patch
2258 name, keeps popping off patches until the named patch is at the
2262 name, keeps popping off patches until the named patch is at the
2259 top of the stack.
2263 top of the stack.
2260 """
2264 """
2261 localupdate = True
2265 localupdate = True
2262 if opts['name']:
2266 if opts['name']:
2263 q = queue(ui, repo.join(""), repo.join(opts['name']))
2267 q = queue(ui, repo.join(""), repo.join(opts['name']))
2264 ui.warn(_('using patch queue: %s\n') % q.path)
2268 ui.warn(_('using patch queue: %s\n') % q.path)
2265 localupdate = False
2269 localupdate = False
2266 else:
2270 else:
2267 q = repo.mq
2271 q = repo.mq
2268 ret = q.pop(repo, patch, force=opts['force'], update=localupdate,
2272 ret = q.pop(repo, patch, force=opts['force'], update=localupdate,
2269 all=opts['all'])
2273 all=opts['all'])
2270 q.save_dirty()
2274 q.save_dirty()
2271 return ret
2275 return ret
2272
2276
2273 def rename(ui, repo, patch, name=None, **opts):
2277 def rename(ui, repo, patch, name=None, **opts):
2274 """rename a patch
2278 """rename a patch
2275
2279
2276 With one argument, renames the current patch to PATCH1.
2280 With one argument, renames the current patch to PATCH1.
2277 With two arguments, renames PATCH1 to PATCH2."""
2281 With two arguments, renames PATCH1 to PATCH2."""
2278
2282
2279 q = repo.mq
2283 q = repo.mq
2280
2284
2281 if not name:
2285 if not name:
2282 name = patch
2286 name = patch
2283 patch = None
2287 patch = None
2284
2288
2285 if patch:
2289 if patch:
2286 patch = q.lookup(patch)
2290 patch = q.lookup(patch)
2287 else:
2291 else:
2288 if not q.applied:
2292 if not q.applied:
2289 ui.write(_('no patches applied\n'))
2293 ui.write(_('no patches applied\n'))
2290 return
2294 return
2291 patch = q.lookup('qtip')
2295 patch = q.lookup('qtip')
2292 absdest = q.join(name)
2296 absdest = q.join(name)
2293 if os.path.isdir(absdest):
2297 if os.path.isdir(absdest):
2294 name = normname(os.path.join(name, os.path.basename(patch)))
2298 name = normname(os.path.join(name, os.path.basename(patch)))
2295 absdest = q.join(name)
2299 absdest = q.join(name)
2296 if os.path.exists(absdest):
2300 if os.path.exists(absdest):
2297 raise util.Abort(_('%s already exists') % absdest)
2301 raise util.Abort(_('%s already exists') % absdest)
2298
2302
2299 if name in q.series:
2303 if name in q.series:
2300 raise util.Abort(
2304 raise util.Abort(
2301 _('A patch named %s already exists in the series file') % name)
2305 _('A patch named %s already exists in the series file') % name)
2302
2306
2303 ui.note(_('renaming %s to %s\n') % (patch, name))
2307 ui.note(_('renaming %s to %s\n') % (patch, name))
2304 i = q.find_series(patch)
2308 i = q.find_series(patch)
2305 guards = q.guard_re.findall(q.full_series[i])
2309 guards = q.guard_re.findall(q.full_series[i])
2306 q.full_series[i] = name + ''.join([' #' + g for g in guards])
2310 q.full_series[i] = name + ''.join([' #' + g for g in guards])
2307 q.parse_series()
2311 q.parse_series()
2308 q.series_dirty = 1
2312 q.series_dirty = 1
2309
2313
2310 info = q.isapplied(patch)
2314 info = q.isapplied(patch)
2311 if info:
2315 if info:
2312 q.applied[info[0]] = statusentry(info[1], name)
2316 q.applied[info[0]] = statusentry(info[1], name)
2313 q.applied_dirty = 1
2317 q.applied_dirty = 1
2314
2318
2315 destdir = os.path.dirname(absdest)
2319 destdir = os.path.dirname(absdest)
2316 if not os.path.isdir(destdir):
2320 if not os.path.isdir(destdir):
2317 os.makedirs(destdir)
2321 os.makedirs(destdir)
2318 util.rename(q.join(patch), absdest)
2322 util.rename(q.join(patch), absdest)
2319 r = q.qrepo()
2323 r = q.qrepo()
2320 if r:
2324 if r:
2321 wctx = r[None]
2325 wctx = r[None]
2322 wlock = r.wlock()
2326 wlock = r.wlock()
2323 try:
2327 try:
2324 if r.dirstate[patch] == 'a':
2328 if r.dirstate[patch] == 'a':
2325 r.dirstate.forget(patch)
2329 r.dirstate.forget(patch)
2326 r.dirstate.add(name)
2330 r.dirstate.add(name)
2327 else:
2331 else:
2328 if r.dirstate[name] == 'r':
2332 if r.dirstate[name] == 'r':
2329 wctx.undelete([name])
2333 wctx.undelete([name])
2330 wctx.copy(patch, name)
2334 wctx.copy(patch, name)
2331 wctx.remove([patch], False)
2335 wctx.remove([patch], False)
2332 finally:
2336 finally:
2333 wlock.release()
2337 wlock.release()
2334
2338
2335 q.save_dirty()
2339 q.save_dirty()
2336
2340
2337 def restore(ui, repo, rev, **opts):
2341 def restore(ui, repo, rev, **opts):
2338 """restore the queue state saved by a revision (DEPRECATED)
2342 """restore the queue state saved by a revision (DEPRECATED)
2339
2343
2340 This command is deprecated, use rebase --mq instead."""
2344 This command is deprecated, use rebase --mq instead."""
2341 rev = repo.lookup(rev)
2345 rev = repo.lookup(rev)
2342 q = repo.mq
2346 q = repo.mq
2343 q.restore(repo, rev, delete=opts['delete'],
2347 q.restore(repo, rev, delete=opts['delete'],
2344 qupdate=opts['update'])
2348 qupdate=opts['update'])
2345 q.save_dirty()
2349 q.save_dirty()
2346 return 0
2350 return 0
2347
2351
2348 def save(ui, repo, **opts):
2352 def save(ui, repo, **opts):
2349 """save current queue state (DEPRECATED)
2353 """save current queue state (DEPRECATED)
2350
2354
2351 This command is deprecated, use rebase --mq instead."""
2355 This command is deprecated, use rebase --mq instead."""
2352 q = repo.mq
2356 q = repo.mq
2353 message = cmdutil.logmessage(opts)
2357 message = cmdutil.logmessage(opts)
2354 ret = q.save(repo, msg=message)
2358 ret = q.save(repo, msg=message)
2355 if ret:
2359 if ret:
2356 return ret
2360 return ret
2357 q.save_dirty()
2361 q.save_dirty()
2358 if opts['copy']:
2362 if opts['copy']:
2359 path = q.path
2363 path = q.path
2360 if opts['name']:
2364 if opts['name']:
2361 newpath = os.path.join(q.basepath, opts['name'])
2365 newpath = os.path.join(q.basepath, opts['name'])
2362 if os.path.exists(newpath):
2366 if os.path.exists(newpath):
2363 if not os.path.isdir(newpath):
2367 if not os.path.isdir(newpath):
2364 raise util.Abort(_('destination %s exists and is not '
2368 raise util.Abort(_('destination %s exists and is not '
2365 'a directory') % newpath)
2369 'a directory') % newpath)
2366 if not opts['force']:
2370 if not opts['force']:
2367 raise util.Abort(_('destination %s exists, '
2371 raise util.Abort(_('destination %s exists, '
2368 'use -f to force') % newpath)
2372 'use -f to force') % newpath)
2369 else:
2373 else:
2370 newpath = savename(path)
2374 newpath = savename(path)
2371 ui.warn(_("copy %s to %s\n") % (path, newpath))
2375 ui.warn(_("copy %s to %s\n") % (path, newpath))
2372 util.copyfiles(path, newpath)
2376 util.copyfiles(path, newpath)
2373 if opts['empty']:
2377 if opts['empty']:
2374 try:
2378 try:
2375 os.unlink(q.join(q.status_path))
2379 os.unlink(q.join(q.status_path))
2376 except:
2380 except:
2377 pass
2381 pass
2378 return 0
2382 return 0
2379
2383
2380 def strip(ui, repo, rev, **opts):
2384 def strip(ui, repo, rev, **opts):
2381 """strip a changeset and all its descendants from the repository
2385 """strip a changeset and all its descendants from the repository
2382
2386
2383 The strip command removes all changesets whose local revision
2387 The strip command removes all changesets whose local revision
2384 number is greater than or equal to REV, and then restores any
2388 number is greater than or equal to REV, and then restores any
2385 changesets that are not descendants of REV. If the working
2389 changesets that are not descendants of REV. If the working
2386 directory has uncommitted changes, the operation is aborted unless
2390 directory has uncommitted changes, the operation is aborted unless
2387 the --force flag is supplied.
2391 the --force flag is supplied.
2388
2392
2389 If a parent of the working directory is stripped, then the working
2393 If a parent of the working directory is stripped, then the working
2390 directory will automatically be updated to the most recent
2394 directory will automatically be updated to the most recent
2391 available ancestor of the stripped parent after the operation
2395 available ancestor of the stripped parent after the operation
2392 completes.
2396 completes.
2393
2397
2394 Any stripped changesets are stored in ``.hg/strip-backup`` as a
2398 Any stripped changesets are stored in ``.hg/strip-backup`` as a
2395 bundle (see :hg:`help bundle` and :hg:`help unbundle`). They can
2399 bundle (see :hg:`help bundle` and :hg:`help unbundle`). They can
2396 be restored by running :hg:`unbundle .hg/strip-backup/BUNDLE`,
2400 be restored by running :hg:`unbundle .hg/strip-backup/BUNDLE`,
2397 where BUNDLE is the bundle file created by the strip. Note that
2401 where BUNDLE is the bundle file created by the strip. Note that
2398 the local revision numbers will in general be different after the
2402 the local revision numbers will in general be different after the
2399 restore.
2403 restore.
2400
2404
2401 Use the --nobackup option to discard the backup bundle once the
2405 Use the --nobackup option to discard the backup bundle once the
2402 operation completes.
2406 operation completes.
2403 """
2407 """
2404 backup = 'all'
2408 backup = 'all'
2405 if opts['backup']:
2409 if opts['backup']:
2406 backup = 'strip'
2410 backup = 'strip'
2407 elif opts['nobackup']:
2411 elif opts['nobackup']:
2408 backup = 'none'
2412 backup = 'none'
2409
2413
2410 rev = repo.lookup(rev)
2414 rev = repo.lookup(rev)
2411 p = repo.dirstate.parents()
2415 p = repo.dirstate.parents()
2412 cl = repo.changelog
2416 cl = repo.changelog
2413 update = True
2417 update = True
2414 if p[0] == nullid:
2418 if p[0] == nullid:
2415 update = False
2419 update = False
2416 elif p[1] == nullid and rev != cl.ancestor(p[0], rev):
2420 elif p[1] == nullid and rev != cl.ancestor(p[0], rev):
2417 update = False
2421 update = False
2418 elif rev not in (cl.ancestor(p[0], rev), cl.ancestor(p[1], rev)):
2422 elif rev not in (cl.ancestor(p[0], rev), cl.ancestor(p[1], rev)):
2419 update = False
2423 update = False
2420
2424
2421 q = repo.mq
2425 q = repo.mq
2422 if q.applied:
2426 if q.applied:
2423 if rev == cl.ancestor(repo.lookup('qtip'), rev):
2427 if rev == cl.ancestor(repo.lookup('qtip'), rev):
2424 q.applied_dirty = True
2428 q.applied_dirty = True
2425 start = 0
2429 start = 0
2426 end = len(q.applied)
2430 end = len(q.applied)
2427 applied_list = [i.node for i in q.applied]
2431 applied_list = [i.node for i in q.applied]
2428 if rev in applied_list:
2432 if rev in applied_list:
2429 start = applied_list.index(rev)
2433 start = applied_list.index(rev)
2430 del q.applied[start:end]
2434 del q.applied[start:end]
2431 q.save_dirty()
2435 q.save_dirty()
2432
2436
2433 repo.mq.strip(repo, rev, backup=backup, update=update, force=opts['force'])
2437 repo.mq.strip(repo, rev, backup=backup, update=update, force=opts['force'])
2434 return 0
2438 return 0
2435
2439
2436 def select(ui, repo, *args, **opts):
2440 def select(ui, repo, *args, **opts):
2437 '''set or print guarded patches to push
2441 '''set or print guarded patches to push
2438
2442
2439 Use the :hg:`qguard` command to set or print guards on patch, then use
2443 Use the :hg:`qguard` command to set or print guards on patch, then use
2440 qselect to tell mq which guards to use. A patch will be pushed if
2444 qselect to tell mq which guards to use. A patch will be pushed if
2441 it has no guards or any positive guards match the currently
2445 it has no guards or any positive guards match the currently
2442 selected guard, but will not be pushed if any negative guards
2446 selected guard, but will not be pushed if any negative guards
2443 match the current guard. For example::
2447 match the current guard. For example::
2444
2448
2445 qguard foo.patch -stable (negative guard)
2449 qguard foo.patch -stable (negative guard)
2446 qguard bar.patch +stable (positive guard)
2450 qguard bar.patch +stable (positive guard)
2447 qselect stable
2451 qselect stable
2448
2452
2449 This activates the "stable" guard. mq will skip foo.patch (because
2453 This activates the "stable" guard. mq will skip foo.patch (because
2450 it has a negative match) but push bar.patch (because it has a
2454 it has a negative match) but push bar.patch (because it has a
2451 positive match).
2455 positive match).
2452
2456
2453 With no arguments, prints the currently active guards.
2457 With no arguments, prints the currently active guards.
2454 With one argument, sets the active guard.
2458 With one argument, sets the active guard.
2455
2459
2456 Use -n/--none to deactivate guards (no other arguments needed).
2460 Use -n/--none to deactivate guards (no other arguments needed).
2457 When no guards are active, patches with positive guards are
2461 When no guards are active, patches with positive guards are
2458 skipped and patches with negative guards are pushed.
2462 skipped and patches with negative guards are pushed.
2459
2463
2460 qselect can change the guards on applied patches. It does not pop
2464 qselect can change the guards on applied patches. It does not pop
2461 guarded patches by default. Use --pop to pop back to the last
2465 guarded patches by default. Use --pop to pop back to the last
2462 applied patch that is not guarded. Use --reapply (which implies
2466 applied patch that is not guarded. Use --reapply (which implies
2463 --pop) to push back to the current patch afterwards, but skip
2467 --pop) to push back to the current patch afterwards, but skip
2464 guarded patches.
2468 guarded patches.
2465
2469
2466 Use -s/--series to print a list of all guards in the series file
2470 Use -s/--series to print a list of all guards in the series file
2467 (no other arguments needed). Use -v for more information.'''
2471 (no other arguments needed). Use -v for more information.'''
2468
2472
2469 q = repo.mq
2473 q = repo.mq
2470 guards = q.active()
2474 guards = q.active()
2471 if args or opts['none']:
2475 if args or opts['none']:
2472 old_unapplied = q.unapplied(repo)
2476 old_unapplied = q.unapplied(repo)
2473 old_guarded = [i for i in xrange(len(q.applied)) if
2477 old_guarded = [i for i in xrange(len(q.applied)) if
2474 not q.pushable(i)[0]]
2478 not q.pushable(i)[0]]
2475 q.set_active(args)
2479 q.set_active(args)
2476 q.save_dirty()
2480 q.save_dirty()
2477 if not args:
2481 if not args:
2478 ui.status(_('guards deactivated\n'))
2482 ui.status(_('guards deactivated\n'))
2479 if not opts['pop'] and not opts['reapply']:
2483 if not opts['pop'] and not opts['reapply']:
2480 unapplied = q.unapplied(repo)
2484 unapplied = q.unapplied(repo)
2481 guarded = [i for i in xrange(len(q.applied))
2485 guarded = [i for i in xrange(len(q.applied))
2482 if not q.pushable(i)[0]]
2486 if not q.pushable(i)[0]]
2483 if len(unapplied) != len(old_unapplied):
2487 if len(unapplied) != len(old_unapplied):
2484 ui.status(_('number of unguarded, unapplied patches has '
2488 ui.status(_('number of unguarded, unapplied patches has '
2485 'changed from %d to %d\n') %
2489 'changed from %d to %d\n') %
2486 (len(old_unapplied), len(unapplied)))
2490 (len(old_unapplied), len(unapplied)))
2487 if len(guarded) != len(old_guarded):
2491 if len(guarded) != len(old_guarded):
2488 ui.status(_('number of guarded, applied patches has changed '
2492 ui.status(_('number of guarded, applied patches has changed '
2489 'from %d to %d\n') %
2493 'from %d to %d\n') %
2490 (len(old_guarded), len(guarded)))
2494 (len(old_guarded), len(guarded)))
2491 elif opts['series']:
2495 elif opts['series']:
2492 guards = {}
2496 guards = {}
2493 noguards = 0
2497 noguards = 0
2494 for gs in q.series_guards:
2498 for gs in q.series_guards:
2495 if not gs:
2499 if not gs:
2496 noguards += 1
2500 noguards += 1
2497 for g in gs:
2501 for g in gs:
2498 guards.setdefault(g, 0)
2502 guards.setdefault(g, 0)
2499 guards[g] += 1
2503 guards[g] += 1
2500 if ui.verbose:
2504 if ui.verbose:
2501 guards['NONE'] = noguards
2505 guards['NONE'] = noguards
2502 guards = guards.items()
2506 guards = guards.items()
2503 guards.sort(key=lambda x: x[0][1:])
2507 guards.sort(key=lambda x: x[0][1:])
2504 if guards:
2508 if guards:
2505 ui.note(_('guards in series file:\n'))
2509 ui.note(_('guards in series file:\n'))
2506 for guard, count in guards:
2510 for guard, count in guards:
2507 ui.note('%2d ' % count)
2511 ui.note('%2d ' % count)
2508 ui.write(guard, '\n')
2512 ui.write(guard, '\n')
2509 else:
2513 else:
2510 ui.note(_('no guards in series file\n'))
2514 ui.note(_('no guards in series file\n'))
2511 else:
2515 else:
2512 if guards:
2516 if guards:
2513 ui.note(_('active guards:\n'))
2517 ui.note(_('active guards:\n'))
2514 for g in guards:
2518 for g in guards:
2515 ui.write(g, '\n')
2519 ui.write(g, '\n')
2516 else:
2520 else:
2517 ui.write(_('no active guards\n'))
2521 ui.write(_('no active guards\n'))
2518 reapply = opts['reapply'] and q.applied and q.appliedname(-1)
2522 reapply = opts['reapply'] and q.applied and q.appliedname(-1)
2519 popped = False
2523 popped = False
2520 if opts['pop'] or opts['reapply']:
2524 if opts['pop'] or opts['reapply']:
2521 for i in xrange(len(q.applied)):
2525 for i in xrange(len(q.applied)):
2522 pushable, reason = q.pushable(i)
2526 pushable, reason = q.pushable(i)
2523 if not pushable:
2527 if not pushable:
2524 ui.status(_('popping guarded patches\n'))
2528 ui.status(_('popping guarded patches\n'))
2525 popped = True
2529 popped = True
2526 if i == 0:
2530 if i == 0:
2527 q.pop(repo, all=True)
2531 q.pop(repo, all=True)
2528 else:
2532 else:
2529 q.pop(repo, i - 1)
2533 q.pop(repo, i - 1)
2530 break
2534 break
2531 if popped:
2535 if popped:
2532 try:
2536 try:
2533 if reapply:
2537 if reapply:
2534 ui.status(_('reapplying unguarded patches\n'))
2538 ui.status(_('reapplying unguarded patches\n'))
2535 q.push(repo, reapply)
2539 q.push(repo, reapply)
2536 finally:
2540 finally:
2537 q.save_dirty()
2541 q.save_dirty()
2538
2542
2539 def finish(ui, repo, *revrange, **opts):
2543 def finish(ui, repo, *revrange, **opts):
2540 """move applied patches into repository history
2544 """move applied patches into repository history
2541
2545
2542 Finishes the specified revisions (corresponding to applied
2546 Finishes the specified revisions (corresponding to applied
2543 patches) by moving them out of mq control into regular repository
2547 patches) by moving them out of mq control into regular repository
2544 history.
2548 history.
2545
2549
2546 Accepts a revision range or the -a/--applied option. If --applied
2550 Accepts a revision range or the -a/--applied option. If --applied
2547 is specified, all applied mq revisions are removed from mq
2551 is specified, all applied mq revisions are removed from mq
2548 control. Otherwise, the given revisions must be at the base of the
2552 control. Otherwise, the given revisions must be at the base of the
2549 stack of applied patches.
2553 stack of applied patches.
2550
2554
2551 This can be especially useful if your changes have been applied to
2555 This can be especially useful if your changes have been applied to
2552 an upstream repository, or if you are about to push your changes
2556 an upstream repository, or if you are about to push your changes
2553 to upstream.
2557 to upstream.
2554 """
2558 """
2555 if not opts['applied'] and not revrange:
2559 if not opts['applied'] and not revrange:
2556 raise util.Abort(_('no revisions specified'))
2560 raise util.Abort(_('no revisions specified'))
2557 elif opts['applied']:
2561 elif opts['applied']:
2558 revrange = ('qbase:qtip',) + revrange
2562 revrange = ('qbase:qtip',) + revrange
2559
2563
2560 q = repo.mq
2564 q = repo.mq
2561 if not q.applied:
2565 if not q.applied:
2562 ui.status(_('no patches applied\n'))
2566 ui.status(_('no patches applied\n'))
2563 return 0
2567 return 0
2564
2568
2565 revs = cmdutil.revrange(repo, revrange)
2569 revs = cmdutil.revrange(repo, revrange)
2566 q.finish(repo, revs)
2570 q.finish(repo, revs)
2567 q.save_dirty()
2571 q.save_dirty()
2568 return 0
2572 return 0
2569
2573
2570 def qqueue(ui, repo, name=None, **opts):
2574 def qqueue(ui, repo, name=None, **opts):
2571 '''manage multiple patch queues
2575 '''manage multiple patch queues
2572
2576
2573 Supports switching between different patch queues, as well as creating
2577 Supports switching between different patch queues, as well as creating
2574 new patch queues and deleting existing ones.
2578 new patch queues and deleting existing ones.
2575
2579
2576 Omitting a queue name or specifying -l/--list will show you the registered
2580 Omitting a queue name or specifying -l/--list will show you the registered
2577 queues - by default the "normal" patches queue is registered. The currently
2581 queues - by default the "normal" patches queue is registered. The currently
2578 active queue will be marked with "(active)".
2582 active queue will be marked with "(active)".
2579
2583
2580 To create a new queue, use -c/--create. The queue is automatically made
2584 To create a new queue, use -c/--create. The queue is automatically made
2581 active, except in the case where there are applied patches from the
2585 active, except in the case where there are applied patches from the
2582 currently active queue in the repository. Then the queue will only be
2586 currently active queue in the repository. Then the queue will only be
2583 created and switching will fail.
2587 created and switching will fail.
2584
2588
2585 To delete an existing queue, use --delete. You cannot delete the currently
2589 To delete an existing queue, use --delete. You cannot delete the currently
2586 active queue.
2590 active queue.
2587 '''
2591 '''
2588
2592
2589 q = repo.mq
2593 q = repo.mq
2590
2594
2591 _defaultqueue = 'patches'
2595 _defaultqueue = 'patches'
2592 _allqueues = 'patches.queues'
2596 _allqueues = 'patches.queues'
2593 _activequeue = 'patches.queue'
2597 _activequeue = 'patches.queue'
2594
2598
2595 def _getcurrent():
2599 def _getcurrent():
2596 cur = os.path.basename(q.path)
2600 cur = os.path.basename(q.path)
2597 if cur.startswith('patches-'):
2601 if cur.startswith('patches-'):
2598 cur = cur[8:]
2602 cur = cur[8:]
2599 return cur
2603 return cur
2600
2604
2601 def _noqueues():
2605 def _noqueues():
2602 try:
2606 try:
2603 fh = repo.opener(_allqueues, 'r')
2607 fh = repo.opener(_allqueues, 'r')
2604 fh.close()
2608 fh.close()
2605 except IOError:
2609 except IOError:
2606 return True
2610 return True
2607
2611
2608 return False
2612 return False
2609
2613
2610 def _getqueues():
2614 def _getqueues():
2611 current = _getcurrent()
2615 current = _getcurrent()
2612
2616
2613 try:
2617 try:
2614 fh = repo.opener(_allqueues, 'r')
2618 fh = repo.opener(_allqueues, 'r')
2615 queues = [queue.strip() for queue in fh if queue.strip()]
2619 queues = [queue.strip() for queue in fh if queue.strip()]
2616 if current not in queues:
2620 if current not in queues:
2617 queues.append(current)
2621 queues.append(current)
2618 except IOError:
2622 except IOError:
2619 queues = [_defaultqueue]
2623 queues = [_defaultqueue]
2620
2624
2621 return sorted(queues)
2625 return sorted(queues)
2622
2626
2623 def _setactive(name):
2627 def _setactive(name):
2624 if q.applied:
2628 if q.applied:
2625 raise util.Abort(_('patches applied - cannot set new queue active'))
2629 raise util.Abort(_('patches applied - cannot set new queue active'))
2626
2630
2627 fh = repo.opener(_activequeue, 'w')
2631 fh = repo.opener(_activequeue, 'w')
2628 if name != 'patches':
2632 if name != 'patches':
2629 fh.write(name)
2633 fh.write(name)
2630 fh.close()
2634 fh.close()
2631
2635
2632 def _addqueue(name):
2636 def _addqueue(name):
2633 fh = repo.opener(_allqueues, 'a')
2637 fh = repo.opener(_allqueues, 'a')
2634 fh.write('%s\n' % (name,))
2638 fh.write('%s\n' % (name,))
2635 fh.close()
2639 fh.close()
2636
2640
2637 def _validname(name):
2641 def _validname(name):
2638 for n in name:
2642 for n in name:
2639 if n in ':\\/.':
2643 if n in ':\\/.':
2640 return False
2644 return False
2641 return True
2645 return True
2642
2646
2643 if not name or opts.get('list'):
2647 if not name or opts.get('list'):
2644 current = _getcurrent()
2648 current = _getcurrent()
2645 for queue in _getqueues():
2649 for queue in _getqueues():
2646 ui.write('%s' % (queue,))
2650 ui.write('%s' % (queue,))
2647 if queue == current:
2651 if queue == current:
2648 ui.write(_(' (active)\n'))
2652 ui.write(_(' (active)\n'))
2649 else:
2653 else:
2650 ui.write('\n')
2654 ui.write('\n')
2651 return
2655 return
2652
2656
2653 if not _validname(name):
2657 if not _validname(name):
2654 raise util.Abort(
2658 raise util.Abort(
2655 _('invalid queue name, may not contain the characters ":\\/."'))
2659 _('invalid queue name, may not contain the characters ":\\/."'))
2656
2660
2657 existing = _getqueues()
2661 existing = _getqueues()
2658
2662
2659 if opts.get('create'):
2663 if opts.get('create'):
2660 if name in existing:
2664 if name in existing:
2661 raise util.Abort(_('queue "%s" already exists') % name)
2665 raise util.Abort(_('queue "%s" already exists') % name)
2662 if _noqueues():
2666 if _noqueues():
2663 _addqueue(_defaultqueue)
2667 _addqueue(_defaultqueue)
2664 _addqueue(name)
2668 _addqueue(name)
2665 _setactive(name)
2669 _setactive(name)
2666 elif opts.get('delete'):
2670 elif opts.get('delete'):
2667 if name not in existing:
2671 if name not in existing:
2668 raise util.Abort(_('cannot delete queue that does not exist'))
2672 raise util.Abort(_('cannot delete queue that does not exist'))
2669
2673
2670 current = _getcurrent()
2674 current = _getcurrent()
2671
2675
2672 if name == current:
2676 if name == current:
2673 raise util.Abort(_('cannot delete currently active queue'))
2677 raise util.Abort(_('cannot delete currently active queue'))
2674
2678
2675 fh = repo.opener('patches.queues.new', 'w')
2679 fh = repo.opener('patches.queues.new', 'w')
2676 for queue in existing:
2680 for queue in existing:
2677 if queue == name:
2681 if queue == name:
2678 continue
2682 continue
2679 fh.write('%s\n' % (queue,))
2683 fh.write('%s\n' % (queue,))
2680 fh.close()
2684 fh.close()
2681 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
2685 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
2682 else:
2686 else:
2683 if name not in existing:
2687 if name not in existing:
2684 raise util.Abort(_('use --create to create a new queue'))
2688 raise util.Abort(_('use --create to create a new queue'))
2685 _setactive(name)
2689 _setactive(name)
2686
2690
2687 def reposetup(ui, repo):
2691 def reposetup(ui, repo):
2688 class mqrepo(repo.__class__):
2692 class mqrepo(repo.__class__):
2689 @util.propertycache
2693 @util.propertycache
2690 def mq(self):
2694 def mq(self):
2691 return queue(self.ui, self.join(""))
2695 return queue(self.ui, self.join(""))
2692
2696
2693 def abort_if_wdir_patched(self, errmsg, force=False):
2697 def abort_if_wdir_patched(self, errmsg, force=False):
2694 if self.mq.applied and not force:
2698 if self.mq.applied and not force:
2695 parent = self.dirstate.parents()[0]
2699 parent = self.dirstate.parents()[0]
2696 if parent in [s.node for s in self.mq.applied]:
2700 if parent in [s.node for s in self.mq.applied]:
2697 raise util.Abort(errmsg)
2701 raise util.Abort(errmsg)
2698
2702
2699 def commit(self, text="", user=None, date=None, match=None,
2703 def commit(self, text="", user=None, date=None, match=None,
2700 force=False, editor=False, extra={}):
2704 force=False, editor=False, extra={}):
2701 self.abort_if_wdir_patched(
2705 self.abort_if_wdir_patched(
2702 _('cannot commit over an applied mq patch'),
2706 _('cannot commit over an applied mq patch'),
2703 force)
2707 force)
2704
2708
2705 return super(mqrepo, self).commit(text, user, date, match, force,
2709 return super(mqrepo, self).commit(text, user, date, match, force,
2706 editor, extra)
2710 editor, extra)
2707
2711
2708 def push(self, remote, force=False, revs=None, newbranch=False):
2712 def push(self, remote, force=False, revs=None, newbranch=False):
2709 if self.mq.applied and not force and not revs:
2713 if self.mq.applied and not force and not revs:
2710 raise util.Abort(_('source has mq patches applied'))
2714 raise util.Abort(_('source has mq patches applied'))
2711 return super(mqrepo, self).push(remote, force, revs, newbranch)
2715 return super(mqrepo, self).push(remote, force, revs, newbranch)
2712
2716
2713 def _findtags(self):
2717 def _findtags(self):
2714 '''augment tags from base class with patch tags'''
2718 '''augment tags from base class with patch tags'''
2715 result = super(mqrepo, self)._findtags()
2719 result = super(mqrepo, self)._findtags()
2716
2720
2717 q = self.mq
2721 q = self.mq
2718 if not q.applied:
2722 if not q.applied:
2719 return result
2723 return result
2720
2724
2721 mqtags = [(patch.node, patch.name) for patch in q.applied]
2725 mqtags = [(patch.node, patch.name) for patch in q.applied]
2722
2726
2723 if mqtags[-1][0] not in self.changelog.nodemap:
2727 if mqtags[-1][0] not in self.changelog.nodemap:
2724 self.ui.warn(_('mq status file refers to unknown node %s\n')
2728 self.ui.warn(_('mq status file refers to unknown node %s\n')
2725 % short(mqtags[-1][0]))
2729 % short(mqtags[-1][0]))
2726 return result
2730 return result
2727
2731
2728 mqtags.append((mqtags[-1][0], 'qtip'))
2732 mqtags.append((mqtags[-1][0], 'qtip'))
2729 mqtags.append((mqtags[0][0], 'qbase'))
2733 mqtags.append((mqtags[0][0], 'qbase'))
2730 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
2734 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
2731 tags = result[0]
2735 tags = result[0]
2732 for patch in mqtags:
2736 for patch in mqtags:
2733 if patch[1] in tags:
2737 if patch[1] in tags:
2734 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
2738 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
2735 % patch[1])
2739 % patch[1])
2736 else:
2740 else:
2737 tags[patch[1]] = patch[0]
2741 tags[patch[1]] = patch[0]
2738
2742
2739 return result
2743 return result
2740
2744
2741 def _branchtags(self, partial, lrev):
2745 def _branchtags(self, partial, lrev):
2742 q = self.mq
2746 q = self.mq
2743 if not q.applied:
2747 if not q.applied:
2744 return super(mqrepo, self)._branchtags(partial, lrev)
2748 return super(mqrepo, self)._branchtags(partial, lrev)
2745
2749
2746 cl = self.changelog
2750 cl = self.changelog
2747 qbasenode = q.applied[0].node
2751 qbasenode = q.applied[0].node
2748 if qbasenode not in cl.nodemap:
2752 if qbasenode not in cl.nodemap:
2749 self.ui.warn(_('mq status file refers to unknown node %s\n')
2753 self.ui.warn(_('mq status file refers to unknown node %s\n')
2750 % short(qbasenode))
2754 % short(qbasenode))
2751 return super(mqrepo, self)._branchtags(partial, lrev)
2755 return super(mqrepo, self)._branchtags(partial, lrev)
2752
2756
2753 qbase = cl.rev(qbasenode)
2757 qbase = cl.rev(qbasenode)
2754 start = lrev + 1
2758 start = lrev + 1
2755 if start < qbase:
2759 if start < qbase:
2756 # update the cache (excluding the patches) and save it
2760 # update the cache (excluding the patches) and save it
2757 ctxgen = (self[r] for r in xrange(lrev + 1, qbase))
2761 ctxgen = (self[r] for r in xrange(lrev + 1, qbase))
2758 self._updatebranchcache(partial, ctxgen)
2762 self._updatebranchcache(partial, ctxgen)
2759 self._writebranchcache(partial, cl.node(qbase - 1), qbase - 1)
2763 self._writebranchcache(partial, cl.node(qbase - 1), qbase - 1)
2760 start = qbase
2764 start = qbase
2761 # if start = qbase, the cache is as updated as it should be.
2765 # if start = qbase, the cache is as updated as it should be.
2762 # if start > qbase, the cache includes (part of) the patches.
2766 # if start > qbase, the cache includes (part of) the patches.
2763 # we might as well use it, but we won't save it.
2767 # we might as well use it, but we won't save it.
2764
2768
2765 # update the cache up to the tip
2769 # update the cache up to the tip
2766 ctxgen = (self[r] for r in xrange(start, len(cl)))
2770 ctxgen = (self[r] for r in xrange(start, len(cl)))
2767 self._updatebranchcache(partial, ctxgen)
2771 self._updatebranchcache(partial, ctxgen)
2768
2772
2769 return partial
2773 return partial
2770
2774
2771 if repo.local():
2775 if repo.local():
2772 repo.__class__ = mqrepo
2776 repo.__class__ = mqrepo
2773
2777
2774 def mqimport(orig, ui, repo, *args, **kwargs):
2778 def mqimport(orig, ui, repo, *args, **kwargs):
2775 if (hasattr(repo, 'abort_if_wdir_patched')
2779 if (hasattr(repo, 'abort_if_wdir_patched')
2776 and not kwargs.get('no_commit', False)):
2780 and not kwargs.get('no_commit', False)):
2777 repo.abort_if_wdir_patched(_('cannot import over an applied patch'),
2781 repo.abort_if_wdir_patched(_('cannot import over an applied patch'),
2778 kwargs.get('force'))
2782 kwargs.get('force'))
2779 return orig(ui, repo, *args, **kwargs)
2783 return orig(ui, repo, *args, **kwargs)
2780
2784
2781 def mqinit(orig, ui, *args, **kwargs):
2785 def mqinit(orig, ui, *args, **kwargs):
2782 mq = kwargs.pop('mq', None)
2786 mq = kwargs.pop('mq', None)
2783
2787
2784 if not mq:
2788 if not mq:
2785 return orig(ui, *args, **kwargs)
2789 return orig(ui, *args, **kwargs)
2786
2790
2787 if args:
2791 if args:
2788 repopath = args[0]
2792 repopath = args[0]
2789 if not hg.islocal(repopath):
2793 if not hg.islocal(repopath):
2790 raise util.Abort(_('only a local queue repository '
2794 raise util.Abort(_('only a local queue repository '
2791 'may be initialized'))
2795 'may be initialized'))
2792 else:
2796 else:
2793 repopath = cmdutil.findrepo(os.getcwd())
2797 repopath = cmdutil.findrepo(os.getcwd())
2794 if not repopath:
2798 if not repopath:
2795 raise util.Abort(_('There is no Mercurial repository here '
2799 raise util.Abort(_('There is no Mercurial repository here '
2796 '(.hg not found)'))
2800 '(.hg not found)'))
2797 repo = hg.repository(ui, repopath)
2801 repo = hg.repository(ui, repopath)
2798 return qinit(ui, repo, True)
2802 return qinit(ui, repo, True)
2799
2803
2800 def mqcommand(orig, ui, repo, *args, **kwargs):
2804 def mqcommand(orig, ui, repo, *args, **kwargs):
2801 """Add --mq option to operate on patch repository instead of main"""
2805 """Add --mq option to operate on patch repository instead of main"""
2802
2806
2803 # some commands do not like getting unknown options
2807 # some commands do not like getting unknown options
2804 mq = kwargs.pop('mq', None)
2808 mq = kwargs.pop('mq', None)
2805
2809
2806 if not mq:
2810 if not mq:
2807 return orig(ui, repo, *args, **kwargs)
2811 return orig(ui, repo, *args, **kwargs)
2808
2812
2809 q = repo.mq
2813 q = repo.mq
2810 r = q.qrepo()
2814 r = q.qrepo()
2811 if not r:
2815 if not r:
2812 raise util.Abort(_('no queue repository'))
2816 raise util.Abort(_('no queue repository'))
2813 return orig(r.ui, r, *args, **kwargs)
2817 return orig(r.ui, r, *args, **kwargs)
2814
2818
2815 def summary(orig, ui, repo, *args, **kwargs):
2819 def summary(orig, ui, repo, *args, **kwargs):
2816 r = orig(ui, repo, *args, **kwargs)
2820 r = orig(ui, repo, *args, **kwargs)
2817 q = repo.mq
2821 q = repo.mq
2818 m = []
2822 m = []
2819 a, u = len(q.applied), len(q.unapplied(repo))
2823 a, u = len(q.applied), len(q.unapplied(repo))
2820 if a:
2824 if a:
2821 m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
2825 m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
2822 if u:
2826 if u:
2823 m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
2827 m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
2824 if m:
2828 if m:
2825 ui.write("mq: %s\n" % ', '.join(m))
2829 ui.write("mq: %s\n" % ', '.join(m))
2826 else:
2830 else:
2827 ui.note(_("mq: (empty queue)\n"))
2831 ui.note(_("mq: (empty queue)\n"))
2828 return r
2832 return r
2829
2833
2830 def uisetup(ui):
2834 def uisetup(ui):
2831 mqopt = [('', 'mq', None, _("operate on patch repository"))]
2835 mqopt = [('', 'mq', None, _("operate on patch repository"))]
2832
2836
2833 extensions.wrapcommand(commands.table, 'import', mqimport)
2837 extensions.wrapcommand(commands.table, 'import', mqimport)
2834 extensions.wrapcommand(commands.table, 'summary', summary)
2838 extensions.wrapcommand(commands.table, 'summary', summary)
2835
2839
2836 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
2840 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
2837 entry[1].extend(mqopt)
2841 entry[1].extend(mqopt)
2838
2842
2839 norepo = commands.norepo.split(" ")
2843 norepo = commands.norepo.split(" ")
2840 for cmd in commands.table.keys():
2844 for cmd in commands.table.keys():
2841 cmd = cmdutil.parsealiases(cmd)[0]
2845 cmd = cmdutil.parsealiases(cmd)[0]
2842 if cmd in norepo:
2846 if cmd in norepo:
2843 continue
2847 continue
2844 entry = extensions.wrapcommand(commands.table, cmd, mqcommand)
2848 entry = extensions.wrapcommand(commands.table, cmd, mqcommand)
2845 entry[1].extend(mqopt)
2849 entry[1].extend(mqopt)
2846
2850
2847 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
2851 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
2848
2852
2849 cmdtable = {
2853 cmdtable = {
2850 "qapplied":
2854 "qapplied":
2851 (applied,
2855 (applied,
2852 [('1', 'last', None, _('show only the last patch'))] + seriesopts,
2856 [('1', 'last', None, _('show only the last patch'))] + seriesopts,
2853 _('hg qapplied [-1] [-s] [PATCH]')),
2857 _('hg qapplied [-1] [-s] [PATCH]')),
2854 "qclone":
2858 "qclone":
2855 (clone,
2859 (clone,
2856 [('', 'pull', None, _('use pull protocol to copy metadata')),
2860 [('', 'pull', None, _('use pull protocol to copy metadata')),
2857 ('U', 'noupdate', None, _('do not update the new working directories')),
2861 ('U', 'noupdate', None, _('do not update the new working directories')),
2858 ('', 'uncompressed', None,
2862 ('', 'uncompressed', None,
2859 _('use uncompressed transfer (fast over LAN)')),
2863 _('use uncompressed transfer (fast over LAN)')),
2860 ('p', 'patches', '',
2864 ('p', 'patches', '',
2861 _('location of source patch repository'), _('REPO')),
2865 _('location of source patch repository'), _('REPO')),
2862 ] + commands.remoteopts,
2866 ] + commands.remoteopts,
2863 _('hg qclone [OPTION]... SOURCE [DEST]')),
2867 _('hg qclone [OPTION]... SOURCE [DEST]')),
2864 "qcommit|qci":
2868 "qcommit|qci":
2865 (commit,
2869 (commit,
2866 commands.table["^commit|ci"][1],
2870 commands.table["^commit|ci"][1],
2867 _('hg qcommit [OPTION]... [FILE]...')),
2871 _('hg qcommit [OPTION]... [FILE]...')),
2868 "^qdiff":
2872 "^qdiff":
2869 (diff,
2873 (diff,
2870 commands.diffopts + commands.diffopts2 + commands.walkopts,
2874 commands.diffopts + commands.diffopts2 + commands.walkopts,
2871 _('hg qdiff [OPTION]... [FILE]...')),
2875 _('hg qdiff [OPTION]... [FILE]...')),
2872 "qdelete|qremove|qrm":
2876 "qdelete|qremove|qrm":
2873 (delete,
2877 (delete,
2874 [('k', 'keep', None, _('keep patch file')),
2878 [('k', 'keep', None, _('keep patch file')),
2875 ('r', 'rev', [],
2879 ('r', 'rev', [],
2876 _('stop managing a revision (DEPRECATED)'), _('REV'))],
2880 _('stop managing a revision (DEPRECATED)'), _('REV'))],
2877 _('hg qdelete [-k] [-r REV]... [PATCH]...')),
2881 _('hg qdelete [-k] [-r REV]... [PATCH]...')),
2878 'qfold':
2882 'qfold':
2879 (fold,
2883 (fold,
2880 [('e', 'edit', None, _('edit patch header')),
2884 [('e', 'edit', None, _('edit patch header')),
2881 ('k', 'keep', None, _('keep folded patch files')),
2885 ('k', 'keep', None, _('keep folded patch files')),
2882 ] + commands.commitopts,
2886 ] + commands.commitopts,
2883 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...')),
2887 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...')),
2884 'qgoto':
2888 'qgoto':
2885 (goto,
2889 (goto,
2886 [('f', 'force', None, _('overwrite any local changes'))],
2890 [('f', 'force', None, _('overwrite any local changes'))],
2887 _('hg qgoto [OPTION]... PATCH')),
2891 _('hg qgoto [OPTION]... PATCH')),
2888 'qguard':
2892 'qguard':
2889 (guard,
2893 (guard,
2890 [('l', 'list', None, _('list all patches and guards')),
2894 [('l', 'list', None, _('list all patches and guards')),
2891 ('n', 'none', None, _('drop all guards'))],
2895 ('n', 'none', None, _('drop all guards'))],
2892 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]')),
2896 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]')),
2893 'qheader': (header, [], _('hg qheader [PATCH]')),
2897 'qheader': (header, [], _('hg qheader [PATCH]')),
2894 "qimport":
2898 "qimport":
2895 (qimport,
2899 (qimport,
2896 [('e', 'existing', None, _('import file in patch directory')),
2900 [('e', 'existing', None, _('import file in patch directory')),
2897 ('n', 'name', '',
2901 ('n', 'name', '',
2898 _('name of patch file'), _('NAME')),
2902 _('name of patch file'), _('NAME')),
2899 ('f', 'force', None, _('overwrite existing files')),
2903 ('f', 'force', None, _('overwrite existing files')),
2900 ('r', 'rev', [],
2904 ('r', 'rev', [],
2901 _('place existing revisions under mq control'), _('REV')),
2905 _('place existing revisions under mq control'), _('REV')),
2902 ('g', 'git', None, _('use git extended diff format')),
2906 ('g', 'git', None, _('use git extended diff format')),
2903 ('P', 'push', None, _('qpush after importing'))],
2907 ('P', 'push', None, _('qpush after importing'))],
2904 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... FILE...')),
2908 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... FILE...')),
2905 "^qinit":
2909 "^qinit":
2906 (init,
2910 (init,
2907 [('c', 'create-repo', None, _('create queue repository'))],
2911 [('c', 'create-repo', None, _('create queue repository'))],
2908 _('hg qinit [-c]')),
2912 _('hg qinit [-c]')),
2909 "^qnew":
2913 "^qnew":
2910 (new,
2914 (new,
2911 [('e', 'edit', None, _('edit commit message')),
2915 [('e', 'edit', None, _('edit commit message')),
2912 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2916 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2913 ('g', 'git', None, _('use git extended diff format')),
2917 ('g', 'git', None, _('use git extended diff format')),
2914 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2918 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2915 ('u', 'user', '',
2919 ('u', 'user', '',
2916 _('add "From: <USER>" to patch'), _('USER')),
2920 _('add "From: <USER>" to patch'), _('USER')),
2917 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2921 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2918 ('d', 'date', '',
2922 ('d', 'date', '',
2919 _('add "Date: <DATE>" to patch'), _('DATE'))
2923 _('add "Date: <DATE>" to patch'), _('DATE'))
2920 ] + commands.walkopts + commands.commitopts,
2924 ] + commands.walkopts + commands.commitopts,
2921 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...')),
2925 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...')),
2922 "qnext": (next, [] + seriesopts, _('hg qnext [-s]')),
2926 "qnext": (next, [] + seriesopts, _('hg qnext [-s]')),
2923 "qprev": (prev, [] + seriesopts, _('hg qprev [-s]')),
2927 "qprev": (prev, [] + seriesopts, _('hg qprev [-s]')),
2924 "^qpop":
2928 "^qpop":
2925 (pop,
2929 (pop,
2926 [('a', 'all', None, _('pop all patches')),
2930 [('a', 'all', None, _('pop all patches')),
2927 ('n', 'name', '',
2931 ('n', 'name', '',
2928 _('queue name to pop (DEPRECATED)'), _('NAME')),
2932 _('queue name to pop (DEPRECATED)'), _('NAME')),
2929 ('f', 'force', None, _('forget any local changes to patched files'))],
2933 ('f', 'force', None, _('forget any local changes to patched files'))],
2930 _('hg qpop [-a] [-n NAME] [-f] [PATCH | INDEX]')),
2934 _('hg qpop [-a] [-n NAME] [-f] [PATCH | INDEX]')),
2931 "^qpush":
2935 "^qpush":
2932 (push,
2936 (push,
2933 [('f', 'force', None, _('apply if the patch has rejects')),
2937 [('f', 'force', None, _('apply if the patch has rejects')),
2934 ('l', 'list', None, _('list patch name in commit text')),
2938 ('l', 'list', None, _('list patch name in commit text')),
2935 ('a', 'all', None, _('apply all patches')),
2939 ('a', 'all', None, _('apply all patches')),
2936 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2940 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2937 ('n', 'name', '',
2941 ('n', 'name', '',
2938 _('merge queue name (DEPRECATED)'), _('NAME')),
2942 _('merge queue name (DEPRECATED)'), _('NAME')),
2939 ('', 'move', None, _('reorder patch series and apply only the patch'))],
2943 ('', 'move', None, _('reorder patch series and apply only the patch'))],
2940 _('hg qpush [-f] [-l] [-a] [-m] [-n NAME] [--move] [PATCH | INDEX]')),
2944 _('hg qpush [-f] [-l] [-a] [-m] [-n NAME] [--move] [PATCH | INDEX]')),
2941 "^qrefresh":
2945 "^qrefresh":
2942 (refresh,
2946 (refresh,
2943 [('e', 'edit', None, _('edit commit message')),
2947 [('e', 'edit', None, _('edit commit message')),
2944 ('g', 'git', None, _('use git extended diff format')),
2948 ('g', 'git', None, _('use git extended diff format')),
2945 ('s', 'short', None,
2949 ('s', 'short', None,
2946 _('refresh only files already in the patch and specified files')),
2950 _('refresh only files already in the patch and specified files')),
2947 ('U', 'currentuser', None,
2951 ('U', 'currentuser', None,
2948 _('add/update author field in patch with current user')),
2952 _('add/update author field in patch with current user')),
2949 ('u', 'user', '',
2953 ('u', 'user', '',
2950 _('add/update author field in patch with given user'), _('USER')),
2954 _('add/update author field in patch with given user'), _('USER')),
2951 ('D', 'currentdate', None,
2955 ('D', 'currentdate', None,
2952 _('add/update date field in patch with current date')),
2956 _('add/update date field in patch with current date')),
2953 ('d', 'date', '',
2957 ('d', 'date', '',
2954 _('add/update date field in patch with given date'), _('DATE'))
2958 _('add/update date field in patch with given date'), _('DATE'))
2955 ] + commands.walkopts + commands.commitopts,
2959 ] + commands.walkopts + commands.commitopts,
2956 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...')),
2960 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...')),
2957 'qrename|qmv':
2961 'qrename|qmv':
2958 (rename, [], _('hg qrename PATCH1 [PATCH2]')),
2962 (rename, [], _('hg qrename PATCH1 [PATCH2]')),
2959 "qrestore":
2963 "qrestore":
2960 (restore,
2964 (restore,
2961 [('d', 'delete', None, _('delete save entry')),
2965 [('d', 'delete', None, _('delete save entry')),
2962 ('u', 'update', None, _('update queue working directory'))],
2966 ('u', 'update', None, _('update queue working directory'))],
2963 _('hg qrestore [-d] [-u] REV')),
2967 _('hg qrestore [-d] [-u] REV')),
2964 "qsave":
2968 "qsave":
2965 (save,
2969 (save,
2966 [('c', 'copy', None, _('copy patch directory')),
2970 [('c', 'copy', None, _('copy patch directory')),
2967 ('n', 'name', '',
2971 ('n', 'name', '',
2968 _('copy directory name'), _('NAME')),
2972 _('copy directory name'), _('NAME')),
2969 ('e', 'empty', None, _('clear queue status file')),
2973 ('e', 'empty', None, _('clear queue status file')),
2970 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2974 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2971 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]')),
2975 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]')),
2972 "qselect":
2976 "qselect":
2973 (select,
2977 (select,
2974 [('n', 'none', None, _('disable all guards')),
2978 [('n', 'none', None, _('disable all guards')),
2975 ('s', 'series', None, _('list all guards in series file')),
2979 ('s', 'series', None, _('list all guards in series file')),
2976 ('', 'pop', None, _('pop to before first guarded applied patch')),
2980 ('', 'pop', None, _('pop to before first guarded applied patch')),
2977 ('', 'reapply', None, _('pop, then reapply patches'))],
2981 ('', 'reapply', None, _('pop, then reapply patches'))],
2978 _('hg qselect [OPTION]... [GUARD]...')),
2982 _('hg qselect [OPTION]... [GUARD]...')),
2979 "qseries":
2983 "qseries":
2980 (series,
2984 (series,
2981 [('m', 'missing', None, _('print patches not in series')),
2985 [('m', 'missing', None, _('print patches not in series')),
2982 ] + seriesopts,
2986 ] + seriesopts,
2983 _('hg qseries [-ms]')),
2987 _('hg qseries [-ms]')),
2984 "strip":
2988 "strip":
2985 (strip,
2989 (strip,
2986 [('f', 'force', None, _('force removal of changesets even if the '
2990 [('f', 'force', None, _('force removal of changesets even if the '
2987 'working directory has uncommitted changes')),
2991 'working directory has uncommitted changes')),
2988 ('b', 'backup', None, _('bundle only changesets with local revision'
2992 ('b', 'backup', None, _('bundle only changesets with local revision'
2989 ' number greater than REV which are not'
2993 ' number greater than REV which are not'
2990 ' descendants of REV (DEPRECATED)')),
2994 ' descendants of REV (DEPRECATED)')),
2991 ('n', 'nobackup', None, _('no backups'))],
2995 ('n', 'nobackup', None, _('no backups'))],
2992 _('hg strip [-f] [-n] REV')),
2996 _('hg strip [-f] [-n] REV')),
2993 "qtop": (top, [] + seriesopts, _('hg qtop [-s]')),
2997 "qtop": (top, [] + seriesopts, _('hg qtop [-s]')),
2994 "qunapplied":
2998 "qunapplied":
2995 (unapplied,
2999 (unapplied,
2996 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
3000 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
2997 _('hg qunapplied [-1] [-s] [PATCH]')),
3001 _('hg qunapplied [-1] [-s] [PATCH]')),
2998 "qfinish":
3002 "qfinish":
2999 (finish,
3003 (finish,
3000 [('a', 'applied', None, _('finish all applied changesets'))],
3004 [('a', 'applied', None, _('finish all applied changesets'))],
3001 _('hg qfinish [-a] [REV]...')),
3005 _('hg qfinish [-a] [REV]...')),
3002 'qqueue':
3006 'qqueue':
3003 (qqueue,
3007 (qqueue,
3004 [
3008 [
3005 ('l', 'list', False, _('list all available queues')),
3009 ('l', 'list', False, _('list all available queues')),
3006 ('c', 'create', False, _('create new queue')),
3010 ('c', 'create', False, _('create new queue')),
3007 ('', 'delete', False, _('delete reference to queue')),
3011 ('', 'delete', False, _('delete reference to queue')),
3008 ],
3012 ],
3009 _('[OPTION] [QUEUE]')),
3013 _('[OPTION] [QUEUE]')),
3010 }
3014 }
3011
3015
3012 colortable = {'qguard.negative': 'red',
3016 colortable = {'qguard.negative': 'red',
3013 'qguard.positive': 'yellow',
3017 'qguard.positive': 'yellow',
3014 'qguard.unguarded': 'green',
3018 'qguard.unguarded': 'green',
3015 'qseries.applied': 'blue bold underline',
3019 'qseries.applied': 'blue bold underline',
3016 'qseries.guarded': 'black bold',
3020 'qseries.guarded': 'black bold',
3017 'qseries.missing': 'red bold',
3021 'qseries.missing': 'red bold',
3018 'qseries.unapplied': 'black bold'}
3022 'qseries.unapplied': 'black bold'}
@@ -1,4470 +1,4472 b''
1 # commands.py - command processing for mercurial
1 # commands.py - command processing for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from node import hex, nullid, nullrev, short
8 from node import hex, nullid, nullrev, short
9 from lock import release
9 from lock import release
10 from i18n import _, gettext
10 from i18n import _, gettext
11 import os, re, sys, difflib, time, tempfile
11 import os, re, sys, difflib, time, tempfile
12 import hg, util, revlog, bundlerepo, extensions, copies, error
12 import hg, util, revlog, bundlerepo, extensions, copies, error
13 import patch, help, mdiff, url, encoding, templatekw, discovery
13 import patch, help, mdiff, url, encoding, templatekw, discovery
14 import archival, changegroup, cmdutil, sshserver, hbisect, hgweb, hgweb.server
14 import archival, changegroup, cmdutil, sshserver, hbisect, hgweb, hgweb.server
15 import merge as mergemod
15 import merge as mergemod
16 import minirst, revset
16 import minirst, revset
17 import dagparser
17 import dagparser
18
18
19 # Commands start here, listed alphabetically
19 # Commands start here, listed alphabetically
20
20
21 def add(ui, repo, *pats, **opts):
21 def add(ui, repo, *pats, **opts):
22 """add the specified files on the next commit
22 """add the specified files on the next commit
23
23
24 Schedule files to be version controlled and added to the
24 Schedule files to be version controlled and added to the
25 repository.
25 repository.
26
26
27 The files will be added to the repository at the next commit. To
27 The files will be added to the repository at the next commit. To
28 undo an add before that, see :hg:`forget`.
28 undo an add before that, see :hg:`forget`.
29
29
30 If no names are given, add all files to the repository.
30 If no names are given, add all files to the repository.
31
31
32 .. container:: verbose
32 .. container:: verbose
33
33
34 An example showing how new (unknown) files are added
34 An example showing how new (unknown) files are added
35 automatically by :hg:`add`::
35 automatically by :hg:`add`::
36
36
37 $ ls
37 $ ls
38 foo.c
38 foo.c
39 $ hg status
39 $ hg status
40 ? foo.c
40 ? foo.c
41 $ hg add
41 $ hg add
42 adding foo.c
42 adding foo.c
43 $ hg status
43 $ hg status
44 A foo.c
44 A foo.c
45
45
46 Returns 0 if all files are successfully added.
46 Returns 0 if all files are successfully added.
47 """
47 """
48
48
49 bad = []
49 bad = []
50 names = []
50 names = []
51 m = cmdutil.match(repo, pats, opts)
51 m = cmdutil.match(repo, pats, opts)
52 oldbad = m.bad
52 oldbad = m.bad
53 m.bad = lambda x, y: bad.append(x) or oldbad(x, y)
53 m.bad = lambda x, y: bad.append(x) or oldbad(x, y)
54
54
55 for f in repo.walk(m):
55 for f in repo.walk(m):
56 exact = m.exact(f)
56 exact = m.exact(f)
57 if exact or f not in repo.dirstate:
57 if exact or f not in repo.dirstate:
58 names.append(f)
58 names.append(f)
59 if ui.verbose or not exact:
59 if ui.verbose or not exact:
60 ui.status(_('adding %s\n') % m.rel(f))
60 ui.status(_('adding %s\n') % m.rel(f))
61 if not opts.get('dry_run'):
61 if not opts.get('dry_run'):
62 bad += [f for f in repo[None].add(names) if f in m.files()]
62 bad += [f for f in repo[None].add(names) if f in m.files()]
63 return bad and 1 or 0
63 return bad and 1 or 0
64
64
65 def addremove(ui, repo, *pats, **opts):
65 def addremove(ui, repo, *pats, **opts):
66 """add all new files, delete all missing files
66 """add all new files, delete all missing files
67
67
68 Add all new files and remove all missing files from the
68 Add all new files and remove all missing files from the
69 repository.
69 repository.
70
70
71 New files are ignored if they match any of the patterns in
71 New files are ignored if they match any of the patterns in
72 .hgignore. As with add, these changes take effect at the next
72 .hgignore. As with add, these changes take effect at the next
73 commit.
73 commit.
74
74
75 Use the -s/--similarity option to detect renamed files. With a
75 Use the -s/--similarity option to detect renamed files. With a
76 parameter greater than 0, this compares every removed file with
76 parameter greater than 0, this compares every removed file with
77 every added file and records those similar enough as renames. This
77 every added file and records those similar enough as renames. This
78 option takes a percentage between 0 (disabled) and 100 (files must
78 option takes a percentage between 0 (disabled) and 100 (files must
79 be identical) as its parameter. Detecting renamed files this way
79 be identical) as its parameter. Detecting renamed files this way
80 can be expensive. After using this option, :hg:`status -C` can be
80 can be expensive. After using this option, :hg:`status -C` can be
81 used to check which files were identified as moved or renamed.
81 used to check which files were identified as moved or renamed.
82
82
83 Returns 0 if all files are successfully added.
83 Returns 0 if all files are successfully added.
84 """
84 """
85 try:
85 try:
86 sim = float(opts.get('similarity') or 0)
86 sim = float(opts.get('similarity') or 0)
87 except ValueError:
87 except ValueError:
88 raise util.Abort(_('similarity must be a number'))
88 raise util.Abort(_('similarity must be a number'))
89 if sim < 0 or sim > 100:
89 if sim < 0 or sim > 100:
90 raise util.Abort(_('similarity must be between 0 and 100'))
90 raise util.Abort(_('similarity must be between 0 and 100'))
91 return cmdutil.addremove(repo, pats, opts, similarity=sim / 100.0)
91 return cmdutil.addremove(repo, pats, opts, similarity=sim / 100.0)
92
92
93 def annotate(ui, repo, *pats, **opts):
93 def annotate(ui, repo, *pats, **opts):
94 """show changeset information by line for each file
94 """show changeset information by line for each file
95
95
96 List changes in files, showing the revision id responsible for
96 List changes in files, showing the revision id responsible for
97 each line
97 each line
98
98
99 This command is useful for discovering when a change was made and
99 This command is useful for discovering when a change was made and
100 by whom.
100 by whom.
101
101
102 Without the -a/--text option, annotate will avoid processing files
102 Without the -a/--text option, annotate will avoid processing files
103 it detects as binary. With -a, annotate will annotate the file
103 it detects as binary. With -a, annotate will annotate the file
104 anyway, although the results will probably be neither useful
104 anyway, although the results will probably be neither useful
105 nor desirable.
105 nor desirable.
106
106
107 Returns 0 on success.
107 Returns 0 on success.
108 """
108 """
109 if opts.get('follow'):
109 if opts.get('follow'):
110 # --follow is deprecated and now just an alias for -f/--file
110 # --follow is deprecated and now just an alias for -f/--file
111 # to mimic the behavior of Mercurial before version 1.5
111 # to mimic the behavior of Mercurial before version 1.5
112 opts['file'] = 1
112 opts['file'] = 1
113
113
114 datefunc = ui.quiet and util.shortdate or util.datestr
114 datefunc = ui.quiet and util.shortdate or util.datestr
115 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
115 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
116
116
117 if not pats:
117 if not pats:
118 raise util.Abort(_('at least one filename or pattern is required'))
118 raise util.Abort(_('at least one filename or pattern is required'))
119
119
120 opmap = [('user', lambda x: ui.shortuser(x[0].user())),
120 opmap = [('user', lambda x: ui.shortuser(x[0].user())),
121 ('number', lambda x: str(x[0].rev())),
121 ('number', lambda x: str(x[0].rev())),
122 ('changeset', lambda x: short(x[0].node())),
122 ('changeset', lambda x: short(x[0].node())),
123 ('date', getdate),
123 ('date', getdate),
124 ('file', lambda x: x[0].path()),
124 ('file', lambda x: x[0].path()),
125 ]
125 ]
126
126
127 if (not opts.get('user') and not opts.get('changeset')
127 if (not opts.get('user') and not opts.get('changeset')
128 and not opts.get('date') and not opts.get('file')):
128 and not opts.get('date') and not opts.get('file')):
129 opts['number'] = 1
129 opts['number'] = 1
130
130
131 linenumber = opts.get('line_number') is not None
131 linenumber = opts.get('line_number') is not None
132 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
132 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
133 raise util.Abort(_('at least one of -n/-c is required for -l'))
133 raise util.Abort(_('at least one of -n/-c is required for -l'))
134
134
135 funcmap = [func for op, func in opmap if opts.get(op)]
135 funcmap = [func for op, func in opmap if opts.get(op)]
136 if linenumber:
136 if linenumber:
137 lastfunc = funcmap[-1]
137 lastfunc = funcmap[-1]
138 funcmap[-1] = lambda x: "%s:%s" % (lastfunc(x), x[1])
138 funcmap[-1] = lambda x: "%s:%s" % (lastfunc(x), x[1])
139
139
140 ctx = repo[opts.get('rev')]
140 ctx = repo[opts.get('rev')]
141 m = cmdutil.match(repo, pats, opts)
141 m = cmdutil.match(repo, pats, opts)
142 follow = not opts.get('no_follow')
142 follow = not opts.get('no_follow')
143 for abs in ctx.walk(m):
143 for abs in ctx.walk(m):
144 fctx = ctx[abs]
144 fctx = ctx[abs]
145 if not opts.get('text') and util.binary(fctx.data()):
145 if not opts.get('text') and util.binary(fctx.data()):
146 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
146 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
147 continue
147 continue
148
148
149 lines = fctx.annotate(follow=follow, linenumber=linenumber)
149 lines = fctx.annotate(follow=follow, linenumber=linenumber)
150 pieces = []
150 pieces = []
151
151
152 for f in funcmap:
152 for f in funcmap:
153 l = [f(n) for n, dummy in lines]
153 l = [f(n) for n, dummy in lines]
154 if l:
154 if l:
155 sized = [(x, encoding.colwidth(x)) for x in l]
155 sized = [(x, encoding.colwidth(x)) for x in l]
156 ml = max([w for x, w in sized])
156 ml = max([w for x, w in sized])
157 pieces.append(["%s%s" % (' ' * (ml - w), x) for x, w in sized])
157 pieces.append(["%s%s" % (' ' * (ml - w), x) for x, w in sized])
158
158
159 if pieces:
159 if pieces:
160 for p, l in zip(zip(*pieces), lines):
160 for p, l in zip(zip(*pieces), lines):
161 ui.write("%s: %s" % (" ".join(p), l[1]))
161 ui.write("%s: %s" % (" ".join(p), l[1]))
162
162
163 def archive(ui, repo, dest, **opts):
163 def archive(ui, repo, dest, **opts):
164 '''create an unversioned archive of a repository revision
164 '''create an unversioned archive of a repository revision
165
165
166 By default, the revision used is the parent of the working
166 By default, the revision used is the parent of the working
167 directory; use -r/--rev to specify a different revision.
167 directory; use -r/--rev to specify a different revision.
168
168
169 The archive type is automatically detected based on file
169 The archive type is automatically detected based on file
170 extension (or override using -t/--type).
170 extension (or override using -t/--type).
171
171
172 Valid types are:
172 Valid types are:
173
173
174 :``files``: a directory full of files (default)
174 :``files``: a directory full of files (default)
175 :``tar``: tar archive, uncompressed
175 :``tar``: tar archive, uncompressed
176 :``tbz2``: tar archive, compressed using bzip2
176 :``tbz2``: tar archive, compressed using bzip2
177 :``tgz``: tar archive, compressed using gzip
177 :``tgz``: tar archive, compressed using gzip
178 :``uzip``: zip archive, uncompressed
178 :``uzip``: zip archive, uncompressed
179 :``zip``: zip archive, compressed using deflate
179 :``zip``: zip archive, compressed using deflate
180
180
181 The exact name of the destination archive or directory is given
181 The exact name of the destination archive or directory is given
182 using a format string; see :hg:`help export` for details.
182 using a format string; see :hg:`help export` for details.
183
183
184 Each member added to an archive file has a directory prefix
184 Each member added to an archive file has a directory prefix
185 prepended. Use -p/--prefix to specify a format string for the
185 prepended. Use -p/--prefix to specify a format string for the
186 prefix. The default is the basename of the archive, with suffixes
186 prefix. The default is the basename of the archive, with suffixes
187 removed.
187 removed.
188
188
189 Returns 0 on success.
189 Returns 0 on success.
190 '''
190 '''
191
191
192 ctx = repo[opts.get('rev')]
192 ctx = repo[opts.get('rev')]
193 if not ctx:
193 if not ctx:
194 raise util.Abort(_('no working directory: please specify a revision'))
194 raise util.Abort(_('no working directory: please specify a revision'))
195 node = ctx.node()
195 node = ctx.node()
196 dest = cmdutil.make_filename(repo, dest, node)
196 dest = cmdutil.make_filename(repo, dest, node)
197 if os.path.realpath(dest) == repo.root:
197 if os.path.realpath(dest) == repo.root:
198 raise util.Abort(_('repository root cannot be destination'))
198 raise util.Abort(_('repository root cannot be destination'))
199
199
200 def guess_type():
200 def guess_type():
201 exttypes = {
201 exttypes = {
202 'tar': ['.tar'],
202 'tar': ['.tar'],
203 'tbz2': ['.tbz2', '.tar.bz2'],
203 'tbz2': ['.tbz2', '.tar.bz2'],
204 'tgz': ['.tgz', '.tar.gz'],
204 'tgz': ['.tgz', '.tar.gz'],
205 'zip': ['.zip'],
205 'zip': ['.zip'],
206 }
206 }
207
207
208 for type, extensions in exttypes.items():
208 for type, extensions in exttypes.items():
209 if util.any(dest.endswith(ext) for ext in extensions):
209 if util.any(dest.endswith(ext) for ext in extensions):
210 return type
210 return type
211 return None
211 return None
212
212
213 kind = opts.get('type') or guess_type() or 'files'
213 kind = opts.get('type') or guess_type() or 'files'
214 prefix = opts.get('prefix')
214 prefix = opts.get('prefix')
215
215
216 if dest == '-':
216 if dest == '-':
217 if kind == 'files':
217 if kind == 'files':
218 raise util.Abort(_('cannot archive plain files to stdout'))
218 raise util.Abort(_('cannot archive plain files to stdout'))
219 dest = sys.stdout
219 dest = sys.stdout
220 if not prefix:
220 if not prefix:
221 prefix = os.path.basename(repo.root) + '-%h'
221 prefix = os.path.basename(repo.root) + '-%h'
222
222
223 prefix = cmdutil.make_filename(repo, prefix, node)
223 prefix = cmdutil.make_filename(repo, prefix, node)
224 matchfn = cmdutil.match(repo, [], opts)
224 matchfn = cmdutil.match(repo, [], opts)
225 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
225 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
226 matchfn, prefix)
226 matchfn, prefix)
227
227
228 def backout(ui, repo, node=None, rev=None, **opts):
228 def backout(ui, repo, node=None, rev=None, **opts):
229 '''reverse effect of earlier changeset
229 '''reverse effect of earlier changeset
230
230
231 Commit the backed out changes as a new changeset. The new
231 Commit the backed out changes as a new changeset. The new
232 changeset is a child of the backed out changeset.
232 changeset is a child of the backed out changeset.
233
233
234 If you backout a changeset other than the tip, a new head is
234 If you backout a changeset other than the tip, a new head is
235 created. This head will be the new tip and you should merge this
235 created. This head will be the new tip and you should merge this
236 backout changeset with another head.
236 backout changeset with another head.
237
237
238 The --merge option remembers the parent of the working directory
238 The --merge option remembers the parent of the working directory
239 before starting the backout, then merges the new head with that
239 before starting the backout, then merges the new head with that
240 changeset afterwards. This saves you from doing the merge by hand.
240 changeset afterwards. This saves you from doing the merge by hand.
241 The result of this merge is not committed, as with a normal merge.
241 The result of this merge is not committed, as with a normal merge.
242
242
243 See :hg:`help dates` for a list of formats valid for -d/--date.
243 See :hg:`help dates` for a list of formats valid for -d/--date.
244
244
245 Returns 0 on success.
245 Returns 0 on success.
246 '''
246 '''
247 if rev and node:
247 if rev and node:
248 raise util.Abort(_("please specify just one revision"))
248 raise util.Abort(_("please specify just one revision"))
249
249
250 if not rev:
250 if not rev:
251 rev = node
251 rev = node
252
252
253 if not rev:
253 if not rev:
254 raise util.Abort(_("please specify a revision to backout"))
254 raise util.Abort(_("please specify a revision to backout"))
255
255
256 date = opts.get('date')
256 date = opts.get('date')
257 if date:
257 if date:
258 opts['date'] = util.parsedate(date)
258 opts['date'] = util.parsedate(date)
259
259
260 cmdutil.bail_if_changed(repo)
260 cmdutil.bail_if_changed(repo)
261 node = repo.lookup(rev)
261 node = repo.lookup(rev)
262
262
263 op1, op2 = repo.dirstate.parents()
263 op1, op2 = repo.dirstate.parents()
264 a = repo.changelog.ancestor(op1, node)
264 a = repo.changelog.ancestor(op1, node)
265 if a != node:
265 if a != node:
266 raise util.Abort(_('cannot backout change on a different branch'))
266 raise util.Abort(_('cannot backout change on a different branch'))
267
267
268 p1, p2 = repo.changelog.parents(node)
268 p1, p2 = repo.changelog.parents(node)
269 if p1 == nullid:
269 if p1 == nullid:
270 raise util.Abort(_('cannot backout a change with no parents'))
270 raise util.Abort(_('cannot backout a change with no parents'))
271 if p2 != nullid:
271 if p2 != nullid:
272 if not opts.get('parent'):
272 if not opts.get('parent'):
273 raise util.Abort(_('cannot backout a merge changeset without '
273 raise util.Abort(_('cannot backout a merge changeset without '
274 '--parent'))
274 '--parent'))
275 p = repo.lookup(opts['parent'])
275 p = repo.lookup(opts['parent'])
276 if p not in (p1, p2):
276 if p not in (p1, p2):
277 raise util.Abort(_('%s is not a parent of %s') %
277 raise util.Abort(_('%s is not a parent of %s') %
278 (short(p), short(node)))
278 (short(p), short(node)))
279 parent = p
279 parent = p
280 else:
280 else:
281 if opts.get('parent'):
281 if opts.get('parent'):
282 raise util.Abort(_('cannot use --parent on non-merge changeset'))
282 raise util.Abort(_('cannot use --parent on non-merge changeset'))
283 parent = p1
283 parent = p1
284
284
285 # the backout should appear on the same branch
285 # the backout should appear on the same branch
286 branch = repo.dirstate.branch()
286 branch = repo.dirstate.branch()
287 hg.clean(repo, node, show_stats=False)
287 hg.clean(repo, node, show_stats=False)
288 repo.dirstate.setbranch(branch)
288 repo.dirstate.setbranch(branch)
289 revert_opts = opts.copy()
289 revert_opts = opts.copy()
290 revert_opts['date'] = None
290 revert_opts['date'] = None
291 revert_opts['all'] = True
291 revert_opts['all'] = True
292 revert_opts['rev'] = hex(parent)
292 revert_opts['rev'] = hex(parent)
293 revert_opts['no_backup'] = None
293 revert_opts['no_backup'] = None
294 revert(ui, repo, **revert_opts)
294 revert(ui, repo, **revert_opts)
295 commit_opts = opts.copy()
295 commit_opts = opts.copy()
296 commit_opts['addremove'] = False
296 commit_opts['addremove'] = False
297 if not commit_opts['message'] and not commit_opts['logfile']:
297 if not commit_opts['message'] and not commit_opts['logfile']:
298 # we don't translate commit messages
298 # we don't translate commit messages
299 commit_opts['message'] = "Backed out changeset %s" % short(node)
299 commit_opts['message'] = "Backed out changeset %s" % short(node)
300 commit_opts['force_editor'] = True
300 commit_opts['force_editor'] = True
301 commit(ui, repo, **commit_opts)
301 commit(ui, repo, **commit_opts)
302 def nice(node):
302 def nice(node):
303 return '%d:%s' % (repo.changelog.rev(node), short(node))
303 return '%d:%s' % (repo.changelog.rev(node), short(node))
304 ui.status(_('changeset %s backs out changeset %s\n') %
304 ui.status(_('changeset %s backs out changeset %s\n') %
305 (nice(repo.changelog.tip()), nice(node)))
305 (nice(repo.changelog.tip()), nice(node)))
306 if op1 != node:
306 if op1 != node:
307 hg.clean(repo, op1, show_stats=False)
307 hg.clean(repo, op1, show_stats=False)
308 if opts.get('merge'):
308 if opts.get('merge'):
309 ui.status(_('merging with changeset %s\n')
309 ui.status(_('merging with changeset %s\n')
310 % nice(repo.changelog.tip()))
310 % nice(repo.changelog.tip()))
311 hg.merge(repo, hex(repo.changelog.tip()))
311 hg.merge(repo, hex(repo.changelog.tip()))
312 else:
312 else:
313 ui.status(_('the backout changeset is a new head - '
313 ui.status(_('the backout changeset is a new head - '
314 'do not forget to merge\n'))
314 'do not forget to merge\n'))
315 ui.status(_('(use "backout --merge" '
315 ui.status(_('(use "backout --merge" '
316 'if you want to auto-merge)\n'))
316 'if you want to auto-merge)\n'))
317
317
318 def bisect(ui, repo, rev=None, extra=None, command=None,
318 def bisect(ui, repo, rev=None, extra=None, command=None,
319 reset=None, good=None, bad=None, skip=None, noupdate=None):
319 reset=None, good=None, bad=None, skip=None, noupdate=None):
320 """subdivision search of changesets
320 """subdivision search of changesets
321
321
322 This command helps to find changesets which introduce problems. To
322 This command helps to find changesets which introduce problems. To
323 use, mark the earliest changeset you know exhibits the problem as
323 use, mark the earliest changeset you know exhibits the problem as
324 bad, then mark the latest changeset which is free from the problem
324 bad, then mark the latest changeset which is free from the problem
325 as good. Bisect will update your working directory to a revision
325 as good. Bisect will update your working directory to a revision
326 for testing (unless the -U/--noupdate option is specified). Once
326 for testing (unless the -U/--noupdate option is specified). Once
327 you have performed tests, mark the working directory as good or
327 you have performed tests, mark the working directory as good or
328 bad, and bisect will either update to another candidate changeset
328 bad, and bisect will either update to another candidate changeset
329 or announce that it has found the bad revision.
329 or announce that it has found the bad revision.
330
330
331 As a shortcut, you can also use the revision argument to mark a
331 As a shortcut, you can also use the revision argument to mark a
332 revision as good or bad without checking it out first.
332 revision as good or bad without checking it out first.
333
333
334 If you supply a command, it will be used for automatic bisection.
334 If you supply a command, it will be used for automatic bisection.
335 Its exit status will be used to mark revisions as good or bad:
335 Its exit status will be used to mark revisions as good or bad:
336 status 0 means good, 125 means to skip the revision, 127
336 status 0 means good, 125 means to skip the revision, 127
337 (command not found) will abort the bisection, and any other
337 (command not found) will abort the bisection, and any other
338 non-zero exit status means the revision is bad.
338 non-zero exit status means the revision is bad.
339
339
340 Returns 0 on success.
340 Returns 0 on success.
341 """
341 """
342 def print_result(nodes, good):
342 def print_result(nodes, good):
343 displayer = cmdutil.show_changeset(ui, repo, {})
343 displayer = cmdutil.show_changeset(ui, repo, {})
344 if len(nodes) == 1:
344 if len(nodes) == 1:
345 # narrowed it down to a single revision
345 # narrowed it down to a single revision
346 if good:
346 if good:
347 ui.write(_("The first good revision is:\n"))
347 ui.write(_("The first good revision is:\n"))
348 else:
348 else:
349 ui.write(_("The first bad revision is:\n"))
349 ui.write(_("The first bad revision is:\n"))
350 displayer.show(repo[nodes[0]])
350 displayer.show(repo[nodes[0]])
351 else:
351 else:
352 # multiple possible revisions
352 # multiple possible revisions
353 if good:
353 if good:
354 ui.write(_("Due to skipped revisions, the first "
354 ui.write(_("Due to skipped revisions, the first "
355 "good revision could be any of:\n"))
355 "good revision could be any of:\n"))
356 else:
356 else:
357 ui.write(_("Due to skipped revisions, the first "
357 ui.write(_("Due to skipped revisions, the first "
358 "bad revision could be any of:\n"))
358 "bad revision could be any of:\n"))
359 for n in nodes:
359 for n in nodes:
360 displayer.show(repo[n])
360 displayer.show(repo[n])
361 displayer.close()
361 displayer.close()
362
362
363 def check_state(state, interactive=True):
363 def check_state(state, interactive=True):
364 if not state['good'] or not state['bad']:
364 if not state['good'] or not state['bad']:
365 if (good or bad or skip or reset) and interactive:
365 if (good or bad or skip or reset) and interactive:
366 return
366 return
367 if not state['good']:
367 if not state['good']:
368 raise util.Abort(_('cannot bisect (no known good revisions)'))
368 raise util.Abort(_('cannot bisect (no known good revisions)'))
369 else:
369 else:
370 raise util.Abort(_('cannot bisect (no known bad revisions)'))
370 raise util.Abort(_('cannot bisect (no known bad revisions)'))
371 return True
371 return True
372
372
373 # backward compatibility
373 # backward compatibility
374 if rev in "good bad reset init".split():
374 if rev in "good bad reset init".split():
375 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
375 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
376 cmd, rev, extra = rev, extra, None
376 cmd, rev, extra = rev, extra, None
377 if cmd == "good":
377 if cmd == "good":
378 good = True
378 good = True
379 elif cmd == "bad":
379 elif cmd == "bad":
380 bad = True
380 bad = True
381 else:
381 else:
382 reset = True
382 reset = True
383 elif extra or good + bad + skip + reset + bool(command) > 1:
383 elif extra or good + bad + skip + reset + bool(command) > 1:
384 raise util.Abort(_('incompatible arguments'))
384 raise util.Abort(_('incompatible arguments'))
385
385
386 if reset:
386 if reset:
387 p = repo.join("bisect.state")
387 p = repo.join("bisect.state")
388 if os.path.exists(p):
388 if os.path.exists(p):
389 os.unlink(p)
389 os.unlink(p)
390 return
390 return
391
391
392 state = hbisect.load_state(repo)
392 state = hbisect.load_state(repo)
393
393
394 if command:
394 if command:
395 changesets = 1
395 changesets = 1
396 try:
396 try:
397 while changesets:
397 while changesets:
398 # update state
398 # update state
399 status = util.system(command)
399 status = util.system(command)
400 if status == 125:
400 if status == 125:
401 transition = "skip"
401 transition = "skip"
402 elif status == 0:
402 elif status == 0:
403 transition = "good"
403 transition = "good"
404 # status < 0 means process was killed
404 # status < 0 means process was killed
405 elif status == 127:
405 elif status == 127:
406 raise util.Abort(_("failed to execute %s") % command)
406 raise util.Abort(_("failed to execute %s") % command)
407 elif status < 0:
407 elif status < 0:
408 raise util.Abort(_("%s killed") % command)
408 raise util.Abort(_("%s killed") % command)
409 else:
409 else:
410 transition = "bad"
410 transition = "bad"
411 ctx = repo[rev or '.']
411 ctx = repo[rev or '.']
412 state[transition].append(ctx.node())
412 state[transition].append(ctx.node())
413 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
413 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
414 check_state(state, interactive=False)
414 check_state(state, interactive=False)
415 # bisect
415 # bisect
416 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
416 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
417 # update to next check
417 # update to next check
418 cmdutil.bail_if_changed(repo)
418 cmdutil.bail_if_changed(repo)
419 hg.clean(repo, nodes[0], show_stats=False)
419 hg.clean(repo, nodes[0], show_stats=False)
420 finally:
420 finally:
421 hbisect.save_state(repo, state)
421 hbisect.save_state(repo, state)
422 print_result(nodes, good)
422 print_result(nodes, good)
423 return
423 return
424
424
425 # update state
425 # update state
426 node = repo.lookup(rev or '.')
426 node = repo.lookup(rev or '.')
427 if good or bad or skip:
427 if good or bad or skip:
428 if good:
428 if good:
429 state['good'].append(node)
429 state['good'].append(node)
430 elif bad:
430 elif bad:
431 state['bad'].append(node)
431 state['bad'].append(node)
432 elif skip:
432 elif skip:
433 state['skip'].append(node)
433 state['skip'].append(node)
434 hbisect.save_state(repo, state)
434 hbisect.save_state(repo, state)
435
435
436 if not check_state(state):
436 if not check_state(state):
437 return
437 return
438
438
439 # actually bisect
439 # actually bisect
440 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
440 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
441 if changesets == 0:
441 if changesets == 0:
442 print_result(nodes, good)
442 print_result(nodes, good)
443 else:
443 else:
444 assert len(nodes) == 1 # only a single node can be tested next
444 assert len(nodes) == 1 # only a single node can be tested next
445 node = nodes[0]
445 node = nodes[0]
446 # compute the approximate number of remaining tests
446 # compute the approximate number of remaining tests
447 tests, size = 0, 2
447 tests, size = 0, 2
448 while size <= changesets:
448 while size <= changesets:
449 tests, size = tests + 1, size * 2
449 tests, size = tests + 1, size * 2
450 rev = repo.changelog.rev(node)
450 rev = repo.changelog.rev(node)
451 ui.write(_("Testing changeset %d:%s "
451 ui.write(_("Testing changeset %d:%s "
452 "(%d changesets remaining, ~%d tests)\n")
452 "(%d changesets remaining, ~%d tests)\n")
453 % (rev, short(node), changesets, tests))
453 % (rev, short(node), changesets, tests))
454 if not noupdate:
454 if not noupdate:
455 cmdutil.bail_if_changed(repo)
455 cmdutil.bail_if_changed(repo)
456 return hg.clean(repo, node)
456 return hg.clean(repo, node)
457
457
458 def branch(ui, repo, label=None, **opts):
458 def branch(ui, repo, label=None, **opts):
459 """set or show the current branch name
459 """set or show the current branch name
460
460
461 With no argument, show the current branch name. With one argument,
461 With no argument, show the current branch name. With one argument,
462 set the working directory branch name (the branch will not exist
462 set the working directory branch name (the branch will not exist
463 in the repository until the next commit). Standard practice
463 in the repository until the next commit). Standard practice
464 recommends that primary development take place on the 'default'
464 recommends that primary development take place on the 'default'
465 branch.
465 branch.
466
466
467 Unless -f/--force is specified, branch will not let you set a
467 Unless -f/--force is specified, branch will not let you set a
468 branch name that already exists, even if it's inactive.
468 branch name that already exists, even if it's inactive.
469
469
470 Use -C/--clean to reset the working directory branch to that of
470 Use -C/--clean to reset the working directory branch to that of
471 the parent of the working directory, negating a previous branch
471 the parent of the working directory, negating a previous branch
472 change.
472 change.
473
473
474 Use the command :hg:`update` to switch to an existing branch. Use
474 Use the command :hg:`update` to switch to an existing branch. Use
475 :hg:`commit --close-branch` to mark this branch as closed.
475 :hg:`commit --close-branch` to mark this branch as closed.
476
476
477 Returns 0 on success.
477 Returns 0 on success.
478 """
478 """
479
479
480 if opts.get('clean'):
480 if opts.get('clean'):
481 label = repo[None].parents()[0].branch()
481 label = repo[None].parents()[0].branch()
482 repo.dirstate.setbranch(label)
482 repo.dirstate.setbranch(label)
483 ui.status(_('reset working directory to branch %s\n') % label)
483 ui.status(_('reset working directory to branch %s\n') % label)
484 elif label:
484 elif label:
485 utflabel = encoding.fromlocal(label)
485 utflabel = encoding.fromlocal(label)
486 if not opts.get('force') and utflabel in repo.branchtags():
486 if not opts.get('force') and utflabel in repo.branchtags():
487 if label not in [p.branch() for p in repo.parents()]:
487 if label not in [p.branch() for p in repo.parents()]:
488 raise util.Abort(_('a branch of the same name already exists'
488 raise util.Abort(_('a branch of the same name already exists'
489 " (use 'hg update' to switch to it)"))
489 " (use 'hg update' to switch to it)"))
490 repo.dirstate.setbranch(utflabel)
490 repo.dirstate.setbranch(utflabel)
491 ui.status(_('marked working directory as branch %s\n') % label)
491 ui.status(_('marked working directory as branch %s\n') % label)
492 else:
492 else:
493 ui.write("%s\n" % encoding.tolocal(repo.dirstate.branch()))
493 ui.write("%s\n" % encoding.tolocal(repo.dirstate.branch()))
494
494
495 def branches(ui, repo, active=False, closed=False):
495 def branches(ui, repo, active=False, closed=False):
496 """list repository named branches
496 """list repository named branches
497
497
498 List the repository's named branches, indicating which ones are
498 List the repository's named branches, indicating which ones are
499 inactive. If -c/--closed is specified, also list branches which have
499 inactive. If -c/--closed is specified, also list branches which have
500 been marked closed (see :hg:`commit --close-branch`).
500 been marked closed (see :hg:`commit --close-branch`).
501
501
502 If -a/--active is specified, only show active branches. A branch
502 If -a/--active is specified, only show active branches. A branch
503 is considered active if it contains repository heads.
503 is considered active if it contains repository heads.
504
504
505 Use the command :hg:`update` to switch to an existing branch.
505 Use the command :hg:`update` to switch to an existing branch.
506
506
507 Returns 0.
507 Returns 0.
508 """
508 """
509
509
510 hexfunc = ui.debugflag and hex or short
510 hexfunc = ui.debugflag and hex or short
511 activebranches = [repo[n].branch() for n in repo.heads()]
511 activebranches = [repo[n].branch() for n in repo.heads()]
512 def testactive(tag, node):
512 def testactive(tag, node):
513 realhead = tag in activebranches
513 realhead = tag in activebranches
514 open = node in repo.branchheads(tag, closed=False)
514 open = node in repo.branchheads(tag, closed=False)
515 return realhead and open
515 return realhead and open
516 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
516 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
517 for tag, node in repo.branchtags().items()],
517 for tag, node in repo.branchtags().items()],
518 reverse=True)
518 reverse=True)
519
519
520 for isactive, node, tag in branches:
520 for isactive, node, tag in branches:
521 if (not active) or isactive:
521 if (not active) or isactive:
522 encodedtag = encoding.tolocal(tag)
522 encodedtag = encoding.tolocal(tag)
523 if ui.quiet:
523 if ui.quiet:
524 ui.write("%s\n" % encodedtag)
524 ui.write("%s\n" % encodedtag)
525 else:
525 else:
526 hn = repo.lookup(node)
526 hn = repo.lookup(node)
527 if isactive:
527 if isactive:
528 notice = ''
528 notice = ''
529 elif hn not in repo.branchheads(tag, closed=False):
529 elif hn not in repo.branchheads(tag, closed=False):
530 if not closed:
530 if not closed:
531 continue
531 continue
532 notice = _(' (closed)')
532 notice = _(' (closed)')
533 else:
533 else:
534 notice = _(' (inactive)')
534 notice = _(' (inactive)')
535 rev = str(node).rjust(31 - encoding.colwidth(encodedtag))
535 rev = str(node).rjust(31 - encoding.colwidth(encodedtag))
536 data = encodedtag, rev, hexfunc(hn), notice
536 data = encodedtag, rev, hexfunc(hn), notice
537 ui.write("%s %s:%s%s\n" % data)
537 ui.write("%s %s:%s%s\n" % data)
538
538
539 def bundle(ui, repo, fname, dest=None, **opts):
539 def bundle(ui, repo, fname, dest=None, **opts):
540 """create a changegroup file
540 """create a changegroup file
541
541
542 Generate a compressed changegroup file collecting changesets not
542 Generate a compressed changegroup file collecting changesets not
543 known to be in another repository.
543 known to be in another repository.
544
544
545 If you omit the destination repository, then hg assumes the
545 If you omit the destination repository, then hg assumes the
546 destination will have all the nodes you specify with --base
546 destination will have all the nodes you specify with --base
547 parameters. To create a bundle containing all changesets, use
547 parameters. To create a bundle containing all changesets, use
548 -a/--all (or --base null).
548 -a/--all (or --base null).
549
549
550 You can change compression method with the -t/--type option.
550 You can change compression method with the -t/--type option.
551 The available compression methods are: none, bzip2, and
551 The available compression methods are: none, bzip2, and
552 gzip (by default, bundles are compressed using bzip2).
552 gzip (by default, bundles are compressed using bzip2).
553
553
554 The bundle file can then be transferred using conventional means
554 The bundle file can then be transferred using conventional means
555 and applied to another repository with the unbundle or pull
555 and applied to another repository with the unbundle or pull
556 command. This is useful when direct push and pull are not
556 command. This is useful when direct push and pull are not
557 available or when exporting an entire repository is undesirable.
557 available or when exporting an entire repository is undesirable.
558
558
559 Applying bundles preserves all changeset contents including
559 Applying bundles preserves all changeset contents including
560 permissions, copy/rename information, and revision history.
560 permissions, copy/rename information, and revision history.
561
561
562 Returns 0 on success, 1 if no changes found.
562 Returns 0 on success, 1 if no changes found.
563 """
563 """
564 revs = opts.get('rev') or None
564 revs = opts.get('rev') or None
565 if opts.get('all'):
565 if opts.get('all'):
566 base = ['null']
566 base = ['null']
567 else:
567 else:
568 base = opts.get('base')
568 base = opts.get('base')
569 if base:
569 if base:
570 if dest:
570 if dest:
571 raise util.Abort(_("--base is incompatible with specifying "
571 raise util.Abort(_("--base is incompatible with specifying "
572 "a destination"))
572 "a destination"))
573 base = [repo.lookup(rev) for rev in base]
573 base = [repo.lookup(rev) for rev in base]
574 # create the right base
574 # create the right base
575 # XXX: nodesbetween / changegroup* should be "fixed" instead
575 # XXX: nodesbetween / changegroup* should be "fixed" instead
576 o = []
576 o = []
577 has = set((nullid,))
577 has = set((nullid,))
578 for n in base:
578 for n in base:
579 has.update(repo.changelog.reachable(n))
579 has.update(repo.changelog.reachable(n))
580 if revs:
580 if revs:
581 revs = [repo.lookup(rev) for rev in revs]
581 revs = [repo.lookup(rev) for rev in revs]
582 visit = revs[:]
582 visit = revs[:]
583 has.difference_update(visit)
583 has.difference_update(visit)
584 else:
584 else:
585 visit = repo.changelog.heads()
585 visit = repo.changelog.heads()
586 seen = {}
586 seen = {}
587 while visit:
587 while visit:
588 n = visit.pop(0)
588 n = visit.pop(0)
589 parents = [p for p in repo.changelog.parents(n) if p not in has]
589 parents = [p for p in repo.changelog.parents(n) if p not in has]
590 if len(parents) == 0:
590 if len(parents) == 0:
591 if n not in has:
591 if n not in has:
592 o.append(n)
592 o.append(n)
593 else:
593 else:
594 for p in parents:
594 for p in parents:
595 if p not in seen:
595 if p not in seen:
596 seen[p] = 1
596 seen[p] = 1
597 visit.append(p)
597 visit.append(p)
598 else:
598 else:
599 dest = ui.expandpath(dest or 'default-push', dest or 'default')
599 dest = ui.expandpath(dest or 'default-push', dest or 'default')
600 dest, branches = hg.parseurl(dest, opts.get('branch'))
600 dest, branches = hg.parseurl(dest, opts.get('branch'))
601 other = hg.repository(hg.remoteui(repo, opts), dest)
601 other = hg.repository(hg.remoteui(repo, opts), dest)
602 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
602 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
603 if revs:
603 if revs:
604 revs = [repo.lookup(rev) for rev in revs]
604 revs = [repo.lookup(rev) for rev in revs]
605 o = discovery.findoutgoing(repo, other, force=opts.get('force'))
605 o = discovery.findoutgoing(repo, other, force=opts.get('force'))
606
606
607 if not o:
607 if not o:
608 ui.status(_("no changes found\n"))
608 ui.status(_("no changes found\n"))
609 return 1
609 return 1
610
610
611 if revs:
611 if revs:
612 cg = repo.changegroupsubset(o, revs, 'bundle')
612 cg = repo.changegroupsubset(o, revs, 'bundle')
613 else:
613 else:
614 cg = repo.changegroup(o, 'bundle')
614 cg = repo.changegroup(o, 'bundle')
615
615
616 bundletype = opts.get('type', 'bzip2').lower()
616 bundletype = opts.get('type', 'bzip2').lower()
617 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
617 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
618 bundletype = btypes.get(bundletype)
618 bundletype = btypes.get(bundletype)
619 if bundletype not in changegroup.bundletypes:
619 if bundletype not in changegroup.bundletypes:
620 raise util.Abort(_('unknown bundle type specified with --type'))
620 raise util.Abort(_('unknown bundle type specified with --type'))
621
621
622 changegroup.writebundle(cg, fname, bundletype)
622 changegroup.writebundle(cg, fname, bundletype)
623
623
624 def cat(ui, repo, file1, *pats, **opts):
624 def cat(ui, repo, file1, *pats, **opts):
625 """output the current or given revision of files
625 """output the current or given revision of files
626
626
627 Print the specified files as they were at the given revision. If
627 Print the specified files as they were at the given revision. If
628 no revision is given, the parent of the working directory is used,
628 no revision is given, the parent of the working directory is used,
629 or tip if no revision is checked out.
629 or tip if no revision is checked out.
630
630
631 Output may be to a file, in which case the name of the file is
631 Output may be to a file, in which case the name of the file is
632 given using a format string. The formatting rules are the same as
632 given using a format string. The formatting rules are the same as
633 for the export command, with the following additions:
633 for the export command, with the following additions:
634
634
635 :``%s``: basename of file being printed
635 :``%s``: basename of file being printed
636 :``%d``: dirname of file being printed, or '.' if in repository root
636 :``%d``: dirname of file being printed, or '.' if in repository root
637 :``%p``: root-relative path name of file being printed
637 :``%p``: root-relative path name of file being printed
638
638
639 Returns 0 on success.
639 Returns 0 on success.
640 """
640 """
641 ctx = repo[opts.get('rev')]
641 ctx = repo[opts.get('rev')]
642 err = 1
642 err = 1
643 m = cmdutil.match(repo, (file1,) + pats, opts)
643 m = cmdutil.match(repo, (file1,) + pats, opts)
644 for abs in ctx.walk(m):
644 for abs in ctx.walk(m):
645 fp = cmdutil.make_file(repo, opts.get('output'), ctx.node(), pathname=abs)
645 fp = cmdutil.make_file(repo, opts.get('output'), ctx.node(), pathname=abs)
646 data = ctx[abs].data()
646 data = ctx[abs].data()
647 if opts.get('decode'):
647 if opts.get('decode'):
648 data = repo.wwritedata(abs, data)
648 data = repo.wwritedata(abs, data)
649 fp.write(data)
649 fp.write(data)
650 err = 0
650 err = 0
651 return err
651 return err
652
652
653 def clone(ui, source, dest=None, **opts):
653 def clone(ui, source, dest=None, **opts):
654 """make a copy of an existing repository
654 """make a copy of an existing repository
655
655
656 Create a copy of an existing repository in a new directory.
656 Create a copy of an existing repository in a new directory.
657
657
658 If no destination directory name is specified, it defaults to the
658 If no destination directory name is specified, it defaults to the
659 basename of the source.
659 basename of the source.
660
660
661 The location of the source is added to the new repository's
661 The location of the source is added to the new repository's
662 .hg/hgrc file, as the default to be used for future pulls.
662 .hg/hgrc file, as the default to be used for future pulls.
663
663
664 See :hg:`help urls` for valid source format details.
664 See :hg:`help urls` for valid source format details.
665
665
666 It is possible to specify an ``ssh://`` URL as the destination, but no
666 It is possible to specify an ``ssh://`` URL as the destination, but no
667 .hg/hgrc and working directory will be created on the remote side.
667 .hg/hgrc and working directory will be created on the remote side.
668 Please see :hg:`help urls` for important details about ``ssh://`` URLs.
668 Please see :hg:`help urls` for important details about ``ssh://`` URLs.
669
669
670 A set of changesets (tags, or branch names) to pull may be specified
670 A set of changesets (tags, or branch names) to pull may be specified
671 by listing each changeset (tag, or branch name) with -r/--rev.
671 by listing each changeset (tag, or branch name) with -r/--rev.
672 If -r/--rev is used, the cloned repository will contain only a subset
672 If -r/--rev is used, the cloned repository will contain only a subset
673 of the changesets of the source repository. Only the set of changesets
673 of the changesets of the source repository. Only the set of changesets
674 defined by all -r/--rev options (including all their ancestors)
674 defined by all -r/--rev options (including all their ancestors)
675 will be pulled into the destination repository.
675 will be pulled into the destination repository.
676 No subsequent changesets (including subsequent tags) will be present
676 No subsequent changesets (including subsequent tags) will be present
677 in the destination.
677 in the destination.
678
678
679 Using -r/--rev (or 'clone src#rev dest') implies --pull, even for
679 Using -r/--rev (or 'clone src#rev dest') implies --pull, even for
680 local source repositories.
680 local source repositories.
681
681
682 For efficiency, hardlinks are used for cloning whenever the source
682 For efficiency, hardlinks are used for cloning whenever the source
683 and destination are on the same filesystem (note this applies only
683 and destination are on the same filesystem (note this applies only
684 to the repository data, not to the working directory). Some
684 to the repository data, not to the working directory). Some
685 filesystems, such as AFS, implement hardlinking incorrectly, but
685 filesystems, such as AFS, implement hardlinking incorrectly, but
686 do not report errors. In these cases, use the --pull option to
686 do not report errors. In these cases, use the --pull option to
687 avoid hardlinking.
687 avoid hardlinking.
688
688
689 In some cases, you can clone repositories and the working directory
689 In some cases, you can clone repositories and the working directory
690 using full hardlinks with ::
690 using full hardlinks with ::
691
691
692 $ cp -al REPO REPOCLONE
692 $ cp -al REPO REPOCLONE
693
693
694 This is the fastest way to clone, but it is not always safe. The
694 This is the fastest way to clone, but it is not always safe. The
695 operation is not atomic (making sure REPO is not modified during
695 operation is not atomic (making sure REPO is not modified during
696 the operation is up to you) and you have to make sure your editor
696 the operation is up to you) and you have to make sure your editor
697 breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
697 breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
698 this is not compatible with certain extensions that place their
698 this is not compatible with certain extensions that place their
699 metadata under the .hg directory, such as mq.
699 metadata under the .hg directory, such as mq.
700
700
701 Mercurial will update the working directory to the first applicable
701 Mercurial will update the working directory to the first applicable
702 revision from this list:
702 revision from this list:
703
703
704 a) null if -U or the source repository has no changesets
704 a) null if -U or the source repository has no changesets
705 b) if -u . and the source repository is local, the first parent of
705 b) if -u . and the source repository is local, the first parent of
706 the source repository's working directory
706 the source repository's working directory
707 c) the changeset specified with -u (if a branch name, this means the
707 c) the changeset specified with -u (if a branch name, this means the
708 latest head of that branch)
708 latest head of that branch)
709 d) the changeset specified with -r
709 d) the changeset specified with -r
710 e) the tipmost head specified with -b
710 e) the tipmost head specified with -b
711 f) the tipmost head specified with the url#branch source syntax
711 f) the tipmost head specified with the url#branch source syntax
712 g) the tipmost head of the default branch
712 g) the tipmost head of the default branch
713 h) tip
713 h) tip
714
714
715 Returns 0 on success.
715 Returns 0 on success.
716 """
716 """
717 if opts.get('noupdate') and opts.get('updaterev'):
717 if opts.get('noupdate') and opts.get('updaterev'):
718 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
718 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
719
719
720 r = hg.clone(hg.remoteui(ui, opts), source, dest,
720 r = hg.clone(hg.remoteui(ui, opts), source, dest,
721 pull=opts.get('pull'),
721 pull=opts.get('pull'),
722 stream=opts.get('uncompressed'),
722 stream=opts.get('uncompressed'),
723 rev=opts.get('rev'),
723 rev=opts.get('rev'),
724 update=opts.get('updaterev') or not opts.get('noupdate'),
724 update=opts.get('updaterev') or not opts.get('noupdate'),
725 branch=opts.get('branch'))
725 branch=opts.get('branch'))
726
726
727 return r is None
727 return r is None
728
728
729 def commit(ui, repo, *pats, **opts):
729 def commit(ui, repo, *pats, **opts):
730 """commit the specified files or all outstanding changes
730 """commit the specified files or all outstanding changes
731
731
732 Commit changes to the given files into the repository. Unlike a
732 Commit changes to the given files into the repository. Unlike a
733 centralized RCS, this operation is a local operation. See
733 centralized RCS, this operation is a local operation. See
734 :hg:`push` for a way to actively distribute your changes.
734 :hg:`push` for a way to actively distribute your changes.
735
735
736 If a list of files is omitted, all changes reported by :hg:`status`
736 If a list of files is omitted, all changes reported by :hg:`status`
737 will be committed.
737 will be committed.
738
738
739 If you are committing the result of a merge, do not provide any
739 If you are committing the result of a merge, do not provide any
740 filenames or -I/-X filters.
740 filenames or -I/-X filters.
741
741
742 If no commit message is specified, the configured editor is
742 If no commit message is specified, the configured editor is
743 started to prompt you for a message.
743 started to prompt you for a message.
744
744
745 See :hg:`help dates` for a list of formats valid for -d/--date.
745 See :hg:`help dates` for a list of formats valid for -d/--date.
746
746
747 Returns 0 on success, 1 if nothing changed.
747 Returns 0 on success, 1 if nothing changed.
748 """
748 """
749 extra = {}
749 extra = {}
750 if opts.get('close_branch'):
750 if opts.get('close_branch'):
751 if repo['.'].node() not in repo.branchheads():
751 if repo['.'].node() not in repo.branchheads():
752 # The topo heads set is included in the branch heads set of the
752 # The topo heads set is included in the branch heads set of the
753 # current branch, so it's sufficient to test branchheads
753 # current branch, so it's sufficient to test branchheads
754 raise util.Abort(_('can only close branch heads'))
754 raise util.Abort(_('can only close branch heads'))
755 extra['close'] = 1
755 extra['close'] = 1
756 e = cmdutil.commiteditor
756 e = cmdutil.commiteditor
757 if opts.get('force_editor'):
757 if opts.get('force_editor'):
758 e = cmdutil.commitforceeditor
758 e = cmdutil.commitforceeditor
759
759
760 def commitfunc(ui, repo, message, match, opts):
760 def commitfunc(ui, repo, message, match, opts):
761 return repo.commit(message, opts.get('user'), opts.get('date'), match,
761 return repo.commit(message, opts.get('user'), opts.get('date'), match,
762 editor=e, extra=extra)
762 editor=e, extra=extra)
763
763
764 branch = repo[None].branch()
764 branch = repo[None].branch()
765 bheads = repo.branchheads(branch)
765 bheads = repo.branchheads(branch)
766
766
767 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
767 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
768 if not node:
768 if not node:
769 ui.status(_("nothing changed\n"))
769 ui.status(_("nothing changed\n"))
770 return 1
770 return 1
771
771
772 ctx = repo[node]
772 ctx = repo[node]
773 parents = ctx.parents()
773 parents = ctx.parents()
774
774
775 if bheads and not [x for x in parents
775 if bheads and not [x for x in parents
776 if x.node() in bheads and x.branch() == branch]:
776 if x.node() in bheads and x.branch() == branch]:
777 ui.status(_('created new head\n'))
777 ui.status(_('created new head\n'))
778 # The message is not printed for initial roots. For the other
778 # The message is not printed for initial roots. For the other
779 # changesets, it is printed in the following situations:
779 # changesets, it is printed in the following situations:
780 #
780 #
781 # Par column: for the 2 parents with ...
781 # Par column: for the 2 parents with ...
782 # N: null or no parent
782 # N: null or no parent
783 # B: parent is on another named branch
783 # B: parent is on another named branch
784 # C: parent is a regular non head changeset
784 # C: parent is a regular non head changeset
785 # H: parent was a branch head of the current branch
785 # H: parent was a branch head of the current branch
786 # Msg column: whether we print "created new head" message
786 # Msg column: whether we print "created new head" message
787 # In the following, it is assumed that there already exists some
787 # In the following, it is assumed that there already exists some
788 # initial branch heads of the current branch, otherwise nothing is
788 # initial branch heads of the current branch, otherwise nothing is
789 # printed anyway.
789 # printed anyway.
790 #
790 #
791 # Par Msg Comment
791 # Par Msg Comment
792 # NN y additional topo root
792 # NN y additional topo root
793 #
793 #
794 # BN y additional branch root
794 # BN y additional branch root
795 # CN y additional topo head
795 # CN y additional topo head
796 # HN n usual case
796 # HN n usual case
797 #
797 #
798 # BB y weird additional branch root
798 # BB y weird additional branch root
799 # CB y branch merge
799 # CB y branch merge
800 # HB n merge with named branch
800 # HB n merge with named branch
801 #
801 #
802 # CC y additional head from merge
802 # CC y additional head from merge
803 # CH n merge with a head
803 # CH n merge with a head
804 #
804 #
805 # HH n head merge: head count decreases
805 # HH n head merge: head count decreases
806
806
807 if not opts.get('close_branch'):
807 if not opts.get('close_branch'):
808 for r in parents:
808 for r in parents:
809 if r.extra().get('close') and r.branch() == branch:
809 if r.extra().get('close') and r.branch() == branch:
810 ui.status(_('reopening closed branch head %d\n') % r)
810 ui.status(_('reopening closed branch head %d\n') % r)
811
811
812 if ui.debugflag:
812 if ui.debugflag:
813 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
813 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
814 elif ui.verbose:
814 elif ui.verbose:
815 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
815 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
816
816
817 def copy(ui, repo, *pats, **opts):
817 def copy(ui, repo, *pats, **opts):
818 """mark files as copied for the next commit
818 """mark files as copied for the next commit
819
819
820 Mark dest as having copies of source files. If dest is a
820 Mark dest as having copies of source files. If dest is a
821 directory, copies are put in that directory. If dest is a file,
821 directory, copies are put in that directory. If dest is a file,
822 the source must be a single file.
822 the source must be a single file.
823
823
824 By default, this command copies the contents of files as they
824 By default, this command copies the contents of files as they
825 exist in the working directory. If invoked with -A/--after, the
825 exist in the working directory. If invoked with -A/--after, the
826 operation is recorded, but no copying is performed.
826 operation is recorded, but no copying is performed.
827
827
828 This command takes effect with the next commit. To undo a copy
828 This command takes effect with the next commit. To undo a copy
829 before that, see :hg:`revert`.
829 before that, see :hg:`revert`.
830
830
831 Returns 0 on success, 1 if errors are encountered.
831 Returns 0 on success, 1 if errors are encountered.
832 """
832 """
833 wlock = repo.wlock(False)
833 wlock = repo.wlock(False)
834 try:
834 try:
835 return cmdutil.copy(ui, repo, pats, opts)
835 return cmdutil.copy(ui, repo, pats, opts)
836 finally:
836 finally:
837 wlock.release()
837 wlock.release()
838
838
839 def debugancestor(ui, repo, *args):
839 def debugancestor(ui, repo, *args):
840 """find the ancestor revision of two revisions in a given index"""
840 """find the ancestor revision of two revisions in a given index"""
841 if len(args) == 3:
841 if len(args) == 3:
842 index, rev1, rev2 = args
842 index, rev1, rev2 = args
843 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index)
843 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index)
844 lookup = r.lookup
844 lookup = r.lookup
845 elif len(args) == 2:
845 elif len(args) == 2:
846 if not repo:
846 if not repo:
847 raise util.Abort(_("There is no Mercurial repository here "
847 raise util.Abort(_("There is no Mercurial repository here "
848 "(.hg not found)"))
848 "(.hg not found)"))
849 rev1, rev2 = args
849 rev1, rev2 = args
850 r = repo.changelog
850 r = repo.changelog
851 lookup = repo.lookup
851 lookup = repo.lookup
852 else:
852 else:
853 raise util.Abort(_('either two or three arguments required'))
853 raise util.Abort(_('either two or three arguments required'))
854 a = r.ancestor(lookup(rev1), lookup(rev2))
854 a = r.ancestor(lookup(rev1), lookup(rev2))
855 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
855 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
856
856
857 def debugbuilddag(ui, repo, text,
857 def debugbuilddag(ui, repo, text,
858 mergeable_file=False,
858 mergeable_file=False,
859 appended_file=False,
859 appended_file=False,
860 overwritten_file=False,
860 overwritten_file=False,
861 new_file=False):
861 new_file=False):
862 """builds a repo with a given dag from scratch in the current empty repo
862 """builds a repo with a given dag from scratch in the current empty repo
863
863
864 Elements:
864 Elements:
865
865
866 - "+n" is a linear run of n nodes based on the current default parent
866 - "+n" is a linear run of n nodes based on the current default parent
867 - "." is a single node based on the current default parent
867 - "." is a single node based on the current default parent
868 - "$" resets the default parent to null (implied at the start);
868 - "$" resets the default parent to null (implied at the start);
869 otherwise the default parent is always the last node created
869 otherwise the default parent is always the last node created
870 - "<p" sets the default parent to the backref p
870 - "<p" sets the default parent to the backref p
871 - "*p" is a fork at parent p, which is a backref
871 - "*p" is a fork at parent p, which is a backref
872 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
872 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
873 - "/p2" is a merge of the preceding node and p2
873 - "/p2" is a merge of the preceding node and p2
874 - ":tag" defines a local tag for the preceding node
874 - ":tag" defines a local tag for the preceding node
875 - "@branch" sets the named branch for subsequent nodes
875 - "@branch" sets the named branch for subsequent nodes
876 - "!command" runs the command using your shell
876 - "!command" runs the command using your shell
877 - "!!my command\\n" is like "!", but to the end of the line
877 - "!!my command\\n" is like "!", but to the end of the line
878 - "#...\\n" is a comment up to the end of the line
878 - "#...\\n" is a comment up to the end of the line
879
879
880 Whitespace between the above elements is ignored.
880 Whitespace between the above elements is ignored.
881
881
882 A backref is either
882 A backref is either
883
883
884 - a number n, which references the node curr-n, where curr is the current
884 - a number n, which references the node curr-n, where curr is the current
885 node, or
885 node, or
886 - the name of a local tag you placed earlier using ":tag", or
886 - the name of a local tag you placed earlier using ":tag", or
887 - empty to denote the default parent.
887 - empty to denote the default parent.
888
888
889 All string valued-elements are either strictly alphanumeric, or must
889 All string valued-elements are either strictly alphanumeric, or must
890 be enclosed in double quotes ("..."), with "\" as escape character.
890 be enclosed in double quotes ("..."), with "\" as escape character.
891
891
892 Note that the --overwritten-file and --appended-file options imply the
892 Note that the --overwritten-file and --appended-file options imply the
893 use of "HGMERGE=internal:local" during DAG buildup.
893 use of "HGMERGE=internal:local" during DAG buildup.
894 """
894 """
895
895
896 if not (mergeable_file or appended_file or overwritten_file or new_file):
896 if not (mergeable_file or appended_file or overwritten_file or new_file):
897 raise util.Abort(_('need at least one of -m, -a, -o, -n'))
897 raise util.Abort(_('need at least one of -m, -a, -o, -n'))
898
898
899 if len(repo.changelog) > 0:
899 if len(repo.changelog) > 0:
900 raise util.Abort(_('repository is not empty'))
900 raise util.Abort(_('repository is not empty'))
901
901
902 if overwritten_file or appended_file:
902 if overwritten_file or appended_file:
903 # we don't want to fail in merges during buildup
903 # we don't want to fail in merges during buildup
904 os.environ['HGMERGE'] = 'internal:local'
904 os.environ['HGMERGE'] = 'internal:local'
905
905
906 def writefile(fname, text, fmode="w"):
906 def writefile(fname, text, fmode="w"):
907 f = open(fname, fmode)
907 f = open(fname, fmode)
908 try:
908 try:
909 f.write(text)
909 f.write(text)
910 finally:
910 finally:
911 f.close()
911 f.close()
912
912
913 if mergeable_file:
913 if mergeable_file:
914 linesperrev = 2
914 linesperrev = 2
915 # determine number of revs in DAG
915 # determine number of revs in DAG
916 n = 0
916 n = 0
917 for type, data in dagparser.parsedag(text):
917 for type, data in dagparser.parsedag(text):
918 if type == 'n':
918 if type == 'n':
919 n += 1
919 n += 1
920 # make a file with k lines per rev
920 # make a file with k lines per rev
921 writefile("mf", "\n".join(str(i) for i in xrange(0, n * linesperrev))
921 writefile("mf", "\n".join(str(i) for i in xrange(0, n * linesperrev))
922 + "\n")
922 + "\n")
923
923
924 at = -1
924 at = -1
925 atbranch = 'default'
925 atbranch = 'default'
926 for type, data in dagparser.parsedag(text):
926 for type, data in dagparser.parsedag(text):
927 if type == 'n':
927 if type == 'n':
928 ui.status('node %s\n' % str(data))
928 ui.status('node %s\n' % str(data))
929 id, ps = data
929 id, ps = data
930 p1 = ps[0]
930 p1 = ps[0]
931 if p1 != at:
931 if p1 != at:
932 update(ui, repo, node=p1, clean=True)
932 update(ui, repo, node=p1, clean=True)
933 at = p1
933 at = p1
934 if repo.dirstate.branch() != atbranch:
934 if repo.dirstate.branch() != atbranch:
935 branch(ui, repo, atbranch, force=True)
935 branch(ui, repo, atbranch, force=True)
936 if len(ps) > 1:
936 if len(ps) > 1:
937 p2 = ps[1]
937 p2 = ps[1]
938 merge(ui, repo, node=p2)
938 merge(ui, repo, node=p2)
939
939
940 if mergeable_file:
940 if mergeable_file:
941 f = open("mf", "r+")
941 f = open("mf", "r+")
942 try:
942 try:
943 lines = f.read().split("\n")
943 lines = f.read().split("\n")
944 lines[id * linesperrev] += " r%i" % id
944 lines[id * linesperrev] += " r%i" % id
945 f.seek(0)
945 f.seek(0)
946 f.write("\n".join(lines))
946 f.write("\n".join(lines))
947 finally:
947 finally:
948 f.close()
948 f.close()
949
949
950 if appended_file:
950 if appended_file:
951 writefile("af", "r%i\n" % id, "a")
951 writefile("af", "r%i\n" % id, "a")
952
952
953 if overwritten_file:
953 if overwritten_file:
954 writefile("of", "r%i\n" % id)
954 writefile("of", "r%i\n" % id)
955
955
956 if new_file:
956 if new_file:
957 writefile("nf%i" % id, "r%i\n" % id)
957 writefile("nf%i" % id, "r%i\n" % id)
958
958
959 commit(ui, repo, addremove=True, message="r%i" % id, date=(id, 0))
959 commit(ui, repo, addremove=True, message="r%i" % id, date=(id, 0))
960 at = id
960 at = id
961 elif type == 'l':
961 elif type == 'l':
962 id, name = data
962 id, name = data
963 ui.status('tag %s\n' % name)
963 ui.status('tag %s\n' % name)
964 tag(ui, repo, name, local=True)
964 tag(ui, repo, name, local=True)
965 elif type == 'a':
965 elif type == 'a':
966 ui.status('branch %s\n' % data)
966 ui.status('branch %s\n' % data)
967 atbranch = data
967 atbranch = data
968 elif type in 'cC':
968 elif type in 'cC':
969 r = util.system(data, cwd=repo.root)
969 r = util.system(data, cwd=repo.root)
970 if r:
970 if r:
971 desc, r = util.explain_exit(r)
971 desc, r = util.explain_exit(r)
972 raise util.Abort(_('%s command %s') % (data, desc))
972 raise util.Abort(_('%s command %s') % (data, desc))
973
973
974 def debugcommands(ui, cmd='', *args):
974 def debugcommands(ui, cmd='', *args):
975 """list all available commands and options"""
975 """list all available commands and options"""
976 for cmd, vals in sorted(table.iteritems()):
976 for cmd, vals in sorted(table.iteritems()):
977 cmd = cmd.split('|')[0].strip('^')
977 cmd = cmd.split('|')[0].strip('^')
978 opts = ', '.join([i[1] for i in vals[1]])
978 opts = ', '.join([i[1] for i in vals[1]])
979 ui.write('%s: %s\n' % (cmd, opts))
979 ui.write('%s: %s\n' % (cmd, opts))
980
980
981 def debugcomplete(ui, cmd='', **opts):
981 def debugcomplete(ui, cmd='', **opts):
982 """returns the completion list associated with the given command"""
982 """returns the completion list associated with the given command"""
983
983
984 if opts.get('options'):
984 if opts.get('options'):
985 options = []
985 options = []
986 otables = [globalopts]
986 otables = [globalopts]
987 if cmd:
987 if cmd:
988 aliases, entry = cmdutil.findcmd(cmd, table, False)
988 aliases, entry = cmdutil.findcmd(cmd, table, False)
989 otables.append(entry[1])
989 otables.append(entry[1])
990 for t in otables:
990 for t in otables:
991 for o in t:
991 for o in t:
992 if "(DEPRECATED)" in o[3]:
992 if "(DEPRECATED)" in o[3]:
993 continue
993 continue
994 if o[0]:
994 if o[0]:
995 options.append('-%s' % o[0])
995 options.append('-%s' % o[0])
996 options.append('--%s' % o[1])
996 options.append('--%s' % o[1])
997 ui.write("%s\n" % "\n".join(options))
997 ui.write("%s\n" % "\n".join(options))
998 return
998 return
999
999
1000 cmdlist = cmdutil.findpossible(cmd, table)
1000 cmdlist = cmdutil.findpossible(cmd, table)
1001 if ui.verbose:
1001 if ui.verbose:
1002 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1002 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1003 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1003 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1004
1004
1005 def debugfsinfo(ui, path = "."):
1005 def debugfsinfo(ui, path = "."):
1006 """show information detected about current filesystem"""
1006 """show information detected about current filesystem"""
1007 open('.debugfsinfo', 'w').write('')
1007 open('.debugfsinfo', 'w').write('')
1008 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1008 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1009 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1009 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1010 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1010 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1011 and 'yes' or 'no'))
1011 and 'yes' or 'no'))
1012 os.unlink('.debugfsinfo')
1012 os.unlink('.debugfsinfo')
1013
1013
1014 def debugrebuildstate(ui, repo, rev="tip"):
1014 def debugrebuildstate(ui, repo, rev="tip"):
1015 """rebuild the dirstate as it would look like for the given revision"""
1015 """rebuild the dirstate as it would look like for the given revision"""
1016 ctx = repo[rev]
1016 ctx = repo[rev]
1017 wlock = repo.wlock()
1017 wlock = repo.wlock()
1018 try:
1018 try:
1019 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1019 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1020 finally:
1020 finally:
1021 wlock.release()
1021 wlock.release()
1022
1022
1023 def debugcheckstate(ui, repo):
1023 def debugcheckstate(ui, repo):
1024 """validate the correctness of the current dirstate"""
1024 """validate the correctness of the current dirstate"""
1025 parent1, parent2 = repo.dirstate.parents()
1025 parent1, parent2 = repo.dirstate.parents()
1026 m1 = repo[parent1].manifest()
1026 m1 = repo[parent1].manifest()
1027 m2 = repo[parent2].manifest()
1027 m2 = repo[parent2].manifest()
1028 errors = 0
1028 errors = 0
1029 for f in repo.dirstate:
1029 for f in repo.dirstate:
1030 state = repo.dirstate[f]
1030 state = repo.dirstate[f]
1031 if state in "nr" and f not in m1:
1031 if state in "nr" and f not in m1:
1032 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1032 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1033 errors += 1
1033 errors += 1
1034 if state in "a" and f in m1:
1034 if state in "a" and f in m1:
1035 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1035 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1036 errors += 1
1036 errors += 1
1037 if state in "m" and f not in m1 and f not in m2:
1037 if state in "m" and f not in m1 and f not in m2:
1038 ui.warn(_("%s in state %s, but not in either manifest\n") %
1038 ui.warn(_("%s in state %s, but not in either manifest\n") %
1039 (f, state))
1039 (f, state))
1040 errors += 1
1040 errors += 1
1041 for f in m1:
1041 for f in m1:
1042 state = repo.dirstate[f]
1042 state = repo.dirstate[f]
1043 if state not in "nrm":
1043 if state not in "nrm":
1044 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1044 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1045 errors += 1
1045 errors += 1
1046 if errors:
1046 if errors:
1047 error = _(".hg/dirstate inconsistent with current parent's manifest")
1047 error = _(".hg/dirstate inconsistent with current parent's manifest")
1048 raise util.Abort(error)
1048 raise util.Abort(error)
1049
1049
1050 def showconfig(ui, repo, *values, **opts):
1050 def showconfig(ui, repo, *values, **opts):
1051 """show combined config settings from all hgrc files
1051 """show combined config settings from all hgrc files
1052
1052
1053 With no arguments, print names and values of all config items.
1053 With no arguments, print names and values of all config items.
1054
1054
1055 With one argument of the form section.name, print just the value
1055 With one argument of the form section.name, print just the value
1056 of that config item.
1056 of that config item.
1057
1057
1058 With multiple arguments, print names and values of all config
1058 With multiple arguments, print names and values of all config
1059 items with matching section names.
1059 items with matching section names.
1060
1060
1061 With --debug, the source (filename and line number) is printed
1061 With --debug, the source (filename and line number) is printed
1062 for each config item.
1062 for each config item.
1063
1063
1064 Returns 0 on success.
1064 Returns 0 on success.
1065 """
1065 """
1066
1066
1067 for f in util.rcpath():
1067 for f in util.rcpath():
1068 ui.debug(_('read config from: %s\n') % f)
1068 ui.debug(_('read config from: %s\n') % f)
1069 untrusted = bool(opts.get('untrusted'))
1069 untrusted = bool(opts.get('untrusted'))
1070 if values:
1070 if values:
1071 if len([v for v in values if '.' in v]) > 1:
1071 if len([v for v in values if '.' in v]) > 1:
1072 raise util.Abort(_('only one config item permitted'))
1072 raise util.Abort(_('only one config item permitted'))
1073 for section, name, value in ui.walkconfig(untrusted=untrusted):
1073 for section, name, value in ui.walkconfig(untrusted=untrusted):
1074 sectname = section + '.' + name
1074 sectname = section + '.' + name
1075 if values:
1075 if values:
1076 for v in values:
1076 for v in values:
1077 if v == section:
1077 if v == section:
1078 ui.debug('%s: ' %
1078 ui.debug('%s: ' %
1079 ui.configsource(section, name, untrusted))
1079 ui.configsource(section, name, untrusted))
1080 ui.write('%s=%s\n' % (sectname, value))
1080 ui.write('%s=%s\n' % (sectname, value))
1081 elif v == sectname:
1081 elif v == sectname:
1082 ui.debug('%s: ' %
1082 ui.debug('%s: ' %
1083 ui.configsource(section, name, untrusted))
1083 ui.configsource(section, name, untrusted))
1084 ui.write(value, '\n')
1084 ui.write(value, '\n')
1085 else:
1085 else:
1086 ui.debug('%s: ' %
1086 ui.debug('%s: ' %
1087 ui.configsource(section, name, untrusted))
1087 ui.configsource(section, name, untrusted))
1088 ui.write('%s=%s\n' % (sectname, value))
1088 ui.write('%s=%s\n' % (sectname, value))
1089
1089
1090 def debugpushkey(ui, repopath, namespace, *keyinfo):
1090 def debugpushkey(ui, repopath, namespace, *keyinfo):
1091 '''access the pushkey key/value protocol
1091 '''access the pushkey key/value protocol
1092
1092
1093 With two args, list the keys in the given namespace.
1093 With two args, list the keys in the given namespace.
1094
1094
1095 With five args, set a key to new if it currently is set to old.
1095 With five args, set a key to new if it currently is set to old.
1096 Reports success or failure.
1096 Reports success or failure.
1097 '''
1097 '''
1098
1098
1099 target = hg.repository(ui, repopath)
1099 target = hg.repository(ui, repopath)
1100 if keyinfo:
1100 if keyinfo:
1101 key, old, new = keyinfo
1101 key, old, new = keyinfo
1102 r = target.pushkey(namespace, key, old, new)
1102 r = target.pushkey(namespace, key, old, new)
1103 ui.status(str(r) + '\n')
1103 ui.status(str(r) + '\n')
1104 return not(r)
1104 return not(r)
1105 else:
1105 else:
1106 for k, v in target.listkeys(namespace).iteritems():
1106 for k, v in target.listkeys(namespace).iteritems():
1107 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1107 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1108 v.encode('string-escape')))
1108 v.encode('string-escape')))
1109
1109
1110 def debugrevspec(ui, repo, expr):
1110 def debugrevspec(ui, repo, expr):
1111 '''parse and apply a revision specification'''
1111 '''parse and apply a revision specification'''
1112 if ui.verbose:
1112 if ui.verbose:
1113 tree = revset.parse(expr)
1113 tree = revset.parse(expr)
1114 ui.note(tree, "\n")
1114 ui.note(tree, "\n")
1115 func = revset.match(expr)
1115 func = revset.match(expr)
1116 for c in func(repo, range(len(repo))):
1116 for c in func(repo, range(len(repo))):
1117 ui.write("%s\n" % c)
1117 ui.write("%s\n" % c)
1118
1118
1119 def debugsetparents(ui, repo, rev1, rev2=None):
1119 def debugsetparents(ui, repo, rev1, rev2=None):
1120 """manually set the parents of the current working directory
1120 """manually set the parents of the current working directory
1121
1121
1122 This is useful for writing repository conversion tools, but should
1122 This is useful for writing repository conversion tools, but should
1123 be used with care.
1123 be used with care.
1124
1124
1125 Returns 0 on success.
1125 Returns 0 on success.
1126 """
1126 """
1127
1127
1128 if not rev2:
1128 if not rev2:
1129 rev2 = hex(nullid)
1129 rev2 = hex(nullid)
1130
1130
1131 wlock = repo.wlock()
1131 wlock = repo.wlock()
1132 try:
1132 try:
1133 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
1133 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
1134 finally:
1134 finally:
1135 wlock.release()
1135 wlock.release()
1136
1136
1137 def debugstate(ui, repo, nodates=None):
1137 def debugstate(ui, repo, nodates=None):
1138 """show the contents of the current dirstate"""
1138 """show the contents of the current dirstate"""
1139 timestr = ""
1139 timestr = ""
1140 showdate = not nodates
1140 showdate = not nodates
1141 for file_, ent in sorted(repo.dirstate._map.iteritems()):
1141 for file_, ent in sorted(repo.dirstate._map.iteritems()):
1142 if showdate:
1142 if showdate:
1143 if ent[3] == -1:
1143 if ent[3] == -1:
1144 # Pad or slice to locale representation
1144 # Pad or slice to locale representation
1145 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
1145 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
1146 time.localtime(0)))
1146 time.localtime(0)))
1147 timestr = 'unset'
1147 timestr = 'unset'
1148 timestr = (timestr[:locale_len] +
1148 timestr = (timestr[:locale_len] +
1149 ' ' * (locale_len - len(timestr)))
1149 ' ' * (locale_len - len(timestr)))
1150 else:
1150 else:
1151 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
1151 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
1152 time.localtime(ent[3]))
1152 time.localtime(ent[3]))
1153 if ent[1] & 020000:
1153 if ent[1] & 020000:
1154 mode = 'lnk'
1154 mode = 'lnk'
1155 else:
1155 else:
1156 mode = '%3o' % (ent[1] & 0777)
1156 mode = '%3o' % (ent[1] & 0777)
1157 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
1157 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
1158 for f in repo.dirstate.copies():
1158 for f in repo.dirstate.copies():
1159 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
1159 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
1160
1160
1161 def debugsub(ui, repo, rev=None):
1161 def debugsub(ui, repo, rev=None):
1162 if rev == '':
1162 if rev == '':
1163 rev = None
1163 rev = None
1164 for k, v in sorted(repo[rev].substate.items()):
1164 for k, v in sorted(repo[rev].substate.items()):
1165 ui.write('path %s\n' % k)
1165 ui.write('path %s\n' % k)
1166 ui.write(' source %s\n' % v[0])
1166 ui.write(' source %s\n' % v[0])
1167 ui.write(' revision %s\n' % v[1])
1167 ui.write(' revision %s\n' % v[1])
1168
1168
1169 def debugdag(ui, repo, file_=None, *revs, **opts):
1169 def debugdag(ui, repo, file_=None, *revs, **opts):
1170 """format the changelog or an index DAG as a concise textual description
1170 """format the changelog or an index DAG as a concise textual description
1171
1171
1172 If you pass a revlog index, the revlog's DAG is emitted. If you list
1172 If you pass a revlog index, the revlog's DAG is emitted. If you list
1173 revision numbers, they get labelled in the output as rN.
1173 revision numbers, they get labelled in the output as rN.
1174
1174
1175 Otherwise, the changelog DAG of the current repo is emitted.
1175 Otherwise, the changelog DAG of the current repo is emitted.
1176 """
1176 """
1177 spaces = opts.get('spaces')
1177 spaces = opts.get('spaces')
1178 dots = opts.get('dots')
1178 dots = opts.get('dots')
1179 if file_:
1179 if file_:
1180 rlog = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
1180 rlog = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
1181 revs = set((int(r) for r in revs))
1181 revs = set((int(r) for r in revs))
1182 def events():
1182 def events():
1183 for r in rlog:
1183 for r in rlog:
1184 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1184 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1185 if r in revs:
1185 if r in revs:
1186 yield 'l', (r, "r%i" % r)
1186 yield 'l', (r, "r%i" % r)
1187 elif repo:
1187 elif repo:
1188 cl = repo.changelog
1188 cl = repo.changelog
1189 tags = opts.get('tags')
1189 tags = opts.get('tags')
1190 branches = opts.get('branches')
1190 branches = opts.get('branches')
1191 if tags:
1191 if tags:
1192 labels = {}
1192 labels = {}
1193 for l, n in repo.tags().items():
1193 for l, n in repo.tags().items():
1194 labels.setdefault(cl.rev(n), []).append(l)
1194 labels.setdefault(cl.rev(n), []).append(l)
1195 def events():
1195 def events():
1196 b = "default"
1196 b = "default"
1197 for r in cl:
1197 for r in cl:
1198 if branches:
1198 if branches:
1199 newb = cl.read(cl.node(r))[5]['branch']
1199 newb = cl.read(cl.node(r))[5]['branch']
1200 if newb != b:
1200 if newb != b:
1201 yield 'a', newb
1201 yield 'a', newb
1202 b = newb
1202 b = newb
1203 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1203 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1204 if tags:
1204 if tags:
1205 ls = labels.get(r)
1205 ls = labels.get(r)
1206 if ls:
1206 if ls:
1207 for l in ls:
1207 for l in ls:
1208 yield 'l', (r, l)
1208 yield 'l', (r, l)
1209 else:
1209 else:
1210 raise util.Abort(_('need repo for changelog dag'))
1210 raise util.Abort(_('need repo for changelog dag'))
1211
1211
1212 for line in dagparser.dagtextlines(events(),
1212 for line in dagparser.dagtextlines(events(),
1213 addspaces=spaces,
1213 addspaces=spaces,
1214 wraplabels=True,
1214 wraplabels=True,
1215 wrapannotations=True,
1215 wrapannotations=True,
1216 wrapnonlinear=dots,
1216 wrapnonlinear=dots,
1217 usedots=dots,
1217 usedots=dots,
1218 maxlinewidth=70):
1218 maxlinewidth=70):
1219 ui.write(line)
1219 ui.write(line)
1220 ui.write("\n")
1220 ui.write("\n")
1221
1221
1222 def debugdata(ui, file_, rev):
1222 def debugdata(ui, file_, rev):
1223 """dump the contents of a data file revision"""
1223 """dump the contents of a data file revision"""
1224 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_[:-2] + ".i")
1224 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_[:-2] + ".i")
1225 try:
1225 try:
1226 ui.write(r.revision(r.lookup(rev)))
1226 ui.write(r.revision(r.lookup(rev)))
1227 except KeyError:
1227 except KeyError:
1228 raise util.Abort(_('invalid revision identifier %s') % rev)
1228 raise util.Abort(_('invalid revision identifier %s') % rev)
1229
1229
1230 def debugdate(ui, date, range=None, **opts):
1230 def debugdate(ui, date, range=None, **opts):
1231 """parse and display a date"""
1231 """parse and display a date"""
1232 if opts["extended"]:
1232 if opts["extended"]:
1233 d = util.parsedate(date, util.extendeddateformats)
1233 d = util.parsedate(date, util.extendeddateformats)
1234 else:
1234 else:
1235 d = util.parsedate(date)
1235 d = util.parsedate(date)
1236 ui.write("internal: %s %s\n" % d)
1236 ui.write("internal: %s %s\n" % d)
1237 ui.write("standard: %s\n" % util.datestr(d))
1237 ui.write("standard: %s\n" % util.datestr(d))
1238 if range:
1238 if range:
1239 m = util.matchdate(range)
1239 m = util.matchdate(range)
1240 ui.write("match: %s\n" % m(d[0]))
1240 ui.write("match: %s\n" % m(d[0]))
1241
1241
1242 def debugindex(ui, file_):
1242 def debugindex(ui, file_):
1243 """dump the contents of an index file"""
1243 """dump the contents of an index file"""
1244 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
1244 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
1245 ui.write(" rev offset length base linkrev"
1245 ui.write(" rev offset length base linkrev"
1246 " nodeid p1 p2\n")
1246 " nodeid p1 p2\n")
1247 for i in r:
1247 for i in r:
1248 node = r.node(i)
1248 node = r.node(i)
1249 try:
1249 try:
1250 pp = r.parents(node)
1250 pp = r.parents(node)
1251 except:
1251 except:
1252 pp = [nullid, nullid]
1252 pp = [nullid, nullid]
1253 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1253 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1254 i, r.start(i), r.length(i), r.base(i), r.linkrev(i),
1254 i, r.start(i), r.length(i), r.base(i), r.linkrev(i),
1255 short(node), short(pp[0]), short(pp[1])))
1255 short(node), short(pp[0]), short(pp[1])))
1256
1256
1257 def debugindexdot(ui, file_):
1257 def debugindexdot(ui, file_):
1258 """dump an index DAG as a graphviz dot file"""
1258 """dump an index DAG as a graphviz dot file"""
1259 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
1259 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
1260 ui.write("digraph G {\n")
1260 ui.write("digraph G {\n")
1261 for i in r:
1261 for i in r:
1262 node = r.node(i)
1262 node = r.node(i)
1263 pp = r.parents(node)
1263 pp = r.parents(node)
1264 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1264 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1265 if pp[1] != nullid:
1265 if pp[1] != nullid:
1266 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1266 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1267 ui.write("}\n")
1267 ui.write("}\n")
1268
1268
1269 def debuginstall(ui):
1269 def debuginstall(ui):
1270 '''test Mercurial installation
1270 '''test Mercurial installation
1271
1271
1272 Returns 0 on success.
1272 Returns 0 on success.
1273 '''
1273 '''
1274
1274
1275 def writetemp(contents):
1275 def writetemp(contents):
1276 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1276 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1277 f = os.fdopen(fd, "wb")
1277 f = os.fdopen(fd, "wb")
1278 f.write(contents)
1278 f.write(contents)
1279 f.close()
1279 f.close()
1280 return name
1280 return name
1281
1281
1282 problems = 0
1282 problems = 0
1283
1283
1284 # encoding
1284 # encoding
1285 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1285 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1286 try:
1286 try:
1287 encoding.fromlocal("test")
1287 encoding.fromlocal("test")
1288 except util.Abort, inst:
1288 except util.Abort, inst:
1289 ui.write(" %s\n" % inst)
1289 ui.write(" %s\n" % inst)
1290 ui.write(_(" (check that your locale is properly set)\n"))
1290 ui.write(_(" (check that your locale is properly set)\n"))
1291 problems += 1
1291 problems += 1
1292
1292
1293 # compiled modules
1293 # compiled modules
1294 ui.status(_("Checking extensions...\n"))
1294 ui.status(_("Checking extensions...\n"))
1295 try:
1295 try:
1296 import bdiff, mpatch, base85
1296 import bdiff, mpatch, base85
1297 except Exception, inst:
1297 except Exception, inst:
1298 ui.write(" %s\n" % inst)
1298 ui.write(" %s\n" % inst)
1299 ui.write(_(" One or more extensions could not be found"))
1299 ui.write(_(" One or more extensions could not be found"))
1300 ui.write(_(" (check that you compiled the extensions)\n"))
1300 ui.write(_(" (check that you compiled the extensions)\n"))
1301 problems += 1
1301 problems += 1
1302
1302
1303 # templates
1303 # templates
1304 ui.status(_("Checking templates...\n"))
1304 ui.status(_("Checking templates...\n"))
1305 try:
1305 try:
1306 import templater
1306 import templater
1307 templater.templater(templater.templatepath("map-cmdline.default"))
1307 templater.templater(templater.templatepath("map-cmdline.default"))
1308 except Exception, inst:
1308 except Exception, inst:
1309 ui.write(" %s\n" % inst)
1309 ui.write(" %s\n" % inst)
1310 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1310 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1311 problems += 1
1311 problems += 1
1312
1312
1313 # patch
1313 # patch
1314 ui.status(_("Checking patch...\n"))
1314 ui.status(_("Checking patch...\n"))
1315 patchproblems = 0
1315 patchproblems = 0
1316 a = "1\n2\n3\n4\n"
1316 a = "1\n2\n3\n4\n"
1317 b = "1\n2\n3\ninsert\n4\n"
1317 b = "1\n2\n3\ninsert\n4\n"
1318 fa = writetemp(a)
1318 fa = writetemp(a)
1319 d = mdiff.unidiff(a, None, b, None, os.path.basename(fa),
1319 d = mdiff.unidiff(a, None, b, None, os.path.basename(fa),
1320 os.path.basename(fa))
1320 os.path.basename(fa))
1321 fd = writetemp(d)
1321 fd = writetemp(d)
1322
1322
1323 files = {}
1323 files = {}
1324 try:
1324 try:
1325 patch.patch(fd, ui, cwd=os.path.dirname(fa), files=files)
1325 patch.patch(fd, ui, cwd=os.path.dirname(fa), files=files)
1326 except util.Abort, e:
1326 except util.Abort, e:
1327 ui.write(_(" patch call failed:\n"))
1327 ui.write(_(" patch call failed:\n"))
1328 ui.write(" " + str(e) + "\n")
1328 ui.write(" " + str(e) + "\n")
1329 patchproblems += 1
1329 patchproblems += 1
1330 else:
1330 else:
1331 if list(files) != [os.path.basename(fa)]:
1331 if list(files) != [os.path.basename(fa)]:
1332 ui.write(_(" unexpected patch output!\n"))
1332 ui.write(_(" unexpected patch output!\n"))
1333 patchproblems += 1
1333 patchproblems += 1
1334 a = open(fa).read()
1334 a = open(fa).read()
1335 if a != b:
1335 if a != b:
1336 ui.write(_(" patch test failed!\n"))
1336 ui.write(_(" patch test failed!\n"))
1337 patchproblems += 1
1337 patchproblems += 1
1338
1338
1339 if patchproblems:
1339 if patchproblems:
1340 if ui.config('ui', 'patch'):
1340 if ui.config('ui', 'patch'):
1341 ui.write(_(" (Current patch tool may be incompatible with patch,"
1341 ui.write(_(" (Current patch tool may be incompatible with patch,"
1342 " or misconfigured. Please check your .hgrc file)\n"))
1342 " or misconfigured. Please check your .hgrc file)\n"))
1343 else:
1343 else:
1344 ui.write(_(" Internal patcher failure, please report this error"
1344 ui.write(_(" Internal patcher failure, please report this error"
1345 " to http://mercurial.selenic.com/bts/\n"))
1345 " to http://mercurial.selenic.com/bts/\n"))
1346 problems += patchproblems
1346 problems += patchproblems
1347
1347
1348 os.unlink(fa)
1348 os.unlink(fa)
1349 os.unlink(fd)
1349 os.unlink(fd)
1350
1350
1351 # editor
1351 # editor
1352 ui.status(_("Checking commit editor...\n"))
1352 ui.status(_("Checking commit editor...\n"))
1353 editor = ui.geteditor()
1353 editor = ui.geteditor()
1354 cmdpath = util.find_exe(editor) or util.find_exe(editor.split()[0])
1354 cmdpath = util.find_exe(editor) or util.find_exe(editor.split()[0])
1355 if not cmdpath:
1355 if not cmdpath:
1356 if editor == 'vi':
1356 if editor == 'vi':
1357 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1357 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1358 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
1358 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
1359 else:
1359 else:
1360 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1360 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1361 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
1361 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
1362 problems += 1
1362 problems += 1
1363
1363
1364 # check username
1364 # check username
1365 ui.status(_("Checking username...\n"))
1365 ui.status(_("Checking username...\n"))
1366 try:
1366 try:
1367 user = ui.username()
1367 user = ui.username()
1368 except util.Abort, e:
1368 except util.Abort, e:
1369 ui.write(" %s\n" % e)
1369 ui.write(" %s\n" % e)
1370 ui.write(_(" (specify a username in your .hgrc file)\n"))
1370 ui.write(_(" (specify a username in your .hgrc file)\n"))
1371 problems += 1
1371 problems += 1
1372
1372
1373 if not problems:
1373 if not problems:
1374 ui.status(_("No problems detected\n"))
1374 ui.status(_("No problems detected\n"))
1375 else:
1375 else:
1376 ui.write(_("%s problems detected,"
1376 ui.write(_("%s problems detected,"
1377 " please check your install!\n") % problems)
1377 " please check your install!\n") % problems)
1378
1378
1379 return problems
1379 return problems
1380
1380
1381 def debugrename(ui, repo, file1, *pats, **opts):
1381 def debugrename(ui, repo, file1, *pats, **opts):
1382 """dump rename information"""
1382 """dump rename information"""
1383
1383
1384 ctx = repo[opts.get('rev')]
1384 ctx = repo[opts.get('rev')]
1385 m = cmdutil.match(repo, (file1,) + pats, opts)
1385 m = cmdutil.match(repo, (file1,) + pats, opts)
1386 for abs in ctx.walk(m):
1386 for abs in ctx.walk(m):
1387 fctx = ctx[abs]
1387 fctx = ctx[abs]
1388 o = fctx.filelog().renamed(fctx.filenode())
1388 o = fctx.filelog().renamed(fctx.filenode())
1389 rel = m.rel(abs)
1389 rel = m.rel(abs)
1390 if o:
1390 if o:
1391 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1391 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1392 else:
1392 else:
1393 ui.write(_("%s not renamed\n") % rel)
1393 ui.write(_("%s not renamed\n") % rel)
1394
1394
1395 def debugwalk(ui, repo, *pats, **opts):
1395 def debugwalk(ui, repo, *pats, **opts):
1396 """show how files match on given patterns"""
1396 """show how files match on given patterns"""
1397 m = cmdutil.match(repo, pats, opts)
1397 m = cmdutil.match(repo, pats, opts)
1398 items = list(repo.walk(m))
1398 items = list(repo.walk(m))
1399 if not items:
1399 if not items:
1400 return
1400 return
1401 fmt = 'f %%-%ds %%-%ds %%s' % (
1401 fmt = 'f %%-%ds %%-%ds %%s' % (
1402 max([len(abs) for abs in items]),
1402 max([len(abs) for abs in items]),
1403 max([len(m.rel(abs)) for abs in items]))
1403 max([len(m.rel(abs)) for abs in items]))
1404 for abs in items:
1404 for abs in items:
1405 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
1405 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
1406 ui.write("%s\n" % line.rstrip())
1406 ui.write("%s\n" % line.rstrip())
1407
1407
1408 def diff(ui, repo, *pats, **opts):
1408 def diff(ui, repo, *pats, **opts):
1409 """diff repository (or selected files)
1409 """diff repository (or selected files)
1410
1410
1411 Show differences between revisions for the specified files.
1411 Show differences between revisions for the specified files.
1412
1412
1413 Differences between files are shown using the unified diff format.
1413 Differences between files are shown using the unified diff format.
1414
1414
1415 NOTE: diff may generate unexpected results for merges, as it will
1415 NOTE: diff may generate unexpected results for merges, as it will
1416 default to comparing against the working directory's first parent
1416 default to comparing against the working directory's first parent
1417 changeset if no revisions are specified.
1417 changeset if no revisions are specified.
1418
1418
1419 When two revision arguments are given, then changes are shown
1419 When two revision arguments are given, then changes are shown
1420 between those revisions. If only one revision is specified then
1420 between those revisions. If only one revision is specified then
1421 that revision is compared to the working directory, and, when no
1421 that revision is compared to the working directory, and, when no
1422 revisions are specified, the working directory files are compared
1422 revisions are specified, the working directory files are compared
1423 to its parent.
1423 to its parent.
1424
1424
1425 Alternatively you can specify -c/--change with a revision to see
1425 Alternatively you can specify -c/--change with a revision to see
1426 the changes in that changeset relative to its first parent.
1426 the changes in that changeset relative to its first parent.
1427
1427
1428 Without the -a/--text option, diff will avoid generating diffs of
1428 Without the -a/--text option, diff will avoid generating diffs of
1429 files it detects as binary. With -a, diff will generate a diff
1429 files it detects as binary. With -a, diff will generate a diff
1430 anyway, probably with undesirable results.
1430 anyway, probably with undesirable results.
1431
1431
1432 Use the -g/--git option to generate diffs in the git extended diff
1432 Use the -g/--git option to generate diffs in the git extended diff
1433 format. For more information, read :hg:`help diffs`.
1433 format. For more information, read :hg:`help diffs`.
1434
1434
1435 Returns 0 on success.
1435 Returns 0 on success.
1436 """
1436 """
1437
1437
1438 revs = opts.get('rev')
1438 revs = opts.get('rev')
1439 change = opts.get('change')
1439 change = opts.get('change')
1440 stat = opts.get('stat')
1440 stat = opts.get('stat')
1441 reverse = opts.get('reverse')
1441 reverse = opts.get('reverse')
1442
1442
1443 if revs and change:
1443 if revs and change:
1444 msg = _('cannot specify --rev and --change at the same time')
1444 msg = _('cannot specify --rev and --change at the same time')
1445 raise util.Abort(msg)
1445 raise util.Abort(msg)
1446 elif change:
1446 elif change:
1447 node2 = repo.lookup(change)
1447 node2 = repo.lookup(change)
1448 node1 = repo[node2].parents()[0].node()
1448 node1 = repo[node2].parents()[0].node()
1449 else:
1449 else:
1450 node1, node2 = cmdutil.revpair(repo, revs)
1450 node1, node2 = cmdutil.revpair(repo, revs)
1451
1451
1452 if reverse:
1452 if reverse:
1453 node1, node2 = node2, node1
1453 node1, node2 = node2, node1
1454
1454
1455 diffopts = patch.diffopts(ui, opts)
1455 diffopts = patch.diffopts(ui, opts)
1456 m = cmdutil.match(repo, pats, opts)
1456 m = cmdutil.match(repo, pats, opts)
1457 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat)
1457 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat)
1458
1458
1459 def export(ui, repo, *changesets, **opts):
1459 def export(ui, repo, *changesets, **opts):
1460 """dump the header and diffs for one or more changesets
1460 """dump the header and diffs for one or more changesets
1461
1461
1462 Print the changeset header and diffs for one or more revisions.
1462 Print the changeset header and diffs for one or more revisions.
1463
1463
1464 The information shown in the changeset header is: author, date,
1464 The information shown in the changeset header is: author, date,
1465 branch name (if non-default), changeset hash, parent(s) and commit
1465 branch name (if non-default), changeset hash, parent(s) and commit
1466 comment.
1466 comment.
1467
1467
1468 NOTE: export may generate unexpected diff output for merge
1468 NOTE: export may generate unexpected diff output for merge
1469 changesets, as it will compare the merge changeset against its
1469 changesets, as it will compare the merge changeset against its
1470 first parent only.
1470 first parent only.
1471
1471
1472 Output may be to a file, in which case the name of the file is
1472 Output may be to a file, in which case the name of the file is
1473 given using a format string. The formatting rules are as follows:
1473 given using a format string. The formatting rules are as follows:
1474
1474
1475 :``%%``: literal "%" character
1475 :``%%``: literal "%" character
1476 :``%H``: changeset hash (40 bytes of hexadecimal)
1476 :``%H``: changeset hash (40 bytes of hexadecimal)
1477 :``%N``: number of patches being generated
1477 :``%N``: number of patches being generated
1478 :``%R``: changeset revision number
1478 :``%R``: changeset revision number
1479 :``%b``: basename of the exporting repository
1479 :``%b``: basename of the exporting repository
1480 :``%h``: short-form changeset hash (12 bytes of hexadecimal)
1480 :``%h``: short-form changeset hash (12 bytes of hexadecimal)
1481 :``%n``: zero-padded sequence number, starting at 1
1481 :``%n``: zero-padded sequence number, starting at 1
1482 :``%r``: zero-padded changeset revision number
1482 :``%r``: zero-padded changeset revision number
1483
1483
1484 Without the -a/--text option, export will avoid generating diffs
1484 Without the -a/--text option, export will avoid generating diffs
1485 of files it detects as binary. With -a, export will generate a
1485 of files it detects as binary. With -a, export will generate a
1486 diff anyway, probably with undesirable results.
1486 diff anyway, probably with undesirable results.
1487
1487
1488 Use the -g/--git option to generate diffs in the git extended diff
1488 Use the -g/--git option to generate diffs in the git extended diff
1489 format. See :hg:`help diffs` for more information.
1489 format. See :hg:`help diffs` for more information.
1490
1490
1491 With the --switch-parent option, the diff will be against the
1491 With the --switch-parent option, the diff will be against the
1492 second parent. It can be useful to review a merge.
1492 second parent. It can be useful to review a merge.
1493
1493
1494 Returns 0 on success.
1494 Returns 0 on success.
1495 """
1495 """
1496 changesets += tuple(opts.get('rev', []))
1496 changesets += tuple(opts.get('rev', []))
1497 if not changesets:
1497 if not changesets:
1498 raise util.Abort(_("export requires at least one changeset"))
1498 raise util.Abort(_("export requires at least one changeset"))
1499 revs = cmdutil.revrange(repo, changesets)
1499 revs = cmdutil.revrange(repo, changesets)
1500 if len(revs) > 1:
1500 if len(revs) > 1:
1501 ui.note(_('exporting patches:\n'))
1501 ui.note(_('exporting patches:\n'))
1502 else:
1502 else:
1503 ui.note(_('exporting patch:\n'))
1503 ui.note(_('exporting patch:\n'))
1504 cmdutil.export(repo, revs, template=opts.get('output'),
1504 cmdutil.export(repo, revs, template=opts.get('output'),
1505 switch_parent=opts.get('switch_parent'),
1505 switch_parent=opts.get('switch_parent'),
1506 opts=patch.diffopts(ui, opts))
1506 opts=patch.diffopts(ui, opts))
1507
1507
1508 def forget(ui, repo, *pats, **opts):
1508 def forget(ui, repo, *pats, **opts):
1509 """forget the specified files on the next commit
1509 """forget the specified files on the next commit
1510
1510
1511 Mark the specified files so they will no longer be tracked
1511 Mark the specified files so they will no longer be tracked
1512 after the next commit.
1512 after the next commit.
1513
1513
1514 This only removes files from the current branch, not from the
1514 This only removes files from the current branch, not from the
1515 entire project history, and it does not delete them from the
1515 entire project history, and it does not delete them from the
1516 working directory.
1516 working directory.
1517
1517
1518 To undo a forget before the next commit, see :hg:`add`.
1518 To undo a forget before the next commit, see :hg:`add`.
1519
1519
1520 Returns 0 on success.
1520 Returns 0 on success.
1521 """
1521 """
1522
1522
1523 if not pats:
1523 if not pats:
1524 raise util.Abort(_('no files specified'))
1524 raise util.Abort(_('no files specified'))
1525
1525
1526 m = cmdutil.match(repo, pats, opts)
1526 m = cmdutil.match(repo, pats, opts)
1527 s = repo.status(match=m, clean=True)
1527 s = repo.status(match=m, clean=True)
1528 forget = sorted(s[0] + s[1] + s[3] + s[6])
1528 forget = sorted(s[0] + s[1] + s[3] + s[6])
1529 errs = 0
1529 errs = 0
1530
1530
1531 for f in m.files():
1531 for f in m.files():
1532 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
1532 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
1533 ui.warn(_('not removing %s: file is already untracked\n')
1533 ui.warn(_('not removing %s: file is already untracked\n')
1534 % m.rel(f))
1534 % m.rel(f))
1535 errs = 1
1535 errs = 1
1536
1536
1537 for f in forget:
1537 for f in forget:
1538 if ui.verbose or not m.exact(f):
1538 if ui.verbose or not m.exact(f):
1539 ui.status(_('removing %s\n') % m.rel(f))
1539 ui.status(_('removing %s\n') % m.rel(f))
1540
1540
1541 repo[None].remove(forget, unlink=False)
1541 repo[None].remove(forget, unlink=False)
1542 return errs
1542 return errs
1543
1543
1544 def grep(ui, repo, pattern, *pats, **opts):
1544 def grep(ui, repo, pattern, *pats, **opts):
1545 """search for a pattern in specified files and revisions
1545 """search for a pattern in specified files and revisions
1546
1546
1547 Search revisions of files for a regular expression.
1547 Search revisions of files for a regular expression.
1548
1548
1549 This command behaves differently than Unix grep. It only accepts
1549 This command behaves differently than Unix grep. It only accepts
1550 Python/Perl regexps. It searches repository history, not the
1550 Python/Perl regexps. It searches repository history, not the
1551 working directory. It always prints the revision number in which a
1551 working directory. It always prints the revision number in which a
1552 match appears.
1552 match appears.
1553
1553
1554 By default, grep only prints output for the first revision of a
1554 By default, grep only prints output for the first revision of a
1555 file in which it finds a match. To get it to print every revision
1555 file in which it finds a match. To get it to print every revision
1556 that contains a change in match status ("-" for a match that
1556 that contains a change in match status ("-" for a match that
1557 becomes a non-match, or "+" for a non-match that becomes a match),
1557 becomes a non-match, or "+" for a non-match that becomes a match),
1558 use the --all flag.
1558 use the --all flag.
1559
1559
1560 Returns 0 if a match is found, 1 otherwise.
1560 Returns 0 if a match is found, 1 otherwise.
1561 """
1561 """
1562 reflags = 0
1562 reflags = 0
1563 if opts.get('ignore_case'):
1563 if opts.get('ignore_case'):
1564 reflags |= re.I
1564 reflags |= re.I
1565 try:
1565 try:
1566 regexp = re.compile(pattern, reflags)
1566 regexp = re.compile(pattern, reflags)
1567 except Exception, inst:
1567 except Exception, inst:
1568 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
1568 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
1569 return 1
1569 return 1
1570 sep, eol = ':', '\n'
1570 sep, eol = ':', '\n'
1571 if opts.get('print0'):
1571 if opts.get('print0'):
1572 sep = eol = '\0'
1572 sep = eol = '\0'
1573
1573
1574 getfile = util.lrucachefunc(repo.file)
1574 getfile = util.lrucachefunc(repo.file)
1575
1575
1576 def matchlines(body):
1576 def matchlines(body):
1577 begin = 0
1577 begin = 0
1578 linenum = 0
1578 linenum = 0
1579 while True:
1579 while True:
1580 match = regexp.search(body, begin)
1580 match = regexp.search(body, begin)
1581 if not match:
1581 if not match:
1582 break
1582 break
1583 mstart, mend = match.span()
1583 mstart, mend = match.span()
1584 linenum += body.count('\n', begin, mstart) + 1
1584 linenum += body.count('\n', begin, mstart) + 1
1585 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1585 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1586 begin = body.find('\n', mend) + 1 or len(body)
1586 begin = body.find('\n', mend) + 1 or len(body)
1587 lend = begin - 1
1587 lend = begin - 1
1588 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1588 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1589
1589
1590 class linestate(object):
1590 class linestate(object):
1591 def __init__(self, line, linenum, colstart, colend):
1591 def __init__(self, line, linenum, colstart, colend):
1592 self.line = line
1592 self.line = line
1593 self.linenum = linenum
1593 self.linenum = linenum
1594 self.colstart = colstart
1594 self.colstart = colstart
1595 self.colend = colend
1595 self.colend = colend
1596
1596
1597 def __hash__(self):
1597 def __hash__(self):
1598 return hash((self.linenum, self.line))
1598 return hash((self.linenum, self.line))
1599
1599
1600 def __eq__(self, other):
1600 def __eq__(self, other):
1601 return self.line == other.line
1601 return self.line == other.line
1602
1602
1603 matches = {}
1603 matches = {}
1604 copies = {}
1604 copies = {}
1605 def grepbody(fn, rev, body):
1605 def grepbody(fn, rev, body):
1606 matches[rev].setdefault(fn, [])
1606 matches[rev].setdefault(fn, [])
1607 m = matches[rev][fn]
1607 m = matches[rev][fn]
1608 for lnum, cstart, cend, line in matchlines(body):
1608 for lnum, cstart, cend, line in matchlines(body):
1609 s = linestate(line, lnum, cstart, cend)
1609 s = linestate(line, lnum, cstart, cend)
1610 m.append(s)
1610 m.append(s)
1611
1611
1612 def difflinestates(a, b):
1612 def difflinestates(a, b):
1613 sm = difflib.SequenceMatcher(None, a, b)
1613 sm = difflib.SequenceMatcher(None, a, b)
1614 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
1614 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
1615 if tag == 'insert':
1615 if tag == 'insert':
1616 for i in xrange(blo, bhi):
1616 for i in xrange(blo, bhi):
1617 yield ('+', b[i])
1617 yield ('+', b[i])
1618 elif tag == 'delete':
1618 elif tag == 'delete':
1619 for i in xrange(alo, ahi):
1619 for i in xrange(alo, ahi):
1620 yield ('-', a[i])
1620 yield ('-', a[i])
1621 elif tag == 'replace':
1621 elif tag == 'replace':
1622 for i in xrange(alo, ahi):
1622 for i in xrange(alo, ahi):
1623 yield ('-', a[i])
1623 yield ('-', a[i])
1624 for i in xrange(blo, bhi):
1624 for i in xrange(blo, bhi):
1625 yield ('+', b[i])
1625 yield ('+', b[i])
1626
1626
1627 def display(fn, ctx, pstates, states):
1627 def display(fn, ctx, pstates, states):
1628 rev = ctx.rev()
1628 rev = ctx.rev()
1629 datefunc = ui.quiet and util.shortdate or util.datestr
1629 datefunc = ui.quiet and util.shortdate or util.datestr
1630 found = False
1630 found = False
1631 filerevmatches = {}
1631 filerevmatches = {}
1632 if opts.get('all'):
1632 if opts.get('all'):
1633 iter = difflinestates(pstates, states)
1633 iter = difflinestates(pstates, states)
1634 else:
1634 else:
1635 iter = [('', l) for l in states]
1635 iter = [('', l) for l in states]
1636 for change, l in iter:
1636 for change, l in iter:
1637 cols = [fn, str(rev)]
1637 cols = [fn, str(rev)]
1638 before, match, after = None, None, None
1638 before, match, after = None, None, None
1639 if opts.get('line_number'):
1639 if opts.get('line_number'):
1640 cols.append(str(l.linenum))
1640 cols.append(str(l.linenum))
1641 if opts.get('all'):
1641 if opts.get('all'):
1642 cols.append(change)
1642 cols.append(change)
1643 if opts.get('user'):
1643 if opts.get('user'):
1644 cols.append(ui.shortuser(ctx.user()))
1644 cols.append(ui.shortuser(ctx.user()))
1645 if opts.get('date'):
1645 if opts.get('date'):
1646 cols.append(datefunc(ctx.date()))
1646 cols.append(datefunc(ctx.date()))
1647 if opts.get('files_with_matches'):
1647 if opts.get('files_with_matches'):
1648 c = (fn, rev)
1648 c = (fn, rev)
1649 if c in filerevmatches:
1649 if c in filerevmatches:
1650 continue
1650 continue
1651 filerevmatches[c] = 1
1651 filerevmatches[c] = 1
1652 else:
1652 else:
1653 before = l.line[:l.colstart]
1653 before = l.line[:l.colstart]
1654 match = l.line[l.colstart:l.colend]
1654 match = l.line[l.colstart:l.colend]
1655 after = l.line[l.colend:]
1655 after = l.line[l.colend:]
1656 ui.write(sep.join(cols))
1656 ui.write(sep.join(cols))
1657 if before is not None:
1657 if before is not None:
1658 ui.write(sep + before)
1658 ui.write(sep + before)
1659 ui.write(match, label='grep.match')
1659 ui.write(match, label='grep.match')
1660 ui.write(after)
1660 ui.write(after)
1661 ui.write(eol)
1661 ui.write(eol)
1662 found = True
1662 found = True
1663 return found
1663 return found
1664
1664
1665 skip = {}
1665 skip = {}
1666 revfiles = {}
1666 revfiles = {}
1667 matchfn = cmdutil.match(repo, pats, opts)
1667 matchfn = cmdutil.match(repo, pats, opts)
1668 found = False
1668 found = False
1669 follow = opts.get('follow')
1669 follow = opts.get('follow')
1670
1670
1671 def prep(ctx, fns):
1671 def prep(ctx, fns):
1672 rev = ctx.rev()
1672 rev = ctx.rev()
1673 pctx = ctx.parents()[0]
1673 pctx = ctx.parents()[0]
1674 parent = pctx.rev()
1674 parent = pctx.rev()
1675 matches.setdefault(rev, {})
1675 matches.setdefault(rev, {})
1676 matches.setdefault(parent, {})
1676 matches.setdefault(parent, {})
1677 files = revfiles.setdefault(rev, [])
1677 files = revfiles.setdefault(rev, [])
1678 for fn in fns:
1678 for fn in fns:
1679 flog = getfile(fn)
1679 flog = getfile(fn)
1680 try:
1680 try:
1681 fnode = ctx.filenode(fn)
1681 fnode = ctx.filenode(fn)
1682 except error.LookupError:
1682 except error.LookupError:
1683 continue
1683 continue
1684
1684
1685 copied = flog.renamed(fnode)
1685 copied = flog.renamed(fnode)
1686 copy = follow and copied and copied[0]
1686 copy = follow and copied and copied[0]
1687 if copy:
1687 if copy:
1688 copies.setdefault(rev, {})[fn] = copy
1688 copies.setdefault(rev, {})[fn] = copy
1689 if fn in skip:
1689 if fn in skip:
1690 if copy:
1690 if copy:
1691 skip[copy] = True
1691 skip[copy] = True
1692 continue
1692 continue
1693 files.append(fn)
1693 files.append(fn)
1694
1694
1695 if fn not in matches[rev]:
1695 if fn not in matches[rev]:
1696 grepbody(fn, rev, flog.read(fnode))
1696 grepbody(fn, rev, flog.read(fnode))
1697
1697
1698 pfn = copy or fn
1698 pfn = copy or fn
1699 if pfn not in matches[parent]:
1699 if pfn not in matches[parent]:
1700 try:
1700 try:
1701 fnode = pctx.filenode(pfn)
1701 fnode = pctx.filenode(pfn)
1702 grepbody(pfn, parent, flog.read(fnode))
1702 grepbody(pfn, parent, flog.read(fnode))
1703 except error.LookupError:
1703 except error.LookupError:
1704 pass
1704 pass
1705
1705
1706 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
1706 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
1707 rev = ctx.rev()
1707 rev = ctx.rev()
1708 parent = ctx.parents()[0].rev()
1708 parent = ctx.parents()[0].rev()
1709 for fn in sorted(revfiles.get(rev, [])):
1709 for fn in sorted(revfiles.get(rev, [])):
1710 states = matches[rev][fn]
1710 states = matches[rev][fn]
1711 copy = copies.get(rev, {}).get(fn)
1711 copy = copies.get(rev, {}).get(fn)
1712 if fn in skip:
1712 if fn in skip:
1713 if copy:
1713 if copy:
1714 skip[copy] = True
1714 skip[copy] = True
1715 continue
1715 continue
1716 pstates = matches.get(parent, {}).get(copy or fn, [])
1716 pstates = matches.get(parent, {}).get(copy or fn, [])
1717 if pstates or states:
1717 if pstates or states:
1718 r = display(fn, ctx, pstates, states)
1718 r = display(fn, ctx, pstates, states)
1719 found = found or r
1719 found = found or r
1720 if r and not opts.get('all'):
1720 if r and not opts.get('all'):
1721 skip[fn] = True
1721 skip[fn] = True
1722 if copy:
1722 if copy:
1723 skip[copy] = True
1723 skip[copy] = True
1724 del matches[rev]
1724 del matches[rev]
1725 del revfiles[rev]
1725 del revfiles[rev]
1726
1726
1727 return not found
1727 return not found
1728
1728
1729 def heads(ui, repo, *branchrevs, **opts):
1729 def heads(ui, repo, *branchrevs, **opts):
1730 """show current repository heads or show branch heads
1730 """show current repository heads or show branch heads
1731
1731
1732 With no arguments, show all repository branch heads.
1732 With no arguments, show all repository branch heads.
1733
1733
1734 Repository "heads" are changesets with no child changesets. They are
1734 Repository "heads" are changesets with no child changesets. They are
1735 where development generally takes place and are the usual targets
1735 where development generally takes place and are the usual targets
1736 for update and merge operations. Branch heads are changesets that have
1736 for update and merge operations. Branch heads are changesets that have
1737 no child changeset on the same branch.
1737 no child changeset on the same branch.
1738
1738
1739 If one or more REVs are given, only branch heads on the branches
1739 If one or more REVs are given, only branch heads on the branches
1740 associated with the specified changesets are shown.
1740 associated with the specified changesets are shown.
1741
1741
1742 If -c/--closed is specified, also show branch heads marked closed
1742 If -c/--closed is specified, also show branch heads marked closed
1743 (see :hg:`commit --close-branch`).
1743 (see :hg:`commit --close-branch`).
1744
1744
1745 If STARTREV is specified, only those heads that are descendants of
1745 If STARTREV is specified, only those heads that are descendants of
1746 STARTREV will be displayed.
1746 STARTREV will be displayed.
1747
1747
1748 If -t/--topo is specified, named branch mechanics will be ignored and only
1748 If -t/--topo is specified, named branch mechanics will be ignored and only
1749 changesets without children will be shown.
1749 changesets without children will be shown.
1750
1750
1751 Returns 0 if matching heads are found, 1 if not.
1751 Returns 0 if matching heads are found, 1 if not.
1752 """
1752 """
1753
1753
1754 if opts.get('rev'):
1754 if opts.get('rev'):
1755 start = repo.lookup(opts['rev'])
1755 start = repo.lookup(opts['rev'])
1756 else:
1756 else:
1757 start = None
1757 start = None
1758
1758
1759 if opts.get('topo'):
1759 if opts.get('topo'):
1760 heads = [repo[h] for h in repo.heads(start)]
1760 heads = [repo[h] for h in repo.heads(start)]
1761 else:
1761 else:
1762 heads = []
1762 heads = []
1763 for b, ls in repo.branchmap().iteritems():
1763 for b, ls in repo.branchmap().iteritems():
1764 if start is None:
1764 if start is None:
1765 heads += [repo[h] for h in ls]
1765 heads += [repo[h] for h in ls]
1766 continue
1766 continue
1767 startrev = repo.changelog.rev(start)
1767 startrev = repo.changelog.rev(start)
1768 descendants = set(repo.changelog.descendants(startrev))
1768 descendants = set(repo.changelog.descendants(startrev))
1769 descendants.add(startrev)
1769 descendants.add(startrev)
1770 rev = repo.changelog.rev
1770 rev = repo.changelog.rev
1771 heads += [repo[h] for h in ls if rev(h) in descendants]
1771 heads += [repo[h] for h in ls if rev(h) in descendants]
1772
1772
1773 if branchrevs:
1773 if branchrevs:
1774 decode, encode = encoding.fromlocal, encoding.tolocal
1774 decode, encode = encoding.fromlocal, encoding.tolocal
1775 branches = set(repo[decode(br)].branch() for br in branchrevs)
1775 branches = set(repo[decode(br)].branch() for br in branchrevs)
1776 heads = [h for h in heads if h.branch() in branches]
1776 heads = [h for h in heads if h.branch() in branches]
1777
1777
1778 if not opts.get('closed'):
1778 if not opts.get('closed'):
1779 heads = [h for h in heads if not h.extra().get('close')]
1779 heads = [h for h in heads if not h.extra().get('close')]
1780
1780
1781 if opts.get('active') and branchrevs:
1781 if opts.get('active') and branchrevs:
1782 dagheads = repo.heads(start)
1782 dagheads = repo.heads(start)
1783 heads = [h for h in heads if h.node() in dagheads]
1783 heads = [h for h in heads if h.node() in dagheads]
1784
1784
1785 if branchrevs:
1785 if branchrevs:
1786 haveheads = set(h.branch() for h in heads)
1786 haveheads = set(h.branch() for h in heads)
1787 if branches - haveheads:
1787 if branches - haveheads:
1788 headless = ', '.join(encode(b) for b in branches - haveheads)
1788 headless = ', '.join(encode(b) for b in branches - haveheads)
1789 msg = _('no open branch heads found on branches %s')
1789 msg = _('no open branch heads found on branches %s')
1790 if opts.get('rev'):
1790 if opts.get('rev'):
1791 msg += _(' (started at %s)' % opts['rev'])
1791 msg += _(' (started at %s)' % opts['rev'])
1792 ui.warn((msg + '\n') % headless)
1792 ui.warn((msg + '\n') % headless)
1793
1793
1794 if not heads:
1794 if not heads:
1795 return 1
1795 return 1
1796
1796
1797 heads = sorted(heads, key=lambda x: -x.rev())
1797 heads = sorted(heads, key=lambda x: -x.rev())
1798 displayer = cmdutil.show_changeset(ui, repo, opts)
1798 displayer = cmdutil.show_changeset(ui, repo, opts)
1799 for ctx in heads:
1799 for ctx in heads:
1800 displayer.show(ctx)
1800 displayer.show(ctx)
1801 displayer.close()
1801 displayer.close()
1802
1802
1803 def help_(ui, name=None, with_version=False, unknowncmd=False):
1803 def help_(ui, name=None, with_version=False, unknowncmd=False):
1804 """show help for a given topic or a help overview
1804 """show help for a given topic or a help overview
1805
1805
1806 With no arguments, print a list of commands with short help messages.
1806 With no arguments, print a list of commands with short help messages.
1807
1807
1808 Given a topic, extension, or command name, print help for that
1808 Given a topic, extension, or command name, print help for that
1809 topic.
1809 topic.
1810
1810
1811 Returns 0 if successful.
1811 Returns 0 if successful.
1812 """
1812 """
1813 option_lists = []
1813 option_lists = []
1814 textwidth = util.termwidth() - 2
1814 textwidth = util.termwidth() - 2
1815
1815
1816 def addglobalopts(aliases):
1816 def addglobalopts(aliases):
1817 if ui.verbose:
1817 if ui.verbose:
1818 option_lists.append((_("global options:"), globalopts))
1818 option_lists.append((_("global options:"), globalopts))
1819 if name == 'shortlist':
1819 if name == 'shortlist':
1820 option_lists.append((_('use "hg help" for the full list '
1820 option_lists.append((_('use "hg help" for the full list '
1821 'of commands'), ()))
1821 'of commands'), ()))
1822 else:
1822 else:
1823 if name == 'shortlist':
1823 if name == 'shortlist':
1824 msg = _('use "hg help" for the full list of commands '
1824 msg = _('use "hg help" for the full list of commands '
1825 'or "hg -v" for details')
1825 'or "hg -v" for details')
1826 elif aliases:
1826 elif aliases:
1827 msg = _('use "hg -v help%s" to show aliases and '
1827 msg = _('use "hg -v help%s" to show aliases and '
1828 'global options') % (name and " " + name or "")
1828 'global options') % (name and " " + name or "")
1829 else:
1829 else:
1830 msg = _('use "hg -v help %s" to show global options') % name
1830 msg = _('use "hg -v help %s" to show global options') % name
1831 option_lists.append((msg, ()))
1831 option_lists.append((msg, ()))
1832
1832
1833 def helpcmd(name):
1833 def helpcmd(name):
1834 if with_version:
1834 if with_version:
1835 version_(ui)
1835 version_(ui)
1836 ui.write('\n')
1836 ui.write('\n')
1837
1837
1838 try:
1838 try:
1839 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
1839 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
1840 except error.AmbiguousCommand, inst:
1840 except error.AmbiguousCommand, inst:
1841 # py3k fix: except vars can't be used outside the scope of the
1841 # py3k fix: except vars can't be used outside the scope of the
1842 # except block, nor can be used inside a lambda. python issue4617
1842 # except block, nor can be used inside a lambda. python issue4617
1843 prefix = inst.args[0]
1843 prefix = inst.args[0]
1844 select = lambda c: c.lstrip('^').startswith(prefix)
1844 select = lambda c: c.lstrip('^').startswith(prefix)
1845 helplist(_('list of commands:\n\n'), select)
1845 helplist(_('list of commands:\n\n'), select)
1846 return
1846 return
1847
1847
1848 # check if it's an invalid alias and display its error if it is
1848 # check if it's an invalid alias and display its error if it is
1849 if getattr(entry[0], 'badalias', False):
1849 if getattr(entry[0], 'badalias', False):
1850 if not unknowncmd:
1850 if not unknowncmd:
1851 entry[0](ui)
1851 entry[0](ui)
1852 return
1852 return
1853
1853
1854 # synopsis
1854 # synopsis
1855 if len(entry) > 2:
1855 if len(entry) > 2:
1856 if entry[2].startswith('hg'):
1856 if entry[2].startswith('hg'):
1857 ui.write("%s\n" % entry[2])
1857 ui.write("%s\n" % entry[2])
1858 else:
1858 else:
1859 ui.write('hg %s %s\n' % (aliases[0], entry[2]))
1859 ui.write('hg %s %s\n' % (aliases[0], entry[2]))
1860 else:
1860 else:
1861 ui.write('hg %s\n' % aliases[0])
1861 ui.write('hg %s\n' % aliases[0])
1862
1862
1863 # aliases
1863 # aliases
1864 if not ui.quiet and len(aliases) > 1:
1864 if not ui.quiet and len(aliases) > 1:
1865 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
1865 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
1866
1866
1867 # description
1867 # description
1868 doc = gettext(entry[0].__doc__)
1868 doc = gettext(entry[0].__doc__)
1869 if not doc:
1869 if not doc:
1870 doc = _("(no help text available)")
1870 doc = _("(no help text available)")
1871 if hasattr(entry[0], 'definition'): # aliased command
1871 if hasattr(entry[0], 'definition'): # aliased command
1872 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
1872 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
1873 if ui.quiet:
1873 if ui.quiet:
1874 doc = doc.splitlines()[0]
1874 doc = doc.splitlines()[0]
1875 keep = ui.verbose and ['verbose'] or []
1875 keep = ui.verbose and ['verbose'] or []
1876 formatted, pruned = minirst.format(doc, textwidth, keep=keep)
1876 formatted, pruned = minirst.format(doc, textwidth, keep=keep)
1877 ui.write("\n%s\n" % formatted)
1877 ui.write("\n%s\n" % formatted)
1878 if pruned:
1878 if pruned:
1879 ui.write(_('\nuse "hg -v help %s" to show verbose help\n') % name)
1879 ui.write(_('\nuse "hg -v help %s" to show verbose help\n') % name)
1880
1880
1881 if not ui.quiet:
1881 if not ui.quiet:
1882 # options
1882 # options
1883 if entry[1]:
1883 if entry[1]:
1884 option_lists.append((_("options:\n"), entry[1]))
1884 option_lists.append((_("options:\n"), entry[1]))
1885
1885
1886 addglobalopts(False)
1886 addglobalopts(False)
1887
1887
1888 def helplist(header, select=None):
1888 def helplist(header, select=None):
1889 h = {}
1889 h = {}
1890 cmds = {}
1890 cmds = {}
1891 for c, e in table.iteritems():
1891 for c, e in table.iteritems():
1892 f = c.split("|", 1)[0]
1892 f = c.split("|", 1)[0]
1893 if select and not select(f):
1893 if select and not select(f):
1894 continue
1894 continue
1895 if (not select and name != 'shortlist' and
1895 if (not select and name != 'shortlist' and
1896 e[0].__module__ != __name__):
1896 e[0].__module__ != __name__):
1897 continue
1897 continue
1898 if name == "shortlist" and not f.startswith("^"):
1898 if name == "shortlist" and not f.startswith("^"):
1899 continue
1899 continue
1900 f = f.lstrip("^")
1900 f = f.lstrip("^")
1901 if not ui.debugflag and f.startswith("debug"):
1901 if not ui.debugflag and f.startswith("debug"):
1902 continue
1902 continue
1903 doc = e[0].__doc__
1903 doc = e[0].__doc__
1904 if doc and 'DEPRECATED' in doc and not ui.verbose:
1904 if doc and 'DEPRECATED' in doc and not ui.verbose:
1905 continue
1905 continue
1906 doc = gettext(doc)
1906 doc = gettext(doc)
1907 if not doc:
1907 if not doc:
1908 doc = _("(no help text available)")
1908 doc = _("(no help text available)")
1909 h[f] = doc.splitlines()[0].rstrip()
1909 h[f] = doc.splitlines()[0].rstrip()
1910 cmds[f] = c.lstrip("^")
1910 cmds[f] = c.lstrip("^")
1911
1911
1912 if not h:
1912 if not h:
1913 ui.status(_('no commands defined\n'))
1913 ui.status(_('no commands defined\n'))
1914 return
1914 return
1915
1915
1916 ui.status(header)
1916 ui.status(header)
1917 fns = sorted(h)
1917 fns = sorted(h)
1918 m = max(map(len, fns))
1918 m = max(map(len, fns))
1919 for f in fns:
1919 for f in fns:
1920 if ui.verbose:
1920 if ui.verbose:
1921 commands = cmds[f].replace("|",", ")
1921 commands = cmds[f].replace("|",", ")
1922 ui.write(" %s:\n %s\n"%(commands, h[f]))
1922 ui.write(" %s:\n %s\n"%(commands, h[f]))
1923 else:
1923 else:
1924 ui.write('%s\n' % (util.wrap(h[f],
1924 ui.write('%s\n' % (util.wrap(h[f],
1925 initindent=' %-*s ' % (m, f),
1925 initindent=' %-*s ' % (m, f),
1926 hangindent=' ' * (m + 4))))
1926 hangindent=' ' * (m + 4))))
1927
1927
1928 if not ui.quiet:
1928 if not ui.quiet:
1929 addglobalopts(True)
1929 addglobalopts(True)
1930
1930
1931 def helptopic(name):
1931 def helptopic(name):
1932 for names, header, doc in help.helptable:
1932 for names, header, doc in help.helptable:
1933 if name in names:
1933 if name in names:
1934 break
1934 break
1935 else:
1935 else:
1936 raise error.UnknownCommand(name)
1936 raise error.UnknownCommand(name)
1937
1937
1938 # description
1938 # description
1939 if not doc:
1939 if not doc:
1940 doc = _("(no help text available)")
1940 doc = _("(no help text available)")
1941 if hasattr(doc, '__call__'):
1941 if hasattr(doc, '__call__'):
1942 doc = doc()
1942 doc = doc()
1943
1943
1944 ui.write("%s\n\n" % header)
1944 ui.write("%s\n\n" % header)
1945 ui.write("%s\n" % minirst.format(doc, textwidth, indent=4))
1945 ui.write("%s\n" % minirst.format(doc, textwidth, indent=4))
1946
1946
1947 def helpext(name):
1947 def helpext(name):
1948 try:
1948 try:
1949 mod = extensions.find(name)
1949 mod = extensions.find(name)
1950 doc = gettext(mod.__doc__) or _('no help text available')
1950 doc = gettext(mod.__doc__) or _('no help text available')
1951 except KeyError:
1951 except KeyError:
1952 mod = None
1952 mod = None
1953 doc = extensions.disabledext(name)
1953 doc = extensions.disabledext(name)
1954 if not doc:
1954 if not doc:
1955 raise error.UnknownCommand(name)
1955 raise error.UnknownCommand(name)
1956
1956
1957 if '\n' not in doc:
1957 if '\n' not in doc:
1958 head, tail = doc, ""
1958 head, tail = doc, ""
1959 else:
1959 else:
1960 head, tail = doc.split('\n', 1)
1960 head, tail = doc.split('\n', 1)
1961 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
1961 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
1962 if tail:
1962 if tail:
1963 ui.write(minirst.format(tail, textwidth))
1963 ui.write(minirst.format(tail, textwidth))
1964 ui.status('\n\n')
1964 ui.status('\n\n')
1965
1965
1966 if mod:
1966 if mod:
1967 try:
1967 try:
1968 ct = mod.cmdtable
1968 ct = mod.cmdtable
1969 except AttributeError:
1969 except AttributeError:
1970 ct = {}
1970 ct = {}
1971 modcmds = set([c.split('|', 1)[0] for c in ct])
1971 modcmds = set([c.split('|', 1)[0] for c in ct])
1972 helplist(_('list of commands:\n\n'), modcmds.__contains__)
1972 helplist(_('list of commands:\n\n'), modcmds.__contains__)
1973 else:
1973 else:
1974 ui.write(_('use "hg help extensions" for information on enabling '
1974 ui.write(_('use "hg help extensions" for information on enabling '
1975 'extensions\n'))
1975 'extensions\n'))
1976
1976
1977 def helpextcmd(name):
1977 def helpextcmd(name):
1978 cmd, ext, mod = extensions.disabledcmd(name, ui.config('ui', 'strict'))
1978 cmd, ext, mod = extensions.disabledcmd(name, ui.config('ui', 'strict'))
1979 doc = gettext(mod.__doc__).splitlines()[0]
1979 doc = gettext(mod.__doc__).splitlines()[0]
1980
1980
1981 msg = help.listexts(_("'%s' is provided by the following "
1981 msg = help.listexts(_("'%s' is provided by the following "
1982 "extension:") % cmd, {ext: doc}, len(ext),
1982 "extension:") % cmd, {ext: doc}, len(ext),
1983 indent=4)
1983 indent=4)
1984 ui.write(minirst.format(msg, textwidth))
1984 ui.write(minirst.format(msg, textwidth))
1985 ui.write('\n\n')
1985 ui.write('\n\n')
1986 ui.write(_('use "hg help extensions" for information on enabling '
1986 ui.write(_('use "hg help extensions" for information on enabling '
1987 'extensions\n'))
1987 'extensions\n'))
1988
1988
1989 if name and name != 'shortlist':
1989 if name and name != 'shortlist':
1990 i = None
1990 i = None
1991 if unknowncmd:
1991 if unknowncmd:
1992 queries = (helpextcmd,)
1992 queries = (helpextcmd,)
1993 else:
1993 else:
1994 queries = (helptopic, helpcmd, helpext, helpextcmd)
1994 queries = (helptopic, helpcmd, helpext, helpextcmd)
1995 for f in queries:
1995 for f in queries:
1996 try:
1996 try:
1997 f(name)
1997 f(name)
1998 i = None
1998 i = None
1999 break
1999 break
2000 except error.UnknownCommand, inst:
2000 except error.UnknownCommand, inst:
2001 i = inst
2001 i = inst
2002 if i:
2002 if i:
2003 raise i
2003 raise i
2004
2004
2005 else:
2005 else:
2006 # program name
2006 # program name
2007 if ui.verbose or with_version:
2007 if ui.verbose or with_version:
2008 version_(ui)
2008 version_(ui)
2009 else:
2009 else:
2010 ui.status(_("Mercurial Distributed SCM\n"))
2010 ui.status(_("Mercurial Distributed SCM\n"))
2011 ui.status('\n')
2011 ui.status('\n')
2012
2012
2013 # list of commands
2013 # list of commands
2014 if name == "shortlist":
2014 if name == "shortlist":
2015 header = _('basic commands:\n\n')
2015 header = _('basic commands:\n\n')
2016 else:
2016 else:
2017 header = _('list of commands:\n\n')
2017 header = _('list of commands:\n\n')
2018
2018
2019 helplist(header)
2019 helplist(header)
2020 if name != 'shortlist':
2020 if name != 'shortlist':
2021 exts, maxlength = extensions.enabled()
2021 exts, maxlength = extensions.enabled()
2022 text = help.listexts(_('enabled extensions:'), exts, maxlength)
2022 text = help.listexts(_('enabled extensions:'), exts, maxlength)
2023 if text:
2023 if text:
2024 ui.write("\n%s\n" % minirst.format(text, textwidth))
2024 ui.write("\n%s\n" % minirst.format(text, textwidth))
2025
2025
2026 # list all option lists
2026 # list all option lists
2027 opt_output = []
2027 opt_output = []
2028 multioccur = False
2028 multioccur = False
2029 for title, options in option_lists:
2029 for title, options in option_lists:
2030 opt_output.append(("\n%s" % title, None))
2030 opt_output.append(("\n%s" % title, None))
2031 for option in options:
2031 for option in options:
2032 if len(option) == 5:
2032 if len(option) == 5:
2033 shortopt, longopt, default, desc, optlabel = option
2033 shortopt, longopt, default, desc, optlabel = option
2034 else:
2034 else:
2035 shortopt, longopt, default, desc = option
2035 shortopt, longopt, default, desc = option
2036 optlabel = _("VALUE") # default label
2036 optlabel = _("VALUE") # default label
2037
2037
2038 if _("DEPRECATED") in desc and not ui.verbose:
2038 if _("DEPRECATED") in desc and not ui.verbose:
2039 continue
2039 continue
2040 if isinstance(default, list):
2040 if isinstance(default, list):
2041 numqualifier = " %s [+]" % optlabel
2041 numqualifier = " %s [+]" % optlabel
2042 multioccur = True
2042 multioccur = True
2043 elif (default is not None) and not isinstance(default, bool):
2043 elif (default is not None) and not isinstance(default, bool):
2044 numqualifier = " %s" % optlabel
2044 numqualifier = " %s" % optlabel
2045 else:
2045 else:
2046 numqualifier = ""
2046 numqualifier = ""
2047 opt_output.append(("%2s%s" %
2047 opt_output.append(("%2s%s" %
2048 (shortopt and "-%s" % shortopt,
2048 (shortopt and "-%s" % shortopt,
2049 longopt and " --%s%s" %
2049 longopt and " --%s%s" %
2050 (longopt, numqualifier)),
2050 (longopt, numqualifier)),
2051 "%s%s" % (desc,
2051 "%s%s" % (desc,
2052 default
2052 default
2053 and _(" (default: %s)") % default
2053 and _(" (default: %s)") % default
2054 or "")))
2054 or "")))
2055 if multioccur:
2055 if multioccur:
2056 msg = _("\n[+] marked option can be specified multiple times")
2056 msg = _("\n[+] marked option can be specified multiple times")
2057 if ui.verbose and name != 'shortlist':
2057 if ui.verbose and name != 'shortlist':
2058 opt_output.append((msg, None))
2058 opt_output.append((msg, None))
2059 else:
2059 else:
2060 opt_output.insert(-1, (msg, None))
2060 opt_output.insert(-1, (msg, None))
2061
2061
2062 if not name:
2062 if not name:
2063 ui.write(_("\nadditional help topics:\n\n"))
2063 ui.write(_("\nadditional help topics:\n\n"))
2064 topics = []
2064 topics = []
2065 for names, header, doc in help.helptable:
2065 for names, header, doc in help.helptable:
2066 topics.append((sorted(names, key=len, reverse=True)[0], header))
2066 topics.append((sorted(names, key=len, reverse=True)[0], header))
2067 topics_len = max([len(s[0]) for s in topics])
2067 topics_len = max([len(s[0]) for s in topics])
2068 for t, desc in topics:
2068 for t, desc in topics:
2069 ui.write(" %-*s %s\n" % (topics_len, t, desc))
2069 ui.write(" %-*s %s\n" % (topics_len, t, desc))
2070
2070
2071 if opt_output:
2071 if opt_output:
2072 colwidth = encoding.colwidth
2072 colwidth = encoding.colwidth
2073 # normalize: (opt or message, desc or None, width of opt)
2073 # normalize: (opt or message, desc or None, width of opt)
2074 entries = [desc and (opt, desc, colwidth(opt)) or (opt, None, 0)
2074 entries = [desc and (opt, desc, colwidth(opt)) or (opt, None, 0)
2075 for opt, desc in opt_output]
2075 for opt, desc in opt_output]
2076 hanging = max([e[2] for e in entries])
2076 hanging = max([e[2] for e in entries])
2077 for opt, desc, width in entries:
2077 for opt, desc, width in entries:
2078 if desc:
2078 if desc:
2079 initindent = ' %s%s ' % (opt, ' ' * (hanging - width))
2079 initindent = ' %s%s ' % (opt, ' ' * (hanging - width))
2080 hangindent = ' ' * (hanging + 3)
2080 hangindent = ' ' * (hanging + 3)
2081 ui.write('%s\n' % (util.wrap(desc,
2081 ui.write('%s\n' % (util.wrap(desc,
2082 initindent=initindent,
2082 initindent=initindent,
2083 hangindent=hangindent)))
2083 hangindent=hangindent)))
2084 else:
2084 else:
2085 ui.write("%s\n" % opt)
2085 ui.write("%s\n" % opt)
2086
2086
2087 def identify(ui, repo, source=None,
2087 def identify(ui, repo, source=None,
2088 rev=None, num=None, id=None, branch=None, tags=None):
2088 rev=None, num=None, id=None, branch=None, tags=None):
2089 """identify the working copy or specified revision
2089 """identify the working copy or specified revision
2090
2090
2091 With no revision, print a summary of the current state of the
2091 With no revision, print a summary of the current state of the
2092 repository.
2092 repository.
2093
2093
2094 Specifying a path to a repository root or Mercurial bundle will
2094 Specifying a path to a repository root or Mercurial bundle will
2095 cause lookup to operate on that repository/bundle.
2095 cause lookup to operate on that repository/bundle.
2096
2096
2097 This summary identifies the repository state using one or two
2097 This summary identifies the repository state using one or two
2098 parent hash identifiers, followed by a "+" if there are
2098 parent hash identifiers, followed by a "+" if there are
2099 uncommitted changes in the working directory, a list of tags for
2099 uncommitted changes in the working directory, a list of tags for
2100 this revision and a branch name for non-default branches.
2100 this revision and a branch name for non-default branches.
2101
2101
2102 Returns 0 if successful.
2102 Returns 0 if successful.
2103 """
2103 """
2104
2104
2105 if not repo and not source:
2105 if not repo and not source:
2106 raise util.Abort(_("There is no Mercurial repository here "
2106 raise util.Abort(_("There is no Mercurial repository here "
2107 "(.hg not found)"))
2107 "(.hg not found)"))
2108
2108
2109 hexfunc = ui.debugflag and hex or short
2109 hexfunc = ui.debugflag and hex or short
2110 default = not (num or id or branch or tags)
2110 default = not (num or id or branch or tags)
2111 output = []
2111 output = []
2112
2112
2113 revs = []
2113 revs = []
2114 if source:
2114 if source:
2115 source, branches = hg.parseurl(ui.expandpath(source))
2115 source, branches = hg.parseurl(ui.expandpath(source))
2116 repo = hg.repository(ui, source)
2116 repo = hg.repository(ui, source)
2117 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
2117 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
2118
2118
2119 if not repo.local():
2119 if not repo.local():
2120 if not rev and revs:
2120 if not rev and revs:
2121 rev = revs[0]
2121 rev = revs[0]
2122 if not rev:
2122 if not rev:
2123 rev = "tip"
2123 rev = "tip"
2124 if num or branch or tags:
2124 if num or branch or tags:
2125 raise util.Abort(
2125 raise util.Abort(
2126 "can't query remote revision number, branch, or tags")
2126 "can't query remote revision number, branch, or tags")
2127 output = [hexfunc(repo.lookup(rev))]
2127 output = [hexfunc(repo.lookup(rev))]
2128 elif not rev:
2128 elif not rev:
2129 ctx = repo[None]
2129 ctx = repo[None]
2130 parents = ctx.parents()
2130 parents = ctx.parents()
2131 changed = False
2131 changed = False
2132 if default or id or num:
2132 if default or id or num:
2133 changed = util.any(repo.status())
2133 changed = util.any(repo.status())
2134 if default or id:
2134 if default or id:
2135 output = ["%s%s" % ('+'.join([hexfunc(p.node()) for p in parents]),
2135 output = ["%s%s" % ('+'.join([hexfunc(p.node()) for p in parents]),
2136 (changed) and "+" or "")]
2136 (changed) and "+" or "")]
2137 if num:
2137 if num:
2138 output.append("%s%s" % ('+'.join([str(p.rev()) for p in parents]),
2138 output.append("%s%s" % ('+'.join([str(p.rev()) for p in parents]),
2139 (changed) and "+" or ""))
2139 (changed) and "+" or ""))
2140 else:
2140 else:
2141 ctx = repo[rev]
2141 ctx = repo[rev]
2142 if default or id:
2142 if default or id:
2143 output = [hexfunc(ctx.node())]
2143 output = [hexfunc(ctx.node())]
2144 if num:
2144 if num:
2145 output.append(str(ctx.rev()))
2145 output.append(str(ctx.rev()))
2146
2146
2147 if repo.local() and default and not ui.quiet:
2147 if repo.local() and default and not ui.quiet:
2148 b = encoding.tolocal(ctx.branch())
2148 b = encoding.tolocal(ctx.branch())
2149 if b != 'default':
2149 if b != 'default':
2150 output.append("(%s)" % b)
2150 output.append("(%s)" % b)
2151
2151
2152 # multiple tags for a single parent separated by '/'
2152 # multiple tags for a single parent separated by '/'
2153 t = "/".join(ctx.tags())
2153 t = "/".join(ctx.tags())
2154 if t:
2154 if t:
2155 output.append(t)
2155 output.append(t)
2156
2156
2157 if branch:
2157 if branch:
2158 output.append(encoding.tolocal(ctx.branch()))
2158 output.append(encoding.tolocal(ctx.branch()))
2159
2159
2160 if tags:
2160 if tags:
2161 output.extend(ctx.tags())
2161 output.extend(ctx.tags())
2162
2162
2163 ui.write("%s\n" % ' '.join(output))
2163 ui.write("%s\n" % ' '.join(output))
2164
2164
2165 def import_(ui, repo, patch1, *patches, **opts):
2165 def import_(ui, repo, patch1, *patches, **opts):
2166 """import an ordered set of patches
2166 """import an ordered set of patches
2167
2167
2168 Import a list of patches and commit them individually (unless
2168 Import a list of patches and commit them individually (unless
2169 --no-commit is specified).
2169 --no-commit is specified).
2170
2170
2171 If there are outstanding changes in the working directory, import
2171 If there are outstanding changes in the working directory, import
2172 will abort unless given the -f/--force flag.
2172 will abort unless given the -f/--force flag.
2173
2173
2174 You can import a patch straight from a mail message. Even patches
2174 You can import a patch straight from a mail message. Even patches
2175 as attachments work (to use the body part, it must have type
2175 as attachments work (to use the body part, it must have type
2176 text/plain or text/x-patch). From and Subject headers of email
2176 text/plain or text/x-patch). From and Subject headers of email
2177 message are used as default committer and commit message. All
2177 message are used as default committer and commit message. All
2178 text/plain body parts before first diff are added to commit
2178 text/plain body parts before first diff are added to commit
2179 message.
2179 message.
2180
2180
2181 If the imported patch was generated by :hg:`export`, user and
2181 If the imported patch was generated by :hg:`export`, user and
2182 description from patch override values from message headers and
2182 description from patch override values from message headers and
2183 body. Values given on command line with -m/--message and -u/--user
2183 body. Values given on command line with -m/--message and -u/--user
2184 override these.
2184 override these.
2185
2185
2186 If --exact is specified, import will set the working directory to
2186 If --exact is specified, import will set the working directory to
2187 the parent of each patch before applying it, and will abort if the
2187 the parent of each patch before applying it, and will abort if the
2188 resulting changeset has a different ID than the one recorded in
2188 resulting changeset has a different ID than the one recorded in
2189 the patch. This may happen due to character set problems or other
2189 the patch. This may happen due to character set problems or other
2190 deficiencies in the text patch format.
2190 deficiencies in the text patch format.
2191
2191
2192 With -s/--similarity, hg will attempt to discover renames and
2192 With -s/--similarity, hg will attempt to discover renames and
2193 copies in the patch in the same way as 'addremove'.
2193 copies in the patch in the same way as 'addremove'.
2194
2194
2195 To read a patch from standard input, use "-" as the patch name. If
2195 To read a patch from standard input, use "-" as the patch name. If
2196 a URL is specified, the patch will be downloaded from it.
2196 a URL is specified, the patch will be downloaded from it.
2197 See :hg:`help dates` for a list of formats valid for -d/--date.
2197 See :hg:`help dates` for a list of formats valid for -d/--date.
2198
2198
2199 Returns 0 on success.
2199 Returns 0 on success.
2200 """
2200 """
2201 patches = (patch1,) + patches
2201 patches = (patch1,) + patches
2202
2202
2203 date = opts.get('date')
2203 date = opts.get('date')
2204 if date:
2204 if date:
2205 opts['date'] = util.parsedate(date)
2205 opts['date'] = util.parsedate(date)
2206
2206
2207 try:
2207 try:
2208 sim = float(opts.get('similarity') or 0)
2208 sim = float(opts.get('similarity') or 0)
2209 except ValueError:
2209 except ValueError:
2210 raise util.Abort(_('similarity must be a number'))
2210 raise util.Abort(_('similarity must be a number'))
2211 if sim < 0 or sim > 100:
2211 if sim < 0 or sim > 100:
2212 raise util.Abort(_('similarity must be between 0 and 100'))
2212 raise util.Abort(_('similarity must be between 0 and 100'))
2213
2213
2214 if opts.get('exact') or not opts.get('force'):
2214 if opts.get('exact') or not opts.get('force'):
2215 cmdutil.bail_if_changed(repo)
2215 cmdutil.bail_if_changed(repo)
2216
2216
2217 d = opts["base"]
2217 d = opts["base"]
2218 strip = opts["strip"]
2218 strip = opts["strip"]
2219 wlock = lock = None
2219 wlock = lock = None
2220
2220
2221 def tryone(ui, hunk):
2221 def tryone(ui, hunk):
2222 tmpname, message, user, date, branch, nodeid, p1, p2 = \
2222 tmpname, message, user, date, branch, nodeid, p1, p2 = \
2223 patch.extract(ui, hunk)
2223 patch.extract(ui, hunk)
2224
2224
2225 if not tmpname:
2225 if not tmpname:
2226 return None
2226 return None
2227 commitid = _('to working directory')
2227 commitid = _('to working directory')
2228
2228
2229 try:
2229 try:
2230 cmdline_message = cmdutil.logmessage(opts)
2230 cmdline_message = cmdutil.logmessage(opts)
2231 if cmdline_message:
2231 if cmdline_message:
2232 # pickup the cmdline msg
2232 # pickup the cmdline msg
2233 message = cmdline_message
2233 message = cmdline_message
2234 elif message:
2234 elif message:
2235 # pickup the patch msg
2235 # pickup the patch msg
2236 message = message.strip()
2236 message = message.strip()
2237 else:
2237 else:
2238 # launch the editor
2238 # launch the editor
2239 message = None
2239 message = None
2240 ui.debug('message:\n%s\n' % message)
2240 ui.debug('message:\n%s\n' % message)
2241
2241
2242 wp = repo.parents()
2242 wp = repo.parents()
2243 if opts.get('exact'):
2243 if opts.get('exact'):
2244 if not nodeid or not p1:
2244 if not nodeid or not p1:
2245 raise util.Abort(_('not a Mercurial patch'))
2245 raise util.Abort(_('not a Mercurial patch'))
2246 p1 = repo.lookup(p1)
2246 p1 = repo.lookup(p1)
2247 p2 = repo.lookup(p2 or hex(nullid))
2247 p2 = repo.lookup(p2 or hex(nullid))
2248
2248
2249 if p1 != wp[0].node():
2249 if p1 != wp[0].node():
2250 hg.clean(repo, p1)
2250 hg.clean(repo, p1)
2251 repo.dirstate.setparents(p1, p2)
2251 repo.dirstate.setparents(p1, p2)
2252 elif p2:
2252 elif p2:
2253 try:
2253 try:
2254 p1 = repo.lookup(p1)
2254 p1 = repo.lookup(p1)
2255 p2 = repo.lookup(p2)
2255 p2 = repo.lookup(p2)
2256 if p1 == wp[0].node():
2256 if p1 == wp[0].node():
2257 repo.dirstate.setparents(p1, p2)
2257 repo.dirstate.setparents(p1, p2)
2258 except error.RepoError:
2258 except error.RepoError:
2259 pass
2259 pass
2260 if opts.get('exact') or opts.get('import_branch'):
2260 if opts.get('exact') or opts.get('import_branch'):
2261 repo.dirstate.setbranch(branch or 'default')
2261 repo.dirstate.setbranch(branch or 'default')
2262
2262
2263 files = {}
2263 files = {}
2264 try:
2264 try:
2265 patch.patch(tmpname, ui, strip=strip, cwd=repo.root,
2265 patch.patch(tmpname, ui, strip=strip, cwd=repo.root,
2266 files=files, eolmode=None)
2266 files=files, eolmode=None)
2267 finally:
2267 finally:
2268 files = patch.updatedir(ui, repo, files,
2268 files = patch.updatedir(ui, repo, files,
2269 similarity=sim / 100.0)
2269 similarity=sim / 100.0)
2270 if not opts.get('no_commit'):
2270 if not opts.get('no_commit'):
2271 if opts.get('exact'):
2271 if opts.get('exact'):
2272 m = None
2272 m = None
2273 else:
2273 else:
2274 m = cmdutil.matchfiles(repo, files or [])
2274 m = cmdutil.matchfiles(repo, files or [])
2275 n = repo.commit(message, opts.get('user') or user,
2275 n = repo.commit(message, opts.get('user') or user,
2276 opts.get('date') or date, match=m,
2276 opts.get('date') or date, match=m,
2277 editor=cmdutil.commiteditor)
2277 editor=cmdutil.commiteditor)
2278 if opts.get('exact'):
2278 if opts.get('exact'):
2279 if hex(n) != nodeid:
2279 if hex(n) != nodeid:
2280 repo.rollback()
2280 repo.rollback()
2281 raise util.Abort(_('patch is damaged'
2281 raise util.Abort(_('patch is damaged'
2282 ' or loses information'))
2282 ' or loses information'))
2283 # Force a dirstate write so that the next transaction
2283 # Force a dirstate write so that the next transaction
2284 # backups an up-do-date file.
2284 # backups an up-do-date file.
2285 repo.dirstate.write()
2285 repo.dirstate.write()
2286 if n:
2286 if n:
2287 commitid = short(n)
2287 commitid = short(n)
2288
2288
2289 return commitid
2289 return commitid
2290 finally:
2290 finally:
2291 os.unlink(tmpname)
2291 os.unlink(tmpname)
2292
2292
2293 try:
2293 try:
2294 wlock = repo.wlock()
2294 wlock = repo.wlock()
2295 lock = repo.lock()
2295 lock = repo.lock()
2296 lastcommit = None
2296 lastcommit = None
2297 for p in patches:
2297 for p in patches:
2298 pf = os.path.join(d, p)
2298 pf = os.path.join(d, p)
2299
2299
2300 if pf == '-':
2300 if pf == '-':
2301 ui.status(_("applying patch from stdin\n"))
2301 ui.status(_("applying patch from stdin\n"))
2302 pf = sys.stdin
2302 pf = sys.stdin
2303 else:
2303 else:
2304 ui.status(_("applying %s\n") % p)
2304 ui.status(_("applying %s\n") % p)
2305 pf = url.open(ui, pf)
2305 pf = url.open(ui, pf)
2306
2306
2307 haspatch = False
2307 haspatch = False
2308 for hunk in patch.split(pf):
2308 for hunk in patch.split(pf):
2309 commitid = tryone(ui, hunk)
2309 commitid = tryone(ui, hunk)
2310 if commitid:
2310 if commitid:
2311 haspatch = True
2311 haspatch = True
2312 if lastcommit:
2312 if lastcommit:
2313 ui.status(_('applied %s\n') % lastcommit)
2313 ui.status(_('applied %s\n') % lastcommit)
2314 lastcommit = commitid
2314 lastcommit = commitid
2315
2315
2316 if not haspatch:
2316 if not haspatch:
2317 raise util.Abort(_('no diffs found'))
2317 raise util.Abort(_('no diffs found'))
2318
2318
2319 finally:
2319 finally:
2320 release(lock, wlock)
2320 release(lock, wlock)
2321
2321
2322 def incoming(ui, repo, source="default", **opts):
2322 def incoming(ui, repo, source="default", **opts):
2323 """show new changesets found in source
2323 """show new changesets found in source
2324
2324
2325 Show new changesets found in the specified path/URL or the default
2325 Show new changesets found in the specified path/URL or the default
2326 pull location. These are the changesets that would have been pulled
2326 pull location. These are the changesets that would have been pulled
2327 if a pull at the time you issued this command.
2327 if a pull at the time you issued this command.
2328
2328
2329 For remote repository, using --bundle avoids downloading the
2329 For remote repository, using --bundle avoids downloading the
2330 changesets twice if the incoming is followed by a pull.
2330 changesets twice if the incoming is followed by a pull.
2331
2331
2332 See pull for valid source format details.
2332 See pull for valid source format details.
2333
2333
2334 Returns 0 if there are incoming changes, 1 otherwise.
2334 Returns 0 if there are incoming changes, 1 otherwise.
2335 """
2335 """
2336 limit = cmdutil.loglimit(opts)
2336 limit = cmdutil.loglimit(opts)
2337 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
2337 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
2338 other = hg.repository(hg.remoteui(repo, opts), source)
2338 other = hg.repository(hg.remoteui(repo, opts), source)
2339 ui.status(_('comparing with %s\n') % url.hidepassword(source))
2339 ui.status(_('comparing with %s\n') % url.hidepassword(source))
2340 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
2340 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
2341 if revs:
2341 if revs:
2342 revs = [other.lookup(rev) for rev in revs]
2342 revs = [other.lookup(rev) for rev in revs]
2343
2343
2344 tmp = discovery.findcommonincoming(repo, other, heads=revs,
2344 tmp = discovery.findcommonincoming(repo, other, heads=revs,
2345 force=opts.get('force'))
2345 force=opts.get('force'))
2346 common, incoming, rheads = tmp
2346 common, incoming, rheads = tmp
2347 if not incoming:
2347 if not incoming:
2348 try:
2348 try:
2349 os.unlink(opts["bundle"])
2349 os.unlink(opts["bundle"])
2350 except:
2350 except:
2351 pass
2351 pass
2352 ui.status(_("no changes found\n"))
2352 ui.status(_("no changes found\n"))
2353 return 1
2353 return 1
2354
2354
2355 cleanup = None
2355 cleanup = None
2356 try:
2356 try:
2357 fname = opts["bundle"]
2357 fname = opts["bundle"]
2358 if fname or not other.local():
2358 if fname or not other.local():
2359 # create a bundle (uncompressed if other repo is not local)
2359 # create a bundle (uncompressed if other repo is not local)
2360
2360
2361 if revs is None and other.capable('changegroupsubset'):
2361 if revs is None and other.capable('changegroupsubset'):
2362 revs = rheads
2362 revs = rheads
2363
2363
2364 if revs is None:
2364 if revs is None:
2365 cg = other.changegroup(incoming, "incoming")
2365 cg = other.changegroup(incoming, "incoming")
2366 else:
2366 else:
2367 cg = other.changegroupsubset(incoming, revs, 'incoming')
2367 cg = other.changegroupsubset(incoming, revs, 'incoming')
2368 bundletype = other.local() and "HG10BZ" or "HG10UN"
2368 bundletype = other.local() and "HG10BZ" or "HG10UN"
2369 fname = cleanup = changegroup.writebundle(cg, fname, bundletype)
2369 fname = cleanup = changegroup.writebundle(cg, fname, bundletype)
2370 # keep written bundle?
2370 # keep written bundle?
2371 if opts["bundle"]:
2371 if opts["bundle"]:
2372 cleanup = None
2372 cleanup = None
2373 if not other.local():
2373 if not other.local():
2374 # use the created uncompressed bundlerepo
2374 # use the created uncompressed bundlerepo
2375 other = bundlerepo.bundlerepository(ui, repo.root, fname)
2375 other = bundlerepo.bundlerepository(ui, repo.root, fname)
2376
2376
2377 o = other.changelog.nodesbetween(incoming, revs)[0]
2377 o = other.changelog.nodesbetween(incoming, revs)[0]
2378 if opts.get('newest_first'):
2378 if opts.get('newest_first'):
2379 o.reverse()
2379 o.reverse()
2380 displayer = cmdutil.show_changeset(ui, other, opts)
2380 displayer = cmdutil.show_changeset(ui, other, opts)
2381 count = 0
2381 count = 0
2382 for n in o:
2382 for n in o:
2383 if limit is not None and count >= limit:
2383 if limit is not None and count >= limit:
2384 break
2384 break
2385 parents = [p for p in other.changelog.parents(n) if p != nullid]
2385 parents = [p for p in other.changelog.parents(n) if p != nullid]
2386 if opts.get('no_merges') and len(parents) == 2:
2386 if opts.get('no_merges') and len(parents) == 2:
2387 continue
2387 continue
2388 count += 1
2388 count += 1
2389 displayer.show(other[n])
2389 displayer.show(other[n])
2390 displayer.close()
2390 displayer.close()
2391 finally:
2391 finally:
2392 if hasattr(other, 'close'):
2392 if hasattr(other, 'close'):
2393 other.close()
2393 other.close()
2394 if cleanup:
2394 if cleanup:
2395 os.unlink(cleanup)
2395 os.unlink(cleanup)
2396
2396
2397 def init(ui, dest=".", **opts):
2397 def init(ui, dest=".", **opts):
2398 """create a new repository in the given directory
2398 """create a new repository in the given directory
2399
2399
2400 Initialize a new repository in the given directory. If the given
2400 Initialize a new repository in the given directory. If the given
2401 directory does not exist, it will be created.
2401 directory does not exist, it will be created.
2402
2402
2403 If no directory is given, the current directory is used.
2403 If no directory is given, the current directory is used.
2404
2404
2405 It is possible to specify an ``ssh://`` URL as the destination.
2405 It is possible to specify an ``ssh://`` URL as the destination.
2406 See :hg:`help urls` for more information.
2406 See :hg:`help urls` for more information.
2407
2407
2408 Returns 0 on success.
2408 Returns 0 on success.
2409 """
2409 """
2410 hg.repository(hg.remoteui(ui, opts), dest, create=1)
2410 hg.repository(hg.remoteui(ui, opts), dest, create=1)
2411
2411
2412 def locate(ui, repo, *pats, **opts):
2412 def locate(ui, repo, *pats, **opts):
2413 """locate files matching specific patterns
2413 """locate files matching specific patterns
2414
2414
2415 Print files under Mercurial control in the working directory whose
2415 Print files under Mercurial control in the working directory whose
2416 names match the given patterns.
2416 names match the given patterns.
2417
2417
2418 By default, this command searches all directories in the working
2418 By default, this command searches all directories in the working
2419 directory. To search just the current directory and its
2419 directory. To search just the current directory and its
2420 subdirectories, use "--include .".
2420 subdirectories, use "--include .".
2421
2421
2422 If no patterns are given to match, this command prints the names
2422 If no patterns are given to match, this command prints the names
2423 of all files under Mercurial control in the working directory.
2423 of all files under Mercurial control in the working directory.
2424
2424
2425 If you want to feed the output of this command into the "xargs"
2425 If you want to feed the output of this command into the "xargs"
2426 command, use the -0 option to both this command and "xargs". This
2426 command, use the -0 option to both this command and "xargs". This
2427 will avoid the problem of "xargs" treating single filenames that
2427 will avoid the problem of "xargs" treating single filenames that
2428 contain whitespace as multiple filenames.
2428 contain whitespace as multiple filenames.
2429
2429
2430 Returns 0 if a match is found, 1 otherwise.
2430 Returns 0 if a match is found, 1 otherwise.
2431 """
2431 """
2432 end = opts.get('print0') and '\0' or '\n'
2432 end = opts.get('print0') and '\0' or '\n'
2433 rev = opts.get('rev') or None
2433 rev = opts.get('rev') or None
2434
2434
2435 ret = 1
2435 ret = 1
2436 m = cmdutil.match(repo, pats, opts, default='relglob')
2436 m = cmdutil.match(repo, pats, opts, default='relglob')
2437 m.bad = lambda x, y: False
2437 m.bad = lambda x, y: False
2438 for abs in repo[rev].walk(m):
2438 for abs in repo[rev].walk(m):
2439 if not rev and abs not in repo.dirstate:
2439 if not rev and abs not in repo.dirstate:
2440 continue
2440 continue
2441 if opts.get('fullpath'):
2441 if opts.get('fullpath'):
2442 ui.write(repo.wjoin(abs), end)
2442 ui.write(repo.wjoin(abs), end)
2443 else:
2443 else:
2444 ui.write(((pats and m.rel(abs)) or abs), end)
2444 ui.write(((pats and m.rel(abs)) or abs), end)
2445 ret = 0
2445 ret = 0
2446
2446
2447 return ret
2447 return ret
2448
2448
2449 def log(ui, repo, *pats, **opts):
2449 def log(ui, repo, *pats, **opts):
2450 """show revision history of entire repository or files
2450 """show revision history of entire repository or files
2451
2451
2452 Print the revision history of the specified files or the entire
2452 Print the revision history of the specified files or the entire
2453 project.
2453 project.
2454
2454
2455 File history is shown without following rename or copy history of
2455 File history is shown without following rename or copy history of
2456 files. Use -f/--follow with a filename to follow history across
2456 files. Use -f/--follow with a filename to follow history across
2457 renames and copies. --follow without a filename will only show
2457 renames and copies. --follow without a filename will only show
2458 ancestors or descendants of the starting revision. --follow-first
2458 ancestors or descendants of the starting revision. --follow-first
2459 only follows the first parent of merge revisions.
2459 only follows the first parent of merge revisions.
2460
2460
2461 If no revision range is specified, the default is tip:0 unless
2461 If no revision range is specified, the default is tip:0 unless
2462 --follow is set, in which case the working directory parent is
2462 --follow is set, in which case the working directory parent is
2463 used as the starting revision. You can specify a revision set for
2463 used as the starting revision. You can specify a revision set for
2464 log, see :hg:`help revsets` for more information.
2464 log, see :hg:`help revsets` for more information.
2465
2465
2466 See :hg:`help dates` for a list of formats valid for -d/--date.
2466 See :hg:`help dates` for a list of formats valid for -d/--date.
2467
2467
2468 By default this command prints revision number and changeset id,
2468 By default this command prints revision number and changeset id,
2469 tags, non-trivial parents, user, date and time, and a summary for
2469 tags, non-trivial parents, user, date and time, and a summary for
2470 each commit. When the -v/--verbose switch is used, the list of
2470 each commit. When the -v/--verbose switch is used, the list of
2471 changed files and full commit message are shown.
2471 changed files and full commit message are shown.
2472
2472
2473 NOTE: log -p/--patch may generate unexpected diff output for merge
2473 NOTE: log -p/--patch may generate unexpected diff output for merge
2474 changesets, as it will only compare the merge changeset against
2474 changesets, as it will only compare the merge changeset against
2475 its first parent. Also, only files different from BOTH parents
2475 its first parent. Also, only files different from BOTH parents
2476 will appear in files:.
2476 will appear in files:.
2477
2477
2478 Returns 0 on success.
2478 Returns 0 on success.
2479 """
2479 """
2480
2480
2481 matchfn = cmdutil.match(repo, pats, opts)
2481 matchfn = cmdutil.match(repo, pats, opts)
2482 limit = cmdutil.loglimit(opts)
2482 limit = cmdutil.loglimit(opts)
2483 count = 0
2483 count = 0
2484
2484
2485 endrev = None
2485 endrev = None
2486 if opts.get('copies') and opts.get('rev'):
2486 if opts.get('copies') and opts.get('rev'):
2487 endrev = max(cmdutil.revrange(repo, opts.get('rev'))) + 1
2487 endrev = max(cmdutil.revrange(repo, opts.get('rev'))) + 1
2488
2488
2489 df = False
2489 df = False
2490 if opts["date"]:
2490 if opts["date"]:
2491 df = util.matchdate(opts["date"])
2491 df = util.matchdate(opts["date"])
2492
2492
2493 branches = opts.get('branch', []) + opts.get('only_branch', [])
2493 branches = opts.get('branch', []) + opts.get('only_branch', [])
2494 opts['branch'] = [repo.lookupbranch(b) for b in branches]
2494 opts['branch'] = [repo.lookupbranch(b) for b in branches]
2495
2495
2496 displayer = cmdutil.show_changeset(ui, repo, opts, True)
2496 displayer = cmdutil.show_changeset(ui, repo, opts, True)
2497 def prep(ctx, fns):
2497 def prep(ctx, fns):
2498 rev = ctx.rev()
2498 rev = ctx.rev()
2499 parents = [p for p in repo.changelog.parentrevs(rev)
2499 parents = [p for p in repo.changelog.parentrevs(rev)
2500 if p != nullrev]
2500 if p != nullrev]
2501 if opts.get('no_merges') and len(parents) == 2:
2501 if opts.get('no_merges') and len(parents) == 2:
2502 return
2502 return
2503 if opts.get('only_merges') and len(parents) != 2:
2503 if opts.get('only_merges') and len(parents) != 2:
2504 return
2504 return
2505 if opts.get('branch') and ctx.branch() not in opts['branch']:
2505 if opts.get('branch') and ctx.branch() not in opts['branch']:
2506 return
2506 return
2507 if df and not df(ctx.date()[0]):
2507 if df and not df(ctx.date()[0]):
2508 return
2508 return
2509 if opts['user'] and not [k for k in opts['user'] if k in ctx.user()]:
2509 if opts['user'] and not [k for k in opts['user'] if k in ctx.user()]:
2510 return
2510 return
2511 if opts.get('keyword'):
2511 if opts.get('keyword'):
2512 for k in [kw.lower() for kw in opts['keyword']]:
2512 for k in [kw.lower() for kw in opts['keyword']]:
2513 if (k in ctx.user().lower() or
2513 if (k in ctx.user().lower() or
2514 k in ctx.description().lower() or
2514 k in ctx.description().lower() or
2515 k in " ".join(ctx.files()).lower()):
2515 k in " ".join(ctx.files()).lower()):
2516 break
2516 break
2517 else:
2517 else:
2518 return
2518 return
2519
2519
2520 copies = None
2520 copies = None
2521 if opts.get('copies') and rev:
2521 if opts.get('copies') and rev:
2522 copies = []
2522 copies = []
2523 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2523 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2524 for fn in ctx.files():
2524 for fn in ctx.files():
2525 rename = getrenamed(fn, rev)
2525 rename = getrenamed(fn, rev)
2526 if rename:
2526 if rename:
2527 copies.append((fn, rename[0]))
2527 copies.append((fn, rename[0]))
2528
2528
2529 revmatchfn = None
2529 revmatchfn = None
2530 if opts.get('patch') or opts.get('stat'):
2530 if opts.get('patch') or opts.get('stat'):
2531 revmatchfn = cmdutil.match(repo, fns, default='path')
2531 revmatchfn = cmdutil.match(repo, fns, default='path')
2532
2532
2533 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
2533 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
2534
2534
2535 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2535 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2536 if count == limit:
2536 if count == limit:
2537 break
2537 break
2538 if displayer.flush(ctx.rev()):
2538 if displayer.flush(ctx.rev()):
2539 count += 1
2539 count += 1
2540 displayer.close()
2540 displayer.close()
2541
2541
2542 def manifest(ui, repo, node=None, rev=None):
2542 def manifest(ui, repo, node=None, rev=None):
2543 """output the current or given revision of the project manifest
2543 """output the current or given revision of the project manifest
2544
2544
2545 Print a list of version controlled files for the given revision.
2545 Print a list of version controlled files for the given revision.
2546 If no revision is given, the first parent of the working directory
2546 If no revision is given, the first parent of the working directory
2547 is used, or the null revision if no revision is checked out.
2547 is used, or the null revision if no revision is checked out.
2548
2548
2549 With -v, print file permissions, symlink and executable bits.
2549 With -v, print file permissions, symlink and executable bits.
2550 With --debug, print file revision hashes.
2550 With --debug, print file revision hashes.
2551
2551
2552 Returns 0 on success.
2552 Returns 0 on success.
2553 """
2553 """
2554
2554
2555 if rev and node:
2555 if rev and node:
2556 raise util.Abort(_("please specify just one revision"))
2556 raise util.Abort(_("please specify just one revision"))
2557
2557
2558 if not node:
2558 if not node:
2559 node = rev
2559 node = rev
2560
2560
2561 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
2561 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
2562 ctx = repo[node]
2562 ctx = repo[node]
2563 for f in ctx:
2563 for f in ctx:
2564 if ui.debugflag:
2564 if ui.debugflag:
2565 ui.write("%40s " % hex(ctx.manifest()[f]))
2565 ui.write("%40s " % hex(ctx.manifest()[f]))
2566 if ui.verbose:
2566 if ui.verbose:
2567 ui.write(decor[ctx.flags(f)])
2567 ui.write(decor[ctx.flags(f)])
2568 ui.write("%s\n" % f)
2568 ui.write("%s\n" % f)
2569
2569
2570 def merge(ui, repo, node=None, **opts):
2570 def merge(ui, repo, node=None, **opts):
2571 """merge working directory with another revision
2571 """merge working directory with another revision
2572
2572
2573 The current working directory is updated with all changes made in
2573 The current working directory is updated with all changes made in
2574 the requested revision since the last common predecessor revision.
2574 the requested revision since the last common predecessor revision.
2575
2575
2576 Files that changed between either parent are marked as changed for
2576 Files that changed between either parent are marked as changed for
2577 the next commit and a commit must be performed before any further
2577 the next commit and a commit must be performed before any further
2578 updates to the repository are allowed. The next commit will have
2578 updates to the repository are allowed. The next commit will have
2579 two parents.
2579 two parents.
2580
2580
2581 If no revision is specified, the working directory's parent is a
2581 If no revision is specified, the working directory's parent is a
2582 head revision, and the current branch contains exactly one other
2582 head revision, and the current branch contains exactly one other
2583 head, the other head is merged with by default. Otherwise, an
2583 head, the other head is merged with by default. Otherwise, an
2584 explicit revision with which to merge with must be provided.
2584 explicit revision with which to merge with must be provided.
2585
2585
2586 To undo an uncommitted merge, use :hg:`update --clean .` which
2586 To undo an uncommitted merge, use :hg:`update --clean .` which
2587 will check out a clean copy of the original merge parent, losing
2587 will check out a clean copy of the original merge parent, losing
2588 all changes.
2588 all changes.
2589
2589
2590 Returns 0 on success, 1 if there are unresolved files.
2590 Returns 0 on success, 1 if there are unresolved files.
2591 """
2591 """
2592
2592
2593 if opts.get('rev') and node:
2593 if opts.get('rev') and node:
2594 raise util.Abort(_("please specify just one revision"))
2594 raise util.Abort(_("please specify just one revision"))
2595 if not node:
2595 if not node:
2596 node = opts.get('rev')
2596 node = opts.get('rev')
2597
2597
2598 if not node:
2598 if not node:
2599 branch = repo.changectx(None).branch()
2599 branch = repo.changectx(None).branch()
2600 bheads = repo.branchheads(branch)
2600 bheads = repo.branchheads(branch)
2601 if len(bheads) > 2:
2601 if len(bheads) > 2:
2602 raise util.Abort(_(
2602 raise util.Abort(_(
2603 'branch \'%s\' has %d heads - '
2603 'branch \'%s\' has %d heads - '
2604 'please merge with an explicit rev\n'
2604 'please merge with an explicit rev\n'
2605 '(run \'hg heads .\' to see heads)')
2605 '(run \'hg heads .\' to see heads)')
2606 % (branch, len(bheads)))
2606 % (branch, len(bheads)))
2607
2607
2608 parent = repo.dirstate.parents()[0]
2608 parent = repo.dirstate.parents()[0]
2609 if len(bheads) == 1:
2609 if len(bheads) == 1:
2610 if len(repo.heads()) > 1:
2610 if len(repo.heads()) > 1:
2611 raise util.Abort(_(
2611 raise util.Abort(_(
2612 'branch \'%s\' has one head - '
2612 'branch \'%s\' has one head - '
2613 'please merge with an explicit rev\n'
2613 'please merge with an explicit rev\n'
2614 '(run \'hg heads\' to see all heads)')
2614 '(run \'hg heads\' to see all heads)')
2615 % branch)
2615 % branch)
2616 msg = _('there is nothing to merge')
2616 msg = _('there is nothing to merge')
2617 if parent != repo.lookup(repo[None].branch()):
2617 if parent != repo.lookup(repo[None].branch()):
2618 msg = _('%s - use "hg update" instead') % msg
2618 msg = _('%s - use "hg update" instead') % msg
2619 raise util.Abort(msg)
2619 raise util.Abort(msg)
2620
2620
2621 if parent not in bheads:
2621 if parent not in bheads:
2622 raise util.Abort(_('working dir not at a head rev - '
2622 raise util.Abort(_('working dir not at a head rev - '
2623 'use "hg update" or merge with an explicit rev'))
2623 'use "hg update" or merge with an explicit rev'))
2624 node = parent == bheads[0] and bheads[-1] or bheads[0]
2624 node = parent == bheads[0] and bheads[-1] or bheads[0]
2625
2625
2626 if opts.get('preview'):
2626 if opts.get('preview'):
2627 # find nodes that are ancestors of p2 but not of p1
2627 # find nodes that are ancestors of p2 but not of p1
2628 p1 = repo.lookup('.')
2628 p1 = repo.lookup('.')
2629 p2 = repo.lookup(node)
2629 p2 = repo.lookup(node)
2630 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
2630 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
2631
2631
2632 displayer = cmdutil.show_changeset(ui, repo, opts)
2632 displayer = cmdutil.show_changeset(ui, repo, opts)
2633 for node in nodes:
2633 for node in nodes:
2634 displayer.show(repo[node])
2634 displayer.show(repo[node])
2635 displayer.close()
2635 displayer.close()
2636 return 0
2636 return 0
2637
2637
2638 return hg.merge(repo, node, force=opts.get('force'))
2638 return hg.merge(repo, node, force=opts.get('force'))
2639
2639
2640 def outgoing(ui, repo, dest=None, **opts):
2640 def outgoing(ui, repo, dest=None, **opts):
2641 """show changesets not found in the destination
2641 """show changesets not found in the destination
2642
2642
2643 Show changesets not found in the specified destination repository
2643 Show changesets not found in the specified destination repository
2644 or the default push location. These are the changesets that would
2644 or the default push location. These are the changesets that would
2645 be pushed if a push was requested.
2645 be pushed if a push was requested.
2646
2646
2647 See pull for details of valid destination formats.
2647 See pull for details of valid destination formats.
2648
2648
2649 Returns 0 if there are outgoing changes, 1 otherwise.
2649 Returns 0 if there are outgoing changes, 1 otherwise.
2650 """
2650 """
2651 limit = cmdutil.loglimit(opts)
2651 limit = cmdutil.loglimit(opts)
2652 dest = ui.expandpath(dest or 'default-push', dest or 'default')
2652 dest = ui.expandpath(dest or 'default-push', dest or 'default')
2653 dest, branches = hg.parseurl(dest, opts.get('branch'))
2653 dest, branches = hg.parseurl(dest, opts.get('branch'))
2654 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
2654 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
2655 if revs:
2655 if revs:
2656 revs = [repo.lookup(rev) for rev in revs]
2656 revs = [repo.lookup(rev) for rev in revs]
2657
2657
2658 other = hg.repository(hg.remoteui(repo, opts), dest)
2658 other = hg.repository(hg.remoteui(repo, opts), dest)
2659 ui.status(_('comparing with %s\n') % url.hidepassword(dest))
2659 ui.status(_('comparing with %s\n') % url.hidepassword(dest))
2660 o = discovery.findoutgoing(repo, other, force=opts.get('force'))
2660 o = discovery.findoutgoing(repo, other, force=opts.get('force'))
2661 if not o:
2661 if not o:
2662 ui.status(_("no changes found\n"))
2662 ui.status(_("no changes found\n"))
2663 return 1
2663 return 1
2664 o = repo.changelog.nodesbetween(o, revs)[0]
2664 o = repo.changelog.nodesbetween(o, revs)[0]
2665 if opts.get('newest_first'):
2665 if opts.get('newest_first'):
2666 o.reverse()
2666 o.reverse()
2667 displayer = cmdutil.show_changeset(ui, repo, opts)
2667 displayer = cmdutil.show_changeset(ui, repo, opts)
2668 count = 0
2668 count = 0
2669 for n in o:
2669 for n in o:
2670 if limit is not None and count >= limit:
2670 if limit is not None and count >= limit:
2671 break
2671 break
2672 parents = [p for p in repo.changelog.parents(n) if p != nullid]
2672 parents = [p for p in repo.changelog.parents(n) if p != nullid]
2673 if opts.get('no_merges') and len(parents) == 2:
2673 if opts.get('no_merges') and len(parents) == 2:
2674 continue
2674 continue
2675 count += 1
2675 count += 1
2676 displayer.show(repo[n])
2676 displayer.show(repo[n])
2677 displayer.close()
2677 displayer.close()
2678
2678
2679 def parents(ui, repo, file_=None, **opts):
2679 def parents(ui, repo, file_=None, **opts):
2680 """show the parents of the working directory or revision
2680 """show the parents of the working directory or revision
2681
2681
2682 Print the working directory's parent revisions. If a revision is
2682 Print the working directory's parent revisions. If a revision is
2683 given via -r/--rev, the parent of that revision will be printed.
2683 given via -r/--rev, the parent of that revision will be printed.
2684 If a file argument is given, the revision in which the file was
2684 If a file argument is given, the revision in which the file was
2685 last changed (before the working directory revision or the
2685 last changed (before the working directory revision or the
2686 argument to --rev if given) is printed.
2686 argument to --rev if given) is printed.
2687
2687
2688 Returns 0 on success.
2688 Returns 0 on success.
2689 """
2689 """
2690 rev = opts.get('rev')
2690 rev = opts.get('rev')
2691 if rev:
2691 if rev:
2692 ctx = repo[rev]
2692 ctx = repo[rev]
2693 else:
2693 else:
2694 ctx = repo[None]
2694 ctx = repo[None]
2695
2695
2696 if file_:
2696 if file_:
2697 m = cmdutil.match(repo, (file_,), opts)
2697 m = cmdutil.match(repo, (file_,), opts)
2698 if m.anypats() or len(m.files()) != 1:
2698 if m.anypats() or len(m.files()) != 1:
2699 raise util.Abort(_('can only specify an explicit filename'))
2699 raise util.Abort(_('can only specify an explicit filename'))
2700 file_ = m.files()[0]
2700 file_ = m.files()[0]
2701 filenodes = []
2701 filenodes = []
2702 for cp in ctx.parents():
2702 for cp in ctx.parents():
2703 if not cp:
2703 if not cp:
2704 continue
2704 continue
2705 try:
2705 try:
2706 filenodes.append(cp.filenode(file_))
2706 filenodes.append(cp.filenode(file_))
2707 except error.LookupError:
2707 except error.LookupError:
2708 pass
2708 pass
2709 if not filenodes:
2709 if not filenodes:
2710 raise util.Abort(_("'%s' not found in manifest!") % file_)
2710 raise util.Abort(_("'%s' not found in manifest!") % file_)
2711 fl = repo.file(file_)
2711 fl = repo.file(file_)
2712 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
2712 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
2713 else:
2713 else:
2714 p = [cp.node() for cp in ctx.parents()]
2714 p = [cp.node() for cp in ctx.parents()]
2715
2715
2716 displayer = cmdutil.show_changeset(ui, repo, opts)
2716 displayer = cmdutil.show_changeset(ui, repo, opts)
2717 for n in p:
2717 for n in p:
2718 if n != nullid:
2718 if n != nullid:
2719 displayer.show(repo[n])
2719 displayer.show(repo[n])
2720 displayer.close()
2720 displayer.close()
2721
2721
2722 def paths(ui, repo, search=None):
2722 def paths(ui, repo, search=None):
2723 """show aliases for remote repositories
2723 """show aliases for remote repositories
2724
2724
2725 Show definition of symbolic path name NAME. If no name is given,
2725 Show definition of symbolic path name NAME. If no name is given,
2726 show definition of all available names.
2726 show definition of all available names.
2727
2727
2728 Path names are defined in the [paths] section of
2728 Path names are defined in the [paths] section of
2729 ``/etc/mercurial/hgrc`` and ``$HOME/.hgrc``. If run inside a
2729 ``/etc/mercurial/hgrc`` and ``$HOME/.hgrc``. If run inside a
2730 repository, ``.hg/hgrc`` is used, too.
2730 repository, ``.hg/hgrc`` is used, too.
2731
2731
2732 The path names ``default`` and ``default-push`` have a special
2732 The path names ``default`` and ``default-push`` have a special
2733 meaning. When performing a push or pull operation, they are used
2733 meaning. When performing a push or pull operation, they are used
2734 as fallbacks if no location is specified on the command-line.
2734 as fallbacks if no location is specified on the command-line.
2735 When ``default-push`` is set, it will be used for push and
2735 When ``default-push`` is set, it will be used for push and
2736 ``default`` will be used for pull; otherwise ``default`` is used
2736 ``default`` will be used for pull; otherwise ``default`` is used
2737 as the fallback for both. When cloning a repository, the clone
2737 as the fallback for both. When cloning a repository, the clone
2738 source is written as ``default`` in ``.hg/hgrc``. Note that
2738 source is written as ``default`` in ``.hg/hgrc``. Note that
2739 ``default`` and ``default-push`` apply to all inbound (e.g.
2739 ``default`` and ``default-push`` apply to all inbound (e.g.
2740 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
2740 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
2741 :hg:`bundle`) operations.
2741 :hg:`bundle`) operations.
2742
2742
2743 See :hg:`help urls` for more information.
2743 See :hg:`help urls` for more information.
2744
2744
2745 Returns 0 on success.
2745 Returns 0 on success.
2746 """
2746 """
2747 if search:
2747 if search:
2748 for name, path in ui.configitems("paths"):
2748 for name, path in ui.configitems("paths"):
2749 if name == search:
2749 if name == search:
2750 ui.write("%s\n" % url.hidepassword(path))
2750 ui.write("%s\n" % url.hidepassword(path))
2751 return
2751 return
2752 ui.warn(_("not found!\n"))
2752 ui.warn(_("not found!\n"))
2753 return 1
2753 return 1
2754 else:
2754 else:
2755 for name, path in ui.configitems("paths"):
2755 for name, path in ui.configitems("paths"):
2756 ui.write("%s = %s\n" % (name, url.hidepassword(path)))
2756 ui.write("%s = %s\n" % (name, url.hidepassword(path)))
2757
2757
2758 def postincoming(ui, repo, modheads, optupdate, checkout):
2758 def postincoming(ui, repo, modheads, optupdate, checkout):
2759 if modheads == 0:
2759 if modheads == 0:
2760 return
2760 return
2761 if optupdate:
2761 if optupdate:
2762 if (modheads <= 1 or len(repo.branchheads()) == 1) or checkout:
2762 if (modheads <= 1 or len(repo.branchheads()) == 1) or checkout:
2763 return hg.update(repo, checkout)
2763 return hg.update(repo, checkout)
2764 else:
2764 else:
2765 ui.status(_("not updating, since new heads added\n"))
2765 ui.status(_("not updating, since new heads added\n"))
2766 if modheads > 1:
2766 if modheads > 1:
2767 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
2767 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
2768 else:
2768 else:
2769 ui.status(_("(run 'hg update' to get a working copy)\n"))
2769 ui.status(_("(run 'hg update' to get a working copy)\n"))
2770
2770
2771 def pull(ui, repo, source="default", **opts):
2771 def pull(ui, repo, source="default", **opts):
2772 """pull changes from the specified source
2772 """pull changes from the specified source
2773
2773
2774 Pull changes from a remote repository to a local one.
2774 Pull changes from a remote repository to a local one.
2775
2775
2776 This finds all changes from the repository at the specified path
2776 This finds all changes from the repository at the specified path
2777 or URL and adds them to a local repository (the current one unless
2777 or URL and adds them to a local repository (the current one unless
2778 -R is specified). By default, this does not update the copy of the
2778 -R is specified). By default, this does not update the copy of the
2779 project in the working directory.
2779 project in the working directory.
2780
2780
2781 Use :hg:`incoming` if you want to see what would have been added
2781 Use :hg:`incoming` if you want to see what would have been added
2782 by a pull at the time you issued this command. If you then decide
2782 by a pull at the time you issued this command. If you then decide
2783 to add those changes to the repository, you should use :hg:`pull
2783 to add those changes to the repository, you should use :hg:`pull
2784 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
2784 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
2785
2785
2786 If SOURCE is omitted, the 'default' path will be used.
2786 If SOURCE is omitted, the 'default' path will be used.
2787 See :hg:`help urls` for more information.
2787 See :hg:`help urls` for more information.
2788
2788
2789 Returns 0 on success, 1 if an update had unresolved files.
2789 Returns 0 on success, 1 if an update had unresolved files.
2790 """
2790 """
2791 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
2791 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
2792 other = hg.repository(hg.remoteui(repo, opts), source)
2792 other = hg.repository(hg.remoteui(repo, opts), source)
2793 ui.status(_('pulling from %s\n') % url.hidepassword(source))
2793 ui.status(_('pulling from %s\n') % url.hidepassword(source))
2794 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
2794 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
2795 if revs:
2795 if revs:
2796 try:
2796 try:
2797 revs = [other.lookup(rev) for rev in revs]
2797 revs = [other.lookup(rev) for rev in revs]
2798 except error.CapabilityError:
2798 except error.CapabilityError:
2799 err = _("Other repository doesn't support revision lookup, "
2799 err = _("Other repository doesn't support revision lookup, "
2800 "so a rev cannot be specified.")
2800 "so a rev cannot be specified.")
2801 raise util.Abort(err)
2801 raise util.Abort(err)
2802
2802
2803 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
2803 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
2804 if checkout:
2804 if checkout:
2805 checkout = str(repo.changelog.rev(other.lookup(checkout)))
2805 checkout = str(repo.changelog.rev(other.lookup(checkout)))
2806 return postincoming(ui, repo, modheads, opts.get('update'), checkout)
2806 return postincoming(ui, repo, modheads, opts.get('update'), checkout)
2807
2807
2808 def push(ui, repo, dest=None, **opts):
2808 def push(ui, repo, dest=None, **opts):
2809 """push changes to the specified destination
2809 """push changes to the specified destination
2810
2810
2811 Push changesets from the local repository to the specified
2811 Push changesets from the local repository to the specified
2812 destination.
2812 destination.
2813
2813
2814 This operation is symmetrical to pull: it is identical to a pull
2814 This operation is symmetrical to pull: it is identical to a pull
2815 in the destination repository from the current one.
2815 in the destination repository from the current one.
2816
2816
2817 By default, push will not allow creation of new heads at the
2817 By default, push will not allow creation of new heads at the
2818 destination, since multiple heads would make it unclear which head
2818 destination, since multiple heads would make it unclear which head
2819 to use. In this situation, it is recommended to pull and merge
2819 to use. In this situation, it is recommended to pull and merge
2820 before pushing.
2820 before pushing.
2821
2821
2822 Use --new-branch if you want to allow push to create a new named
2822 Use --new-branch if you want to allow push to create a new named
2823 branch that is not present at the destination. This allows you to
2823 branch that is not present at the destination. This allows you to
2824 only create a new branch without forcing other changes.
2824 only create a new branch without forcing other changes.
2825
2825
2826 Use -f/--force to override the default behavior and push all
2826 Use -f/--force to override the default behavior and push all
2827 changesets on all branches.
2827 changesets on all branches.
2828
2828
2829 If -r/--rev is used, the specified revision and all its ancestors
2829 If -r/--rev is used, the specified revision and all its ancestors
2830 will be pushed to the remote repository.
2830 will be pushed to the remote repository.
2831
2831
2832 Please see :hg:`help urls` for important details about ``ssh://``
2832 Please see :hg:`help urls` for important details about ``ssh://``
2833 URLs. If DESTINATION is omitted, a default path will be used.
2833 URLs. If DESTINATION is omitted, a default path will be used.
2834
2834
2835 Returns 0 if push was successful, 1 if nothing to push.
2835 Returns 0 if push was successful, 1 if nothing to push.
2836 """
2836 """
2837 dest = ui.expandpath(dest or 'default-push', dest or 'default')
2837 dest = ui.expandpath(dest or 'default-push', dest or 'default')
2838 dest, branches = hg.parseurl(dest, opts.get('branch'))
2838 dest, branches = hg.parseurl(dest, opts.get('branch'))
2839 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
2839 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
2840 other = hg.repository(hg.remoteui(repo, opts), dest)
2840 other = hg.repository(hg.remoteui(repo, opts), dest)
2841 ui.status(_('pushing to %s\n') % url.hidepassword(dest))
2841 ui.status(_('pushing to %s\n') % url.hidepassword(dest))
2842 if revs:
2842 if revs:
2843 revs = [repo.lookup(rev) for rev in revs]
2843 revs = [repo.lookup(rev) for rev in revs]
2844
2844
2845 # push subrepos depth-first for coherent ordering
2845 # push subrepos depth-first for coherent ordering
2846 c = repo['']
2846 c = repo['']
2847 subs = c.substate # only repos that are committed
2847 subs = c.substate # only repos that are committed
2848 for s in sorted(subs):
2848 for s in sorted(subs):
2849 if not c.sub(s).push(opts.get('force')):
2849 if not c.sub(s).push(opts.get('force')):
2850 return False
2850 return False
2851
2851
2852 r = repo.push(other, opts.get('force'), revs=revs,
2852 r = repo.push(other, opts.get('force'), revs=revs,
2853 newbranch=opts.get('new_branch'))
2853 newbranch=opts.get('new_branch'))
2854 return r == 0
2854 return r == 0
2855
2855
2856 def recover(ui, repo):
2856 def recover(ui, repo):
2857 """roll back an interrupted transaction
2857 """roll back an interrupted transaction
2858
2858
2859 Recover from an interrupted commit or pull.
2859 Recover from an interrupted commit or pull.
2860
2860
2861 This command tries to fix the repository status after an
2861 This command tries to fix the repository status after an
2862 interrupted operation. It should only be necessary when Mercurial
2862 interrupted operation. It should only be necessary when Mercurial
2863 suggests it.
2863 suggests it.
2864
2864
2865 Returns 0 if successful, 1 if nothing to recover or verify fails.
2865 Returns 0 if successful, 1 if nothing to recover or verify fails.
2866 """
2866 """
2867 if repo.recover():
2867 if repo.recover():
2868 return hg.verify(repo)
2868 return hg.verify(repo)
2869 return 1
2869 return 1
2870
2870
2871 def remove(ui, repo, *pats, **opts):
2871 def remove(ui, repo, *pats, **opts):
2872 """remove the specified files on the next commit
2872 """remove the specified files on the next commit
2873
2873
2874 Schedule the indicated files for removal from the repository.
2874 Schedule the indicated files for removal from the repository.
2875
2875
2876 This only removes files from the current branch, not from the
2876 This only removes files from the current branch, not from the
2877 entire project history. -A/--after can be used to remove only
2877 entire project history. -A/--after can be used to remove only
2878 files that have already been deleted, -f/--force can be used to
2878 files that have already been deleted, -f/--force can be used to
2879 force deletion, and -Af can be used to remove files from the next
2879 force deletion, and -Af can be used to remove files from the next
2880 revision without deleting them from the working directory.
2880 revision without deleting them from the working directory.
2881
2881
2882 The following table details the behavior of remove for different
2882 The following table details the behavior of remove for different
2883 file states (columns) and option combinations (rows). The file
2883 file states (columns) and option combinations (rows). The file
2884 states are Added [A], Clean [C], Modified [M] and Missing [!] (as
2884 states are Added [A], Clean [C], Modified [M] and Missing [!] (as
2885 reported by :hg:`status`). The actions are Warn, Remove (from
2885 reported by :hg:`status`). The actions are Warn, Remove (from
2886 branch) and Delete (from disk)::
2886 branch) and Delete (from disk)::
2887
2887
2888 A C M !
2888 A C M !
2889 none W RD W R
2889 none W RD W R
2890 -f R RD RD R
2890 -f R RD RD R
2891 -A W W W R
2891 -A W W W R
2892 -Af R R R R
2892 -Af R R R R
2893
2893
2894 This command schedules the files to be removed at the next commit.
2894 This command schedules the files to be removed at the next commit.
2895 To undo a remove before that, see :hg:`revert`.
2895 To undo a remove before that, see :hg:`revert`.
2896
2896
2897 Returns 0 on success, 1 if any warnings encountered.
2897 Returns 0 on success, 1 if any warnings encountered.
2898 """
2898 """
2899
2899
2900 ret = 0
2900 ret = 0
2901 after, force = opts.get('after'), opts.get('force')
2901 after, force = opts.get('after'), opts.get('force')
2902 if not pats and not after:
2902 if not pats and not after:
2903 raise util.Abort(_('no files specified'))
2903 raise util.Abort(_('no files specified'))
2904
2904
2905 m = cmdutil.match(repo, pats, opts)
2905 m = cmdutil.match(repo, pats, opts)
2906 s = repo.status(match=m, clean=True)
2906 s = repo.status(match=m, clean=True)
2907 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2907 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2908
2908
2909 for f in m.files():
2909 for f in m.files():
2910 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2910 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2911 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
2911 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
2912 ret = 1
2912 ret = 1
2913
2913
2914 def warn(files, reason):
2914 def warn(files, reason):
2915 for f in files:
2915 for f in files:
2916 ui.warn(_('not removing %s: file %s (use -f to force removal)\n')
2916 ui.warn(_('not removing %s: file %s (use -f to force removal)\n')
2917 % (m.rel(f), reason))
2917 % (m.rel(f), reason))
2918 ret = 1
2918 ret = 1
2919
2919
2920 if force:
2920 if force:
2921 remove, forget = modified + deleted + clean, added
2921 remove, forget = modified + deleted + clean, added
2922 elif after:
2922 elif after:
2923 remove, forget = deleted, []
2923 remove, forget = deleted, []
2924 warn(modified + added + clean, _('still exists'))
2924 warn(modified + added + clean, _('still exists'))
2925 else:
2925 else:
2926 remove, forget = deleted + clean, []
2926 remove, forget = deleted + clean, []
2927 warn(modified, _('is modified'))
2927 warn(modified, _('is modified'))
2928 warn(added, _('has been marked for add'))
2928 warn(added, _('has been marked for add'))
2929
2929
2930 for f in sorted(remove + forget):
2930 for f in sorted(remove + forget):
2931 if ui.verbose or not m.exact(f):
2931 if ui.verbose or not m.exact(f):
2932 ui.status(_('removing %s\n') % m.rel(f))
2932 ui.status(_('removing %s\n') % m.rel(f))
2933
2933
2934 repo[None].forget(forget)
2934 repo[None].forget(forget)
2935 repo[None].remove(remove, unlink=not after)
2935 repo[None].remove(remove, unlink=not after)
2936 return ret
2936 return ret
2937
2937
2938 def rename(ui, repo, *pats, **opts):
2938 def rename(ui, repo, *pats, **opts):
2939 """rename files; equivalent of copy + remove
2939 """rename files; equivalent of copy + remove
2940
2940
2941 Mark dest as copies of sources; mark sources for deletion. If dest
2941 Mark dest as copies of sources; mark sources for deletion. If dest
2942 is a directory, copies are put in that directory. If dest is a
2942 is a directory, copies are put in that directory. If dest is a
2943 file, there can only be one source.
2943 file, there can only be one source.
2944
2944
2945 By default, this command copies the contents of files as they
2945 By default, this command copies the contents of files as they
2946 exist in the working directory. If invoked with -A/--after, the
2946 exist in the working directory. If invoked with -A/--after, the
2947 operation is recorded, but no copying is performed.
2947 operation is recorded, but no copying is performed.
2948
2948
2949 This command takes effect at the next commit. To undo a rename
2949 This command takes effect at the next commit. To undo a rename
2950 before that, see :hg:`revert`.
2950 before that, see :hg:`revert`.
2951
2951
2952 Returns 0 on success, 1 if errors are encountered.
2952 Returns 0 on success, 1 if errors are encountered.
2953 """
2953 """
2954 wlock = repo.wlock(False)
2954 wlock = repo.wlock(False)
2955 try:
2955 try:
2956 return cmdutil.copy(ui, repo, pats, opts, rename=True)
2956 return cmdutil.copy(ui, repo, pats, opts, rename=True)
2957 finally:
2957 finally:
2958 wlock.release()
2958 wlock.release()
2959
2959
2960 def resolve(ui, repo, *pats, **opts):
2960 def resolve(ui, repo, *pats, **opts):
2961 """various operations to help finish a merge
2961 """various operations to help finish a merge
2962
2962
2963 This command includes several actions that are often useful while
2963 This command includes several actions that are often useful while
2964 performing a merge, after running ``merge`` but before running
2964 performing a merge, after running ``merge`` but before running
2965 ``commit``. (It is only meaningful if your working directory has
2965 ``commit``. (It is only meaningful if your working directory has
2966 two parents.) It is most relevant for merges with unresolved
2966 two parents.) It is most relevant for merges with unresolved
2967 conflicts, which are typically a result of non-interactive merging with
2967 conflicts, which are typically a result of non-interactive merging with
2968 ``internal:merge`` or a command-line merge tool like ``diff3``.
2968 ``internal:merge`` or a command-line merge tool like ``diff3``.
2969
2969
2970 The available actions are:
2970 The available actions are:
2971
2971
2972 1) list files that were merged with conflicts (U, for unresolved)
2972 1) list files that were merged with conflicts (U, for unresolved)
2973 and without conflicts (R, for resolved): ``hg resolve -l``
2973 and without conflicts (R, for resolved): ``hg resolve -l``
2974 (this is like ``status`` for merges)
2974 (this is like ``status`` for merges)
2975 2) record that you have resolved conflicts in certain files:
2975 2) record that you have resolved conflicts in certain files:
2976 ``hg resolve -m [file ...]`` (default: mark all unresolved files)
2976 ``hg resolve -m [file ...]`` (default: mark all unresolved files)
2977 3) forget that you have resolved conflicts in certain files:
2977 3) forget that you have resolved conflicts in certain files:
2978 ``hg resolve -u [file ...]`` (default: unmark all resolved files)
2978 ``hg resolve -u [file ...]`` (default: unmark all resolved files)
2979 4) discard your current attempt(s) at resolving conflicts and
2979 4) discard your current attempt(s) at resolving conflicts and
2980 restart the merge from scratch: ``hg resolve file...``
2980 restart the merge from scratch: ``hg resolve file...``
2981 (or ``-a`` for all unresolved files)
2981 (or ``-a`` for all unresolved files)
2982
2982
2983 Note that Mercurial will not let you commit files with unresolved merge
2983 Note that Mercurial will not let you commit files with unresolved merge
2984 conflicts. You must use ``hg resolve -m ...`` before you can commit
2984 conflicts. You must use ``hg resolve -m ...`` before you can commit
2985 after a conflicting merge.
2985 after a conflicting merge.
2986
2986
2987 Returns 0 on success, 1 if any files fail a resolve attempt.
2987 Returns 0 on success, 1 if any files fail a resolve attempt.
2988 """
2988 """
2989
2989
2990 all, mark, unmark, show, nostatus = \
2990 all, mark, unmark, show, nostatus = \
2991 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
2991 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
2992
2992
2993 if (show and (mark or unmark)) or (mark and unmark):
2993 if (show and (mark or unmark)) or (mark and unmark):
2994 raise util.Abort(_("too many options specified"))
2994 raise util.Abort(_("too many options specified"))
2995 if pats and all:
2995 if pats and all:
2996 raise util.Abort(_("can't specify --all and patterns"))
2996 raise util.Abort(_("can't specify --all and patterns"))
2997 if not (all or pats or show or mark or unmark):
2997 if not (all or pats or show or mark or unmark):
2998 raise util.Abort(_('no files or directories specified; '
2998 raise util.Abort(_('no files or directories specified; '
2999 'use --all to remerge all files'))
2999 'use --all to remerge all files'))
3000
3000
3001 ms = mergemod.mergestate(repo)
3001 ms = mergemod.mergestate(repo)
3002 m = cmdutil.match(repo, pats, opts)
3002 m = cmdutil.match(repo, pats, opts)
3003 ret = 0
3003 ret = 0
3004
3004
3005 for f in ms:
3005 for f in ms:
3006 if m(f):
3006 if m(f):
3007 if show:
3007 if show:
3008 if nostatus:
3008 if nostatus:
3009 ui.write("%s\n" % f)
3009 ui.write("%s\n" % f)
3010 else:
3010 else:
3011 ui.write("%s %s\n" % (ms[f].upper(), f),
3011 ui.write("%s %s\n" % (ms[f].upper(), f),
3012 label='resolve.' +
3012 label='resolve.' +
3013 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
3013 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
3014 elif mark:
3014 elif mark:
3015 ms.mark(f, "r")
3015 ms.mark(f, "r")
3016 elif unmark:
3016 elif unmark:
3017 ms.mark(f, "u")
3017 ms.mark(f, "u")
3018 else:
3018 else:
3019 wctx = repo[None]
3019 wctx = repo[None]
3020 mctx = wctx.parents()[-1]
3020 mctx = wctx.parents()[-1]
3021
3021
3022 # backup pre-resolve (merge uses .orig for its own purposes)
3022 # backup pre-resolve (merge uses .orig for its own purposes)
3023 a = repo.wjoin(f)
3023 a = repo.wjoin(f)
3024 util.copyfile(a, a + ".resolve")
3024 util.copyfile(a, a + ".resolve")
3025
3025
3026 # resolve file
3026 # resolve file
3027 if ms.resolve(f, wctx, mctx):
3027 if ms.resolve(f, wctx, mctx):
3028 ret = 1
3028 ret = 1
3029
3029
3030 # replace filemerge's .orig file with our resolve file
3030 # replace filemerge's .orig file with our resolve file
3031 util.rename(a + ".resolve", a + ".orig")
3031 util.rename(a + ".resolve", a + ".orig")
3032 return ret
3032 return ret
3033
3033
3034 def revert(ui, repo, *pats, **opts):
3034 def revert(ui, repo, *pats, **opts):
3035 """restore individual files or directories to an earlier state
3035 """restore individual files or directories to an earlier state
3036
3036
3037 NOTE: This command is most likely not what you are looking for. revert
3037 NOTE: This command is most likely not what you are looking for. revert
3038 will partially overwrite content in the working directory without changing
3038 will partially overwrite content in the working directory without changing
3039 the working directory parents. Use :hg:`update -r rev` to check out earlier
3039 the working directory parents. Use :hg:`update -r rev` to check out earlier
3040 revisions, or :hg:`update --clean .` to undo a merge which has added
3040 revisions, or :hg:`update --clean .` to undo a merge which has added
3041 another parent.
3041 another parent.
3042
3042
3043 With no revision specified, revert the named files or directories
3043 With no revision specified, revert the named files or directories
3044 to the contents they had in the parent of the working directory.
3044 to the contents they had in the parent of the working directory.
3045 This restores the contents of the affected files to an unmodified
3045 This restores the contents of the affected files to an unmodified
3046 state and unschedules adds, removes, copies, and renames. If the
3046 state and unschedules adds, removes, copies, and renames. If the
3047 working directory has two parents, you must explicitly specify a
3047 working directory has two parents, you must explicitly specify a
3048 revision.
3048 revision.
3049
3049
3050 Using the -r/--rev option, revert the given files or directories
3050 Using the -r/--rev option, revert the given files or directories
3051 to their contents as of a specific revision. This can be helpful
3051 to their contents as of a specific revision. This can be helpful
3052 to "roll back" some or all of an earlier change. See :hg:`help
3052 to "roll back" some or all of an earlier change. See :hg:`help
3053 dates` for a list of formats valid for -d/--date.
3053 dates` for a list of formats valid for -d/--date.
3054
3054
3055 Revert modifies the working directory. It does not commit any
3055 Revert modifies the working directory. It does not commit any
3056 changes, or change the parent of the working directory. If you
3056 changes, or change the parent of the working directory. If you
3057 revert to a revision other than the parent of the working
3057 revert to a revision other than the parent of the working
3058 directory, the reverted files will thus appear modified
3058 directory, the reverted files will thus appear modified
3059 afterwards.
3059 afterwards.
3060
3060
3061 If a file has been deleted, it is restored. If the executable mode
3061 If a file has been deleted, it is restored. If the executable mode
3062 of a file was changed, it is reset.
3062 of a file was changed, it is reset.
3063
3063
3064 If names are given, all files matching the names are reverted.
3064 If names are given, all files matching the names are reverted.
3065 If no arguments are given, no files are reverted.
3065 If no arguments are given, no files are reverted.
3066
3066
3067 Modified files are saved with a .orig suffix before reverting.
3067 Modified files are saved with a .orig suffix before reverting.
3068 To disable these backups, use --no-backup.
3068 To disable these backups, use --no-backup.
3069
3069
3070 Returns 0 on success.
3070 Returns 0 on success.
3071 """
3071 """
3072
3072
3073 if opts["date"]:
3073 if opts["date"]:
3074 if opts["rev"]:
3074 if opts["rev"]:
3075 raise util.Abort(_("you can't specify a revision and a date"))
3075 raise util.Abort(_("you can't specify a revision and a date"))
3076 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
3076 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
3077
3077
3078 if not pats and not opts.get('all'):
3078 if not pats and not opts.get('all'):
3079 raise util.Abort(_('no files or directories specified; '
3079 raise util.Abort(_('no files or directories specified; '
3080 'use --all to revert the whole repo'))
3080 'use --all to revert the whole repo'))
3081
3081
3082 parent, p2 = repo.dirstate.parents()
3082 parent, p2 = repo.dirstate.parents()
3083 if not opts.get('rev') and p2 != nullid:
3083 if not opts.get('rev') and p2 != nullid:
3084 raise util.Abort(_('uncommitted merge - please provide a '
3084 raise util.Abort(_('uncommitted merge - please provide a '
3085 'specific revision'))
3085 'specific revision'))
3086 ctx = repo[opts.get('rev')]
3086 ctx = repo[opts.get('rev')]
3087 node = ctx.node()
3087 node = ctx.node()
3088 mf = ctx.manifest()
3088 mf = ctx.manifest()
3089 if node == parent:
3089 if node == parent:
3090 pmf = mf
3090 pmf = mf
3091 else:
3091 else:
3092 pmf = None
3092 pmf = None
3093
3093
3094 # need all matching names in dirstate and manifest of target rev,
3094 # need all matching names in dirstate and manifest of target rev,
3095 # so have to walk both. do not print errors if files exist in one
3095 # so have to walk both. do not print errors if files exist in one
3096 # but not other.
3096 # but not other.
3097
3097
3098 names = {}
3098 names = {}
3099
3099
3100 wlock = repo.wlock()
3100 wlock = repo.wlock()
3101 try:
3101 try:
3102 # walk dirstate.
3102 # walk dirstate.
3103
3103
3104 m = cmdutil.match(repo, pats, opts)
3104 m = cmdutil.match(repo, pats, opts)
3105 m.bad = lambda x, y: False
3105 m.bad = lambda x, y: False
3106 for abs in repo.walk(m):
3106 for abs in repo.walk(m):
3107 names[abs] = m.rel(abs), m.exact(abs)
3107 names[abs] = m.rel(abs), m.exact(abs)
3108
3108
3109 # walk target manifest.
3109 # walk target manifest.
3110
3110
3111 def badfn(path, msg):
3111 def badfn(path, msg):
3112 if path in names:
3112 if path in names:
3113 return
3113 return
3114 path_ = path + '/'
3114 path_ = path + '/'
3115 for f in names:
3115 for f in names:
3116 if f.startswith(path_):
3116 if f.startswith(path_):
3117 return
3117 return
3118 ui.warn("%s: %s\n" % (m.rel(path), msg))
3118 ui.warn("%s: %s\n" % (m.rel(path), msg))
3119
3119
3120 m = cmdutil.match(repo, pats, opts)
3120 m = cmdutil.match(repo, pats, opts)
3121 m.bad = badfn
3121 m.bad = badfn
3122 for abs in repo[node].walk(m):
3122 for abs in repo[node].walk(m):
3123 if abs not in names:
3123 if abs not in names:
3124 names[abs] = m.rel(abs), m.exact(abs)
3124 names[abs] = m.rel(abs), m.exact(abs)
3125
3125
3126 m = cmdutil.matchfiles(repo, names)
3126 m = cmdutil.matchfiles(repo, names)
3127 changes = repo.status(match=m)[:4]
3127 changes = repo.status(match=m)[:4]
3128 modified, added, removed, deleted = map(set, changes)
3128 modified, added, removed, deleted = map(set, changes)
3129
3129
3130 # if f is a rename, also revert the source
3130 # if f is a rename, also revert the source
3131 cwd = repo.getcwd()
3131 cwd = repo.getcwd()
3132 for f in added:
3132 for f in added:
3133 src = repo.dirstate.copied(f)
3133 src = repo.dirstate.copied(f)
3134 if src and src not in names and repo.dirstate[src] == 'r':
3134 if src and src not in names and repo.dirstate[src] == 'r':
3135 removed.add(src)
3135 removed.add(src)
3136 names[src] = (repo.pathto(src, cwd), True)
3136 names[src] = (repo.pathto(src, cwd), True)
3137
3137
3138 def removeforget(abs):
3138 def removeforget(abs):
3139 if repo.dirstate[abs] == 'a':
3139 if repo.dirstate[abs] == 'a':
3140 return _('forgetting %s\n')
3140 return _('forgetting %s\n')
3141 return _('removing %s\n')
3141 return _('removing %s\n')
3142
3142
3143 revert = ([], _('reverting %s\n'))
3143 revert = ([], _('reverting %s\n'))
3144 add = ([], _('adding %s\n'))
3144 add = ([], _('adding %s\n'))
3145 remove = ([], removeforget)
3145 remove = ([], removeforget)
3146 undelete = ([], _('undeleting %s\n'))
3146 undelete = ([], _('undeleting %s\n'))
3147
3147
3148 disptable = (
3148 disptable = (
3149 # dispatch table:
3149 # dispatch table:
3150 # file state
3150 # file state
3151 # action if in target manifest
3151 # action if in target manifest
3152 # action if not in target manifest
3152 # action if not in target manifest
3153 # make backup if in target manifest
3153 # make backup if in target manifest
3154 # make backup if not in target manifest
3154 # make backup if not in target manifest
3155 (modified, revert, remove, True, True),
3155 (modified, revert, remove, True, True),
3156 (added, revert, remove, True, False),
3156 (added, revert, remove, True, False),
3157 (removed, undelete, None, False, False),
3157 (removed, undelete, None, False, False),
3158 (deleted, revert, remove, False, False),
3158 (deleted, revert, remove, False, False),
3159 )
3159 )
3160
3160
3161 for abs, (rel, exact) in sorted(names.items()):
3161 for abs, (rel, exact) in sorted(names.items()):
3162 mfentry = mf.get(abs)
3162 mfentry = mf.get(abs)
3163 target = repo.wjoin(abs)
3163 target = repo.wjoin(abs)
3164 def handle(xlist, dobackup):
3164 def handle(xlist, dobackup):
3165 xlist[0].append(abs)
3165 xlist[0].append(abs)
3166 if dobackup and not opts.get('no_backup') and util.lexists(target):
3166 if dobackup and not opts.get('no_backup') and util.lexists(target):
3167 bakname = "%s.orig" % rel
3167 bakname = "%s.orig" % rel
3168 ui.note(_('saving current version of %s as %s\n') %
3168 ui.note(_('saving current version of %s as %s\n') %
3169 (rel, bakname))
3169 (rel, bakname))
3170 if not opts.get('dry_run'):
3170 if not opts.get('dry_run'):
3171 util.rename(target, bakname)
3171 util.rename(target, bakname)
3172 if ui.verbose or not exact:
3172 if ui.verbose or not exact:
3173 msg = xlist[1]
3173 msg = xlist[1]
3174 if not isinstance(msg, basestring):
3174 if not isinstance(msg, basestring):
3175 msg = msg(abs)
3175 msg = msg(abs)
3176 ui.status(msg % rel)
3176 ui.status(msg % rel)
3177 for table, hitlist, misslist, backuphit, backupmiss in disptable:
3177 for table, hitlist, misslist, backuphit, backupmiss in disptable:
3178 if abs not in table:
3178 if abs not in table:
3179 continue
3179 continue
3180 # file has changed in dirstate
3180 # file has changed in dirstate
3181 if mfentry:
3181 if mfentry:
3182 handle(hitlist, backuphit)
3182 handle(hitlist, backuphit)
3183 elif misslist is not None:
3183 elif misslist is not None:
3184 handle(misslist, backupmiss)
3184 handle(misslist, backupmiss)
3185 break
3185 break
3186 else:
3186 else:
3187 if abs not in repo.dirstate:
3187 if abs not in repo.dirstate:
3188 if mfentry:
3188 if mfentry:
3189 handle(add, True)
3189 handle(add, True)
3190 elif exact:
3190 elif exact:
3191 ui.warn(_('file not managed: %s\n') % rel)
3191 ui.warn(_('file not managed: %s\n') % rel)
3192 continue
3192 continue
3193 # file has not changed in dirstate
3193 # file has not changed in dirstate
3194 if node == parent:
3194 if node == parent:
3195 if exact:
3195 if exact:
3196 ui.warn(_('no changes needed to %s\n') % rel)
3196 ui.warn(_('no changes needed to %s\n') % rel)
3197 continue
3197 continue
3198 if pmf is None:
3198 if pmf is None:
3199 # only need parent manifest in this unlikely case,
3199 # only need parent manifest in this unlikely case,
3200 # so do not read by default
3200 # so do not read by default
3201 pmf = repo[parent].manifest()
3201 pmf = repo[parent].manifest()
3202 if abs in pmf:
3202 if abs in pmf:
3203 if mfentry:
3203 if mfentry:
3204 # if version of file is same in parent and target
3204 # if version of file is same in parent and target
3205 # manifests, do nothing
3205 # manifests, do nothing
3206 if (pmf[abs] != mfentry or
3206 if (pmf[abs] != mfentry or
3207 pmf.flags(abs) != mf.flags(abs)):
3207 pmf.flags(abs) != mf.flags(abs)):
3208 handle(revert, False)
3208 handle(revert, False)
3209 else:
3209 else:
3210 handle(remove, False)
3210 handle(remove, False)
3211
3211
3212 if not opts.get('dry_run'):
3212 if not opts.get('dry_run'):
3213 def checkout(f):
3213 def checkout(f):
3214 fc = ctx[f]
3214 fc = ctx[f]
3215 repo.wwrite(f, fc.data(), fc.flags())
3215 repo.wwrite(f, fc.data(), fc.flags())
3216
3216
3217 audit_path = util.path_auditor(repo.root)
3217 audit_path = util.path_auditor(repo.root)
3218 for f in remove[0]:
3218 for f in remove[0]:
3219 if repo.dirstate[f] == 'a':
3219 if repo.dirstate[f] == 'a':
3220 repo.dirstate.forget(f)
3220 repo.dirstate.forget(f)
3221 continue
3221 continue
3222 audit_path(f)
3222 audit_path(f)
3223 try:
3223 try:
3224 util.unlink(repo.wjoin(f))
3224 util.unlink(repo.wjoin(f))
3225 except OSError:
3225 except OSError:
3226 pass
3226 pass
3227 repo.dirstate.remove(f)
3227 repo.dirstate.remove(f)
3228
3228
3229 normal = None
3229 normal = None
3230 if node == parent:
3230 if node == parent:
3231 # We're reverting to our parent. If possible, we'd like status
3231 # We're reverting to our parent. If possible, we'd like status
3232 # to report the file as clean. We have to use normallookup for
3232 # to report the file as clean. We have to use normallookup for
3233 # merges to avoid losing information about merged/dirty files.
3233 # merges to avoid losing information about merged/dirty files.
3234 if p2 != nullid:
3234 if p2 != nullid:
3235 normal = repo.dirstate.normallookup
3235 normal = repo.dirstate.normallookup
3236 else:
3236 else:
3237 normal = repo.dirstate.normal
3237 normal = repo.dirstate.normal
3238 for f in revert[0]:
3238 for f in revert[0]:
3239 checkout(f)
3239 checkout(f)
3240 if normal:
3240 if normal:
3241 normal(f)
3241 normal(f)
3242
3242
3243 for f in add[0]:
3243 for f in add[0]:
3244 checkout(f)
3244 checkout(f)
3245 repo.dirstate.add(f)
3245 repo.dirstate.add(f)
3246
3246
3247 normal = repo.dirstate.normallookup
3247 normal = repo.dirstate.normallookup
3248 if node == parent and p2 == nullid:
3248 if node == parent and p2 == nullid:
3249 normal = repo.dirstate.normal
3249 normal = repo.dirstate.normal
3250 for f in undelete[0]:
3250 for f in undelete[0]:
3251 checkout(f)
3251 checkout(f)
3252 normal(f)
3252 normal(f)
3253
3253
3254 finally:
3254 finally:
3255 wlock.release()
3255 wlock.release()
3256
3256
3257 def rollback(ui, repo, **opts):
3257 def rollback(ui, repo, **opts):
3258 """roll back the last transaction (dangerous)
3258 """roll back the last transaction (dangerous)
3259
3259
3260 This command should be used with care. There is only one level of
3260 This command should be used with care. There is only one level of
3261 rollback, and there is no way to undo a rollback. It will also
3261 rollback, and there is no way to undo a rollback. It will also
3262 restore the dirstate at the time of the last transaction, losing
3262 restore the dirstate at the time of the last transaction, losing
3263 any dirstate changes since that time. This command does not alter
3263 any dirstate changes since that time. This command does not alter
3264 the working directory.
3264 the working directory.
3265
3265
3266 Transactions are used to encapsulate the effects of all commands
3266 Transactions are used to encapsulate the effects of all commands
3267 that create new changesets or propagate existing changesets into a
3267 that create new changesets or propagate existing changesets into a
3268 repository. For example, the following commands are transactional,
3268 repository. For example, the following commands are transactional,
3269 and their effects can be rolled back:
3269 and their effects can be rolled back:
3270
3270
3271 - commit
3271 - commit
3272 - import
3272 - import
3273 - pull
3273 - pull
3274 - push (with this repository as the destination)
3274 - push (with this repository as the destination)
3275 - unbundle
3275 - unbundle
3276
3276
3277 This command is not intended for use on public repositories. Once
3277 This command is not intended for use on public repositories. Once
3278 changes are visible for pull by other users, rolling a transaction
3278 changes are visible for pull by other users, rolling a transaction
3279 back locally is ineffective (someone else may already have pulled
3279 back locally is ineffective (someone else may already have pulled
3280 the changes). Furthermore, a race is possible with readers of the
3280 the changes). Furthermore, a race is possible with readers of the
3281 repository; for example an in-progress pull from the repository
3281 repository; for example an in-progress pull from the repository
3282 may fail if a rollback is performed.
3282 may fail if a rollback is performed.
3283
3283
3284 Returns 0 on success, 1 if no rollback data is available.
3284 Returns 0 on success, 1 if no rollback data is available.
3285 """
3285 """
3286 return repo.rollback(opts.get('dry_run'))
3286 return repo.rollback(opts.get('dry_run'))
3287
3287
3288 def root(ui, repo):
3288 def root(ui, repo):
3289 """print the root (top) of the current working directory
3289 """print the root (top) of the current working directory
3290
3290
3291 Print the root directory of the current repository.
3291 Print the root directory of the current repository.
3292
3292
3293 Returns 0 on success.
3293 Returns 0 on success.
3294 """
3294 """
3295 ui.write(repo.root + "\n")
3295 ui.write(repo.root + "\n")
3296
3296
3297 def serve(ui, repo, **opts):
3297 def serve(ui, repo, **opts):
3298 """start stand-alone webserver
3298 """start stand-alone webserver
3299
3299
3300 Start a local HTTP repository browser and pull server. You can use
3300 Start a local HTTP repository browser and pull server. You can use
3301 this for ad-hoc sharing and browing of repositories. It is
3301 this for ad-hoc sharing and browing of repositories. It is
3302 recommended to use a real web server to serve a repository for
3302 recommended to use a real web server to serve a repository for
3303 longer periods of time.
3303 longer periods of time.
3304
3304
3305 Please note that the server does not implement access control.
3305 Please note that the server does not implement access control.
3306 This means that, by default, anybody can read from the server and
3306 This means that, by default, anybody can read from the server and
3307 nobody can write to it by default. Set the ``web.allow_push``
3307 nobody can write to it by default. Set the ``web.allow_push``
3308 option to ``*`` to allow everybody to push to the server. You
3308 option to ``*`` to allow everybody to push to the server. You
3309 should use a real web server if you need to authenticate users.
3309 should use a real web server if you need to authenticate users.
3310
3310
3311 By default, the server logs accesses to stdout and errors to
3311 By default, the server logs accesses to stdout and errors to
3312 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
3312 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
3313 files.
3313 files.
3314
3314
3315 To have the server choose a free port number to listen on, specify
3315 To have the server choose a free port number to listen on, specify
3316 a port number of 0; in this case, the server will print the port
3316 a port number of 0; in this case, the server will print the port
3317 number it uses.
3317 number it uses.
3318
3318
3319 Returns 0 on success.
3319 Returns 0 on success.
3320 """
3320 """
3321
3321
3322 if opts["stdio"]:
3322 if opts["stdio"]:
3323 if repo is None:
3323 if repo is None:
3324 raise error.RepoError(_("There is no Mercurial repository here"
3324 raise error.RepoError(_("There is no Mercurial repository here"
3325 " (.hg not found)"))
3325 " (.hg not found)"))
3326 s = sshserver.sshserver(ui, repo)
3326 s = sshserver.sshserver(ui, repo)
3327 s.serve_forever()
3327 s.serve_forever()
3328
3328
3329 # this way we can check if something was given in the command-line
3329 # this way we can check if something was given in the command-line
3330 if opts.get('port'):
3330 if opts.get('port'):
3331 opts['port'] = int(opts.get('port'))
3331 opts['port'] = int(opts.get('port'))
3332
3332
3333 baseui = repo and repo.baseui or ui
3333 baseui = repo and repo.baseui or ui
3334 optlist = ("name templates style address port prefix ipv6"
3334 optlist = ("name templates style address port prefix ipv6"
3335 " accesslog errorlog certificate encoding")
3335 " accesslog errorlog certificate encoding")
3336 for o in optlist.split():
3336 for o in optlist.split():
3337 val = opts.get(o, '')
3337 val = opts.get(o, '')
3338 if val in (None, ''): # should check against default options instead
3338 if val in (None, ''): # should check against default options instead
3339 continue
3339 continue
3340 baseui.setconfig("web", o, val)
3340 baseui.setconfig("web", o, val)
3341 if repo and repo.ui != baseui:
3341 if repo and repo.ui != baseui:
3342 repo.ui.setconfig("web", o, val)
3342 repo.ui.setconfig("web", o, val)
3343
3343
3344 o = opts.get('web_conf') or opts.get('webdir_conf')
3344 o = opts.get('web_conf') or opts.get('webdir_conf')
3345 if not o:
3345 if not o:
3346 if not repo:
3346 if not repo:
3347 raise error.RepoError(_("There is no Mercurial repository"
3347 raise error.RepoError(_("There is no Mercurial repository"
3348 " here (.hg not found)"))
3348 " here (.hg not found)"))
3349 o = repo.root
3349 o = repo.root
3350
3350
3351 app = hgweb.hgweb(o, baseui=ui)
3351 app = hgweb.hgweb(o, baseui=ui)
3352
3352
3353 class service(object):
3353 class service(object):
3354 def init(self):
3354 def init(self):
3355 util.set_signal_handler()
3355 util.set_signal_handler()
3356 self.httpd = hgweb.server.create_server(ui, app)
3356 self.httpd = hgweb.server.create_server(ui, app)
3357
3357
3358 if opts['port'] and not ui.verbose:
3358 if opts['port'] and not ui.verbose:
3359 return
3359 return
3360
3360
3361 if self.httpd.prefix:
3361 if self.httpd.prefix:
3362 prefix = self.httpd.prefix.strip('/') + '/'
3362 prefix = self.httpd.prefix.strip('/') + '/'
3363 else:
3363 else:
3364 prefix = ''
3364 prefix = ''
3365
3365
3366 port = ':%d' % self.httpd.port
3366 port = ':%d' % self.httpd.port
3367 if port == ':80':
3367 if port == ':80':
3368 port = ''
3368 port = ''
3369
3369
3370 bindaddr = self.httpd.addr
3370 bindaddr = self.httpd.addr
3371 if bindaddr == '0.0.0.0':
3371 if bindaddr == '0.0.0.0':
3372 bindaddr = '*'
3372 bindaddr = '*'
3373 elif ':' in bindaddr: # IPv6
3373 elif ':' in bindaddr: # IPv6
3374 bindaddr = '[%s]' % bindaddr
3374 bindaddr = '[%s]' % bindaddr
3375
3375
3376 fqaddr = self.httpd.fqaddr
3376 fqaddr = self.httpd.fqaddr
3377 if ':' in fqaddr:
3377 if ':' in fqaddr:
3378 fqaddr = '[%s]' % fqaddr
3378 fqaddr = '[%s]' % fqaddr
3379 if opts['port']:
3379 if opts['port']:
3380 write = ui.status
3380 write = ui.status
3381 else:
3381 else:
3382 write = ui.write
3382 write = ui.write
3383 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
3383 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
3384 (fqaddr, port, prefix, bindaddr, self.httpd.port))
3384 (fqaddr, port, prefix, bindaddr, self.httpd.port))
3385
3385
3386 def run(self):
3386 def run(self):
3387 self.httpd.serve_forever()
3387 self.httpd.serve_forever()
3388
3388
3389 service = service()
3389 service = service()
3390
3390
3391 cmdutil.service(opts, initfn=service.init, runfn=service.run)
3391 cmdutil.service(opts, initfn=service.init, runfn=service.run)
3392
3392
3393 def status(ui, repo, *pats, **opts):
3393 def status(ui, repo, *pats, **opts):
3394 """show changed files in the working directory
3394 """show changed files in the working directory
3395
3395
3396 Show status of files in the repository. If names are given, only
3396 Show status of files in the repository. If names are given, only
3397 files that match are shown. Files that are clean or ignored or
3397 files that match are shown. Files that are clean or ignored or
3398 the source of a copy/move operation, are not listed unless
3398 the source of a copy/move operation, are not listed unless
3399 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
3399 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
3400 Unless options described with "show only ..." are given, the
3400 Unless options described with "show only ..." are given, the
3401 options -mardu are used.
3401 options -mardu are used.
3402
3402
3403 Option -q/--quiet hides untracked (unknown and ignored) files
3403 Option -q/--quiet hides untracked (unknown and ignored) files
3404 unless explicitly requested with -u/--unknown or -i/--ignored.
3404 unless explicitly requested with -u/--unknown or -i/--ignored.
3405
3405
3406 NOTE: status may appear to disagree with diff if permissions have
3406 NOTE: status may appear to disagree with diff if permissions have
3407 changed or a merge has occurred. The standard diff format does not
3407 changed or a merge has occurred. The standard diff format does not
3408 report permission changes and diff only reports changes relative
3408 report permission changes and diff only reports changes relative
3409 to one merge parent.
3409 to one merge parent.
3410
3410
3411 If one revision is given, it is used as the base revision.
3411 If one revision is given, it is used as the base revision.
3412 If two revisions are given, the differences between them are
3412 If two revisions are given, the differences between them are
3413 shown. The --change option can also be used as a shortcut to list
3413 shown. The --change option can also be used as a shortcut to list
3414 the changed files of a revision from its first parent.
3414 the changed files of a revision from its first parent.
3415
3415
3416 The codes used to show the status of files are::
3416 The codes used to show the status of files are::
3417
3417
3418 M = modified
3418 M = modified
3419 A = added
3419 A = added
3420 R = removed
3420 R = removed
3421 C = clean
3421 C = clean
3422 ! = missing (deleted by non-hg command, but still tracked)
3422 ! = missing (deleted by non-hg command, but still tracked)
3423 ? = not tracked
3423 ? = not tracked
3424 I = ignored
3424 I = ignored
3425 = origin of the previous file listed as A (added)
3425 = origin of the previous file listed as A (added)
3426
3426
3427 Returns 0 on success.
3427 Returns 0 on success.
3428 """
3428 """
3429
3429
3430 revs = opts.get('rev')
3430 revs = opts.get('rev')
3431 change = opts.get('change')
3431 change = opts.get('change')
3432
3432
3433 if revs and change:
3433 if revs and change:
3434 msg = _('cannot specify --rev and --change at the same time')
3434 msg = _('cannot specify --rev and --change at the same time')
3435 raise util.Abort(msg)
3435 raise util.Abort(msg)
3436 elif change:
3436 elif change:
3437 node2 = repo.lookup(change)
3437 node2 = repo.lookup(change)
3438 node1 = repo[node2].parents()[0].node()
3438 node1 = repo[node2].parents()[0].node()
3439 else:
3439 else:
3440 node1, node2 = cmdutil.revpair(repo, revs)
3440 node1, node2 = cmdutil.revpair(repo, revs)
3441
3441
3442 cwd = (pats and repo.getcwd()) or ''
3442 cwd = (pats and repo.getcwd()) or ''
3443 end = opts.get('print0') and '\0' or '\n'
3443 end = opts.get('print0') and '\0' or '\n'
3444 copy = {}
3444 copy = {}
3445 states = 'modified added removed deleted unknown ignored clean'.split()
3445 states = 'modified added removed deleted unknown ignored clean'.split()
3446 show = [k for k in states if opts.get(k)]
3446 show = [k for k in states if opts.get(k)]
3447 if opts.get('all'):
3447 if opts.get('all'):
3448 show += ui.quiet and (states[:4] + ['clean']) or states
3448 show += ui.quiet and (states[:4] + ['clean']) or states
3449 if not show:
3449 if not show:
3450 show = ui.quiet and states[:4] or states[:5]
3450 show = ui.quiet and states[:4] or states[:5]
3451
3451
3452 stat = repo.status(node1, node2, cmdutil.match(repo, pats, opts),
3452 stat = repo.status(node1, node2, cmdutil.match(repo, pats, opts),
3453 'ignored' in show, 'clean' in show, 'unknown' in show)
3453 'ignored' in show, 'clean' in show, 'unknown' in show)
3454 changestates = zip(states, 'MAR!?IC', stat)
3454 changestates = zip(states, 'MAR!?IC', stat)
3455
3455
3456 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
3456 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
3457 ctxn = repo[nullid]
3457 ctxn = repo[nullid]
3458 ctx1 = repo[node1]
3458 ctx1 = repo[node1]
3459 ctx2 = repo[node2]
3459 ctx2 = repo[node2]
3460 added = stat[1]
3460 added = stat[1]
3461 if node2 is None:
3461 if node2 is None:
3462 added = stat[0] + stat[1] # merged?
3462 added = stat[0] + stat[1] # merged?
3463
3463
3464 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
3464 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
3465 if k in added:
3465 if k in added:
3466 copy[k] = v
3466 copy[k] = v
3467 elif v in added:
3467 elif v in added:
3468 copy[v] = k
3468 copy[v] = k
3469
3469
3470 for state, char, files in changestates:
3470 for state, char, files in changestates:
3471 if state in show:
3471 if state in show:
3472 format = "%s %%s%s" % (char, end)
3472 format = "%s %%s%s" % (char, end)
3473 if opts.get('no_status'):
3473 if opts.get('no_status'):
3474 format = "%%s%s" % end
3474 format = "%%s%s" % end
3475
3475
3476 for f in files:
3476 for f in files:
3477 ui.write(format % repo.pathto(f, cwd),
3477 ui.write(format % repo.pathto(f, cwd),
3478 label='status.' + state)
3478 label='status.' + state)
3479 if f in copy:
3479 if f in copy:
3480 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
3480 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
3481 label='status.copied')
3481 label='status.copied')
3482
3482
3483 def summary(ui, repo, **opts):
3483 def summary(ui, repo, **opts):
3484 """summarize working directory state
3484 """summarize working directory state
3485
3485
3486 This generates a brief summary of the working directory state,
3486 This generates a brief summary of the working directory state,
3487 including parents, branch, commit status, and available updates.
3487 including parents, branch, commit status, and available updates.
3488
3488
3489 With the --remote option, this will check the default paths for
3489 With the --remote option, this will check the default paths for
3490 incoming and outgoing changes. This can be time-consuming.
3490 incoming and outgoing changes. This can be time-consuming.
3491
3491
3492 Returns 0 on success.
3492 Returns 0 on success.
3493 """
3493 """
3494
3494
3495 ctx = repo[None]
3495 ctx = repo[None]
3496 parents = ctx.parents()
3496 parents = ctx.parents()
3497 pnode = parents[0].node()
3497 pnode = parents[0].node()
3498
3498
3499 for p in parents:
3499 for p in parents:
3500 # label with log.changeset (instead of log.parent) since this
3500 # label with log.changeset (instead of log.parent) since this
3501 # shows a working directory parent *changeset*:
3501 # shows a working directory parent *changeset*:
3502 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
3502 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
3503 label='log.changeset')
3503 label='log.changeset')
3504 ui.write(' '.join(p.tags()), label='log.tag')
3504 ui.write(' '.join(p.tags()), label='log.tag')
3505 if p.rev() == -1:
3505 if p.rev() == -1:
3506 if not len(repo):
3506 if not len(repo):
3507 ui.write(_(' (empty repository)'))
3507 ui.write(_(' (empty repository)'))
3508 else:
3508 else:
3509 ui.write(_(' (no revision checked out)'))
3509 ui.write(_(' (no revision checked out)'))
3510 ui.write('\n')
3510 ui.write('\n')
3511 if p.description():
3511 if p.description():
3512 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
3512 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
3513 label='log.summary')
3513 label='log.summary')
3514
3514
3515 branch = ctx.branch()
3515 branch = ctx.branch()
3516 bheads = repo.branchheads(branch)
3516 bheads = repo.branchheads(branch)
3517 m = _('branch: %s\n') % branch
3517 m = _('branch: %s\n') % branch
3518 if branch != 'default':
3518 if branch != 'default':
3519 ui.write(m, label='log.branch')
3519 ui.write(m, label='log.branch')
3520 else:
3520 else:
3521 ui.status(m, label='log.branch')
3521 ui.status(m, label='log.branch')
3522
3522
3523 st = list(repo.status(unknown=True))[:6]
3523 st = list(repo.status(unknown=True))[:6]
3524
3524
3525 c = repo.dirstate.copies()
3525 c = repo.dirstate.copies()
3526 copied, renamed = [], []
3526 copied, renamed = [], []
3527 for d, s in c.iteritems():
3527 for d, s in c.iteritems():
3528 if s in st[2]:
3528 if s in st[2]:
3529 st[2].remove(s)
3529 st[2].remove(s)
3530 renamed.append(d)
3530 renamed.append(d)
3531 else:
3531 else:
3532 copied.append(d)
3532 copied.append(d)
3533 if d in st[1]:
3533 if d in st[1]:
3534 st[1].remove(d)
3534 st[1].remove(d)
3535 st.insert(3, renamed)
3535 st.insert(3, renamed)
3536 st.insert(4, copied)
3536 st.insert(4, copied)
3537
3537
3538 ms = mergemod.mergestate(repo)
3538 ms = mergemod.mergestate(repo)
3539 st.append([f for f in ms if ms[f] == 'u'])
3539 st.append([f for f in ms if ms[f] == 'u'])
3540
3540
3541 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
3541 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
3542 st.append(subs)
3542 st.append(subs)
3543
3543
3544 labels = [ui.label(_('%d modified'), 'status.modified'),
3544 labels = [ui.label(_('%d modified'), 'status.modified'),
3545 ui.label(_('%d added'), 'status.added'),
3545 ui.label(_('%d added'), 'status.added'),
3546 ui.label(_('%d removed'), 'status.removed'),
3546 ui.label(_('%d removed'), 'status.removed'),
3547 ui.label(_('%d renamed'), 'status.copied'),
3547 ui.label(_('%d renamed'), 'status.copied'),
3548 ui.label(_('%d copied'), 'status.copied'),
3548 ui.label(_('%d copied'), 'status.copied'),
3549 ui.label(_('%d deleted'), 'status.deleted'),
3549 ui.label(_('%d deleted'), 'status.deleted'),
3550 ui.label(_('%d unknown'), 'status.unknown'),
3550 ui.label(_('%d unknown'), 'status.unknown'),
3551 ui.label(_('%d ignored'), 'status.ignored'),
3551 ui.label(_('%d ignored'), 'status.ignored'),
3552 ui.label(_('%d unresolved'), 'resolve.unresolved'),
3552 ui.label(_('%d unresolved'), 'resolve.unresolved'),
3553 ui.label(_('%d subrepos'), 'status.modified')]
3553 ui.label(_('%d subrepos'), 'status.modified')]
3554 t = []
3554 t = []
3555 for s, l in zip(st, labels):
3555 for s, l in zip(st, labels):
3556 if s:
3556 if s:
3557 t.append(l % len(s))
3557 t.append(l % len(s))
3558
3558
3559 t = ', '.join(t)
3559 t = ', '.join(t)
3560 cleanworkdir = False
3560 cleanworkdir = False
3561
3561
3562 if len(parents) > 1:
3562 if len(parents) > 1:
3563 t += _(' (merge)')
3563 t += _(' (merge)')
3564 elif branch != parents[0].branch():
3564 elif branch != parents[0].branch():
3565 t += _(' (new branch)')
3565 t += _(' (new branch)')
3566 elif (parents[0].extra().get('close') and
3566 elif (parents[0].extra().get('close') and
3567 pnode in repo.branchheads(branch, closed=True)):
3567 pnode in repo.branchheads(branch, closed=True)):
3568 t += _(' (head closed)')
3568 t += _(' (head closed)')
3569 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
3569 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
3570 t += _(' (clean)')
3570 t += _(' (clean)')
3571 cleanworkdir = True
3571 cleanworkdir = True
3572 elif pnode not in bheads:
3572 elif pnode not in bheads:
3573 t += _(' (new branch head)')
3573 t += _(' (new branch head)')
3574
3574
3575 if cleanworkdir:
3575 if cleanworkdir:
3576 ui.status(_('commit: %s\n') % t.strip())
3576 ui.status(_('commit: %s\n') % t.strip())
3577 else:
3577 else:
3578 ui.write(_('commit: %s\n') % t.strip())
3578 ui.write(_('commit: %s\n') % t.strip())
3579
3579
3580 # all ancestors of branch heads - all ancestors of parent = new csets
3580 # all ancestors of branch heads - all ancestors of parent = new csets
3581 new = [0] * len(repo)
3581 new = [0] * len(repo)
3582 cl = repo.changelog
3582 cl = repo.changelog
3583 for a in [cl.rev(n) for n in bheads]:
3583 for a in [cl.rev(n) for n in bheads]:
3584 new[a] = 1
3584 new[a] = 1
3585 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
3585 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
3586 new[a] = 1
3586 new[a] = 1
3587 for a in [p.rev() for p in parents]:
3587 for a in [p.rev() for p in parents]:
3588 if a >= 0:
3588 if a >= 0:
3589 new[a] = 0
3589 new[a] = 0
3590 for a in cl.ancestors(*[p.rev() for p in parents]):
3590 for a in cl.ancestors(*[p.rev() for p in parents]):
3591 new[a] = 0
3591 new[a] = 0
3592 new = sum(new)
3592 new = sum(new)
3593
3593
3594 if new == 0:
3594 if new == 0:
3595 ui.status(_('update: (current)\n'))
3595 ui.status(_('update: (current)\n'))
3596 elif pnode not in bheads:
3596 elif pnode not in bheads:
3597 ui.write(_('update: %d new changesets (update)\n') % new)
3597 ui.write(_('update: %d new changesets (update)\n') % new)
3598 else:
3598 else:
3599 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
3599 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
3600 (new, len(bheads)))
3600 (new, len(bheads)))
3601
3601
3602 if opts.get('remote'):
3602 if opts.get('remote'):
3603 t = []
3603 t = []
3604 source, branches = hg.parseurl(ui.expandpath('default'))
3604 source, branches = hg.parseurl(ui.expandpath('default'))
3605 other = hg.repository(hg.remoteui(repo, {}), source)
3605 other = hg.repository(hg.remoteui(repo, {}), source)
3606 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
3606 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
3607 ui.debug('comparing with %s\n' % url.hidepassword(source))
3607 ui.debug('comparing with %s\n' % url.hidepassword(source))
3608 repo.ui.pushbuffer()
3608 repo.ui.pushbuffer()
3609 common, incoming, rheads = discovery.findcommonincoming(repo, other)
3609 common, incoming, rheads = discovery.findcommonincoming(repo, other)
3610 repo.ui.popbuffer()
3610 repo.ui.popbuffer()
3611 if incoming:
3611 if incoming:
3612 t.append(_('1 or more incoming'))
3612 t.append(_('1 or more incoming'))
3613
3613
3614 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
3614 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
3615 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
3615 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
3616 other = hg.repository(hg.remoteui(repo, {}), dest)
3616 other = hg.repository(hg.remoteui(repo, {}), dest)
3617 ui.debug('comparing with %s\n' % url.hidepassword(dest))
3617 ui.debug('comparing with %s\n' % url.hidepassword(dest))
3618 repo.ui.pushbuffer()
3618 repo.ui.pushbuffer()
3619 o = discovery.findoutgoing(repo, other)
3619 o = discovery.findoutgoing(repo, other)
3620 repo.ui.popbuffer()
3620 repo.ui.popbuffer()
3621 o = repo.changelog.nodesbetween(o, None)[0]
3621 o = repo.changelog.nodesbetween(o, None)[0]
3622 if o:
3622 if o:
3623 t.append(_('%d outgoing') % len(o))
3623 t.append(_('%d outgoing') % len(o))
3624
3624
3625 if t:
3625 if t:
3626 ui.write(_('remote: %s\n') % (', '.join(t)))
3626 ui.write(_('remote: %s\n') % (', '.join(t)))
3627 else:
3627 else:
3628 ui.status(_('remote: (synced)\n'))
3628 ui.status(_('remote: (synced)\n'))
3629
3629
3630 def tag(ui, repo, name1, *names, **opts):
3630 def tag(ui, repo, name1, *names, **opts):
3631 """add one or more tags for the current or given revision
3631 """add one or more tags for the current or given revision
3632
3632
3633 Name a particular revision using <name>.
3633 Name a particular revision using <name>.
3634
3634
3635 Tags are used to name particular revisions of the repository and are
3635 Tags are used to name particular revisions of the repository and are
3636 very useful to compare different revisions, to go back to significant
3636 very useful to compare different revisions, to go back to significant
3637 earlier versions or to mark branch points as releases, etc.
3637 earlier versions or to mark branch points as releases, etc.
3638
3638
3639 If no revision is given, the parent of the working directory is
3639 If no revision is given, the parent of the working directory is
3640 used, or tip if no revision is checked out.
3640 used, or tip if no revision is checked out.
3641
3641
3642 To facilitate version control, distribution, and merging of tags,
3642 To facilitate version control, distribution, and merging of tags,
3643 they are stored as a file named ".hgtags" which is managed
3643 they are stored as a file named ".hgtags" which is managed
3644 similarly to other project files and can be hand-edited if
3644 similarly to other project files and can be hand-edited if
3645 necessary. The file '.hg/localtags' is used for local tags (not
3645 necessary. The file '.hg/localtags' is used for local tags (not
3646 shared among repositories).
3646 shared among repositories).
3647
3647
3648 See :hg:`help dates` for a list of formats valid for -d/--date.
3648 See :hg:`help dates` for a list of formats valid for -d/--date.
3649
3649
3650 Since tag names have priority over branch names during revision
3650 Since tag names have priority over branch names during revision
3651 lookup, using an existing branch name as a tag name is discouraged.
3651 lookup, using an existing branch name as a tag name is discouraged.
3652
3652
3653 Returns 0 on success.
3653 Returns 0 on success.
3654 """
3654 """
3655
3655
3656 rev_ = "."
3656 rev_ = "."
3657 names = [t.strip() for t in (name1,) + names]
3657 names = [t.strip() for t in (name1,) + names]
3658 if len(names) != len(set(names)):
3658 if len(names) != len(set(names)):
3659 raise util.Abort(_('tag names must be unique'))
3659 raise util.Abort(_('tag names must be unique'))
3660 for n in names:
3660 for n in names:
3661 if n in ['tip', '.', 'null']:
3661 if n in ['tip', '.', 'null']:
3662 raise util.Abort(_('the name \'%s\' is reserved') % n)
3662 raise util.Abort(_('the name \'%s\' is reserved') % n)
3663 if not n:
3664 raise util.Abort(_('tag names cannot consist entirely of whitespace'))
3663 if opts.get('rev') and opts.get('remove'):
3665 if opts.get('rev') and opts.get('remove'):
3664 raise util.Abort(_("--rev and --remove are incompatible"))
3666 raise util.Abort(_("--rev and --remove are incompatible"))
3665 if opts.get('rev'):
3667 if opts.get('rev'):
3666 rev_ = opts['rev']
3668 rev_ = opts['rev']
3667 message = opts.get('message')
3669 message = opts.get('message')
3668 if opts.get('remove'):
3670 if opts.get('remove'):
3669 expectedtype = opts.get('local') and 'local' or 'global'
3671 expectedtype = opts.get('local') and 'local' or 'global'
3670 for n in names:
3672 for n in names:
3671 if not repo.tagtype(n):
3673 if not repo.tagtype(n):
3672 raise util.Abort(_('tag \'%s\' does not exist') % n)
3674 raise util.Abort(_('tag \'%s\' does not exist') % n)
3673 if repo.tagtype(n) != expectedtype:
3675 if repo.tagtype(n) != expectedtype:
3674 if expectedtype == 'global':
3676 if expectedtype == 'global':
3675 raise util.Abort(_('tag \'%s\' is not a global tag') % n)
3677 raise util.Abort(_('tag \'%s\' is not a global tag') % n)
3676 else:
3678 else:
3677 raise util.Abort(_('tag \'%s\' is not a local tag') % n)
3679 raise util.Abort(_('tag \'%s\' is not a local tag') % n)
3678 rev_ = nullid
3680 rev_ = nullid
3679 if not message:
3681 if not message:
3680 # we don't translate commit messages
3682 # we don't translate commit messages
3681 message = 'Removed tag %s' % ', '.join(names)
3683 message = 'Removed tag %s' % ', '.join(names)
3682 elif not opts.get('force'):
3684 elif not opts.get('force'):
3683 for n in names:
3685 for n in names:
3684 if n in repo.tags():
3686 if n in repo.tags():
3685 raise util.Abort(_('tag \'%s\' already exists '
3687 raise util.Abort(_('tag \'%s\' already exists '
3686 '(use -f to force)') % n)
3688 '(use -f to force)') % n)
3687 if not rev_ and repo.dirstate.parents()[1] != nullid:
3689 if not rev_ and repo.dirstate.parents()[1] != nullid:
3688 raise util.Abort(_('uncommitted merge - please provide a '
3690 raise util.Abort(_('uncommitted merge - please provide a '
3689 'specific revision'))
3691 'specific revision'))
3690 r = repo[rev_].node()
3692 r = repo[rev_].node()
3691
3693
3692 if not message:
3694 if not message:
3693 # we don't translate commit messages
3695 # we don't translate commit messages
3694 message = ('Added tag %s for changeset %s' %
3696 message = ('Added tag %s for changeset %s' %
3695 (', '.join(names), short(r)))
3697 (', '.join(names), short(r)))
3696
3698
3697 date = opts.get('date')
3699 date = opts.get('date')
3698 if date:
3700 if date:
3699 date = util.parsedate(date)
3701 date = util.parsedate(date)
3700
3702
3701 if opts.get('edit'):
3703 if opts.get('edit'):
3702 message = ui.edit(message, ui.username())
3704 message = ui.edit(message, ui.username())
3703
3705
3704 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
3706 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
3705
3707
3706 def tags(ui, repo):
3708 def tags(ui, repo):
3707 """list repository tags
3709 """list repository tags
3708
3710
3709 This lists both regular and local tags. When the -v/--verbose
3711 This lists both regular and local tags. When the -v/--verbose
3710 switch is used, a third column "local" is printed for local tags.
3712 switch is used, a third column "local" is printed for local tags.
3711
3713
3712 Returns 0 on success.
3714 Returns 0 on success.
3713 """
3715 """
3714
3716
3715 hexfunc = ui.debugflag and hex or short
3717 hexfunc = ui.debugflag and hex or short
3716 tagtype = ""
3718 tagtype = ""
3717
3719
3718 for t, n in reversed(repo.tagslist()):
3720 for t, n in reversed(repo.tagslist()):
3719 if ui.quiet:
3721 if ui.quiet:
3720 ui.write("%s\n" % t)
3722 ui.write("%s\n" % t)
3721 continue
3723 continue
3722
3724
3723 try:
3725 try:
3724 hn = hexfunc(n)
3726 hn = hexfunc(n)
3725 r = "%5d:%s" % (repo.changelog.rev(n), hn)
3727 r = "%5d:%s" % (repo.changelog.rev(n), hn)
3726 except error.LookupError:
3728 except error.LookupError:
3727 r = " ?:%s" % hn
3729 r = " ?:%s" % hn
3728 else:
3730 else:
3729 spaces = " " * (30 - encoding.colwidth(t))
3731 spaces = " " * (30 - encoding.colwidth(t))
3730 if ui.verbose:
3732 if ui.verbose:
3731 if repo.tagtype(t) == 'local':
3733 if repo.tagtype(t) == 'local':
3732 tagtype = " local"
3734 tagtype = " local"
3733 else:
3735 else:
3734 tagtype = ""
3736 tagtype = ""
3735 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
3737 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
3736
3738
3737 def tip(ui, repo, **opts):
3739 def tip(ui, repo, **opts):
3738 """show the tip revision
3740 """show the tip revision
3739
3741
3740 The tip revision (usually just called the tip) is the changeset
3742 The tip revision (usually just called the tip) is the changeset
3741 most recently added to the repository (and therefore the most
3743 most recently added to the repository (and therefore the most
3742 recently changed head).
3744 recently changed head).
3743
3745
3744 If you have just made a commit, that commit will be the tip. If
3746 If you have just made a commit, that commit will be the tip. If
3745 you have just pulled changes from another repository, the tip of
3747 you have just pulled changes from another repository, the tip of
3746 that repository becomes the current tip. The "tip" tag is special
3748 that repository becomes the current tip. The "tip" tag is special
3747 and cannot be renamed or assigned to a different changeset.
3749 and cannot be renamed or assigned to a different changeset.
3748
3750
3749 Returns 0 on success.
3751 Returns 0 on success.
3750 """
3752 """
3751 displayer = cmdutil.show_changeset(ui, repo, opts)
3753 displayer = cmdutil.show_changeset(ui, repo, opts)
3752 displayer.show(repo[len(repo) - 1])
3754 displayer.show(repo[len(repo) - 1])
3753 displayer.close()
3755 displayer.close()
3754
3756
3755 def unbundle(ui, repo, fname1, *fnames, **opts):
3757 def unbundle(ui, repo, fname1, *fnames, **opts):
3756 """apply one or more changegroup files
3758 """apply one or more changegroup files
3757
3759
3758 Apply one or more compressed changegroup files generated by the
3760 Apply one or more compressed changegroup files generated by the
3759 bundle command.
3761 bundle command.
3760
3762
3761 Returns 0 on success, 1 if an update has unresolved files.
3763 Returns 0 on success, 1 if an update has unresolved files.
3762 """
3764 """
3763 fnames = (fname1,) + fnames
3765 fnames = (fname1,) + fnames
3764
3766
3765 lock = repo.lock()
3767 lock = repo.lock()
3766 try:
3768 try:
3767 for fname in fnames:
3769 for fname in fnames:
3768 f = url.open(ui, fname)
3770 f = url.open(ui, fname)
3769 gen = changegroup.readbundle(f, fname)
3771 gen = changegroup.readbundle(f, fname)
3770 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
3772 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
3771 lock=lock)
3773 lock=lock)
3772 finally:
3774 finally:
3773 lock.release()
3775 lock.release()
3774
3776
3775 return postincoming(ui, repo, modheads, opts.get('update'), None)
3777 return postincoming(ui, repo, modheads, opts.get('update'), None)
3776
3778
3777 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
3779 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
3778 """update working directory (or switch revisions)
3780 """update working directory (or switch revisions)
3779
3781
3780 Update the repository's working directory to the specified
3782 Update the repository's working directory to the specified
3781 changeset.
3783 changeset.
3782
3784
3783 If no changeset is specified, attempt to update to the tip of the
3785 If no changeset is specified, attempt to update to the tip of the
3784 current branch. If this changeset is a descendant of the working
3786 current branch. If this changeset is a descendant of the working
3785 directory's parent, update to it, otherwise abort.
3787 directory's parent, update to it, otherwise abort.
3786
3788
3787 The following rules apply when the working directory contains
3789 The following rules apply when the working directory contains
3788 uncommitted changes:
3790 uncommitted changes:
3789
3791
3790 1. If neither -c/--check nor -C/--clean is specified, and if
3792 1. If neither -c/--check nor -C/--clean is specified, and if
3791 the requested changeset is an ancestor or descendant of
3793 the requested changeset is an ancestor or descendant of
3792 the working directory's parent, the uncommitted changes
3794 the working directory's parent, the uncommitted changes
3793 are merged into the requested changeset and the merged
3795 are merged into the requested changeset and the merged
3794 result is left uncommitted. If the requested changeset is
3796 result is left uncommitted. If the requested changeset is
3795 not an ancestor or descendant (that is, it is on another
3797 not an ancestor or descendant (that is, it is on another
3796 branch), the update is aborted and the uncommitted changes
3798 branch), the update is aborted and the uncommitted changes
3797 are preserved.
3799 are preserved.
3798
3800
3799 2. With the -c/--check option, the update is aborted and the
3801 2. With the -c/--check option, the update is aborted and the
3800 uncommitted changes are preserved.
3802 uncommitted changes are preserved.
3801
3803
3802 3. With the -C/--clean option, uncommitted changes are discarded and
3804 3. With the -C/--clean option, uncommitted changes are discarded and
3803 the working directory is updated to the requested changeset.
3805 the working directory is updated to the requested changeset.
3804
3806
3805 Use null as the changeset to remove the working directory (like
3807 Use null as the changeset to remove the working directory (like
3806 :hg:`clone -U`).
3808 :hg:`clone -U`).
3807
3809
3808 If you want to update just one file to an older changeset, use :hg:`revert`.
3810 If you want to update just one file to an older changeset, use :hg:`revert`.
3809
3811
3810 See :hg:`help dates` for a list of formats valid for -d/--date.
3812 See :hg:`help dates` for a list of formats valid for -d/--date.
3811
3813
3812 Returns 0 on success, 1 if there are unresolved files.
3814 Returns 0 on success, 1 if there are unresolved files.
3813 """
3815 """
3814 if rev and node:
3816 if rev and node:
3815 raise util.Abort(_("please specify just one revision"))
3817 raise util.Abort(_("please specify just one revision"))
3816
3818
3817 if not rev:
3819 if not rev:
3818 rev = node
3820 rev = node
3819
3821
3820 if check and clean:
3822 if check and clean:
3821 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
3823 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
3822
3824
3823 if check:
3825 if check:
3824 # we could use dirty() but we can ignore merge and branch trivia
3826 # we could use dirty() but we can ignore merge and branch trivia
3825 c = repo[None]
3827 c = repo[None]
3826 if c.modified() or c.added() or c.removed():
3828 if c.modified() or c.added() or c.removed():
3827 raise util.Abort(_("uncommitted local changes"))
3829 raise util.Abort(_("uncommitted local changes"))
3828
3830
3829 if date:
3831 if date:
3830 if rev:
3832 if rev:
3831 raise util.Abort(_("you can't specify a revision and a date"))
3833 raise util.Abort(_("you can't specify a revision and a date"))
3832 rev = cmdutil.finddate(ui, repo, date)
3834 rev = cmdutil.finddate(ui, repo, date)
3833
3835
3834 if clean or check:
3836 if clean or check:
3835 return hg.clean(repo, rev)
3837 return hg.clean(repo, rev)
3836 else:
3838 else:
3837 return hg.update(repo, rev)
3839 return hg.update(repo, rev)
3838
3840
3839 def verify(ui, repo):
3841 def verify(ui, repo):
3840 """verify the integrity of the repository
3842 """verify the integrity of the repository
3841
3843
3842 Verify the integrity of the current repository.
3844 Verify the integrity of the current repository.
3843
3845
3844 This will perform an extensive check of the repository's
3846 This will perform an extensive check of the repository's
3845 integrity, validating the hashes and checksums of each entry in
3847 integrity, validating the hashes and checksums of each entry in
3846 the changelog, manifest, and tracked files, as well as the
3848 the changelog, manifest, and tracked files, as well as the
3847 integrity of their crosslinks and indices.
3849 integrity of their crosslinks and indices.
3848
3850
3849 Returns 0 on success, 1 if errors are encountered.
3851 Returns 0 on success, 1 if errors are encountered.
3850 """
3852 """
3851 return hg.verify(repo)
3853 return hg.verify(repo)
3852
3854
3853 def version_(ui):
3855 def version_(ui):
3854 """output version and copyright information"""
3856 """output version and copyright information"""
3855 ui.write(_("Mercurial Distributed SCM (version %s)\n")
3857 ui.write(_("Mercurial Distributed SCM (version %s)\n")
3856 % util.version())
3858 % util.version())
3857 ui.status(_(
3859 ui.status(_(
3858 "\nCopyright (C) 2005-2010 Matt Mackall <mpm@selenic.com> and others\n"
3860 "\nCopyright (C) 2005-2010 Matt Mackall <mpm@selenic.com> and others\n"
3859 "This is free software; see the source for copying conditions. "
3861 "This is free software; see the source for copying conditions. "
3860 "There is NO\nwarranty; "
3862 "There is NO\nwarranty; "
3861 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
3863 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
3862 ))
3864 ))
3863
3865
3864 # Command options and aliases are listed here, alphabetically
3866 # Command options and aliases are listed here, alphabetically
3865
3867
3866 globalopts = [
3868 globalopts = [
3867 ('R', 'repository', '',
3869 ('R', 'repository', '',
3868 _('repository root directory or name of overlay bundle file'),
3870 _('repository root directory or name of overlay bundle file'),
3869 _('REPO')),
3871 _('REPO')),
3870 ('', 'cwd', '',
3872 ('', 'cwd', '',
3871 _('change working directory'), _('DIR')),
3873 _('change working directory'), _('DIR')),
3872 ('y', 'noninteractive', None,
3874 ('y', 'noninteractive', None,
3873 _('do not prompt, assume \'yes\' for any required answers')),
3875 _('do not prompt, assume \'yes\' for any required answers')),
3874 ('q', 'quiet', None, _('suppress output')),
3876 ('q', 'quiet', None, _('suppress output')),
3875 ('v', 'verbose', None, _('enable additional output')),
3877 ('v', 'verbose', None, _('enable additional output')),
3876 ('', 'config', [],
3878 ('', 'config', [],
3877 _('set/override config option (use \'section.name=value\')'),
3879 _('set/override config option (use \'section.name=value\')'),
3878 _('CONFIG')),
3880 _('CONFIG')),
3879 ('', 'debug', None, _('enable debugging output')),
3881 ('', 'debug', None, _('enable debugging output')),
3880 ('', 'debugger', None, _('start debugger')),
3882 ('', 'debugger', None, _('start debugger')),
3881 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
3883 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
3882 _('ENCODE')),
3884 _('ENCODE')),
3883 ('', 'encodingmode', encoding.encodingmode,
3885 ('', 'encodingmode', encoding.encodingmode,
3884 _('set the charset encoding mode'), _('MODE')),
3886 _('set the charset encoding mode'), _('MODE')),
3885 ('', 'traceback', None, _('always print a traceback on exception')),
3887 ('', 'traceback', None, _('always print a traceback on exception')),
3886 ('', 'time', None, _('time how long the command takes')),
3888 ('', 'time', None, _('time how long the command takes')),
3887 ('', 'profile', None, _('print command execution profile')),
3889 ('', 'profile', None, _('print command execution profile')),
3888 ('', 'version', None, _('output version information and exit')),
3890 ('', 'version', None, _('output version information and exit')),
3889 ('h', 'help', None, _('display help and exit')),
3891 ('h', 'help', None, _('display help and exit')),
3890 ]
3892 ]
3891
3893
3892 dryrunopts = [('n', 'dry-run', None,
3894 dryrunopts = [('n', 'dry-run', None,
3893 _('do not perform actions, just print output'))]
3895 _('do not perform actions, just print output'))]
3894
3896
3895 remoteopts = [
3897 remoteopts = [
3896 ('e', 'ssh', '',
3898 ('e', 'ssh', '',
3897 _('specify ssh command to use'), _('CMD')),
3899 _('specify ssh command to use'), _('CMD')),
3898 ('', 'remotecmd', '',
3900 ('', 'remotecmd', '',
3899 _('specify hg command to run on the remote side'), _('CMD')),
3901 _('specify hg command to run on the remote side'), _('CMD')),
3900 ]
3902 ]
3901
3903
3902 walkopts = [
3904 walkopts = [
3903 ('I', 'include', [],
3905 ('I', 'include', [],
3904 _('include names matching the given patterns'), _('PATTERN')),
3906 _('include names matching the given patterns'), _('PATTERN')),
3905 ('X', 'exclude', [],
3907 ('X', 'exclude', [],
3906 _('exclude names matching the given patterns'), _('PATTERN')),
3908 _('exclude names matching the given patterns'), _('PATTERN')),
3907 ]
3909 ]
3908
3910
3909 commitopts = [
3911 commitopts = [
3910 ('m', 'message', '',
3912 ('m', 'message', '',
3911 _('use text as commit message'), _('TEXT')),
3913 _('use text as commit message'), _('TEXT')),
3912 ('l', 'logfile', '',
3914 ('l', 'logfile', '',
3913 _('read commit message from file'), _('FILE')),
3915 _('read commit message from file'), _('FILE')),
3914 ]
3916 ]
3915
3917
3916 commitopts2 = [
3918 commitopts2 = [
3917 ('d', 'date', '',
3919 ('d', 'date', '',
3918 _('record datecode as commit date'), _('DATE')),
3920 _('record datecode as commit date'), _('DATE')),
3919 ('u', 'user', '',
3921 ('u', 'user', '',
3920 _('record the specified user as committer'), _('USER')),
3922 _('record the specified user as committer'), _('USER')),
3921 ]
3923 ]
3922
3924
3923 templateopts = [
3925 templateopts = [
3924 ('', 'style', '',
3926 ('', 'style', '',
3925 _('display using template map file'), _('STYLE')),
3927 _('display using template map file'), _('STYLE')),
3926 ('', 'template', '',
3928 ('', 'template', '',
3927 _('display with template'), _('TEMPLATE')),
3929 _('display with template'), _('TEMPLATE')),
3928 ]
3930 ]
3929
3931
3930 logopts = [
3932 logopts = [
3931 ('p', 'patch', None, _('show patch')),
3933 ('p', 'patch', None, _('show patch')),
3932 ('g', 'git', None, _('use git extended diff format')),
3934 ('g', 'git', None, _('use git extended diff format')),
3933 ('l', 'limit', '',
3935 ('l', 'limit', '',
3934 _('limit number of changes displayed'), _('NUM')),
3936 _('limit number of changes displayed'), _('NUM')),
3935 ('M', 'no-merges', None, _('do not show merges')),
3937 ('M', 'no-merges', None, _('do not show merges')),
3936 ('', 'stat', None, _('output diffstat-style summary of changes')),
3938 ('', 'stat', None, _('output diffstat-style summary of changes')),
3937 ] + templateopts
3939 ] + templateopts
3938
3940
3939 diffopts = [
3941 diffopts = [
3940 ('a', 'text', None, _('treat all files as text')),
3942 ('a', 'text', None, _('treat all files as text')),
3941 ('g', 'git', None, _('use git extended diff format')),
3943 ('g', 'git', None, _('use git extended diff format')),
3942 ('', 'nodates', None, _('omit dates from diff headers'))
3944 ('', 'nodates', None, _('omit dates from diff headers'))
3943 ]
3945 ]
3944
3946
3945 diffopts2 = [
3947 diffopts2 = [
3946 ('p', 'show-function', None, _('show which function each change is in')),
3948 ('p', 'show-function', None, _('show which function each change is in')),
3947 ('', 'reverse', None, _('produce a diff that undoes the changes')),
3949 ('', 'reverse', None, _('produce a diff that undoes the changes')),
3948 ('w', 'ignore-all-space', None,
3950 ('w', 'ignore-all-space', None,
3949 _('ignore white space when comparing lines')),
3951 _('ignore white space when comparing lines')),
3950 ('b', 'ignore-space-change', None,
3952 ('b', 'ignore-space-change', None,
3951 _('ignore changes in the amount of white space')),
3953 _('ignore changes in the amount of white space')),
3952 ('B', 'ignore-blank-lines', None,
3954 ('B', 'ignore-blank-lines', None,
3953 _('ignore changes whose lines are all blank')),
3955 _('ignore changes whose lines are all blank')),
3954 ('U', 'unified', '',
3956 ('U', 'unified', '',
3955 _('number of lines of context to show'), _('NUM')),
3957 _('number of lines of context to show'), _('NUM')),
3956 ('', 'stat', None, _('output diffstat-style summary of changes')),
3958 ('', 'stat', None, _('output diffstat-style summary of changes')),
3957 ]
3959 ]
3958
3960
3959 similarityopts = [
3961 similarityopts = [
3960 ('s', 'similarity', '',
3962 ('s', 'similarity', '',
3961 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
3963 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
3962 ]
3964 ]
3963
3965
3964 table = {
3966 table = {
3965 "^add": (add, walkopts + dryrunopts, _('[OPTION]... [FILE]...')),
3967 "^add": (add, walkopts + dryrunopts, _('[OPTION]... [FILE]...')),
3966 "addremove":
3968 "addremove":
3967 (addremove, similarityopts + walkopts + dryrunopts,
3969 (addremove, similarityopts + walkopts + dryrunopts,
3968 _('[OPTION]... [FILE]...')),
3970 _('[OPTION]... [FILE]...')),
3969 "^annotate|blame":
3971 "^annotate|blame":
3970 (annotate,
3972 (annotate,
3971 [('r', 'rev', '',
3973 [('r', 'rev', '',
3972 _('annotate the specified revision'), _('REV')),
3974 _('annotate the specified revision'), _('REV')),
3973 ('', 'follow', None,
3975 ('', 'follow', None,
3974 _('follow copies/renames and list the filename (DEPRECATED)')),
3976 _('follow copies/renames and list the filename (DEPRECATED)')),
3975 ('', 'no-follow', None, _("don't follow copies and renames")),
3977 ('', 'no-follow', None, _("don't follow copies and renames")),
3976 ('a', 'text', None, _('treat all files as text')),
3978 ('a', 'text', None, _('treat all files as text')),
3977 ('u', 'user', None, _('list the author (long with -v)')),
3979 ('u', 'user', None, _('list the author (long with -v)')),
3978 ('f', 'file', None, _('list the filename')),
3980 ('f', 'file', None, _('list the filename')),
3979 ('d', 'date', None, _('list the date (short with -q)')),
3981 ('d', 'date', None, _('list the date (short with -q)')),
3980 ('n', 'number', None, _('list the revision number (default)')),
3982 ('n', 'number', None, _('list the revision number (default)')),
3981 ('c', 'changeset', None, _('list the changeset')),
3983 ('c', 'changeset', None, _('list the changeset')),
3982 ('l', 'line-number', None,
3984 ('l', 'line-number', None,
3983 _('show line number at the first appearance'))
3985 _('show line number at the first appearance'))
3984 ] + walkopts,
3986 ] + walkopts,
3985 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...')),
3987 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...')),
3986 "archive":
3988 "archive":
3987 (archive,
3989 (archive,
3988 [('', 'no-decode', None, _('do not pass files through decoders')),
3990 [('', 'no-decode', None, _('do not pass files through decoders')),
3989 ('p', 'prefix', '',
3991 ('p', 'prefix', '',
3990 _('directory prefix for files in archive'), _('PREFIX')),
3992 _('directory prefix for files in archive'), _('PREFIX')),
3991 ('r', 'rev', '',
3993 ('r', 'rev', '',
3992 _('revision to distribute'), _('REV')),
3994 _('revision to distribute'), _('REV')),
3993 ('t', 'type', '',
3995 ('t', 'type', '',
3994 _('type of distribution to create'), _('TYPE')),
3996 _('type of distribution to create'), _('TYPE')),
3995 ] + walkopts,
3997 ] + walkopts,
3996 _('[OPTION]... DEST')),
3998 _('[OPTION]... DEST')),
3997 "backout":
3999 "backout":
3998 (backout,
4000 (backout,
3999 [('', 'merge', None,
4001 [('', 'merge', None,
4000 _('merge with old dirstate parent after backout')),
4002 _('merge with old dirstate parent after backout')),
4001 ('', 'parent', '',
4003 ('', 'parent', '',
4002 _('parent to choose when backing out merge'), _('REV')),
4004 _('parent to choose when backing out merge'), _('REV')),
4003 ('r', 'rev', '',
4005 ('r', 'rev', '',
4004 _('revision to backout'), _('REV')),
4006 _('revision to backout'), _('REV')),
4005 ] + walkopts + commitopts + commitopts2,
4007 ] + walkopts + commitopts + commitopts2,
4006 _('[OPTION]... [-r] REV')),
4008 _('[OPTION]... [-r] REV')),
4007 "bisect":
4009 "bisect":
4008 (bisect,
4010 (bisect,
4009 [('r', 'reset', False, _('reset bisect state')),
4011 [('r', 'reset', False, _('reset bisect state')),
4010 ('g', 'good', False, _('mark changeset good')),
4012 ('g', 'good', False, _('mark changeset good')),
4011 ('b', 'bad', False, _('mark changeset bad')),
4013 ('b', 'bad', False, _('mark changeset bad')),
4012 ('s', 'skip', False, _('skip testing changeset')),
4014 ('s', 'skip', False, _('skip testing changeset')),
4013 ('c', 'command', '',
4015 ('c', 'command', '',
4014 _('use command to check changeset state'), _('CMD')),
4016 _('use command to check changeset state'), _('CMD')),
4015 ('U', 'noupdate', False, _('do not update to target'))],
4017 ('U', 'noupdate', False, _('do not update to target'))],
4016 _("[-gbsr] [-U] [-c CMD] [REV]")),
4018 _("[-gbsr] [-U] [-c CMD] [REV]")),
4017 "branch":
4019 "branch":
4018 (branch,
4020 (branch,
4019 [('f', 'force', None,
4021 [('f', 'force', None,
4020 _('set branch name even if it shadows an existing branch')),
4022 _('set branch name even if it shadows an existing branch')),
4021 ('C', 'clean', None, _('reset branch name to parent branch name'))],
4023 ('C', 'clean', None, _('reset branch name to parent branch name'))],
4022 _('[-fC] [NAME]')),
4024 _('[-fC] [NAME]')),
4023 "branches":
4025 "branches":
4024 (branches,
4026 (branches,
4025 [('a', 'active', False,
4027 [('a', 'active', False,
4026 _('show only branches that have unmerged heads')),
4028 _('show only branches that have unmerged heads')),
4027 ('c', 'closed', False,
4029 ('c', 'closed', False,
4028 _('show normal and closed branches'))],
4030 _('show normal and closed branches'))],
4029 _('[-ac]')),
4031 _('[-ac]')),
4030 "bundle":
4032 "bundle":
4031 (bundle,
4033 (bundle,
4032 [('f', 'force', None,
4034 [('f', 'force', None,
4033 _('run even when the destination is unrelated')),
4035 _('run even when the destination is unrelated')),
4034 ('r', 'rev', [],
4036 ('r', 'rev', [],
4035 _('a changeset intended to be added to the destination'),
4037 _('a changeset intended to be added to the destination'),
4036 _('REV')),
4038 _('REV')),
4037 ('b', 'branch', [],
4039 ('b', 'branch', [],
4038 _('a specific branch you would like to bundle'),
4040 _('a specific branch you would like to bundle'),
4039 _('BRANCH')),
4041 _('BRANCH')),
4040 ('', 'base', [],
4042 ('', 'base', [],
4041 _('a base changeset assumed to be available at the destination'),
4043 _('a base changeset assumed to be available at the destination'),
4042 _('REV')),
4044 _('REV')),
4043 ('a', 'all', None, _('bundle all changesets in the repository')),
4045 ('a', 'all', None, _('bundle all changesets in the repository')),
4044 ('t', 'type', 'bzip2',
4046 ('t', 'type', 'bzip2',
4045 _('bundle compression type to use'), _('TYPE')),
4047 _('bundle compression type to use'), _('TYPE')),
4046 ] + remoteopts,
4048 ] + remoteopts,
4047 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]')),
4049 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]')),
4048 "cat":
4050 "cat":
4049 (cat,
4051 (cat,
4050 [('o', 'output', '',
4052 [('o', 'output', '',
4051 _('print output to file with formatted name'), _('FORMAT')),
4053 _('print output to file with formatted name'), _('FORMAT')),
4052 ('r', 'rev', '',
4054 ('r', 'rev', '',
4053 _('print the given revision'), _('REV')),
4055 _('print the given revision'), _('REV')),
4054 ('', 'decode', None, _('apply any matching decode filter')),
4056 ('', 'decode', None, _('apply any matching decode filter')),
4055 ] + walkopts,
4057 ] + walkopts,
4056 _('[OPTION]... FILE...')),
4058 _('[OPTION]... FILE...')),
4057 "^clone":
4059 "^clone":
4058 (clone,
4060 (clone,
4059 [('U', 'noupdate', None,
4061 [('U', 'noupdate', None,
4060 _('the clone will include an empty working copy (only a repository)')),
4062 _('the clone will include an empty working copy (only a repository)')),
4061 ('u', 'updaterev', '',
4063 ('u', 'updaterev', '',
4062 _('revision, tag or branch to check out'), _('REV')),
4064 _('revision, tag or branch to check out'), _('REV')),
4063 ('r', 'rev', [],
4065 ('r', 'rev', [],
4064 _('include the specified changeset'), _('REV')),
4066 _('include the specified changeset'), _('REV')),
4065 ('b', 'branch', [],
4067 ('b', 'branch', [],
4066 _('clone only the specified branch'), _('BRANCH')),
4068 _('clone only the specified branch'), _('BRANCH')),
4067 ('', 'pull', None, _('use pull protocol to copy metadata')),
4069 ('', 'pull', None, _('use pull protocol to copy metadata')),
4068 ('', 'uncompressed', None,
4070 ('', 'uncompressed', None,
4069 _('use uncompressed transfer (fast over LAN)')),
4071 _('use uncompressed transfer (fast over LAN)')),
4070 ] + remoteopts,
4072 ] + remoteopts,
4071 _('[OPTION]... SOURCE [DEST]')),
4073 _('[OPTION]... SOURCE [DEST]')),
4072 "^commit|ci":
4074 "^commit|ci":
4073 (commit,
4075 (commit,
4074 [('A', 'addremove', None,
4076 [('A', 'addremove', None,
4075 _('mark new/missing files as added/removed before committing')),
4077 _('mark new/missing files as added/removed before committing')),
4076 ('', 'close-branch', None,
4078 ('', 'close-branch', None,
4077 _('mark a branch as closed, hiding it from the branch list')),
4079 _('mark a branch as closed, hiding it from the branch list')),
4078 ] + walkopts + commitopts + commitopts2,
4080 ] + walkopts + commitopts + commitopts2,
4079 _('[OPTION]... [FILE]...')),
4081 _('[OPTION]... [FILE]...')),
4080 "copy|cp":
4082 "copy|cp":
4081 (copy,
4083 (copy,
4082 [('A', 'after', None, _('record a copy that has already occurred')),
4084 [('A', 'after', None, _('record a copy that has already occurred')),
4083 ('f', 'force', None,
4085 ('f', 'force', None,
4084 _('forcibly copy over an existing managed file')),
4086 _('forcibly copy over an existing managed file')),
4085 ] + walkopts + dryrunopts,
4087 ] + walkopts + dryrunopts,
4086 _('[OPTION]... [SOURCE]... DEST')),
4088 _('[OPTION]... [SOURCE]... DEST')),
4087 "debugancestor": (debugancestor, [], _('[INDEX] REV1 REV2')),
4089 "debugancestor": (debugancestor, [], _('[INDEX] REV1 REV2')),
4088 "debugbuilddag":
4090 "debugbuilddag":
4089 (debugbuilddag,
4091 (debugbuilddag,
4090 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
4092 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
4091 ('a', 'appended-file', None, _('add single file all revs append to')),
4093 ('a', 'appended-file', None, _('add single file all revs append to')),
4092 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
4094 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
4093 ('n', 'new-file', None, _('add new file at each rev')),
4095 ('n', 'new-file', None, _('add new file at each rev')),
4094 ],
4096 ],
4095 _('[OPTION]... TEXT')),
4097 _('[OPTION]... TEXT')),
4096 "debugcheckstate": (debugcheckstate, [], ''),
4098 "debugcheckstate": (debugcheckstate, [], ''),
4097 "debugcommands": (debugcommands, [], _('[COMMAND]')),
4099 "debugcommands": (debugcommands, [], _('[COMMAND]')),
4098 "debugcomplete":
4100 "debugcomplete":
4099 (debugcomplete,
4101 (debugcomplete,
4100 [('o', 'options', None, _('show the command options'))],
4102 [('o', 'options', None, _('show the command options'))],
4101 _('[-o] CMD')),
4103 _('[-o] CMD')),
4102 "debugdag":
4104 "debugdag":
4103 (debugdag,
4105 (debugdag,
4104 [('t', 'tags', None, _('use tags as labels')),
4106 [('t', 'tags', None, _('use tags as labels')),
4105 ('b', 'branches', None, _('annotate with branch names')),
4107 ('b', 'branches', None, _('annotate with branch names')),
4106 ('', 'dots', None, _('use dots for runs')),
4108 ('', 'dots', None, _('use dots for runs')),
4107 ('s', 'spaces', None, _('separate elements by spaces')),
4109 ('s', 'spaces', None, _('separate elements by spaces')),
4108 ],
4110 ],
4109 _('[OPTION]... [FILE [REV]...]')),
4111 _('[OPTION]... [FILE [REV]...]')),
4110 "debugdate":
4112 "debugdate":
4111 (debugdate,
4113 (debugdate,
4112 [('e', 'extended', None, _('try extended date formats'))],
4114 [('e', 'extended', None, _('try extended date formats'))],
4113 _('[-e] DATE [RANGE]')),
4115 _('[-e] DATE [RANGE]')),
4114 "debugdata": (debugdata, [], _('FILE REV')),
4116 "debugdata": (debugdata, [], _('FILE REV')),
4115 "debugfsinfo": (debugfsinfo, [], _('[PATH]')),
4117 "debugfsinfo": (debugfsinfo, [], _('[PATH]')),
4116 "debugindex": (debugindex, [], _('FILE')),
4118 "debugindex": (debugindex, [], _('FILE')),
4117 "debugindexdot": (debugindexdot, [], _('FILE')),
4119 "debugindexdot": (debugindexdot, [], _('FILE')),
4118 "debuginstall": (debuginstall, [], ''),
4120 "debuginstall": (debuginstall, [], ''),
4119 "debugpushkey": (debugpushkey, [], _('REPO NAMESPACE [KEY OLD NEW]')),
4121 "debugpushkey": (debugpushkey, [], _('REPO NAMESPACE [KEY OLD NEW]')),
4120 "debugrebuildstate":
4122 "debugrebuildstate":
4121 (debugrebuildstate,
4123 (debugrebuildstate,
4122 [('r', 'rev', '',
4124 [('r', 'rev', '',
4123 _('revision to rebuild to'), _('REV'))],
4125 _('revision to rebuild to'), _('REV'))],
4124 _('[-r REV] [REV]')),
4126 _('[-r REV] [REV]')),
4125 "debugrename":
4127 "debugrename":
4126 (debugrename,
4128 (debugrename,
4127 [('r', 'rev', '',
4129 [('r', 'rev', '',
4128 _('revision to debug'), _('REV'))],
4130 _('revision to debug'), _('REV'))],
4129 _('[-r REV] FILE')),
4131 _('[-r REV] FILE')),
4130 "debugrevspec":
4132 "debugrevspec":
4131 (debugrevspec, [], ('REVSPEC')),
4133 (debugrevspec, [], ('REVSPEC')),
4132 "debugsetparents":
4134 "debugsetparents":
4133 (debugsetparents, [], _('REV1 [REV2]')),
4135 (debugsetparents, [], _('REV1 [REV2]')),
4134 "debugstate":
4136 "debugstate":
4135 (debugstate,
4137 (debugstate,
4136 [('', 'nodates', None, _('do not display the saved mtime'))],
4138 [('', 'nodates', None, _('do not display the saved mtime'))],
4137 _('[OPTION]...')),
4139 _('[OPTION]...')),
4138 "debugsub":
4140 "debugsub":
4139 (debugsub,
4141 (debugsub,
4140 [('r', 'rev', '',
4142 [('r', 'rev', '',
4141 _('revision to check'), _('REV'))],
4143 _('revision to check'), _('REV'))],
4142 _('[-r REV] [REV]')),
4144 _('[-r REV] [REV]')),
4143 "debugwalk": (debugwalk, walkopts, _('[OPTION]... [FILE]...')),
4145 "debugwalk": (debugwalk, walkopts, _('[OPTION]... [FILE]...')),
4144 "^diff":
4146 "^diff":
4145 (diff,
4147 (diff,
4146 [('r', 'rev', [],
4148 [('r', 'rev', [],
4147 _('revision'), _('REV')),
4149 _('revision'), _('REV')),
4148 ('c', 'change', '',
4150 ('c', 'change', '',
4149 _('change made by revision'), _('REV'))
4151 _('change made by revision'), _('REV'))
4150 ] + diffopts + diffopts2 + walkopts,
4152 ] + diffopts + diffopts2 + walkopts,
4151 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...')),
4153 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...')),
4152 "^export":
4154 "^export":
4153 (export,
4155 (export,
4154 [('o', 'output', '',
4156 [('o', 'output', '',
4155 _('print output to file with formatted name'), _('FORMAT')),
4157 _('print output to file with formatted name'), _('FORMAT')),
4156 ('', 'switch-parent', None, _('diff against the second parent')),
4158 ('', 'switch-parent', None, _('diff against the second parent')),
4157 ('r', 'rev', [],
4159 ('r', 'rev', [],
4158 _('revisions to export'), _('REV')),
4160 _('revisions to export'), _('REV')),
4159 ] + diffopts,
4161 ] + diffopts,
4160 _('[OPTION]... [-o OUTFILESPEC] REV...')),
4162 _('[OPTION]... [-o OUTFILESPEC] REV...')),
4161 "^forget":
4163 "^forget":
4162 (forget,
4164 (forget,
4163 [] + walkopts,
4165 [] + walkopts,
4164 _('[OPTION]... FILE...')),
4166 _('[OPTION]... FILE...')),
4165 "grep":
4167 "grep":
4166 (grep,
4168 (grep,
4167 [('0', 'print0', None, _('end fields with NUL')),
4169 [('0', 'print0', None, _('end fields with NUL')),
4168 ('', 'all', None, _('print all revisions that match')),
4170 ('', 'all', None, _('print all revisions that match')),
4169 ('f', 'follow', None,
4171 ('f', 'follow', None,
4170 _('follow changeset history,'
4172 _('follow changeset history,'
4171 ' or file history across copies and renames')),
4173 ' or file history across copies and renames')),
4172 ('i', 'ignore-case', None, _('ignore case when matching')),
4174 ('i', 'ignore-case', None, _('ignore case when matching')),
4173 ('l', 'files-with-matches', None,
4175 ('l', 'files-with-matches', None,
4174 _('print only filenames and revisions that match')),
4176 _('print only filenames and revisions that match')),
4175 ('n', 'line-number', None, _('print matching line numbers')),
4177 ('n', 'line-number', None, _('print matching line numbers')),
4176 ('r', 'rev', [],
4178 ('r', 'rev', [],
4177 _('only search files changed within revision range'), _('REV')),
4179 _('only search files changed within revision range'), _('REV')),
4178 ('u', 'user', None, _('list the author (long with -v)')),
4180 ('u', 'user', None, _('list the author (long with -v)')),
4179 ('d', 'date', None, _('list the date (short with -q)')),
4181 ('d', 'date', None, _('list the date (short with -q)')),
4180 ] + walkopts,
4182 ] + walkopts,
4181 _('[OPTION]... PATTERN [FILE]...')),
4183 _('[OPTION]... PATTERN [FILE]...')),
4182 "heads":
4184 "heads":
4183 (heads,
4185 (heads,
4184 [('r', 'rev', '',
4186 [('r', 'rev', '',
4185 _('show only heads which are descendants of REV'), _('REV')),
4187 _('show only heads which are descendants of REV'), _('REV')),
4186 ('t', 'topo', False, _('show topological heads only')),
4188 ('t', 'topo', False, _('show topological heads only')),
4187 ('a', 'active', False,
4189 ('a', 'active', False,
4188 _('show active branchheads only [DEPRECATED]')),
4190 _('show active branchheads only [DEPRECATED]')),
4189 ('c', 'closed', False,
4191 ('c', 'closed', False,
4190 _('show normal and closed branch heads')),
4192 _('show normal and closed branch heads')),
4191 ] + templateopts,
4193 ] + templateopts,
4192 _('[-ac] [-r REV] [REV]...')),
4194 _('[-ac] [-r REV] [REV]...')),
4193 "help": (help_, [], _('[TOPIC]')),
4195 "help": (help_, [], _('[TOPIC]')),
4194 "identify|id":
4196 "identify|id":
4195 (identify,
4197 (identify,
4196 [('r', 'rev', '',
4198 [('r', 'rev', '',
4197 _('identify the specified revision'), _('REV')),
4199 _('identify the specified revision'), _('REV')),
4198 ('n', 'num', None, _('show local revision number')),
4200 ('n', 'num', None, _('show local revision number')),
4199 ('i', 'id', None, _('show global revision id')),
4201 ('i', 'id', None, _('show global revision id')),
4200 ('b', 'branch', None, _('show branch')),
4202 ('b', 'branch', None, _('show branch')),
4201 ('t', 'tags', None, _('show tags'))],
4203 ('t', 'tags', None, _('show tags'))],
4202 _('[-nibt] [-r REV] [SOURCE]')),
4204 _('[-nibt] [-r REV] [SOURCE]')),
4203 "import|patch":
4205 "import|patch":
4204 (import_,
4206 (import_,
4205 [('p', 'strip', 1,
4207 [('p', 'strip', 1,
4206 _('directory strip option for patch. This has the same '
4208 _('directory strip option for patch. This has the same '
4207 'meaning as the corresponding patch option'),
4209 'meaning as the corresponding patch option'),
4208 _('NUM')),
4210 _('NUM')),
4209 ('b', 'base', '',
4211 ('b', 'base', '',
4210 _('base path'), _('PATH')),
4212 _('base path'), _('PATH')),
4211 ('f', 'force', None,
4213 ('f', 'force', None,
4212 _('skip check for outstanding uncommitted changes')),
4214 _('skip check for outstanding uncommitted changes')),
4213 ('', 'no-commit', None,
4215 ('', 'no-commit', None,
4214 _("don't commit, just update the working directory")),
4216 _("don't commit, just update the working directory")),
4215 ('', 'exact', None,
4217 ('', 'exact', None,
4216 _('apply patch to the nodes from which it was generated')),
4218 _('apply patch to the nodes from which it was generated')),
4217 ('', 'import-branch', None,
4219 ('', 'import-branch', None,
4218 _('use any branch information in patch (implied by --exact)'))] +
4220 _('use any branch information in patch (implied by --exact)'))] +
4219 commitopts + commitopts2 + similarityopts,
4221 commitopts + commitopts2 + similarityopts,
4220 _('[OPTION]... PATCH...')),
4222 _('[OPTION]... PATCH...')),
4221 "incoming|in":
4223 "incoming|in":
4222 (incoming,
4224 (incoming,
4223 [('f', 'force', None,
4225 [('f', 'force', None,
4224 _('run even if remote repository is unrelated')),
4226 _('run even if remote repository is unrelated')),
4225 ('n', 'newest-first', None, _('show newest record first')),
4227 ('n', 'newest-first', None, _('show newest record first')),
4226 ('', 'bundle', '',
4228 ('', 'bundle', '',
4227 _('file to store the bundles into'), _('FILE')),
4229 _('file to store the bundles into'), _('FILE')),
4228 ('r', 'rev', [],
4230 ('r', 'rev', [],
4229 _('a remote changeset intended to be added'), _('REV')),
4231 _('a remote changeset intended to be added'), _('REV')),
4230 ('b', 'branch', [],
4232 ('b', 'branch', [],
4231 _('a specific branch you would like to pull'), _('BRANCH')),
4233 _('a specific branch you would like to pull'), _('BRANCH')),
4232 ] + logopts + remoteopts,
4234 ] + logopts + remoteopts,
4233 _('[-p] [-n] [-M] [-f] [-r REV]...'
4235 _('[-p] [-n] [-M] [-f] [-r REV]...'
4234 ' [--bundle FILENAME] [SOURCE]')),
4236 ' [--bundle FILENAME] [SOURCE]')),
4235 "^init":
4237 "^init":
4236 (init,
4238 (init,
4237 remoteopts,
4239 remoteopts,
4238 _('[-e CMD] [--remotecmd CMD] [DEST]')),
4240 _('[-e CMD] [--remotecmd CMD] [DEST]')),
4239 "locate":
4241 "locate":
4240 (locate,
4242 (locate,
4241 [('r', 'rev', '',
4243 [('r', 'rev', '',
4242 _('search the repository as it is in REV'), _('REV')),
4244 _('search the repository as it is in REV'), _('REV')),
4243 ('0', 'print0', None,
4245 ('0', 'print0', None,
4244 _('end filenames with NUL, for use with xargs')),
4246 _('end filenames with NUL, for use with xargs')),
4245 ('f', 'fullpath', None,
4247 ('f', 'fullpath', None,
4246 _('print complete paths from the filesystem root')),
4248 _('print complete paths from the filesystem root')),
4247 ] + walkopts,
4249 ] + walkopts,
4248 _('[OPTION]... [PATTERN]...')),
4250 _('[OPTION]... [PATTERN]...')),
4249 "^log|history":
4251 "^log|history":
4250 (log,
4252 (log,
4251 [('f', 'follow', None,
4253 [('f', 'follow', None,
4252 _('follow changeset history,'
4254 _('follow changeset history,'
4253 ' or file history across copies and renames')),
4255 ' or file history across copies and renames')),
4254 ('', 'follow-first', None,
4256 ('', 'follow-first', None,
4255 _('only follow the first parent of merge changesets')),
4257 _('only follow the first parent of merge changesets')),
4256 ('d', 'date', '',
4258 ('d', 'date', '',
4257 _('show revisions matching date spec'), _('DATE')),
4259 _('show revisions matching date spec'), _('DATE')),
4258 ('C', 'copies', None, _('show copied files')),
4260 ('C', 'copies', None, _('show copied files')),
4259 ('k', 'keyword', [],
4261 ('k', 'keyword', [],
4260 _('do case-insensitive search for a given text'), _('TEXT')),
4262 _('do case-insensitive search for a given text'), _('TEXT')),
4261 ('r', 'rev', [],
4263 ('r', 'rev', [],
4262 _('show the specified revision or range'), _('REV')),
4264 _('show the specified revision or range'), _('REV')),
4263 ('', 'removed', None, _('include revisions where files were removed')),
4265 ('', 'removed', None, _('include revisions where files were removed')),
4264 ('m', 'only-merges', None, _('show only merges')),
4266 ('m', 'only-merges', None, _('show only merges')),
4265 ('u', 'user', [],
4267 ('u', 'user', [],
4266 _('revisions committed by user'), _('USER')),
4268 _('revisions committed by user'), _('USER')),
4267 ('', 'only-branch', [],
4269 ('', 'only-branch', [],
4268 _('show only changesets within the given named branch (DEPRECATED)'),
4270 _('show only changesets within the given named branch (DEPRECATED)'),
4269 _('BRANCH')),
4271 _('BRANCH')),
4270 ('b', 'branch', [],
4272 ('b', 'branch', [],
4271 _('show changesets within the given named branch'), _('BRANCH')),
4273 _('show changesets within the given named branch'), _('BRANCH')),
4272 ('P', 'prune', [],
4274 ('P', 'prune', [],
4273 _('do not display revision or any of its ancestors'), _('REV')),
4275 _('do not display revision or any of its ancestors'), _('REV')),
4274 ] + logopts + walkopts,
4276 ] + logopts + walkopts,
4275 _('[OPTION]... [FILE]')),
4277 _('[OPTION]... [FILE]')),
4276 "manifest":
4278 "manifest":
4277 (manifest,
4279 (manifest,
4278 [('r', 'rev', '',
4280 [('r', 'rev', '',
4279 _('revision to display'), _('REV'))],
4281 _('revision to display'), _('REV'))],
4280 _('[-r REV]')),
4282 _('[-r REV]')),
4281 "^merge":
4283 "^merge":
4282 (merge,
4284 (merge,
4283 [('f', 'force', None, _('force a merge with outstanding changes')),
4285 [('f', 'force', None, _('force a merge with outstanding changes')),
4284 ('r', 'rev', '',
4286 ('r', 'rev', '',
4285 _('revision to merge'), _('REV')),
4287 _('revision to merge'), _('REV')),
4286 ('P', 'preview', None,
4288 ('P', 'preview', None,
4287 _('review revisions to merge (no merge is performed)'))],
4289 _('review revisions to merge (no merge is performed)'))],
4288 _('[-P] [-f] [[-r] REV]')),
4290 _('[-P] [-f] [[-r] REV]')),
4289 "outgoing|out":
4291 "outgoing|out":
4290 (outgoing,
4292 (outgoing,
4291 [('f', 'force', None,
4293 [('f', 'force', None,
4292 _('run even when the destination is unrelated')),
4294 _('run even when the destination is unrelated')),
4293 ('r', 'rev', [],
4295 ('r', 'rev', [],
4294 _('a changeset intended to be included in the destination'),
4296 _('a changeset intended to be included in the destination'),
4295 _('REV')),
4297 _('REV')),
4296 ('n', 'newest-first', None, _('show newest record first')),
4298 ('n', 'newest-first', None, _('show newest record first')),
4297 ('b', 'branch', [],
4299 ('b', 'branch', [],
4298 _('a specific branch you would like to push'), _('BRANCH')),
4300 _('a specific branch you would like to push'), _('BRANCH')),
4299 ] + logopts + remoteopts,
4301 ] + logopts + remoteopts,
4300 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]')),
4302 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]')),
4301 "parents":
4303 "parents":
4302 (parents,
4304 (parents,
4303 [('r', 'rev', '',
4305 [('r', 'rev', '',
4304 _('show parents of the specified revision'), _('REV')),
4306 _('show parents of the specified revision'), _('REV')),
4305 ] + templateopts,
4307 ] + templateopts,
4306 _('[-r REV] [FILE]')),
4308 _('[-r REV] [FILE]')),
4307 "paths": (paths, [], _('[NAME]')),
4309 "paths": (paths, [], _('[NAME]')),
4308 "^pull":
4310 "^pull":
4309 (pull,
4311 (pull,
4310 [('u', 'update', None,
4312 [('u', 'update', None,
4311 _('update to new branch head if changesets were pulled')),
4313 _('update to new branch head if changesets were pulled')),
4312 ('f', 'force', None,
4314 ('f', 'force', None,
4313 _('run even when remote repository is unrelated')),
4315 _('run even when remote repository is unrelated')),
4314 ('r', 'rev', [],
4316 ('r', 'rev', [],
4315 _('a remote changeset intended to be added'), _('REV')),
4317 _('a remote changeset intended to be added'), _('REV')),
4316 ('b', 'branch', [],
4318 ('b', 'branch', [],
4317 _('a specific branch you would like to pull'), _('BRANCH')),
4319 _('a specific branch you would like to pull'), _('BRANCH')),
4318 ] + remoteopts,
4320 ] + remoteopts,
4319 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]')),
4321 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]')),
4320 "^push":
4322 "^push":
4321 (push,
4323 (push,
4322 [('f', 'force', None, _('force push')),
4324 [('f', 'force', None, _('force push')),
4323 ('r', 'rev', [],
4325 ('r', 'rev', [],
4324 _('a changeset intended to be included in the destination'),
4326 _('a changeset intended to be included in the destination'),
4325 _('REV')),
4327 _('REV')),
4326 ('b', 'branch', [],
4328 ('b', 'branch', [],
4327 _('a specific branch you would like to push'), _('BRANCH')),
4329 _('a specific branch you would like to push'), _('BRANCH')),
4328 ('', 'new-branch', False, _('allow pushing a new branch')),
4330 ('', 'new-branch', False, _('allow pushing a new branch')),
4329 ] + remoteopts,
4331 ] + remoteopts,
4330 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]')),
4332 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]')),
4331 "recover": (recover, []),
4333 "recover": (recover, []),
4332 "^remove|rm":
4334 "^remove|rm":
4333 (remove,
4335 (remove,
4334 [('A', 'after', None, _('record delete for missing files')),
4336 [('A', 'after', None, _('record delete for missing files')),
4335 ('f', 'force', None,
4337 ('f', 'force', None,
4336 _('remove (and delete) file even if added or modified')),
4338 _('remove (and delete) file even if added or modified')),
4337 ] + walkopts,
4339 ] + walkopts,
4338 _('[OPTION]... FILE...')),
4340 _('[OPTION]... FILE...')),
4339 "rename|mv":
4341 "rename|mv":
4340 (rename,
4342 (rename,
4341 [('A', 'after', None, _('record a rename that has already occurred')),
4343 [('A', 'after', None, _('record a rename that has already occurred')),
4342 ('f', 'force', None,
4344 ('f', 'force', None,
4343 _('forcibly copy over an existing managed file')),
4345 _('forcibly copy over an existing managed file')),
4344 ] + walkopts + dryrunopts,
4346 ] + walkopts + dryrunopts,
4345 _('[OPTION]... SOURCE... DEST')),
4347 _('[OPTION]... SOURCE... DEST')),
4346 "resolve":
4348 "resolve":
4347 (resolve,
4349 (resolve,
4348 [('a', 'all', None, _('select all unresolved files')),
4350 [('a', 'all', None, _('select all unresolved files')),
4349 ('l', 'list', None, _('list state of files needing merge')),
4351 ('l', 'list', None, _('list state of files needing merge')),
4350 ('m', 'mark', None, _('mark files as resolved')),
4352 ('m', 'mark', None, _('mark files as resolved')),
4351 ('u', 'unmark', None, _('unmark files as resolved')),
4353 ('u', 'unmark', None, _('unmark files as resolved')),
4352 ('n', 'no-status', None, _('hide status prefix'))]
4354 ('n', 'no-status', None, _('hide status prefix'))]
4353 + walkopts,
4355 + walkopts,
4354 _('[OPTION]... [FILE]...')),
4356 _('[OPTION]... [FILE]...')),
4355 "revert":
4357 "revert":
4356 (revert,
4358 (revert,
4357 [('a', 'all', None, _('revert all changes when no arguments given')),
4359 [('a', 'all', None, _('revert all changes when no arguments given')),
4358 ('d', 'date', '',
4360 ('d', 'date', '',
4359 _('tipmost revision matching date'), _('DATE')),
4361 _('tipmost revision matching date'), _('DATE')),
4360 ('r', 'rev', '',
4362 ('r', 'rev', '',
4361 _('revert to the specified revision'), _('REV')),
4363 _('revert to the specified revision'), _('REV')),
4362 ('', 'no-backup', None, _('do not save backup copies of files')),
4364 ('', 'no-backup', None, _('do not save backup copies of files')),
4363 ] + walkopts + dryrunopts,
4365 ] + walkopts + dryrunopts,
4364 _('[OPTION]... [-r REV] [NAME]...')),
4366 _('[OPTION]... [-r REV] [NAME]...')),
4365 "rollback": (rollback, dryrunopts),
4367 "rollback": (rollback, dryrunopts),
4366 "root": (root, []),
4368 "root": (root, []),
4367 "^serve":
4369 "^serve":
4368 (serve,
4370 (serve,
4369 [('A', 'accesslog', '',
4371 [('A', 'accesslog', '',
4370 _('name of access log file to write to'), _('FILE')),
4372 _('name of access log file to write to'), _('FILE')),
4371 ('d', 'daemon', None, _('run server in background')),
4373 ('d', 'daemon', None, _('run server in background')),
4372 ('', 'daemon-pipefds', '',
4374 ('', 'daemon-pipefds', '',
4373 _('used internally by daemon mode'), _('NUM')),
4375 _('used internally by daemon mode'), _('NUM')),
4374 ('E', 'errorlog', '',
4376 ('E', 'errorlog', '',
4375 _('name of error log file to write to'), _('FILE')),
4377 _('name of error log file to write to'), _('FILE')),
4376 # use string type, then we can check if something was passed
4378 # use string type, then we can check if something was passed
4377 ('p', 'port', '',
4379 ('p', 'port', '',
4378 _('port to listen on (default: 8000)'), _('PORT')),
4380 _('port to listen on (default: 8000)'), _('PORT')),
4379 ('a', 'address', '',
4381 ('a', 'address', '',
4380 _('address to listen on (default: all interfaces)'), _('ADDR')),
4382 _('address to listen on (default: all interfaces)'), _('ADDR')),
4381 ('', 'prefix', '',
4383 ('', 'prefix', '',
4382 _('prefix path to serve from (default: server root)'), _('PREFIX')),
4384 _('prefix path to serve from (default: server root)'), _('PREFIX')),
4383 ('n', 'name', '',
4385 ('n', 'name', '',
4384 _('name to show in web pages (default: working directory)'),
4386 _('name to show in web pages (default: working directory)'),
4385 _('NAME')),
4387 _('NAME')),
4386 ('', 'web-conf', '',
4388 ('', 'web-conf', '',
4387 _('name of the hgweb config file (serve more than one repository)'),
4389 _('name of the hgweb config file (serve more than one repository)'),
4388 _('FILE')),
4390 _('FILE')),
4389 ('', 'webdir-conf', '',
4391 ('', 'webdir-conf', '',
4390 _('name of the hgweb config file (DEPRECATED)'), _('FILE')),
4392 _('name of the hgweb config file (DEPRECATED)'), _('FILE')),
4391 ('', 'pid-file', '',
4393 ('', 'pid-file', '',
4392 _('name of file to write process ID to'), _('FILE')),
4394 _('name of file to write process ID to'), _('FILE')),
4393 ('', 'stdio', None, _('for remote clients')),
4395 ('', 'stdio', None, _('for remote clients')),
4394 ('t', 'templates', '',
4396 ('t', 'templates', '',
4395 _('web templates to use'), _('TEMPLATE')),
4397 _('web templates to use'), _('TEMPLATE')),
4396 ('', 'style', '',
4398 ('', 'style', '',
4397 _('template style to use'), _('STYLE')),
4399 _('template style to use'), _('STYLE')),
4398 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4400 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4399 ('', 'certificate', '',
4401 ('', 'certificate', '',
4400 _('SSL certificate file'), _('FILE'))],
4402 _('SSL certificate file'), _('FILE'))],
4401 _('[OPTION]...')),
4403 _('[OPTION]...')),
4402 "showconfig|debugconfig":
4404 "showconfig|debugconfig":
4403 (showconfig,
4405 (showconfig,
4404 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4406 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4405 _('[-u] [NAME]...')),
4407 _('[-u] [NAME]...')),
4406 "^summary|sum":
4408 "^summary|sum":
4407 (summary,
4409 (summary,
4408 [('', 'remote', None, _('check for push and pull'))], '[--remote]'),
4410 [('', 'remote', None, _('check for push and pull'))], '[--remote]'),
4409 "^status|st":
4411 "^status|st":
4410 (status,
4412 (status,
4411 [('A', 'all', None, _('show status of all files')),
4413 [('A', 'all', None, _('show status of all files')),
4412 ('m', 'modified', None, _('show only modified files')),
4414 ('m', 'modified', None, _('show only modified files')),
4413 ('a', 'added', None, _('show only added files')),
4415 ('a', 'added', None, _('show only added files')),
4414 ('r', 'removed', None, _('show only removed files')),
4416 ('r', 'removed', None, _('show only removed files')),
4415 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4417 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4416 ('c', 'clean', None, _('show only files without changes')),
4418 ('c', 'clean', None, _('show only files without changes')),
4417 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4419 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4418 ('i', 'ignored', None, _('show only ignored files')),
4420 ('i', 'ignored', None, _('show only ignored files')),
4419 ('n', 'no-status', None, _('hide status prefix')),
4421 ('n', 'no-status', None, _('hide status prefix')),
4420 ('C', 'copies', None, _('show source of copied files')),
4422 ('C', 'copies', None, _('show source of copied files')),
4421 ('0', 'print0', None,
4423 ('0', 'print0', None,
4422 _('end filenames with NUL, for use with xargs')),
4424 _('end filenames with NUL, for use with xargs')),
4423 ('', 'rev', [],
4425 ('', 'rev', [],
4424 _('show difference from revision'), _('REV')),
4426 _('show difference from revision'), _('REV')),
4425 ('', 'change', '',
4427 ('', 'change', '',
4426 _('list the changed files of a revision'), _('REV')),
4428 _('list the changed files of a revision'), _('REV')),
4427 ] + walkopts,
4429 ] + walkopts,
4428 _('[OPTION]... [FILE]...')),
4430 _('[OPTION]... [FILE]...')),
4429 "tag":
4431 "tag":
4430 (tag,
4432 (tag,
4431 [('f', 'force', None, _('replace existing tag')),
4433 [('f', 'force', None, _('replace existing tag')),
4432 ('l', 'local', None, _('make the tag local')),
4434 ('l', 'local', None, _('make the tag local')),
4433 ('r', 'rev', '',
4435 ('r', 'rev', '',
4434 _('revision to tag'), _('REV')),
4436 _('revision to tag'), _('REV')),
4435 ('', 'remove', None, _('remove a tag')),
4437 ('', 'remove', None, _('remove a tag')),
4436 # -l/--local is already there, commitopts cannot be used
4438 # -l/--local is already there, commitopts cannot be used
4437 ('e', 'edit', None, _('edit commit message')),
4439 ('e', 'edit', None, _('edit commit message')),
4438 ('m', 'message', '',
4440 ('m', 'message', '',
4439 _('use <text> as commit message'), _('TEXT')),
4441 _('use <text> as commit message'), _('TEXT')),
4440 ] + commitopts2,
4442 ] + commitopts2,
4441 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...')),
4443 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...')),
4442 "tags": (tags, [], ''),
4444 "tags": (tags, [], ''),
4443 "tip":
4445 "tip":
4444 (tip,
4446 (tip,
4445 [('p', 'patch', None, _('show patch')),
4447 [('p', 'patch', None, _('show patch')),
4446 ('g', 'git', None, _('use git extended diff format')),
4448 ('g', 'git', None, _('use git extended diff format')),
4447 ] + templateopts,
4449 ] + templateopts,
4448 _('[-p] [-g]')),
4450 _('[-p] [-g]')),
4449 "unbundle":
4451 "unbundle":
4450 (unbundle,
4452 (unbundle,
4451 [('u', 'update', None,
4453 [('u', 'update', None,
4452 _('update to new branch head if changesets were unbundled'))],
4454 _('update to new branch head if changesets were unbundled'))],
4453 _('[-u] FILE...')),
4455 _('[-u] FILE...')),
4454 "^update|up|checkout|co":
4456 "^update|up|checkout|co":
4455 (update,
4457 (update,
4456 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
4458 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
4457 ('c', 'check', None, _('check for uncommitted changes')),
4459 ('c', 'check', None, _('check for uncommitted changes')),
4458 ('d', 'date', '',
4460 ('d', 'date', '',
4459 _('tipmost revision matching date'), _('DATE')),
4461 _('tipmost revision matching date'), _('DATE')),
4460 ('r', 'rev', '',
4462 ('r', 'rev', '',
4461 _('revision'), _('REV'))],
4463 _('revision'), _('REV'))],
4462 _('[-c] [-C] [-d DATE] [[-r] REV]')),
4464 _('[-c] [-C] [-d DATE] [[-r] REV]')),
4463 "verify": (verify, []),
4465 "verify": (verify, []),
4464 "version": (version_, []),
4466 "version": (version_, []),
4465 }
4467 }
4466
4468
4467 norepo = ("clone init version help debugcommands debugcomplete debugdata"
4469 norepo = ("clone init version help debugcommands debugcomplete debugdata"
4468 " debugindex debugindexdot debugdate debuginstall debugfsinfo"
4470 " debugindex debugindexdot debugdate debuginstall debugfsinfo"
4469 " debugpushkey")
4471 " debugpushkey")
4470 optionalrepo = ("identify paths serve showconfig debugancestor debugdag")
4472 optionalrepo = ("identify paths serve showconfig debugancestor debugdag")
@@ -1,536 +1,541 b''
1 # dispatch.py - command dispatching for mercurial
1 # dispatch.py - command dispatching for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from i18n import _
8 from i18n import _
9 import os, sys, atexit, signal, pdb, socket, errno, shlex, time
9 import os, sys, atexit, signal, pdb, socket, errno, shlex, time
10 import util, commands, hg, fancyopts, extensions, hook, error
10 import util, commands, hg, fancyopts, extensions, hook, error
11 import cmdutil, encoding
11 import cmdutil, encoding
12 import ui as uimod
12 import ui as uimod
13
13
14 def run():
14 def run():
15 "run the command in sys.argv"
15 "run the command in sys.argv"
16 sys.exit(dispatch(sys.argv[1:]))
16 sys.exit(dispatch(sys.argv[1:]))
17
17
18 def dispatch(args):
18 def dispatch(args):
19 "run the command specified in args"
19 "run the command specified in args"
20 try:
20 try:
21 u = uimod.ui()
21 u = uimod.ui()
22 if '--traceback' in args:
22 if '--traceback' in args:
23 u.setconfig('ui', 'traceback', 'on')
23 u.setconfig('ui', 'traceback', 'on')
24 except util.Abort, inst:
24 except util.Abort, inst:
25 sys.stderr.write(_("abort: %s\n") % inst)
25 sys.stderr.write(_("abort: %s\n") % inst)
26 return -1
26 return -1
27 except error.ParseError, inst:
27 except error.ParseError, inst:
28 if len(inst.args) > 1:
28 if len(inst.args) > 1:
29 sys.stderr.write(_("hg: parse error at %s: %s\n") %
29 sys.stderr.write(_("hg: parse error at %s: %s\n") %
30 (inst.args[1], inst.args[0]))
30 (inst.args[1], inst.args[0]))
31 else:
31 else:
32 sys.stderr.write(_("hg: parse error: %s\n") % inst.args[0])
32 sys.stderr.write(_("hg: parse error: %s\n") % inst.args[0])
33 return -1
33 return -1
34 return _runcatch(u, args)
34 return _runcatch(u, args)
35
35
36 def _runcatch(ui, args):
36 def _runcatch(ui, args):
37 def catchterm(*args):
37 def catchterm(*args):
38 raise error.SignalInterrupt
38 raise error.SignalInterrupt
39
39
40 try:
40 try:
41 for name in 'SIGBREAK', 'SIGHUP', 'SIGTERM':
41 for name in 'SIGBREAK', 'SIGHUP', 'SIGTERM':
42 num = getattr(signal, name, None)
42 num = getattr(signal, name, None)
43 if num:
43 if num:
44 signal.signal(num, catchterm)
44 signal.signal(num, catchterm)
45 except ValueError:
45 except ValueError:
46 pass # happens if called in a thread
46 pass # happens if called in a thread
47
47
48 try:
48 try:
49 try:
49 try:
50 # enter the debugger before command execution
50 # enter the debugger before command execution
51 if '--debugger' in args:
51 if '--debugger' in args:
52 pdb.set_trace()
52 pdb.set_trace()
53 try:
53 try:
54 return _dispatch(ui, args)
54 return _dispatch(ui, args)
55 finally:
55 finally:
56 ui.flush()
56 ui.flush()
57 except:
57 except:
58 # enter the debugger when we hit an exception
58 # enter the debugger when we hit an exception
59 if '--debugger' in args:
59 if '--debugger' in args:
60 pdb.post_mortem(sys.exc_info()[2])
60 pdb.post_mortem(sys.exc_info()[2])
61 ui.traceback()
61 ui.traceback()
62 raise
62 raise
63
63
64 # Global exception handling, alphabetically
64 # Global exception handling, alphabetically
65 # Mercurial-specific first, followed by built-in and library exceptions
65 # Mercurial-specific first, followed by built-in and library exceptions
66 except error.AmbiguousCommand, inst:
66 except error.AmbiguousCommand, inst:
67 ui.warn(_("hg: command '%s' is ambiguous:\n %s\n") %
67 ui.warn(_("hg: command '%s' is ambiguous:\n %s\n") %
68 (inst.args[0], " ".join(inst.args[1])))
68 (inst.args[0], " ".join(inst.args[1])))
69 except error.ParseError, inst:
69 except error.ParseError, inst:
70 if len(inst.args) > 1:
70 if len(inst.args) > 1:
71 ui.warn(_("hg: parse error at %s: %s\n") %
71 ui.warn(_("hg: parse error at %s: %s\n") %
72 (inst.args[1], inst.args[0]))
72 (inst.args[1], inst.args[0]))
73 else:
73 else:
74 ui.warn(_("hg: parse error: %s\n") % inst.args[0])
74 ui.warn(_("hg: parse error: %s\n") % inst.args[0])
75 return -1
75 return -1
76 except error.LockHeld, inst:
76 except error.LockHeld, inst:
77 if inst.errno == errno.ETIMEDOUT:
77 if inst.errno == errno.ETIMEDOUT:
78 reason = _('timed out waiting for lock held by %s') % inst.locker
78 reason = _('timed out waiting for lock held by %s') % inst.locker
79 else:
79 else:
80 reason = _('lock held by %s') % inst.locker
80 reason = _('lock held by %s') % inst.locker
81 ui.warn(_("abort: %s: %s\n") % (inst.desc or inst.filename, reason))
81 ui.warn(_("abort: %s: %s\n") % (inst.desc or inst.filename, reason))
82 except error.LockUnavailable, inst:
82 except error.LockUnavailable, inst:
83 ui.warn(_("abort: could not lock %s: %s\n") %
83 ui.warn(_("abort: could not lock %s: %s\n") %
84 (inst.desc or inst.filename, inst.strerror))
84 (inst.desc or inst.filename, inst.strerror))
85 except error.CommandError, inst:
85 except error.CommandError, inst:
86 if inst.args[0]:
86 if inst.args[0]:
87 ui.warn(_("hg %s: %s\n") % (inst.args[0], inst.args[1]))
87 ui.warn(_("hg %s: %s\n") % (inst.args[0], inst.args[1]))
88 commands.help_(ui, inst.args[0])
88 commands.help_(ui, inst.args[0])
89 else:
89 else:
90 ui.warn(_("hg: %s\n") % inst.args[1])
90 ui.warn(_("hg: %s\n") % inst.args[1])
91 commands.help_(ui, 'shortlist')
91 commands.help_(ui, 'shortlist')
92 except error.RepoError, inst:
92 except error.RepoError, inst:
93 ui.warn(_("abort: %s!\n") % inst)
93 ui.warn(_("abort: %s!\n") % inst)
94 except error.ResponseError, inst:
94 except error.ResponseError, inst:
95 ui.warn(_("abort: %s") % inst.args[0])
95 ui.warn(_("abort: %s") % inst.args[0])
96 if not isinstance(inst.args[1], basestring):
96 if not isinstance(inst.args[1], basestring):
97 ui.warn(" %r\n" % (inst.args[1],))
97 ui.warn(" %r\n" % (inst.args[1],))
98 elif not inst.args[1]:
98 elif not inst.args[1]:
99 ui.warn(_(" empty string\n"))
99 ui.warn(_(" empty string\n"))
100 else:
100 else:
101 ui.warn("\n%r\n" % util.ellipsis(inst.args[1]))
101 ui.warn("\n%r\n" % util.ellipsis(inst.args[1]))
102 except error.RevlogError, inst:
102 except error.RevlogError, inst:
103 ui.warn(_("abort: %s!\n") % inst)
103 ui.warn(_("abort: %s!\n") % inst)
104 except error.SignalInterrupt:
104 except error.SignalInterrupt:
105 ui.warn(_("killed!\n"))
105 ui.warn(_("killed!\n"))
106 except error.UnknownCommand, inst:
106 except error.UnknownCommand, inst:
107 ui.warn(_("hg: unknown command '%s'\n") % inst.args[0])
107 ui.warn(_("hg: unknown command '%s'\n") % inst.args[0])
108 try:
108 try:
109 # check if the command is in a disabled extension
109 # check if the command is in a disabled extension
110 # (but don't check for extensions themselves)
110 # (but don't check for extensions themselves)
111 commands.help_(ui, inst.args[0], unknowncmd=True)
111 commands.help_(ui, inst.args[0], unknowncmd=True)
112 except error.UnknownCommand:
112 except error.UnknownCommand:
113 commands.help_(ui, 'shortlist')
113 commands.help_(ui, 'shortlist')
114 except util.Abort, inst:
114 except util.Abort, inst:
115 ui.warn(_("abort: %s\n") % inst)
115 ui.warn(_("abort: %s\n") % inst)
116 except ImportError, inst:
116 except ImportError, inst:
117 ui.warn(_("abort: %s!\n") % inst)
117 ui.warn(_("abort: %s!\n") % inst)
118 m = str(inst).split()[-1]
118 m = str(inst).split()[-1]
119 if m in "mpatch bdiff".split():
119 if m in "mpatch bdiff".split():
120 ui.warn(_("(did you forget to compile extensions?)\n"))
120 ui.warn(_("(did you forget to compile extensions?)\n"))
121 elif m in "zlib".split():
121 elif m in "zlib".split():
122 ui.warn(_("(is your Python install correct?)\n"))
122 ui.warn(_("(is your Python install correct?)\n"))
123 except IOError, inst:
123 except IOError, inst:
124 if hasattr(inst, "code"):
124 if hasattr(inst, "code"):
125 ui.warn(_("abort: %s\n") % inst)
125 ui.warn(_("abort: %s\n") % inst)
126 elif hasattr(inst, "reason"):
126 elif hasattr(inst, "reason"):
127 try: # usually it is in the form (errno, strerror)
127 try: # usually it is in the form (errno, strerror)
128 reason = inst.reason.args[1]
128 reason = inst.reason.args[1]
129 except: # it might be anything, for example a string
129 except: # it might be anything, for example a string
130 reason = inst.reason
130 reason = inst.reason
131 ui.warn(_("abort: error: %s\n") % reason)
131 ui.warn(_("abort: error: %s\n") % reason)
132 elif hasattr(inst, "args") and inst.args[0] == errno.EPIPE:
132 elif hasattr(inst, "args") and inst.args[0] == errno.EPIPE:
133 if ui.debugflag:
133 if ui.debugflag:
134 ui.warn(_("broken pipe\n"))
134 ui.warn(_("broken pipe\n"))
135 elif getattr(inst, "strerror", None):
135 elif getattr(inst, "strerror", None):
136 if getattr(inst, "filename", None):
136 if getattr(inst, "filename", None):
137 ui.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
137 ui.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
138 else:
138 else:
139 ui.warn(_("abort: %s\n") % inst.strerror)
139 ui.warn(_("abort: %s\n") % inst.strerror)
140 else:
140 else:
141 raise
141 raise
142 except OSError, inst:
142 except OSError, inst:
143 if getattr(inst, "filename", None):
143 if getattr(inst, "filename", None):
144 ui.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
144 ui.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
145 else:
145 else:
146 ui.warn(_("abort: %s\n") % inst.strerror)
146 ui.warn(_("abort: %s\n") % inst.strerror)
147 except KeyboardInterrupt:
147 except KeyboardInterrupt:
148 try:
148 try:
149 ui.warn(_("interrupted!\n"))
149 ui.warn(_("interrupted!\n"))
150 except IOError, inst:
150 except IOError, inst:
151 if inst.errno == errno.EPIPE:
151 if inst.errno == errno.EPIPE:
152 if ui.debugflag:
152 if ui.debugflag:
153 ui.warn(_("\nbroken pipe\n"))
153 ui.warn(_("\nbroken pipe\n"))
154 else:
154 else:
155 raise
155 raise
156 except MemoryError:
156 except MemoryError:
157 ui.warn(_("abort: out of memory\n"))
157 ui.warn(_("abort: out of memory\n"))
158 except SystemExit, inst:
158 except SystemExit, inst:
159 # Commands shouldn't sys.exit directly, but give a return code.
159 # Commands shouldn't sys.exit directly, but give a return code.
160 # Just in case catch this and and pass exit code to caller.
160 # Just in case catch this and and pass exit code to caller.
161 return inst.code
161 return inst.code
162 except socket.error, inst:
162 except socket.error, inst:
163 ui.warn(_("abort: %s\n") % inst.args[-1])
163 ui.warn(_("abort: %s\n") % inst.args[-1])
164 except:
164 except:
165 ui.warn(_("** unknown exception encountered, details follow\n"))
165 ui.warn(_("** unknown exception encountered, details follow\n"))
166 ui.warn(_("** report bug details to "
166 ui.warn(_("** report bug details to "
167 "http://mercurial.selenic.com/bts/\n"))
167 "http://mercurial.selenic.com/bts/\n"))
168 ui.warn(_("** or mercurial@selenic.com\n"))
168 ui.warn(_("** or mercurial@selenic.com\n"))
169 ui.warn(_("** Python %s\n") % sys.version.replace('\n', ''))
169 ui.warn(_("** Python %s\n") % sys.version.replace('\n', ''))
170 ui.warn(_("** Mercurial Distributed SCM (version %s)\n")
170 ui.warn(_("** Mercurial Distributed SCM (version %s)\n")
171 % util.version())
171 % util.version())
172 ui.warn(_("** Extensions loaded: %s\n")
172 ui.warn(_("** Extensions loaded: %s\n")
173 % ", ".join([x[0] for x in extensions.extensions()]))
173 % ", ".join([x[0] for x in extensions.extensions()]))
174 raise
174 raise
175
175
176 return -1
176 return -1
177
177
178 def aliasargs(fn):
178 def aliasargs(fn):
179 if hasattr(fn, 'args'):
179 if hasattr(fn, 'args'):
180 return fn.args
180 return fn.args
181 return []
181 return []
182
182
183 class cmdalias(object):
183 class cmdalias(object):
184 def __init__(self, name, definition, cmdtable):
184 def __init__(self, name, definition, cmdtable):
185 self.name = name
185 self.name = name
186 self.definition = definition
186 self.definition = definition
187 self.args = []
187 self.args = []
188 self.opts = []
188 self.opts = []
189 self.help = ''
189 self.help = ''
190 self.norepo = True
190 self.norepo = True
191 self.badalias = False
191 self.badalias = False
192
192
193 try:
193 try:
194 cmdutil.findcmd(self.name, cmdtable, True)
194 cmdutil.findcmd(self.name, cmdtable, True)
195 self.shadows = True
195 self.shadows = True
196 except error.UnknownCommand:
196 except error.UnknownCommand:
197 self.shadows = False
197 self.shadows = False
198
198
199 if not self.definition:
199 if not self.definition:
200 def fn(ui, *args):
200 def fn(ui, *args):
201 ui.warn(_("no definition for alias '%s'\n") % self.name)
201 ui.warn(_("no definition for alias '%s'\n") % self.name)
202 return 1
202 return 1
203 self.fn = fn
203 self.fn = fn
204 self.badalias = True
204 self.badalias = True
205
205
206 return
206 return
207
207
208 args = shlex.split(self.definition)
208 args = shlex.split(self.definition)
209 cmd = args.pop(0)
209 cmd = args.pop(0)
210 args = map(util.expandpath, args)
210 args = map(util.expandpath, args)
211
211
212 try:
212 try:
213 tableentry = cmdutil.findcmd(cmd, cmdtable, False)[1]
213 tableentry = cmdutil.findcmd(cmd, cmdtable, False)[1]
214 if len(tableentry) > 2:
214 if len(tableentry) > 2:
215 self.fn, self.opts, self.help = tableentry
215 self.fn, self.opts, self.help = tableentry
216 else:
216 else:
217 self.fn, self.opts = tableentry
217 self.fn, self.opts = tableentry
218
218
219 self.args = aliasargs(self.fn) + args
219 self.args = aliasargs(self.fn) + args
220 if cmd not in commands.norepo.split(' '):
220 if cmd not in commands.norepo.split(' '):
221 self.norepo = False
221 self.norepo = False
222 if self.help.startswith("hg " + cmd):
222 if self.help.startswith("hg " + cmd):
223 # drop prefix in old-style help lines so hg shows the alias
223 # drop prefix in old-style help lines so hg shows the alias
224 self.help = self.help[4 + len(cmd):]
224 self.help = self.help[4 + len(cmd):]
225 self.__doc__ = self.fn.__doc__
225 self.__doc__ = self.fn.__doc__
226
226
227 except error.UnknownCommand:
227 except error.UnknownCommand:
228 def fn(ui, *args):
228 def fn(ui, *args):
229 ui.warn(_("alias '%s' resolves to unknown command '%s'\n") \
229 ui.warn(_("alias '%s' resolves to unknown command '%s'\n") \
230 % (self.name, cmd))
230 % (self.name, cmd))
231 try:
231 try:
232 # check if the command is in a disabled extension
232 # check if the command is in a disabled extension
233 commands.help_(ui, cmd, unknowncmd=True)
233 commands.help_(ui, cmd, unknowncmd=True)
234 except error.UnknownCommand:
234 except error.UnknownCommand:
235 pass
235 pass
236 return 1
236 return 1
237 self.fn = fn
237 self.fn = fn
238 self.badalias = True
238 self.badalias = True
239 except error.AmbiguousCommand:
239 except error.AmbiguousCommand:
240 def fn(ui, *args):
240 def fn(ui, *args):
241 ui.warn(_("alias '%s' resolves to ambiguous command '%s'\n") \
241 ui.warn(_("alias '%s' resolves to ambiguous command '%s'\n") \
242 % (self.name, cmd))
242 % (self.name, cmd))
243 return 1
243 return 1
244 self.fn = fn
244 self.fn = fn
245 self.badalias = True
245 self.badalias = True
246
246
247 def __call__(self, ui, *args, **opts):
247 def __call__(self, ui, *args, **opts):
248 if self.shadows:
248 if self.shadows:
249 ui.debug("alias '%s' shadows command\n" % self.name)
249 ui.debug("alias '%s' shadows command\n" % self.name)
250
250
251 return self.fn(ui, *args, **opts)
251 return util.checksignature(self.fn)(ui, *args, **opts)
252
252
253 def addaliases(ui, cmdtable):
253 def addaliases(ui, cmdtable):
254 # aliases are processed after extensions have been loaded, so they
254 # aliases are processed after extensions have been loaded, so they
255 # may use extension commands. Aliases can also use other alias definitions,
255 # may use extension commands. Aliases can also use other alias definitions,
256 # but only if they have been defined prior to the current definition.
256 # but only if they have been defined prior to the current definition.
257 for alias, definition in ui.configitems('alias'):
257 for alias, definition in ui.configitems('alias'):
258 aliasdef = cmdalias(alias, definition, cmdtable)
258 aliasdef = cmdalias(alias, definition, cmdtable)
259 cmdtable[alias] = (aliasdef, aliasdef.opts, aliasdef.help)
259 cmdtable[alias] = (aliasdef, aliasdef.opts, aliasdef.help)
260 if aliasdef.norepo:
260 if aliasdef.norepo:
261 commands.norepo += ' %s' % alias
261 commands.norepo += ' %s' % alias
262
262
263 def _parse(ui, args):
263 def _parse(ui, args):
264 options = {}
264 options = {}
265 cmdoptions = {}
265 cmdoptions = {}
266
266
267 try:
267 try:
268 args = fancyopts.fancyopts(args, commands.globalopts, options)
268 args = fancyopts.fancyopts(args, commands.globalopts, options)
269 except fancyopts.getopt.GetoptError, inst:
269 except fancyopts.getopt.GetoptError, inst:
270 raise error.CommandError(None, inst)
270 raise error.CommandError(None, inst)
271
271
272 if args:
272 if args:
273 cmd, args = args[0], args[1:]
273 cmd, args = args[0], args[1:]
274 aliases, entry = cmdutil.findcmd(cmd, commands.table,
274 aliases, entry = cmdutil.findcmd(cmd, commands.table,
275 ui.config("ui", "strict"))
275 ui.config("ui", "strict"))
276 cmd = aliases[0]
276 cmd = aliases[0]
277 args = aliasargs(entry[0]) + args
277 args = aliasargs(entry[0]) + args
278 defaults = ui.config("defaults", cmd)
278 defaults = ui.config("defaults", cmd)
279 if defaults:
279 if defaults:
280 args = map(util.expandpath, shlex.split(defaults)) + args
280 args = map(util.expandpath, shlex.split(defaults)) + args
281 c = list(entry[1])
281 c = list(entry[1])
282 else:
282 else:
283 cmd = None
283 cmd = None
284 c = []
284 c = []
285
285
286 # combine global options into local
286 # combine global options into local
287 for o in commands.globalopts:
287 for o in commands.globalopts:
288 c.append((o[0], o[1], options[o[1]], o[3]))
288 c.append((o[0], o[1], options[o[1]], o[3]))
289
289
290 try:
290 try:
291 args = fancyopts.fancyopts(args, c, cmdoptions, True)
291 args = fancyopts.fancyopts(args, c, cmdoptions, True)
292 except fancyopts.getopt.GetoptError, inst:
292 except fancyopts.getopt.GetoptError, inst:
293 raise error.CommandError(cmd, inst)
293 raise error.CommandError(cmd, inst)
294
294
295 # separate global options back out
295 # separate global options back out
296 for o in commands.globalopts:
296 for o in commands.globalopts:
297 n = o[1]
297 n = o[1]
298 options[n] = cmdoptions[n]
298 options[n] = cmdoptions[n]
299 del cmdoptions[n]
299 del cmdoptions[n]
300
300
301 return (cmd, cmd and entry[0] or None, args, options, cmdoptions)
301 return (cmd, cmd and entry[0] or None, args, options, cmdoptions)
302
302
303 def _parseconfig(ui, config):
303 def _parseconfig(ui, config):
304 """parse the --config options from the command line"""
304 """parse the --config options from the command line"""
305 for cfg in config:
305 for cfg in config:
306 try:
306 try:
307 name, value = cfg.split('=', 1)
307 name, value = cfg.split('=', 1)
308 section, name = name.split('.', 1)
308 section, name = name.split('.', 1)
309 if not section or not name:
309 if not section or not name:
310 raise IndexError
310 raise IndexError
311 ui.setconfig(section, name, value)
311 ui.setconfig(section, name, value)
312 except (IndexError, ValueError):
312 except (IndexError, ValueError):
313 raise util.Abort(_('malformed --config option: %r '
313 raise util.Abort(_('malformed --config option: %r '
314 '(use --config section.name=value)') % cfg)
314 '(use --config section.name=value)') % cfg)
315
315
316 def _earlygetopt(aliases, args):
316 def _earlygetopt(aliases, args):
317 """Return list of values for an option (or aliases).
317 """Return list of values for an option (or aliases).
318
318
319 The values are listed in the order they appear in args.
319 The values are listed in the order they appear in args.
320 The options and values are removed from args.
320 The options and values are removed from args.
321 """
321 """
322 try:
322 try:
323 argcount = args.index("--")
323 argcount = args.index("--")
324 except ValueError:
324 except ValueError:
325 argcount = len(args)
325 argcount = len(args)
326 shortopts = [opt for opt in aliases if len(opt) == 2]
326 shortopts = [opt for opt in aliases if len(opt) == 2]
327 values = []
327 values = []
328 pos = 0
328 pos = 0
329 while pos < argcount:
329 while pos < argcount:
330 if args[pos] in aliases:
330 if args[pos] in aliases:
331 if pos + 1 >= argcount:
331 if pos + 1 >= argcount:
332 # ignore and let getopt report an error if there is no value
332 # ignore and let getopt report an error if there is no value
333 break
333 break
334 del args[pos]
334 del args[pos]
335 values.append(args.pop(pos))
335 values.append(args.pop(pos))
336 argcount -= 2
336 argcount -= 2
337 elif args[pos][:2] in shortopts:
337 elif args[pos][:2] in shortopts:
338 # short option can have no following space, e.g. hg log -Rfoo
338 # short option can have no following space, e.g. hg log -Rfoo
339 values.append(args.pop(pos)[2:])
339 values.append(args.pop(pos)[2:])
340 argcount -= 1
340 argcount -= 1
341 else:
341 else:
342 pos += 1
342 pos += 1
343 return values
343 return values
344
344
345 def runcommand(lui, repo, cmd, fullargs, ui, options, d, cmdpats, cmdoptions):
345 def runcommand(lui, repo, cmd, fullargs, ui, options, d, cmdpats, cmdoptions):
346 # run pre-hook, and abort if it fails
346 # run pre-hook, and abort if it fails
347 ret = hook.hook(lui, repo, "pre-%s" % cmd, False, args=" ".join(fullargs),
347 ret = hook.hook(lui, repo, "pre-%s" % cmd, False, args=" ".join(fullargs),
348 pats=cmdpats, opts=cmdoptions)
348 pats=cmdpats, opts=cmdoptions)
349 if ret:
349 if ret:
350 return ret
350 return ret
351 ret = _runcommand(ui, options, cmd, d)
351 ret = _runcommand(ui, options, cmd, d)
352 # run post-hook, passing command result
352 # run post-hook, passing command result
353 hook.hook(lui, repo, "post-%s" % cmd, False, args=" ".join(fullargs),
353 hook.hook(lui, repo, "post-%s" % cmd, False, args=" ".join(fullargs),
354 result=ret, pats=cmdpats, opts=cmdoptions)
354 result=ret, pats=cmdpats, opts=cmdoptions)
355 return ret
355 return ret
356
356
357 _loaded = set()
357 _loaded = set()
358 def _dispatch(ui, args):
358 def _dispatch(ui, args):
359 # read --config before doing anything else
359 # read --config before doing anything else
360 # (e.g. to change trust settings for reading .hg/hgrc)
360 # (e.g. to change trust settings for reading .hg/hgrc)
361 _parseconfig(ui, _earlygetopt(['--config'], args))
361 _parseconfig(ui, _earlygetopt(['--config'], args))
362
362
363 # check for cwd
363 # check for cwd
364 cwd = _earlygetopt(['--cwd'], args)
364 cwd = _earlygetopt(['--cwd'], args)
365 if cwd:
365 if cwd:
366 os.chdir(cwd[-1])
366 os.chdir(cwd[-1])
367
367
368 # read the local repository .hgrc into a local ui object
368 # read the local repository .hgrc into a local ui object
369 path = cmdutil.findrepo(os.getcwd()) or ""
369 try:
370 wd = os.getcwd()
371 except OSError, e:
372 raise util.Abort(_("error getting current working directory: %s") %
373 e.strerror)
374 path = cmdutil.findrepo(wd) or ""
370 if not path:
375 if not path:
371 lui = ui
376 lui = ui
372 else:
377 else:
373 try:
378 try:
374 lui = ui.copy()
379 lui = ui.copy()
375 lui.readconfig(os.path.join(path, ".hg", "hgrc"))
380 lui.readconfig(os.path.join(path, ".hg", "hgrc"))
376 except IOError:
381 except IOError:
377 pass
382 pass
378
383
379 # now we can expand paths, even ones in .hg/hgrc
384 # now we can expand paths, even ones in .hg/hgrc
380 rpath = _earlygetopt(["-R", "--repository", "--repo"], args)
385 rpath = _earlygetopt(["-R", "--repository", "--repo"], args)
381 if rpath:
386 if rpath:
382 path = lui.expandpath(rpath[-1])
387 path = lui.expandpath(rpath[-1])
383 lui = ui.copy()
388 lui = ui.copy()
384 lui.readconfig(os.path.join(path, ".hg", "hgrc"))
389 lui.readconfig(os.path.join(path, ".hg", "hgrc"))
385
390
386 # Configure extensions in phases: uisetup, extsetup, cmdtable, and
391 # Configure extensions in phases: uisetup, extsetup, cmdtable, and
387 # reposetup. Programs like TortoiseHg will call _dispatch several
392 # reposetup. Programs like TortoiseHg will call _dispatch several
388 # times so we keep track of configured extensions in _loaded.
393 # times so we keep track of configured extensions in _loaded.
389 extensions.loadall(lui)
394 extensions.loadall(lui)
390 exts = [ext for ext in extensions.extensions() if ext[0] not in _loaded]
395 exts = [ext for ext in extensions.extensions() if ext[0] not in _loaded]
391 # Propagate any changes to lui.__class__ by extensions
396 # Propagate any changes to lui.__class__ by extensions
392 ui.__class__ = lui.__class__
397 ui.__class__ = lui.__class__
393
398
394 # (uisetup and extsetup are handled in extensions.loadall)
399 # (uisetup and extsetup are handled in extensions.loadall)
395
400
396 for name, module in exts:
401 for name, module in exts:
397 cmdtable = getattr(module, 'cmdtable', {})
402 cmdtable = getattr(module, 'cmdtable', {})
398 overrides = [cmd for cmd in cmdtable if cmd in commands.table]
403 overrides = [cmd for cmd in cmdtable if cmd in commands.table]
399 if overrides:
404 if overrides:
400 ui.warn(_("extension '%s' overrides commands: %s\n")
405 ui.warn(_("extension '%s' overrides commands: %s\n")
401 % (name, " ".join(overrides)))
406 % (name, " ".join(overrides)))
402 commands.table.update(cmdtable)
407 commands.table.update(cmdtable)
403 _loaded.add(name)
408 _loaded.add(name)
404
409
405 # (reposetup is handled in hg.repository)
410 # (reposetup is handled in hg.repository)
406
411
407 addaliases(lui, commands.table)
412 addaliases(lui, commands.table)
408
413
409 # check for fallback encoding
414 # check for fallback encoding
410 fallback = lui.config('ui', 'fallbackencoding')
415 fallback = lui.config('ui', 'fallbackencoding')
411 if fallback:
416 if fallback:
412 encoding.fallbackencoding = fallback
417 encoding.fallbackencoding = fallback
413
418
414 fullargs = args
419 fullargs = args
415 cmd, func, args, options, cmdoptions = _parse(lui, args)
420 cmd, func, args, options, cmdoptions = _parse(lui, args)
416
421
417 if options["config"]:
422 if options["config"]:
418 raise util.Abort(_("Option --config may not be abbreviated!"))
423 raise util.Abort(_("Option --config may not be abbreviated!"))
419 if options["cwd"]:
424 if options["cwd"]:
420 raise util.Abort(_("Option --cwd may not be abbreviated!"))
425 raise util.Abort(_("Option --cwd may not be abbreviated!"))
421 if options["repository"]:
426 if options["repository"]:
422 raise util.Abort(_(
427 raise util.Abort(_(
423 "Option -R has to be separated from other options (e.g. not -qR) "
428 "Option -R has to be separated from other options (e.g. not -qR) "
424 "and --repository may only be abbreviated as --repo!"))
429 "and --repository may only be abbreviated as --repo!"))
425
430
426 if options["encoding"]:
431 if options["encoding"]:
427 encoding.encoding = options["encoding"]
432 encoding.encoding = options["encoding"]
428 if options["encodingmode"]:
433 if options["encodingmode"]:
429 encoding.encodingmode = options["encodingmode"]
434 encoding.encodingmode = options["encodingmode"]
430 if options["time"]:
435 if options["time"]:
431 def get_times():
436 def get_times():
432 t = os.times()
437 t = os.times()
433 if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
438 if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
434 t = (t[0], t[1], t[2], t[3], time.clock())
439 t = (t[0], t[1], t[2], t[3], time.clock())
435 return t
440 return t
436 s = get_times()
441 s = get_times()
437 def print_time():
442 def print_time():
438 t = get_times()
443 t = get_times()
439 ui.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
444 ui.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
440 (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
445 (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
441 atexit.register(print_time)
446 atexit.register(print_time)
442
447
443 if options['verbose'] or options['debug'] or options['quiet']:
448 if options['verbose'] or options['debug'] or options['quiet']:
444 ui.setconfig('ui', 'verbose', str(bool(options['verbose'])))
449 ui.setconfig('ui', 'verbose', str(bool(options['verbose'])))
445 ui.setconfig('ui', 'debug', str(bool(options['debug'])))
450 ui.setconfig('ui', 'debug', str(bool(options['debug'])))
446 ui.setconfig('ui', 'quiet', str(bool(options['quiet'])))
451 ui.setconfig('ui', 'quiet', str(bool(options['quiet'])))
447 if options['traceback']:
452 if options['traceback']:
448 ui.setconfig('ui', 'traceback', 'on')
453 ui.setconfig('ui', 'traceback', 'on')
449 if options['noninteractive']:
454 if options['noninteractive']:
450 ui.setconfig('ui', 'interactive', 'off')
455 ui.setconfig('ui', 'interactive', 'off')
451
456
452 if options['help']:
457 if options['help']:
453 return commands.help_(ui, cmd, options['version'])
458 return commands.help_(ui, cmd, options['version'])
454 elif options['version']:
459 elif options['version']:
455 return commands.version_(ui)
460 return commands.version_(ui)
456 elif not cmd:
461 elif not cmd:
457 return commands.help_(ui, 'shortlist')
462 return commands.help_(ui, 'shortlist')
458
463
459 repo = None
464 repo = None
460 cmdpats = args[:]
465 cmdpats = args[:]
461 if cmd not in commands.norepo.split():
466 if cmd not in commands.norepo.split():
462 try:
467 try:
463 repo = hg.repository(ui, path=path)
468 repo = hg.repository(ui, path=path)
464 ui = repo.ui
469 ui = repo.ui
465 if not repo.local():
470 if not repo.local():
466 raise util.Abort(_("repository '%s' is not local") % path)
471 raise util.Abort(_("repository '%s' is not local") % path)
467 ui.setconfig("bundle", "mainreporoot", repo.root)
472 ui.setconfig("bundle", "mainreporoot", repo.root)
468 except error.RepoError:
473 except error.RepoError:
469 if cmd not in commands.optionalrepo.split():
474 if cmd not in commands.optionalrepo.split():
470 if args and not path: # try to infer -R from command args
475 if args and not path: # try to infer -R from command args
471 repos = map(cmdutil.findrepo, args)
476 repos = map(cmdutil.findrepo, args)
472 guess = repos[0]
477 guess = repos[0]
473 if guess and repos.count(guess) == len(repos):
478 if guess and repos.count(guess) == len(repos):
474 return _dispatch(ui, ['--repository', guess] + fullargs)
479 return _dispatch(ui, ['--repository', guess] + fullargs)
475 if not path:
480 if not path:
476 raise error.RepoError(_("There is no Mercurial repository"
481 raise error.RepoError(_("There is no Mercurial repository"
477 " here (.hg not found)"))
482 " here (.hg not found)"))
478 raise
483 raise
479 args.insert(0, repo)
484 args.insert(0, repo)
480 elif rpath:
485 elif rpath:
481 ui.warn(_("warning: --repository ignored\n"))
486 ui.warn(_("warning: --repository ignored\n"))
482
487
483 d = lambda: util.checksignature(func)(ui, *args, **cmdoptions)
488 d = lambda: util.checksignature(func)(ui, *args, **cmdoptions)
484 return runcommand(lui, repo, cmd, fullargs, ui, options, d,
489 return runcommand(lui, repo, cmd, fullargs, ui, options, d,
485 cmdpats, cmdoptions)
490 cmdpats, cmdoptions)
486
491
487 def _runcommand(ui, options, cmd, cmdfunc):
492 def _runcommand(ui, options, cmd, cmdfunc):
488 def checkargs():
493 def checkargs():
489 try:
494 try:
490 return cmdfunc()
495 return cmdfunc()
491 except error.SignatureError:
496 except error.SignatureError:
492 raise error.CommandError(cmd, _("invalid arguments"))
497 raise error.CommandError(cmd, _("invalid arguments"))
493
498
494 if options['profile']:
499 if options['profile']:
495 format = ui.config('profiling', 'format', default='text')
500 format = ui.config('profiling', 'format', default='text')
496
501
497 if not format in ['text', 'kcachegrind']:
502 if not format in ['text', 'kcachegrind']:
498 ui.warn(_("unrecognized profiling format '%s'"
503 ui.warn(_("unrecognized profiling format '%s'"
499 " - Ignored\n") % format)
504 " - Ignored\n") % format)
500 format = 'text'
505 format = 'text'
501
506
502 output = ui.config('profiling', 'output')
507 output = ui.config('profiling', 'output')
503
508
504 if output:
509 if output:
505 path = ui.expandpath(output)
510 path = ui.expandpath(output)
506 ostream = open(path, 'wb')
511 ostream = open(path, 'wb')
507 else:
512 else:
508 ostream = sys.stderr
513 ostream = sys.stderr
509
514
510 try:
515 try:
511 from mercurial import lsprof
516 from mercurial import lsprof
512 except ImportError:
517 except ImportError:
513 raise util.Abort(_(
518 raise util.Abort(_(
514 'lsprof not available - install from '
519 'lsprof not available - install from '
515 'http://codespeak.net/svn/user/arigo/hack/misc/lsprof/'))
520 'http://codespeak.net/svn/user/arigo/hack/misc/lsprof/'))
516 p = lsprof.Profiler()
521 p = lsprof.Profiler()
517 p.enable(subcalls=True)
522 p.enable(subcalls=True)
518 try:
523 try:
519 return checkargs()
524 return checkargs()
520 finally:
525 finally:
521 p.disable()
526 p.disable()
522
527
523 if format == 'kcachegrind':
528 if format == 'kcachegrind':
524 import lsprofcalltree
529 import lsprofcalltree
525 calltree = lsprofcalltree.KCacheGrind(p)
530 calltree = lsprofcalltree.KCacheGrind(p)
526 calltree.output(ostream)
531 calltree.output(ostream)
527 else:
532 else:
528 # format == 'text'
533 # format == 'text'
529 stats = lsprof.Stats(p.getstats())
534 stats = lsprof.Stats(p.getstats())
530 stats.sort()
535 stats.sort()
531 stats.pprint(top=10, file=ostream, climit=5)
536 stats.pprint(top=10, file=ostream, climit=5)
532
537
533 if output:
538 if output:
534 ostream.close()
539 ostream.close()
535 else:
540 else:
536 return checkargs()
541 return checkargs()
@@ -1,352 +1,352 b''
1 # hgweb/hgwebdir_mod.py - Web interface for a directory of repositories.
1 # hgweb/hgwebdir_mod.py - Web interface for a directory of repositories.
2 #
2 #
3 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
3 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
4 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
4 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
7 # GNU General Public License version 2 or any later version.
8
8
9 import os, re, time, urlparse
9 import os, re, time, urlparse
10 from mercurial.i18n import _
10 from mercurial.i18n import _
11 from mercurial import ui, hg, util, templater
11 from mercurial import ui, hg, util, templater
12 from mercurial import error, encoding
12 from mercurial import error, encoding
13 from common import ErrorResponse, get_mtime, staticfile, paritygen, \
13 from common import ErrorResponse, get_mtime, staticfile, paritygen, \
14 get_contact, HTTP_OK, HTTP_NOT_FOUND, HTTP_SERVER_ERROR
14 get_contact, HTTP_OK, HTTP_NOT_FOUND, HTTP_SERVER_ERROR
15 from hgweb_mod import hgweb
15 from hgweb_mod import hgweb
16 from request import wsgirequest
16 from request import wsgirequest
17 import webutil
17 import webutil
18
18
19 def cleannames(items):
19 def cleannames(items):
20 return [(util.pconvert(name).strip('/'), path) for name, path in items]
20 return [(util.pconvert(name).strip('/'), path) for name, path in items]
21
21
22 def findrepos(paths):
22 def findrepos(paths):
23 repos = []
23 repos = []
24 for prefix, root in cleannames(paths):
24 for prefix, root in cleannames(paths):
25 roothead, roottail = os.path.split(root)
25 roothead, roottail = os.path.split(root)
26 # "foo = /bar/*" makes every subrepo of /bar/ to be
26 # "foo = /bar/*" makes every subrepo of /bar/ to be
27 # mounted as foo/subrepo
27 # mounted as foo/subrepo
28 # and "foo = /bar/**" also recurses into the subdirectories,
28 # and "foo = /bar/**" also recurses into the subdirectories,
29 # remember to use it without working dir.
29 # remember to use it without working dir.
30 try:
30 try:
31 recurse = {'*': False, '**': True}[roottail]
31 recurse = {'*': False, '**': True}[roottail]
32 except KeyError:
32 except KeyError:
33 repos.append((prefix, root))
33 repos.append((prefix, root))
34 continue
34 continue
35 roothead = os.path.normpath(roothead)
35 roothead = os.path.normpath(os.path.abspath(roothead))
36 for path in util.walkrepos(roothead, followsym=True, recurse=recurse):
36 for path in util.walkrepos(roothead, followsym=True, recurse=recurse):
37 path = os.path.normpath(path)
37 path = os.path.normpath(path)
38 name = util.pconvert(path[len(roothead):]).strip('/')
38 name = util.pconvert(path[len(roothead):]).strip('/')
39 if prefix:
39 if prefix:
40 name = prefix + '/' + name
40 name = prefix + '/' + name
41 repos.append((name, path))
41 repos.append((name, path))
42 return repos
42 return repos
43
43
44 class hgwebdir(object):
44 class hgwebdir(object):
45 refreshinterval = 20
45 refreshinterval = 20
46
46
47 def __init__(self, conf, baseui=None):
47 def __init__(self, conf, baseui=None):
48 self.conf = conf
48 self.conf = conf
49 self.baseui = baseui
49 self.baseui = baseui
50 self.lastrefresh = 0
50 self.lastrefresh = 0
51 self.motd = None
51 self.motd = None
52 self.refresh()
52 self.refresh()
53
53
54 def refresh(self):
54 def refresh(self):
55 if self.lastrefresh + self.refreshinterval > time.time():
55 if self.lastrefresh + self.refreshinterval > time.time():
56 return
56 return
57
57
58 if self.baseui:
58 if self.baseui:
59 u = self.baseui.copy()
59 u = self.baseui.copy()
60 else:
60 else:
61 u = ui.ui()
61 u = ui.ui()
62 u.setconfig('ui', 'report_untrusted', 'off')
62 u.setconfig('ui', 'report_untrusted', 'off')
63 u.setconfig('ui', 'interactive', 'off')
63 u.setconfig('ui', 'interactive', 'off')
64
64
65 if not isinstance(self.conf, (dict, list, tuple)):
65 if not isinstance(self.conf, (dict, list, tuple)):
66 map = {'paths': 'hgweb-paths'}
66 map = {'paths': 'hgweb-paths'}
67 u.readconfig(self.conf, remap=map, trust=True)
67 u.readconfig(self.conf, remap=map, trust=True)
68 paths = u.configitems('hgweb-paths')
68 paths = u.configitems('hgweb-paths')
69 elif isinstance(self.conf, (list, tuple)):
69 elif isinstance(self.conf, (list, tuple)):
70 paths = self.conf
70 paths = self.conf
71 elif isinstance(self.conf, dict):
71 elif isinstance(self.conf, dict):
72 paths = self.conf.items()
72 paths = self.conf.items()
73
73
74 repos = findrepos(paths)
74 repos = findrepos(paths)
75 for prefix, root in u.configitems('collections'):
75 for prefix, root in u.configitems('collections'):
76 prefix = util.pconvert(prefix)
76 prefix = util.pconvert(prefix)
77 for path in util.walkrepos(root, followsym=True):
77 for path in util.walkrepos(root, followsym=True):
78 repo = os.path.normpath(path)
78 repo = os.path.normpath(path)
79 name = util.pconvert(repo)
79 name = util.pconvert(repo)
80 if name.startswith(prefix):
80 if name.startswith(prefix):
81 name = name[len(prefix):]
81 name = name[len(prefix):]
82 repos.append((name.lstrip('/'), repo))
82 repos.append((name.lstrip('/'), repo))
83
83
84 self.repos = repos
84 self.repos = repos
85 self.ui = u
85 self.ui = u
86 encoding.encoding = self.ui.config('web', 'encoding',
86 encoding.encoding = self.ui.config('web', 'encoding',
87 encoding.encoding)
87 encoding.encoding)
88 self.style = self.ui.config('web', 'style', 'paper')
88 self.style = self.ui.config('web', 'style', 'paper')
89 self.templatepath = self.ui.config('web', 'templates', None)
89 self.templatepath = self.ui.config('web', 'templates', None)
90 self.stripecount = self.ui.config('web', 'stripes', 1)
90 self.stripecount = self.ui.config('web', 'stripes', 1)
91 if self.stripecount:
91 if self.stripecount:
92 self.stripecount = int(self.stripecount)
92 self.stripecount = int(self.stripecount)
93 self._baseurl = self.ui.config('web', 'baseurl')
93 self._baseurl = self.ui.config('web', 'baseurl')
94 self.lastrefresh = time.time()
94 self.lastrefresh = time.time()
95
95
96 def run(self):
96 def run(self):
97 if not os.environ.get('GATEWAY_INTERFACE', '').startswith("CGI/1."):
97 if not os.environ.get('GATEWAY_INTERFACE', '').startswith("CGI/1."):
98 raise RuntimeError("This function is only intended to be "
98 raise RuntimeError("This function is only intended to be "
99 "called while running as a CGI script.")
99 "called while running as a CGI script.")
100 import mercurial.hgweb.wsgicgi as wsgicgi
100 import mercurial.hgweb.wsgicgi as wsgicgi
101 wsgicgi.launch(self)
101 wsgicgi.launch(self)
102
102
103 def __call__(self, env, respond):
103 def __call__(self, env, respond):
104 req = wsgirequest(env, respond)
104 req = wsgirequest(env, respond)
105 return self.run_wsgi(req)
105 return self.run_wsgi(req)
106
106
107 def read_allowed(self, ui, req):
107 def read_allowed(self, ui, req):
108 """Check allow_read and deny_read config options of a repo's ui object
108 """Check allow_read and deny_read config options of a repo's ui object
109 to determine user permissions. By default, with neither option set (or
109 to determine user permissions. By default, with neither option set (or
110 both empty), allow all users to read the repo. There are two ways a
110 both empty), allow all users to read the repo. There are two ways a
111 user can be denied read access: (1) deny_read is not empty, and the
111 user can be denied read access: (1) deny_read is not empty, and the
112 user is unauthenticated or deny_read contains user (or *), and (2)
112 user is unauthenticated or deny_read contains user (or *), and (2)
113 allow_read is not empty and the user is not in allow_read. Return True
113 allow_read is not empty and the user is not in allow_read. Return True
114 if user is allowed to read the repo, else return False."""
114 if user is allowed to read the repo, else return False."""
115
115
116 user = req.env.get('REMOTE_USER')
116 user = req.env.get('REMOTE_USER')
117
117
118 deny_read = ui.configlist('web', 'deny_read', untrusted=True)
118 deny_read = ui.configlist('web', 'deny_read', untrusted=True)
119 if deny_read and (not user or deny_read == ['*'] or user in deny_read):
119 if deny_read and (not user or deny_read == ['*'] or user in deny_read):
120 return False
120 return False
121
121
122 allow_read = ui.configlist('web', 'allow_read', untrusted=True)
122 allow_read = ui.configlist('web', 'allow_read', untrusted=True)
123 # by default, allow reading if no allow_read option has been set
123 # by default, allow reading if no allow_read option has been set
124 if (not allow_read) or (allow_read == ['*']) or (user in allow_read):
124 if (not allow_read) or (allow_read == ['*']) or (user in allow_read):
125 return True
125 return True
126
126
127 return False
127 return False
128
128
129 def run_wsgi(self, req):
129 def run_wsgi(self, req):
130 try:
130 try:
131 try:
131 try:
132 self.refresh()
132 self.refresh()
133
133
134 virtual = req.env.get("PATH_INFO", "").strip('/')
134 virtual = req.env.get("PATH_INFO", "").strip('/')
135 tmpl = self.templater(req)
135 tmpl = self.templater(req)
136 ctype = tmpl('mimetype', encoding=encoding.encoding)
136 ctype = tmpl('mimetype', encoding=encoding.encoding)
137 ctype = templater.stringify(ctype)
137 ctype = templater.stringify(ctype)
138
138
139 # a static file
139 # a static file
140 if virtual.startswith('static/') or 'static' in req.form:
140 if virtual.startswith('static/') or 'static' in req.form:
141 if virtual.startswith('static/'):
141 if virtual.startswith('static/'):
142 fname = virtual[7:]
142 fname = virtual[7:]
143 else:
143 else:
144 fname = req.form['static'][0]
144 fname = req.form['static'][0]
145 static = templater.templatepath('static')
145 static = templater.templatepath('static')
146 return (staticfile(static, fname, req),)
146 return (staticfile(static, fname, req),)
147
147
148 # top-level index
148 # top-level index
149 elif not virtual:
149 elif not virtual:
150 req.respond(HTTP_OK, ctype)
150 req.respond(HTTP_OK, ctype)
151 return self.makeindex(req, tmpl)
151 return self.makeindex(req, tmpl)
152
152
153 # nested indexes and hgwebs
153 # nested indexes and hgwebs
154
154
155 repos = dict(self.repos)
155 repos = dict(self.repos)
156 while virtual:
156 while virtual:
157 real = repos.get(virtual)
157 real = repos.get(virtual)
158 if real:
158 if real:
159 req.env['REPO_NAME'] = virtual
159 req.env['REPO_NAME'] = virtual
160 try:
160 try:
161 repo = hg.repository(self.ui, real)
161 repo = hg.repository(self.ui, real)
162 return hgweb(repo).run_wsgi(req)
162 return hgweb(repo).run_wsgi(req)
163 except IOError, inst:
163 except IOError, inst:
164 msg = inst.strerror
164 msg = inst.strerror
165 raise ErrorResponse(HTTP_SERVER_ERROR, msg)
165 raise ErrorResponse(HTTP_SERVER_ERROR, msg)
166 except error.RepoError, inst:
166 except error.RepoError, inst:
167 raise ErrorResponse(HTTP_SERVER_ERROR, str(inst))
167 raise ErrorResponse(HTTP_SERVER_ERROR, str(inst))
168
168
169 # browse subdirectories
169 # browse subdirectories
170 subdir = virtual + '/'
170 subdir = virtual + '/'
171 if [r for r in repos if r.startswith(subdir)]:
171 if [r for r in repos if r.startswith(subdir)]:
172 req.respond(HTTP_OK, ctype)
172 req.respond(HTTP_OK, ctype)
173 return self.makeindex(req, tmpl, subdir)
173 return self.makeindex(req, tmpl, subdir)
174
174
175 up = virtual.rfind('/')
175 up = virtual.rfind('/')
176 if up < 0:
176 if up < 0:
177 break
177 break
178 virtual = virtual[:up]
178 virtual = virtual[:up]
179
179
180 # prefixes not found
180 # prefixes not found
181 req.respond(HTTP_NOT_FOUND, ctype)
181 req.respond(HTTP_NOT_FOUND, ctype)
182 return tmpl("notfound", repo=virtual)
182 return tmpl("notfound", repo=virtual)
183
183
184 except ErrorResponse, err:
184 except ErrorResponse, err:
185 req.respond(err, ctype)
185 req.respond(err, ctype)
186 return tmpl('error', error=err.message or '')
186 return tmpl('error', error=err.message or '')
187 finally:
187 finally:
188 tmpl = None
188 tmpl = None
189
189
190 def makeindex(self, req, tmpl, subdir=""):
190 def makeindex(self, req, tmpl, subdir=""):
191
191
192 def archivelist(ui, nodeid, url):
192 def archivelist(ui, nodeid, url):
193 allowed = ui.configlist("web", "allow_archive", untrusted=True)
193 allowed = ui.configlist("web", "allow_archive", untrusted=True)
194 for i in [('zip', '.zip'), ('gz', '.tar.gz'), ('bz2', '.tar.bz2')]:
194 for i in [('zip', '.zip'), ('gz', '.tar.gz'), ('bz2', '.tar.bz2')]:
195 if i[0] in allowed or ui.configbool("web", "allow" + i[0],
195 if i[0] in allowed or ui.configbool("web", "allow" + i[0],
196 untrusted=True):
196 untrusted=True):
197 yield {"type" : i[0], "extension": i[1],
197 yield {"type" : i[0], "extension": i[1],
198 "node": nodeid, "url": url}
198 "node": nodeid, "url": url}
199
199
200 def rawentries(subdir="", **map):
200 def rawentries(subdir="", **map):
201
201
202 descend = self.ui.configbool('web', 'descend', True)
202 descend = self.ui.configbool('web', 'descend', True)
203 for name, path in self.repos:
203 for name, path in self.repos:
204
204
205 if not name.startswith(subdir):
205 if not name.startswith(subdir):
206 continue
206 continue
207 name = name[len(subdir):]
207 name = name[len(subdir):]
208 if not descend and '/' in name:
208 if not descend and '/' in name:
209 continue
209 continue
210
210
211 u = self.ui.copy()
211 u = self.ui.copy()
212 try:
212 try:
213 u.readconfig(os.path.join(path, '.hg', 'hgrc'))
213 u.readconfig(os.path.join(path, '.hg', 'hgrc'))
214 except Exception, e:
214 except Exception, e:
215 u.warn(_('error reading %s/.hg/hgrc: %s\n') % (path, e))
215 u.warn(_('error reading %s/.hg/hgrc: %s\n') % (path, e))
216 continue
216 continue
217 def get(section, name, default=None):
217 def get(section, name, default=None):
218 return u.config(section, name, default, untrusted=True)
218 return u.config(section, name, default, untrusted=True)
219
219
220 if u.configbool("web", "hidden", untrusted=True):
220 if u.configbool("web", "hidden", untrusted=True):
221 continue
221 continue
222
222
223 if not self.read_allowed(u, req):
223 if not self.read_allowed(u, req):
224 continue
224 continue
225
225
226 parts = [name]
226 parts = [name]
227 if 'PATH_INFO' in req.env:
227 if 'PATH_INFO' in req.env:
228 parts.insert(0, req.env['PATH_INFO'].rstrip('/'))
228 parts.insert(0, req.env['PATH_INFO'].rstrip('/'))
229 if req.env['SCRIPT_NAME']:
229 if req.env['SCRIPT_NAME']:
230 parts.insert(0, req.env['SCRIPT_NAME'])
230 parts.insert(0, req.env['SCRIPT_NAME'])
231 url = re.sub(r'/+', '/', '/'.join(parts) + '/')
231 url = re.sub(r'/+', '/', '/'.join(parts) + '/')
232
232
233 # update time with local timezone
233 # update time with local timezone
234 try:
234 try:
235 r = hg.repository(self.ui, path)
235 r = hg.repository(self.ui, path)
236 d = (get_mtime(r.spath), util.makedate()[1])
236 d = (get_mtime(r.spath), util.makedate()[1])
237 except OSError:
237 except OSError:
238 continue
238 continue
239
239
240 contact = get_contact(get)
240 contact = get_contact(get)
241 description = get("web", "description", "")
241 description = get("web", "description", "")
242 name = get("web", "name", name)
242 name = get("web", "name", name)
243 row = dict(contact=contact or "unknown",
243 row = dict(contact=contact or "unknown",
244 contact_sort=contact.upper() or "unknown",
244 contact_sort=contact.upper() or "unknown",
245 name=name,
245 name=name,
246 name_sort=name,
246 name_sort=name,
247 url=url,
247 url=url,
248 description=description or "unknown",
248 description=description or "unknown",
249 description_sort=description.upper() or "unknown",
249 description_sort=description.upper() or "unknown",
250 lastchange=d,
250 lastchange=d,
251 lastchange_sort=d[1]-d[0],
251 lastchange_sort=d[1]-d[0],
252 archives=archivelist(u, "tip", url))
252 archives=archivelist(u, "tip", url))
253 yield row
253 yield row
254
254
255 sortdefault = None, False
255 sortdefault = None, False
256 def entries(sortcolumn="", descending=False, subdir="", **map):
256 def entries(sortcolumn="", descending=False, subdir="", **map):
257 rows = rawentries(subdir=subdir, **map)
257 rows = rawentries(subdir=subdir, **map)
258
258
259 if sortcolumn and sortdefault != (sortcolumn, descending):
259 if sortcolumn and sortdefault != (sortcolumn, descending):
260 sortkey = '%s_sort' % sortcolumn
260 sortkey = '%s_sort' % sortcolumn
261 rows = sorted(rows, key=lambda x: x[sortkey],
261 rows = sorted(rows, key=lambda x: x[sortkey],
262 reverse=descending)
262 reverse=descending)
263 for row, parity in zip(rows, paritygen(self.stripecount)):
263 for row, parity in zip(rows, paritygen(self.stripecount)):
264 row['parity'] = parity
264 row['parity'] = parity
265 yield row
265 yield row
266
266
267 self.refresh()
267 self.refresh()
268 sortable = ["name", "description", "contact", "lastchange"]
268 sortable = ["name", "description", "contact", "lastchange"]
269 sortcolumn, descending = sortdefault
269 sortcolumn, descending = sortdefault
270 if 'sort' in req.form:
270 if 'sort' in req.form:
271 sortcolumn = req.form['sort'][0]
271 sortcolumn = req.form['sort'][0]
272 descending = sortcolumn.startswith('-')
272 descending = sortcolumn.startswith('-')
273 if descending:
273 if descending:
274 sortcolumn = sortcolumn[1:]
274 sortcolumn = sortcolumn[1:]
275 if sortcolumn not in sortable:
275 if sortcolumn not in sortable:
276 sortcolumn = ""
276 sortcolumn = ""
277
277
278 sort = [("sort_%s" % column,
278 sort = [("sort_%s" % column,
279 "%s%s" % ((not descending and column == sortcolumn)
279 "%s%s" % ((not descending and column == sortcolumn)
280 and "-" or "", column))
280 and "-" or "", column))
281 for column in sortable]
281 for column in sortable]
282
282
283 self.refresh()
283 self.refresh()
284 self.updatereqenv(req.env)
284 self.updatereqenv(req.env)
285
285
286 return tmpl("index", entries=entries, subdir=subdir,
286 return tmpl("index", entries=entries, subdir=subdir,
287 sortcolumn=sortcolumn, descending=descending,
287 sortcolumn=sortcolumn, descending=descending,
288 **dict(sort))
288 **dict(sort))
289
289
290 def templater(self, req):
290 def templater(self, req):
291
291
292 def header(**map):
292 def header(**map):
293 yield tmpl('header', encoding=encoding.encoding, **map)
293 yield tmpl('header', encoding=encoding.encoding, **map)
294
294
295 def footer(**map):
295 def footer(**map):
296 yield tmpl("footer", **map)
296 yield tmpl("footer", **map)
297
297
298 def motd(**map):
298 def motd(**map):
299 if self.motd is not None:
299 if self.motd is not None:
300 yield self.motd
300 yield self.motd
301 else:
301 else:
302 yield config('web', 'motd', '')
302 yield config('web', 'motd', '')
303
303
304 def config(section, name, default=None, untrusted=True):
304 def config(section, name, default=None, untrusted=True):
305 return self.ui.config(section, name, default, untrusted)
305 return self.ui.config(section, name, default, untrusted)
306
306
307 self.updatereqenv(req.env)
307 self.updatereqenv(req.env)
308
308
309 url = req.env.get('SCRIPT_NAME', '')
309 url = req.env.get('SCRIPT_NAME', '')
310 if not url.endswith('/'):
310 if not url.endswith('/'):
311 url += '/'
311 url += '/'
312
312
313 vars = {}
313 vars = {}
314 styles = (
314 styles = (
315 req.form.get('style', [None])[0],
315 req.form.get('style', [None])[0],
316 config('web', 'style'),
316 config('web', 'style'),
317 'paper'
317 'paper'
318 )
318 )
319 style, mapfile = templater.stylemap(styles, self.templatepath)
319 style, mapfile = templater.stylemap(styles, self.templatepath)
320 if style == styles[0]:
320 if style == styles[0]:
321 vars['style'] = style
321 vars['style'] = style
322
322
323 start = url[-1] == '?' and '&' or '?'
323 start = url[-1] == '?' and '&' or '?'
324 sessionvars = webutil.sessionvars(vars, start)
324 sessionvars = webutil.sessionvars(vars, start)
325 staticurl = config('web', 'staticurl') or url + 'static/'
325 staticurl = config('web', 'staticurl') or url + 'static/'
326 if not staticurl.endswith('/'):
326 if not staticurl.endswith('/'):
327 staticurl += '/'
327 staticurl += '/'
328
328
329 tmpl = templater.templater(mapfile,
329 tmpl = templater.templater(mapfile,
330 defaults={"header": header,
330 defaults={"header": header,
331 "footer": footer,
331 "footer": footer,
332 "motd": motd,
332 "motd": motd,
333 "url": url,
333 "url": url,
334 "staticurl": staticurl,
334 "staticurl": staticurl,
335 "sessionvars": sessionvars})
335 "sessionvars": sessionvars})
336 return tmpl
336 return tmpl
337
337
338 def updatereqenv(self, env):
338 def updatereqenv(self, env):
339 def splitnetloc(netloc):
339 def splitnetloc(netloc):
340 if ':' in netloc:
340 if ':' in netloc:
341 return netloc.split(':', 1)
341 return netloc.split(':', 1)
342 else:
342 else:
343 return (netloc, None)
343 return (netloc, None)
344
344
345 if self._baseurl is not None:
345 if self._baseurl is not None:
346 urlcomp = urlparse.urlparse(self._baseurl)
346 urlcomp = urlparse.urlparse(self._baseurl)
347 host, port = splitnetloc(urlcomp[1])
347 host, port = splitnetloc(urlcomp[1])
348 path = urlcomp[2]
348 path = urlcomp[2]
349 env['SERVER_NAME'] = host
349 env['SERVER_NAME'] = host
350 if port:
350 if port:
351 env['SERVER_PORT'] = port
351 env['SERVER_PORT'] = port
352 env['SCRIPT_NAME'] = path
352 env['SCRIPT_NAME'] = path
@@ -1,527 +1,527 b''
1 # merge.py - directory-level update/merge handling for Mercurial
1 # merge.py - directory-level update/merge handling for Mercurial
2 #
2 #
3 # Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from node import nullid, nullrev, hex, bin
8 from node import nullid, nullrev, hex, bin
9 from i18n import _
9 from i18n import _
10 import util, filemerge, copies, subrepo
10 import util, filemerge, copies, subrepo
11 import errno, os, shutil
11 import errno, os, shutil
12
12
13 class mergestate(object):
13 class mergestate(object):
14 '''track 3-way merge state of individual files'''
14 '''track 3-way merge state of individual files'''
15 def __init__(self, repo):
15 def __init__(self, repo):
16 self._repo = repo
16 self._repo = repo
17 self._read()
17 self._read()
18 def reset(self, node=None):
18 def reset(self, node=None):
19 self._state = {}
19 self._state = {}
20 if node:
20 if node:
21 self._local = node
21 self._local = node
22 shutil.rmtree(self._repo.join("merge"), True)
22 shutil.rmtree(self._repo.join("merge"), True)
23 def _read(self):
23 def _read(self):
24 self._state = {}
24 self._state = {}
25 try:
25 try:
26 f = self._repo.opener("merge/state")
26 f = self._repo.opener("merge/state")
27 for i, l in enumerate(f):
27 for i, l in enumerate(f):
28 if i == 0:
28 if i == 0:
29 self._local = bin(l[:-1])
29 self._local = bin(l[:-1])
30 else:
30 else:
31 bits = l[:-1].split("\0")
31 bits = l[:-1].split("\0")
32 self._state[bits[0]] = bits[1:]
32 self._state[bits[0]] = bits[1:]
33 except IOError, err:
33 except IOError, err:
34 if err.errno != errno.ENOENT:
34 if err.errno != errno.ENOENT:
35 raise
35 raise
36 def _write(self):
36 def _write(self):
37 f = self._repo.opener("merge/state", "w")
37 f = self._repo.opener("merge/state", "w")
38 f.write(hex(self._local) + "\n")
38 f.write(hex(self._local) + "\n")
39 for d, v in self._state.iteritems():
39 for d, v in self._state.iteritems():
40 f.write("\0".join([d] + v) + "\n")
40 f.write("\0".join([d] + v) + "\n")
41 def add(self, fcl, fco, fca, fd, flags):
41 def add(self, fcl, fco, fca, fd, flags):
42 hash = util.sha1(fcl.path()).hexdigest()
42 hash = util.sha1(fcl.path()).hexdigest()
43 self._repo.opener("merge/" + hash, "w").write(fcl.data())
43 self._repo.opener("merge/" + hash, "w").write(fcl.data())
44 self._state[fd] = ['u', hash, fcl.path(), fca.path(),
44 self._state[fd] = ['u', hash, fcl.path(), fca.path(),
45 hex(fca.filenode()), fco.path(), flags]
45 hex(fca.filenode()), fco.path(), flags]
46 self._write()
46 self._write()
47 def __contains__(self, dfile):
47 def __contains__(self, dfile):
48 return dfile in self._state
48 return dfile in self._state
49 def __getitem__(self, dfile):
49 def __getitem__(self, dfile):
50 return self._state[dfile][0]
50 return self._state[dfile][0]
51 def __iter__(self):
51 def __iter__(self):
52 l = self._state.keys()
52 l = self._state.keys()
53 l.sort()
53 l.sort()
54 for f in l:
54 for f in l:
55 yield f
55 yield f
56 def mark(self, dfile, state):
56 def mark(self, dfile, state):
57 self._state[dfile][0] = state
57 self._state[dfile][0] = state
58 self._write()
58 self._write()
59 def resolve(self, dfile, wctx, octx):
59 def resolve(self, dfile, wctx, octx):
60 if self[dfile] == 'r':
60 if self[dfile] == 'r':
61 return 0
61 return 0
62 state, hash, lfile, afile, anode, ofile, flags = self._state[dfile]
62 state, hash, lfile, afile, anode, ofile, flags = self._state[dfile]
63 f = self._repo.opener("merge/" + hash)
63 f = self._repo.opener("merge/" + hash)
64 self._repo.wwrite(dfile, f.read(), flags)
64 self._repo.wwrite(dfile, f.read(), flags)
65 fcd = wctx[dfile]
65 fcd = wctx[dfile]
66 fco = octx[ofile]
66 fco = octx[ofile]
67 fca = self._repo.filectx(afile, fileid=anode)
67 fca = self._repo.filectx(afile, fileid=anode)
68 r = filemerge.filemerge(self._repo, self._local, lfile, fcd, fco, fca)
68 r = filemerge.filemerge(self._repo, self._local, lfile, fcd, fco, fca)
69 if not r:
69 if not r:
70 self.mark(dfile, 'r')
70 self.mark(dfile, 'r')
71 return r
71 return r
72
72
73 def _checkunknown(wctx, mctx):
73 def _checkunknown(wctx, mctx):
74 "check for collisions between unknown files and files in mctx"
74 "check for collisions between unknown files and files in mctx"
75 for f in wctx.unknown():
75 for f in wctx.unknown():
76 if f in mctx and mctx[f].cmp(wctx[f].data()):
76 if f in mctx and mctx[f].cmp(wctx[f].data()):
77 raise util.Abort(_("untracked file in working directory differs"
77 raise util.Abort(_("untracked file in working directory differs"
78 " from file in requested revision: '%s'") % f)
78 " from file in requested revision: '%s'") % f)
79
79
80 def _checkcollision(mctx):
80 def _checkcollision(mctx):
81 "check for case folding collisions in the destination context"
81 "check for case folding collisions in the destination context"
82 folded = {}
82 folded = {}
83 for fn in mctx:
83 for fn in mctx:
84 fold = fn.lower()
84 fold = fn.lower()
85 if fold in folded:
85 if fold in folded:
86 raise util.Abort(_("case-folding collision between %s and %s")
86 raise util.Abort(_("case-folding collision between %s and %s")
87 % (fn, folded[fold]))
87 % (fn, folded[fold]))
88 folded[fold] = fn
88 folded[fold] = fn
89
89
90 def _forgetremoved(wctx, mctx, branchmerge):
90 def _forgetremoved(wctx, mctx, branchmerge):
91 """
91 """
92 Forget removed files
92 Forget removed files
93
93
94 If we're jumping between revisions (as opposed to merging), and if
94 If we're jumping between revisions (as opposed to merging), and if
95 neither the working directory nor the target rev has the file,
95 neither the working directory nor the target rev has the file,
96 then we need to remove it from the dirstate, to prevent the
96 then we need to remove it from the dirstate, to prevent the
97 dirstate from listing the file when it is no longer in the
97 dirstate from listing the file when it is no longer in the
98 manifest.
98 manifest.
99
99
100 If we're merging, and the other revision has removed a file
100 If we're merging, and the other revision has removed a file
101 that is not present in the working directory, we need to mark it
101 that is not present in the working directory, we need to mark it
102 as removed.
102 as removed.
103 """
103 """
104
104
105 action = []
105 action = []
106 state = branchmerge and 'r' or 'f'
106 state = branchmerge and 'r' or 'f'
107 for f in wctx.deleted():
107 for f in wctx.deleted():
108 if f not in mctx:
108 if f not in mctx:
109 action.append((f, state))
109 action.append((f, state))
110
110
111 if not branchmerge:
111 if not branchmerge:
112 for f in wctx.removed():
112 for f in wctx.removed():
113 if f not in mctx:
113 if f not in mctx:
114 action.append((f, "f"))
114 action.append((f, "f"))
115
115
116 return action
116 return action
117
117
118 def manifestmerge(repo, p1, p2, pa, overwrite, partial):
118 def manifestmerge(repo, p1, p2, pa, overwrite, partial):
119 """
119 """
120 Merge p1 and p2 with ancestor ma and generate merge action list
120 Merge p1 and p2 with ancestor ma and generate merge action list
121
121
122 overwrite = whether we clobber working files
122 overwrite = whether we clobber working files
123 partial = function to filter file lists
123 partial = function to filter file lists
124 """
124 """
125
125
126 def fmerge(f, f2, fa):
126 def fmerge(f, f2, fa):
127 """merge flags"""
127 """merge flags"""
128 a, m, n = ma.flags(fa), m1.flags(f), m2.flags(f2)
128 a, m, n = ma.flags(fa), m1.flags(f), m2.flags(f2)
129 if m == n: # flags agree
129 if m == n: # flags agree
130 return m # unchanged
130 return m # unchanged
131 if m and n and not a: # flags set, don't agree, differ from parent
131 if m and n and not a: # flags set, don't agree, differ from parent
132 r = repo.ui.promptchoice(
132 r = repo.ui.promptchoice(
133 _(" conflicting flags for %s\n"
133 _(" conflicting flags for %s\n"
134 "(n)one, e(x)ec or sym(l)ink?") % f,
134 "(n)one, e(x)ec or sym(l)ink?") % f,
135 (_("&None"), _("E&xec"), _("Sym&link")), 0)
135 (_("&None"), _("E&xec"), _("Sym&link")), 0)
136 if r == 1:
136 if r == 1:
137 return "x" # Exec
137 return "x" # Exec
138 if r == 2:
138 if r == 2:
139 return "l" # Symlink
139 return "l" # Symlink
140 return ""
140 return ""
141 if m and m != a: # changed from a to m
141 if m and m != a: # changed from a to m
142 return m
142 return m
143 if n and n != a: # changed from a to n
143 if n and n != a: # changed from a to n
144 return n
144 return n
145 return '' # flag was cleared
145 return '' # flag was cleared
146
146
147 def act(msg, m, f, *args):
147 def act(msg, m, f, *args):
148 repo.ui.debug(" %s: %s -> %s\n" % (f, msg, m))
148 repo.ui.debug(" %s: %s -> %s\n" % (f, msg, m))
149 action.append((f, m) + args)
149 action.append((f, m) + args)
150
150
151 action, copy = [], {}
151 action, copy = [], {}
152
152
153 if overwrite:
153 if overwrite:
154 pa = p1
154 pa = p1
155 elif pa == p2: # backwards
155 elif pa == p2: # backwards
156 pa = p1.p1()
156 pa = p1.p1()
157 elif pa and repo.ui.configbool("merge", "followcopies", True):
157 elif pa and repo.ui.configbool("merge", "followcopies", True):
158 dirs = repo.ui.configbool("merge", "followdirs", True)
158 dirs = repo.ui.configbool("merge", "followdirs", True)
159 copy, diverge = copies.copies(repo, p1, p2, pa, dirs)
159 copy, diverge = copies.copies(repo, p1, p2, pa, dirs)
160 for of, fl in diverge.iteritems():
160 for of, fl in diverge.iteritems():
161 act("divergent renames", "dr", of, fl)
161 act("divergent renames", "dr", of, fl)
162
162
163 repo.ui.note(_("resolving manifests\n"))
163 repo.ui.note(_("resolving manifests\n"))
164 repo.ui.debug(" overwrite %s partial %s\n" % (overwrite, bool(partial)))
164 repo.ui.debug(" overwrite %s partial %s\n" % (overwrite, bool(partial)))
165 repo.ui.debug(" ancestor %s local %s remote %s\n" % (pa, p1, p2))
165 repo.ui.debug(" ancestor %s local %s remote %s\n" % (pa, p1, p2))
166
166
167 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
167 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
168 copied = set(copy.values())
168 copied = set(copy.values())
169
169
170 if '.hgsubstate' in m1:
170 if '.hgsubstate' in m1:
171 # check whether sub state is modified
171 # check whether sub state is modified
172 for s in p1.substate:
172 for s in p1.substate:
173 if p1.sub(s).dirty():
173 if p1.sub(s).dirty():
174 m1['.hgsubstate'] += "+"
174 m1['.hgsubstate'] += "+"
175 break
175 break
176
176
177 # Compare manifests
177 # Compare manifests
178 for f, n in m1.iteritems():
178 for f, n in m1.iteritems():
179 if partial and not partial(f):
179 if partial and not partial(f):
180 continue
180 continue
181 if f in m2:
181 if f in m2:
182 rflags = fmerge(f, f, f)
182 rflags = fmerge(f, f, f)
183 a = ma.get(f, nullid)
183 a = ma.get(f, nullid)
184 if n == m2[f] or m2[f] == a: # same or local newer
184 if n == m2[f] or m2[f] == a: # same or local newer
185 # is file locally modified or flags need changing?
185 # is file locally modified or flags need changing?
186 # dirstate flags may need to be made current
186 # dirstate flags may need to be made current
187 if m1.flags(f) != rflags or n[20:]:
187 if m1.flags(f) != rflags or n[20:]:
188 act("update permissions", "e", f, rflags)
188 act("update permissions", "e", f, rflags)
189 elif n == a: # remote newer
189 elif n == a: # remote newer
190 act("remote is newer", "g", f, rflags)
190 act("remote is newer", "g", f, rflags)
191 else: # both changed
191 else: # both changed
192 act("versions differ", "m", f, f, f, rflags, False)
192 act("versions differ", "m", f, f, f, rflags, False)
193 elif f in copied: # files we'll deal with on m2 side
193 elif f in copied: # files we'll deal with on m2 side
194 pass
194 pass
195 elif f in copy:
195 elif f in copy:
196 f2 = copy[f]
196 f2 = copy[f]
197 if f2 not in m2: # directory rename
197 if f2 not in m2: # directory rename
198 act("remote renamed directory to " + f2, "d",
198 act("remote renamed directory to " + f2, "d",
199 f, None, f2, m1.flags(f))
199 f, None, f2, m1.flags(f))
200 else: # case 2 A,B/B/B or case 4,21 A/B/B
200 else: # case 2 A,B/B/B or case 4,21 A/B/B
201 act("local copied/moved to " + f2, "m",
201 act("local copied/moved to " + f2, "m",
202 f, f2, f, fmerge(f, f2, f2), False)
202 f, f2, f, fmerge(f, f2, f2), False)
203 elif f in ma: # clean, a different, no remote
203 elif f in ma: # clean, a different, no remote
204 if n != ma[f]:
204 if n != ma[f]:
205 if repo.ui.promptchoice(
205 if repo.ui.promptchoice(
206 _(" local changed %s which remote deleted\n"
206 _(" local changed %s which remote deleted\n"
207 "use (c)hanged version or (d)elete?") % f,
207 "use (c)hanged version or (d)elete?") % f,
208 (_("&Changed"), _("&Delete")), 0):
208 (_("&Changed"), _("&Delete")), 0):
209 act("prompt delete", "r", f)
209 act("prompt delete", "r", f)
210 else:
210 else:
211 act("prompt keep", "a", f)
211 act("prompt keep", "a", f)
212 elif n[20:] == "a": # added, no remote
212 elif n[20:] == "a": # added, no remote
213 act("remote deleted", "f", f)
213 act("remote deleted", "f", f)
214 elif n[20:] != "u":
214 elif n[20:] != "u":
215 act("other deleted", "r", f)
215 act("other deleted", "r", f)
216
216
217 for f, n in m2.iteritems():
217 for f, n in m2.iteritems():
218 if partial and not partial(f):
218 if partial and not partial(f):
219 continue
219 continue
220 if f in m1 or f in copied: # files already visited
220 if f in m1 or f in copied: # files already visited
221 continue
221 continue
222 if f in copy:
222 if f in copy:
223 f2 = copy[f]
223 f2 = copy[f]
224 if f2 not in m1: # directory rename
224 if f2 not in m1: # directory rename
225 act("local renamed directory to " + f2, "d",
225 act("local renamed directory to " + f2, "d",
226 None, f, f2, m2.flags(f))
226 None, f, f2, m2.flags(f))
227 elif f2 in m2: # rename case 1, A/A,B/A
227 elif f2 in m2: # rename case 1, A/A,B/A
228 act("remote copied to " + f, "m",
228 act("remote copied to " + f, "m",
229 f2, f, f, fmerge(f2, f, f2), False)
229 f2, f, f, fmerge(f2, f, f2), False)
230 else: # case 3,20 A/B/A
230 else: # case 3,20 A/B/A
231 act("remote moved to " + f, "m",
231 act("remote moved to " + f, "m",
232 f2, f, f, fmerge(f2, f, f2), True)
232 f2, f, f, fmerge(f2, f, f2), True)
233 elif f not in ma:
233 elif f not in ma:
234 act("remote created", "g", f, m2.flags(f))
234 act("remote created", "g", f, m2.flags(f))
235 elif n != ma[f]:
235 elif n != ma[f]:
236 if repo.ui.promptchoice(
236 if repo.ui.promptchoice(
237 _("remote changed %s which local deleted\n"
237 _("remote changed %s which local deleted\n"
238 "use (c)hanged version or leave (d)eleted?") % f,
238 "use (c)hanged version or leave (d)eleted?") % f,
239 (_("&Changed"), _("&Deleted")), 0) == 0:
239 (_("&Changed"), _("&Deleted")), 0) == 0:
240 act("prompt recreating", "g", f, m2.flags(f))
240 act("prompt recreating", "g", f, m2.flags(f))
241
241
242 return action
242 return action
243
243
244 def actionkey(a):
244 def actionkey(a):
245 return a[1] == 'r' and -1 or 0, a
245 return a[1] == 'r' and -1 or 0, a
246
246
247 def applyupdates(repo, action, wctx, mctx, actx):
247 def applyupdates(repo, action, wctx, mctx, actx):
248 """apply the merge action list to the working directory
248 """apply the merge action list to the working directory
249
249
250 wctx is the working copy context
250 wctx is the working copy context
251 mctx is the context to be merged into the working copy
251 mctx is the context to be merged into the working copy
252 actx is the context of the common ancestor
252 actx is the context of the common ancestor
253 """
253 """
254
254
255 updated, merged, removed, unresolved = 0, 0, 0, 0
255 updated, merged, removed, unresolved = 0, 0, 0, 0
256 ms = mergestate(repo)
256 ms = mergestate(repo)
257 ms.reset(wctx.parents()[0].node())
257 ms.reset(wctx.parents()[0].node())
258 moves = []
258 moves = []
259 action.sort(key=actionkey)
259 action.sort(key=actionkey)
260 substate = wctx.substate # prime
260 substate = wctx.substate # prime
261
261
262 # prescan for merges
262 # prescan for merges
263 u = repo.ui
263 u = repo.ui
264 for a in action:
264 for a in action:
265 f, m = a[:2]
265 f, m = a[:2]
266 if m == 'm': # merge
266 if m == 'm': # merge
267 f2, fd, flags, move = a[2:]
267 f2, fd, flags, move = a[2:]
268 if f == '.hgsubstate': # merged internally
268 if f == '.hgsubstate': # merged internally
269 continue
269 continue
270 repo.ui.debug("preserving %s for resolve of %s\n" % (f, fd))
270 repo.ui.debug("preserving %s for resolve of %s\n" % (f, fd))
271 fcl = wctx[f]
271 fcl = wctx[f]
272 fco = mctx[f2]
272 fco = mctx[f2]
273 fca = fcl.ancestor(fco, actx) or repo.filectx(f, fileid=nullrev)
273 fca = fcl.ancestor(fco, actx) or repo.filectx(f, fileid=nullrev)
274 ms.add(fcl, fco, fca, fd, flags)
274 ms.add(fcl, fco, fca, fd, flags)
275 if f != fd and move:
275 if f != fd and move:
276 moves.append(f)
276 moves.append(f)
277
277
278 # remove renamed files after safely stored
278 # remove renamed files after safely stored
279 for f in moves:
279 for f in moves:
280 if util.lexists(repo.wjoin(f)):
280 if util.lexists(repo.wjoin(f)):
281 repo.ui.debug("removing %s\n" % f)
281 repo.ui.debug("removing %s\n" % f)
282 os.unlink(repo.wjoin(f))
282 os.unlink(repo.wjoin(f))
283
283
284 audit_path = util.path_auditor(repo.root)
284 audit_path = util.path_auditor(repo.root)
285
285
286 numupdates = len(action)
286 numupdates = len(action)
287 for i, a in enumerate(action):
287 for i, a in enumerate(action):
288 f, m = a[:2]
288 f, m = a[:2]
289 u.progress('update', i + 1, item=f, total=numupdates, unit='files')
289 u.progress(_('updating'), i + 1, item=f, total=numupdates, unit='files')
290 if f and f[0] == "/":
290 if f and f[0] == "/":
291 continue
291 continue
292 if m == "r": # remove
292 if m == "r": # remove
293 repo.ui.note(_("removing %s\n") % f)
293 repo.ui.note(_("removing %s\n") % f)
294 audit_path(f)
294 audit_path(f)
295 if f == '.hgsubstate': # subrepo states need updating
295 if f == '.hgsubstate': # subrepo states need updating
296 subrepo.submerge(repo, wctx, mctx, wctx)
296 subrepo.submerge(repo, wctx, mctx, wctx)
297 try:
297 try:
298 util.unlink(repo.wjoin(f))
298 util.unlink(repo.wjoin(f))
299 except OSError, inst:
299 except OSError, inst:
300 if inst.errno != errno.ENOENT:
300 if inst.errno != errno.ENOENT:
301 repo.ui.warn(_("update failed to remove %s: %s!\n") %
301 repo.ui.warn(_("update failed to remove %s: %s!\n") %
302 (f, inst.strerror))
302 (f, inst.strerror))
303 removed += 1
303 removed += 1
304 elif m == "m": # merge
304 elif m == "m": # merge
305 if f == '.hgsubstate': # subrepo states need updating
305 if f == '.hgsubstate': # subrepo states need updating
306 subrepo.submerge(repo, wctx, mctx, wctx.ancestor(mctx))
306 subrepo.submerge(repo, wctx, mctx, wctx.ancestor(mctx))
307 continue
307 continue
308 f2, fd, flags, move = a[2:]
308 f2, fd, flags, move = a[2:]
309 r = ms.resolve(fd, wctx, mctx)
309 r = ms.resolve(fd, wctx, mctx)
310 if r is not None and r > 0:
310 if r is not None and r > 0:
311 unresolved += 1
311 unresolved += 1
312 else:
312 else:
313 if r is None:
313 if r is None:
314 updated += 1
314 updated += 1
315 else:
315 else:
316 merged += 1
316 merged += 1
317 util.set_flags(repo.wjoin(fd), 'l' in flags, 'x' in flags)
317 util.set_flags(repo.wjoin(fd), 'l' in flags, 'x' in flags)
318 if f != fd and move and util.lexists(repo.wjoin(f)):
318 if f != fd and move and util.lexists(repo.wjoin(f)):
319 repo.ui.debug("removing %s\n" % f)
319 repo.ui.debug("removing %s\n" % f)
320 os.unlink(repo.wjoin(f))
320 os.unlink(repo.wjoin(f))
321 elif m == "g": # get
321 elif m == "g": # get
322 flags = a[2]
322 flags = a[2]
323 repo.ui.note(_("getting %s\n") % f)
323 repo.ui.note(_("getting %s\n") % f)
324 t = mctx.filectx(f).data()
324 t = mctx.filectx(f).data()
325 repo.wwrite(f, t, flags)
325 repo.wwrite(f, t, flags)
326 updated += 1
326 updated += 1
327 if f == '.hgsubstate': # subrepo states need updating
327 if f == '.hgsubstate': # subrepo states need updating
328 subrepo.submerge(repo, wctx, mctx, wctx)
328 subrepo.submerge(repo, wctx, mctx, wctx)
329 elif m == "d": # directory rename
329 elif m == "d": # directory rename
330 f2, fd, flags = a[2:]
330 f2, fd, flags = a[2:]
331 if f:
331 if f:
332 repo.ui.note(_("moving %s to %s\n") % (f, fd))
332 repo.ui.note(_("moving %s to %s\n") % (f, fd))
333 t = wctx.filectx(f).data()
333 t = wctx.filectx(f).data()
334 repo.wwrite(fd, t, flags)
334 repo.wwrite(fd, t, flags)
335 util.unlink(repo.wjoin(f))
335 util.unlink(repo.wjoin(f))
336 if f2:
336 if f2:
337 repo.ui.note(_("getting %s to %s\n") % (f2, fd))
337 repo.ui.note(_("getting %s to %s\n") % (f2, fd))
338 t = mctx.filectx(f2).data()
338 t = mctx.filectx(f2).data()
339 repo.wwrite(fd, t, flags)
339 repo.wwrite(fd, t, flags)
340 updated += 1
340 updated += 1
341 elif m == "dr": # divergent renames
341 elif m == "dr": # divergent renames
342 fl = a[2]
342 fl = a[2]
343 repo.ui.warn(_("warning: detected divergent renames of %s to:\n") % f)
343 repo.ui.warn(_("warning: detected divergent renames of %s to:\n") % f)
344 for nf in fl:
344 for nf in fl:
345 repo.ui.warn(" %s\n" % nf)
345 repo.ui.warn(" %s\n" % nf)
346 elif m == "e": # exec
346 elif m == "e": # exec
347 flags = a[2]
347 flags = a[2]
348 util.set_flags(repo.wjoin(f), 'l' in flags, 'x' in flags)
348 util.set_flags(repo.wjoin(f), 'l' in flags, 'x' in flags)
349 u.progress('update', None, total=numupdates, unit='files')
349 u.progress(_('updating'), None, total=numupdates, unit='files')
350
350
351 return updated, merged, removed, unresolved
351 return updated, merged, removed, unresolved
352
352
353 def recordupdates(repo, action, branchmerge):
353 def recordupdates(repo, action, branchmerge):
354 "record merge actions to the dirstate"
354 "record merge actions to the dirstate"
355
355
356 for a in action:
356 for a in action:
357 f, m = a[:2]
357 f, m = a[:2]
358 if m == "r": # remove
358 if m == "r": # remove
359 if branchmerge:
359 if branchmerge:
360 repo.dirstate.remove(f)
360 repo.dirstate.remove(f)
361 else:
361 else:
362 repo.dirstate.forget(f)
362 repo.dirstate.forget(f)
363 elif m == "a": # re-add
363 elif m == "a": # re-add
364 if not branchmerge:
364 if not branchmerge:
365 repo.dirstate.add(f)
365 repo.dirstate.add(f)
366 elif m == "f": # forget
366 elif m == "f": # forget
367 repo.dirstate.forget(f)
367 repo.dirstate.forget(f)
368 elif m == "e": # exec change
368 elif m == "e": # exec change
369 repo.dirstate.normallookup(f)
369 repo.dirstate.normallookup(f)
370 elif m == "g": # get
370 elif m == "g": # get
371 if branchmerge:
371 if branchmerge:
372 repo.dirstate.otherparent(f)
372 repo.dirstate.otherparent(f)
373 else:
373 else:
374 repo.dirstate.normal(f)
374 repo.dirstate.normal(f)
375 elif m == "m": # merge
375 elif m == "m": # merge
376 f2, fd, flag, move = a[2:]
376 f2, fd, flag, move = a[2:]
377 if branchmerge:
377 if branchmerge:
378 # We've done a branch merge, mark this file as merged
378 # We've done a branch merge, mark this file as merged
379 # so that we properly record the merger later
379 # so that we properly record the merger later
380 repo.dirstate.merge(fd)
380 repo.dirstate.merge(fd)
381 if f != f2: # copy/rename
381 if f != f2: # copy/rename
382 if move:
382 if move:
383 repo.dirstate.remove(f)
383 repo.dirstate.remove(f)
384 if f != fd:
384 if f != fd:
385 repo.dirstate.copy(f, fd)
385 repo.dirstate.copy(f, fd)
386 else:
386 else:
387 repo.dirstate.copy(f2, fd)
387 repo.dirstate.copy(f2, fd)
388 else:
388 else:
389 # We've update-merged a locally modified file, so
389 # We've update-merged a locally modified file, so
390 # we set the dirstate to emulate a normal checkout
390 # we set the dirstate to emulate a normal checkout
391 # of that file some time in the past. Thus our
391 # of that file some time in the past. Thus our
392 # merge will appear as a normal local file
392 # merge will appear as a normal local file
393 # modification.
393 # modification.
394 if f2 == fd: # file not locally copied/moved
394 if f2 == fd: # file not locally copied/moved
395 repo.dirstate.normallookup(fd)
395 repo.dirstate.normallookup(fd)
396 if move:
396 if move:
397 repo.dirstate.forget(f)
397 repo.dirstate.forget(f)
398 elif m == "d": # directory rename
398 elif m == "d": # directory rename
399 f2, fd, flag = a[2:]
399 f2, fd, flag = a[2:]
400 if not f2 and f not in repo.dirstate:
400 if not f2 and f not in repo.dirstate:
401 # untracked file moved
401 # untracked file moved
402 continue
402 continue
403 if branchmerge:
403 if branchmerge:
404 repo.dirstate.add(fd)
404 repo.dirstate.add(fd)
405 if f:
405 if f:
406 repo.dirstate.remove(f)
406 repo.dirstate.remove(f)
407 repo.dirstate.copy(f, fd)
407 repo.dirstate.copy(f, fd)
408 if f2:
408 if f2:
409 repo.dirstate.copy(f2, fd)
409 repo.dirstate.copy(f2, fd)
410 else:
410 else:
411 repo.dirstate.normal(fd)
411 repo.dirstate.normal(fd)
412 if f:
412 if f:
413 repo.dirstate.forget(f)
413 repo.dirstate.forget(f)
414
414
415 def update(repo, node, branchmerge, force, partial):
415 def update(repo, node, branchmerge, force, partial):
416 """
416 """
417 Perform a merge between the working directory and the given node
417 Perform a merge between the working directory and the given node
418
418
419 node = the node to update to, or None if unspecified
419 node = the node to update to, or None if unspecified
420 branchmerge = whether to merge between branches
420 branchmerge = whether to merge between branches
421 force = whether to force branch merging or file overwriting
421 force = whether to force branch merging or file overwriting
422 partial = a function to filter file lists (dirstate not updated)
422 partial = a function to filter file lists (dirstate not updated)
423
423
424 The table below shows all the behaviors of the update command
424 The table below shows all the behaviors of the update command
425 given the -c and -C or no options, whether the working directory
425 given the -c and -C or no options, whether the working directory
426 is dirty, whether a revision is specified, and the relationship of
426 is dirty, whether a revision is specified, and the relationship of
427 the parent rev to the target rev (linear, on the same named
427 the parent rev to the target rev (linear, on the same named
428 branch, or on another named branch).
428 branch, or on another named branch).
429
429
430 This logic is tested by test-update-branches.
430 This logic is tested by test-update-branches.
431
431
432 -c -C dirty rev | linear same cross
432 -c -C dirty rev | linear same cross
433 n n n n | ok (1) x
433 n n n n | ok (1) x
434 n n n y | ok ok ok
434 n n n y | ok ok ok
435 n n y * | merge (2) (2)
435 n n y * | merge (2) (2)
436 n y * * | --- discard ---
436 n y * * | --- discard ---
437 y n y * | --- (3) ---
437 y n y * | --- (3) ---
438 y n n * | --- ok ---
438 y n n * | --- ok ---
439 y y * * | --- (4) ---
439 y y * * | --- (4) ---
440
440
441 x = can't happen
441 x = can't happen
442 * = don't-care
442 * = don't-care
443 1 = abort: crosses branches (use 'hg merge' or 'hg update -c')
443 1 = abort: crosses branches (use 'hg merge' or 'hg update -c')
444 2 = abort: crosses branches (use 'hg merge' to merge or
444 2 = abort: crosses branches (use 'hg merge' to merge or
445 use 'hg update -C' to discard changes)
445 use 'hg update -C' to discard changes)
446 3 = abort: uncommitted local changes
446 3 = abort: uncommitted local changes
447 4 = incompatible options (checked in commands.py)
447 4 = incompatible options (checked in commands.py)
448 """
448 """
449
449
450 onode = node
450 onode = node
451 wlock = repo.wlock()
451 wlock = repo.wlock()
452 try:
452 try:
453 wc = repo[None]
453 wc = repo[None]
454 if node is None:
454 if node is None:
455 # tip of current branch
455 # tip of current branch
456 try:
456 try:
457 node = repo.branchtags()[wc.branch()]
457 node = repo.branchtags()[wc.branch()]
458 except KeyError:
458 except KeyError:
459 if wc.branch() == "default": # no default branch!
459 if wc.branch() == "default": # no default branch!
460 node = repo.lookup("tip") # update to tip
460 node = repo.lookup("tip") # update to tip
461 else:
461 else:
462 raise util.Abort(_("branch %s not found") % wc.branch())
462 raise util.Abort(_("branch %s not found") % wc.branch())
463 overwrite = force and not branchmerge
463 overwrite = force and not branchmerge
464 pl = wc.parents()
464 pl = wc.parents()
465 p1, p2 = pl[0], repo[node]
465 p1, p2 = pl[0], repo[node]
466 pa = p1.ancestor(p2)
466 pa = p1.ancestor(p2)
467 fp1, fp2, xp1, xp2 = p1.node(), p2.node(), str(p1), str(p2)
467 fp1, fp2, xp1, xp2 = p1.node(), p2.node(), str(p1), str(p2)
468 fastforward = False
468 fastforward = False
469
469
470 ### check phase
470 ### check phase
471 if not overwrite and len(pl) > 1:
471 if not overwrite and len(pl) > 1:
472 raise util.Abort(_("outstanding uncommitted merges"))
472 raise util.Abort(_("outstanding uncommitted merges"))
473 if branchmerge:
473 if branchmerge:
474 if pa == p2:
474 if pa == p2:
475 raise util.Abort(_("merging with a working directory ancestor"
475 raise util.Abort(_("merging with a working directory ancestor"
476 " has no effect"))
476 " has no effect"))
477 elif pa == p1:
477 elif pa == p1:
478 if p1.branch() != p2.branch():
478 if p1.branch() != p2.branch():
479 fastforward = True
479 fastforward = True
480 else:
480 else:
481 raise util.Abort(_("nothing to merge (use 'hg update'"
481 raise util.Abort(_("nothing to merge (use 'hg update'"
482 " or check 'hg heads')"))
482 " or check 'hg heads')"))
483 if not force and (wc.files() or wc.deleted()):
483 if not force and (wc.files() or wc.deleted()):
484 raise util.Abort(_("outstanding uncommitted changes "
484 raise util.Abort(_("outstanding uncommitted changes "
485 "(use 'hg status' to list changes)"))
485 "(use 'hg status' to list changes)"))
486 elif not overwrite:
486 elif not overwrite:
487 if pa == p1 or pa == p2: # linear
487 if pa == p1 or pa == p2: # linear
488 pass # all good
488 pass # all good
489 elif wc.files() or wc.deleted():
489 elif wc.files() or wc.deleted():
490 raise util.Abort(_("crosses branches (use 'hg merge' to merge "
490 raise util.Abort(_("crosses branches (use 'hg merge' to merge "
491 "or use 'hg update -C' to discard changes)"))
491 "or use 'hg update -C' to discard changes)"))
492 elif onode is None:
492 elif onode is None:
493 raise util.Abort(_("crosses branches (use 'hg merge' or use "
493 raise util.Abort(_("crosses branches (use 'hg merge' or use "
494 "'hg update -c')"))
494 "'hg update -c')"))
495 else:
495 else:
496 # Allow jumping branches if clean and specific rev given
496 # Allow jumping branches if clean and specific rev given
497 overwrite = True
497 overwrite = True
498
498
499 ### calculate phase
499 ### calculate phase
500 action = []
500 action = []
501 wc.status(unknown=True) # prime cache
501 wc.status(unknown=True) # prime cache
502 if not force:
502 if not force:
503 _checkunknown(wc, p2)
503 _checkunknown(wc, p2)
504 if not util.checkcase(repo.path):
504 if not util.checkcase(repo.path):
505 _checkcollision(p2)
505 _checkcollision(p2)
506 action += _forgetremoved(wc, p2, branchmerge)
506 action += _forgetremoved(wc, p2, branchmerge)
507 action += manifestmerge(repo, wc, p2, pa, overwrite, partial)
507 action += manifestmerge(repo, wc, p2, pa, overwrite, partial)
508
508
509 ### apply phase
509 ### apply phase
510 if not branchmerge: # just jump to the new rev
510 if not branchmerge: # just jump to the new rev
511 fp1, fp2, xp1, xp2 = fp2, nullid, xp2, ''
511 fp1, fp2, xp1, xp2 = fp2, nullid, xp2, ''
512 if not partial:
512 if not partial:
513 repo.hook('preupdate', throw=True, parent1=xp1, parent2=xp2)
513 repo.hook('preupdate', throw=True, parent1=xp1, parent2=xp2)
514
514
515 stats = applyupdates(repo, action, wc, p2, pa)
515 stats = applyupdates(repo, action, wc, p2, pa)
516
516
517 if not partial:
517 if not partial:
518 repo.dirstate.setparents(fp1, fp2)
518 repo.dirstate.setparents(fp1, fp2)
519 recordupdates(repo, action, branchmerge)
519 recordupdates(repo, action, branchmerge)
520 if not branchmerge and not fastforward:
520 if not branchmerge and not fastforward:
521 repo.dirstate.setbranch(p2.branch())
521 repo.dirstate.setbranch(p2.branch())
522 finally:
522 finally:
523 wlock.release()
523 wlock.release()
524
524
525 if not partial:
525 if not partial:
526 repo.hook('update', parent1=xp1, parent2=xp2, error=stats[3])
526 repo.hook('update', parent1=xp1, parent2=xp2, error=stats[3])
527 return stats
527 return stats
@@ -1,66 +1,72 b''
1 #!/bin/sh
1 #!/bin/sh
2
2
3 cat >> $HGRCPATH <<EOF
3 cat >> $HGRCPATH <<EOF
4 [alias]
4 [alias]
5 myinit = init
5 myinit = init
6 cleanstatus = status -c
6 cleanstatus = status -c
7 unknown = bargle
7 unknown = bargle
8 ambiguous = s
8 ambiguous = s
9 recursive = recursive
9 recursive = recursive
10 nodefinition =
10 nodefinition =
11 mylog = log
11 mylog = log
12 lognull = log -r null
12 lognull = log -r null
13 shortlog = log --template '{rev} {node|short} | {date|isodate}\n'
13 shortlog = log --template '{rev} {node|short} | {date|isodate}\n'
14 dln = lognull --debug
14 dln = lognull --debug
15 nousage = rollback
15 nousage = rollback
16 put = export -r 0 -o "\$FOO/%R.diff"
16 put = export -r 0 -o "\$FOO/%R.diff"
17 rt = root
17
18
18 [defaults]
19 [defaults]
19 mylog = -q
20 mylog = -q
20 lognull = -q
21 lognull = -q
21 log = -v
22 log = -v
22 EOF
23 EOF
23
24
24 echo '% basic'
25 echo '% basic'
25 hg myinit alias
26 hg myinit alias
26
27
27 echo '% unknown'
28 echo '% unknown'
28 hg unknown
29 hg unknown
29 hg help unknown
30 hg help unknown
30
31
31 echo '% ambiguous'
32 echo '% ambiguous'
32 hg ambiguous
33 hg ambiguous
33 hg help ambiguous
34 hg help ambiguous
34
35
35 echo '% recursive'
36 echo '% recursive'
36 hg recursive
37 hg recursive
37 hg help recursive
38 hg help recursive
38
39
39 echo '% no definition'
40 echo '% no definition'
40 hg nodef
41 hg nodef
41 hg help nodef
42 hg help nodef
42
43
43 cd alias
44 cd alias
44
45
45 echo '% no usage'
46 echo '% no usage'
46 hg nousage
47 hg nousage
47
48
48 echo foo > foo
49 echo foo > foo
49 hg ci -Amfoo
50 hg ci -Amfoo
50
51
51 echo '% with opts'
52 echo '% with opts'
52 hg cleanst
53 hg cleanst
53
54
54 echo '% with opts and whitespace'
55 echo '% with opts and whitespace'
55 hg shortlog
56 hg shortlog
56
57
57 echo '% interaction with defaults'
58 echo '% interaction with defaults'
58 hg mylog
59 hg mylog
59 hg lognull
60 hg lognull
60
61
61 echo '% properly recursive'
62 echo '% properly recursive'
62 hg dln
63 hg dln
63
64
64 echo '% path expanding'
65 echo '% path expanding'
65 FOO=`pwd` hg put
66 FOO=`pwd` hg put
66 cat 0.diff
67 cat 0.diff
68
69 echo '% invalid arguments'
70 hg rt foo
71
72 exit 0
@@ -1,45 +1,58 b''
1 % basic
1 % basic
2 % unknown
2 % unknown
3 alias 'unknown' resolves to unknown command 'bargle'
3 alias 'unknown' resolves to unknown command 'bargle'
4 alias 'unknown' resolves to unknown command 'bargle'
4 alias 'unknown' resolves to unknown command 'bargle'
5 % ambiguous
5 % ambiguous
6 alias 'ambiguous' resolves to ambiguous command 's'
6 alias 'ambiguous' resolves to ambiguous command 's'
7 alias 'ambiguous' resolves to ambiguous command 's'
7 alias 'ambiguous' resolves to ambiguous command 's'
8 % recursive
8 % recursive
9 alias 'recursive' resolves to unknown command 'recursive'
9 alias 'recursive' resolves to unknown command 'recursive'
10 alias 'recursive' resolves to unknown command 'recursive'
10 alias 'recursive' resolves to unknown command 'recursive'
11 % no definition
11 % no definition
12 no definition for alias 'nodefinition'
12 no definition for alias 'nodefinition'
13 no definition for alias 'nodefinition'
13 no definition for alias 'nodefinition'
14 % no usage
14 % no usage
15 no rollback information available
15 no rollback information available
16 adding foo
16 adding foo
17 % with opts
17 % with opts
18 C foo
18 C foo
19 % with opts and whitespace
19 % with opts and whitespace
20 0 e63c23eaa88a | 1970-01-01 00:00 +0000
20 0 e63c23eaa88a | 1970-01-01 00:00 +0000
21 % interaction with defaults
21 % interaction with defaults
22 0:e63c23eaa88a
22 0:e63c23eaa88a
23 -1:000000000000
23 -1:000000000000
24 % properly recursive
24 % properly recursive
25 changeset: -1:0000000000000000000000000000000000000000
25 changeset: -1:0000000000000000000000000000000000000000
26 parent: -1:0000000000000000000000000000000000000000
26 parent: -1:0000000000000000000000000000000000000000
27 parent: -1:0000000000000000000000000000000000000000
27 parent: -1:0000000000000000000000000000000000000000
28 manifest: -1:0000000000000000000000000000000000000000
28 manifest: -1:0000000000000000000000000000000000000000
29 user:
29 user:
30 date: Thu Jan 01 00:00:00 1970 +0000
30 date: Thu Jan 01 00:00:00 1970 +0000
31 extra: branch=default
31 extra: branch=default
32
32
33 % path expanding
33 % path expanding
34 # HG changeset patch
34 # HG changeset patch
35 # User test
35 # User test
36 # Date 0 0
36 # Date 0 0
37 # Node ID e63c23eaa88ae77967edcf4ea194d31167c478b0
37 # Node ID e63c23eaa88ae77967edcf4ea194d31167c478b0
38 # Parent 0000000000000000000000000000000000000000
38 # Parent 0000000000000000000000000000000000000000
39 foo
39 foo
40
40
41 diff -r 000000000000 -r e63c23eaa88a foo
41 diff -r 000000000000 -r e63c23eaa88a foo
42 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
42 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
43 +++ b/foo Thu Jan 01 00:00:00 1970 +0000
43 +++ b/foo Thu Jan 01 00:00:00 1970 +0000
44 @@ -0,0 +1,1 @@
44 @@ -0,0 +1,1 @@
45 +foo
45 +foo
46 % invalid arguments
47 hg rt: invalid arguments
48 hg rt
49
50 alias for: hg root
51
52 print the root (top) of the current working directory
53
54 Print the root directory of the current repository.
55
56 Returns 0 on success.
57
58 use "hg -v help rt" to show global options
@@ -1,103 +1,106 b''
1 #!/bin/sh
1 #!/bin/sh
2
2
3 echo "[extensions]" >> $HGRCPATH
3 echo "[extensions]" >> $HGRCPATH
4 echo "bookmarks=" >> $HGRCPATH
4 echo "bookmarks=" >> $HGRCPATH
5
5
6 hg init
6 hg init
7
7
8 echo % no bookmarks
8 echo % no bookmarks
9 hg bookmarks
9 hg bookmarks
10
10
11 echo % bookmark rev -1
11 echo % bookmark rev -1
12 hg bookmark X
12 hg bookmark X
13
13
14 echo % list bookmarks
14 echo % list bookmarks
15 hg bookmarks
15 hg bookmarks
16
16
17 echo % list bookmarks with color
17 echo % list bookmarks with color
18 hg --config extensions.color= --config color.mode=ansi \
18 hg --config extensions.color= --config color.mode=ansi \
19 bookmarks --color=always
19 bookmarks --color=always
20
20
21 echo a > a
21 echo a > a
22 hg add a
22 hg add a
23 hg commit -m 0
23 hg commit -m 0
24
24
25 echo % bookmark X moved to rev 0
25 echo % bookmark X moved to rev 0
26 hg bookmarks
26 hg bookmarks
27
27
28 echo % look up bookmark
28 echo % look up bookmark
29 hg log -r X
29 hg log -r X
30
30
31 echo % second bookmark for rev 0
31 echo % second bookmark for rev 0
32 hg bookmark X2
32 hg bookmark X2
33
33
34 echo % bookmark rev -1 again
34 echo % bookmark rev -1 again
35 hg bookmark -r null Y
35 hg bookmark -r null Y
36
36
37 echo % list bookmarks
37 echo % list bookmarks
38 hg bookmarks
38 hg bookmarks
39
39
40 echo b > b
40 echo b > b
41 hg add b
41 hg add b
42 hg commit -m 1
42 hg commit -m 1
43
43
44 echo % bookmarks X and X2 moved to rev 1, Y at rev -1
44 echo % bookmarks X and X2 moved to rev 1, Y at rev -1
45 hg bookmarks
45 hg bookmarks
46
46
47 echo % bookmark rev 0 again
47 echo % bookmark rev 0 again
48 hg bookmark -r 0 Z
48 hg bookmark -r 0 Z
49
49
50 echo c > c
50 echo c > c
51 hg add c
51 hg add c
52 hg commit -m 2
52 hg commit -m 2
53
53
54 echo % bookmarks X and X2 moved to rev 2, Y at rev -1, Z at rev 0
54 echo % bookmarks X and X2 moved to rev 2, Y at rev -1, Z at rev 0
55 hg bookmarks
55 hg bookmarks
56
56
57 echo % rename nonexistent bookmark
57 echo % rename nonexistent bookmark
58 hg bookmark -m A B
58 hg bookmark -m A B
59
59
60 echo % rename to existent bookmark
60 echo % rename to existent bookmark
61 hg bookmark -m X Y
61 hg bookmark -m X Y
62
62
63 echo % force rename to existent bookmark
63 echo % force rename to existent bookmark
64 hg bookmark -f -m X Y
64 hg bookmark -f -m X Y
65
65
66 echo % list bookmarks
66 echo % list bookmarks
67 hg bookmark
67 hg bookmark
68
68
69 echo % rename without new name
69 echo % rename without new name
70 hg bookmark -m Y
70 hg bookmark -m Y
71
71
72 echo % delete without name
72 echo % delete without name
73 hg bookmark -d
73 hg bookmark -d
74
74
75 echo % delete nonexistent bookmark
75 echo % delete nonexistent bookmark
76 hg bookmark -d A
76 hg bookmark -d A
77
77
78 echo % bookmark name with spaces should be stripped
78 echo % bookmark name with spaces should be stripped
79 hg bookmark ' x y '
79 hg bookmark ' x y '
80
80
81 echo % list bookmarks
81 echo % list bookmarks
82 hg bookmarks
82 hg bookmarks
83
83
84 echo % look up stripped bookmark name
84 echo % look up stripped bookmark name
85 hg log -r '"x y"'
85 hg log -r '"x y"'
86
86
87 echo % reject bookmark name with newline
87 echo % reject bookmark name with newline
88 hg bookmark '
88 hg bookmark '
89 '
89 '
90
90
91 echo % bookmark with existing name
91 echo % bookmark with existing name
92 hg bookmark Z
92 hg bookmark Z
93
93
94 echo % force bookmark with existing name
94 echo % force bookmark with existing name
95 hg bookmark -f Z
95 hg bookmark -f Z
96
96
97 echo % list bookmarks
97 echo % list bookmarks
98 hg bookmark
98 hg bookmark
99
99
100 echo % revision but no bookmark name
100 echo % revision but no bookmark name
101 hg bookmark -r .
101 hg bookmark -r .
102
102
103 echo % bookmark name with whitespace only
104 hg bookmark ' '
105
103 true
106 true
@@ -1,76 +1,78 b''
1 % no bookmarks
1 % no bookmarks
2 no bookmarks set
2 no bookmarks set
3 % bookmark rev -1
3 % bookmark rev -1
4 % list bookmarks
4 % list bookmarks
5 * X -1:000000000000
5 * X -1:000000000000
6 % list bookmarks with color
6 % list bookmarks with color
7  * X -1:000000000000
7  * X -1:000000000000
8 % bookmark X moved to rev 0
8 % bookmark X moved to rev 0
9 * X 0:f7b1eb17ad24
9 * X 0:f7b1eb17ad24
10 % look up bookmark
10 % look up bookmark
11 changeset: 0:f7b1eb17ad24
11 changeset: 0:f7b1eb17ad24
12 tag: X
12 tag: X
13 tag: tip
13 tag: tip
14 user: test
14 user: test
15 date: Thu Jan 01 00:00:00 1970 +0000
15 date: Thu Jan 01 00:00:00 1970 +0000
16 summary: 0
16 summary: 0
17
17
18 % second bookmark for rev 0
18 % second bookmark for rev 0
19 % bookmark rev -1 again
19 % bookmark rev -1 again
20 % list bookmarks
20 % list bookmarks
21 * X2 0:f7b1eb17ad24
21 * X2 0:f7b1eb17ad24
22 * X 0:f7b1eb17ad24
22 * X 0:f7b1eb17ad24
23 Y -1:000000000000
23 Y -1:000000000000
24 % bookmarks X and X2 moved to rev 1, Y at rev -1
24 % bookmarks X and X2 moved to rev 1, Y at rev -1
25 * X2 1:925d80f479bb
25 * X2 1:925d80f479bb
26 * X 1:925d80f479bb
26 * X 1:925d80f479bb
27 Y -1:000000000000
27 Y -1:000000000000
28 % bookmark rev 0 again
28 % bookmark rev 0 again
29 % bookmarks X and X2 moved to rev 2, Y at rev -1, Z at rev 0
29 % bookmarks X and X2 moved to rev 2, Y at rev -1, Z at rev 0
30 * X2 2:0316ce92851d
30 * X2 2:0316ce92851d
31 * X 2:0316ce92851d
31 * X 2:0316ce92851d
32 Z 0:f7b1eb17ad24
32 Z 0:f7b1eb17ad24
33 Y -1:000000000000
33 Y -1:000000000000
34 % rename nonexistent bookmark
34 % rename nonexistent bookmark
35 abort: a bookmark of this name does not exist
35 abort: a bookmark of this name does not exist
36 % rename to existent bookmark
36 % rename to existent bookmark
37 abort: a bookmark of the same name already exists
37 abort: a bookmark of the same name already exists
38 % force rename to existent bookmark
38 % force rename to existent bookmark
39 % list bookmarks
39 % list bookmarks
40 * X2 2:0316ce92851d
40 * X2 2:0316ce92851d
41 * Y 2:0316ce92851d
41 * Y 2:0316ce92851d
42 Z 0:f7b1eb17ad24
42 Z 0:f7b1eb17ad24
43 % rename without new name
43 % rename without new name
44 abort: new bookmark name required
44 abort: new bookmark name required
45 % delete without name
45 % delete without name
46 abort: bookmark name required
46 abort: bookmark name required
47 % delete nonexistent bookmark
47 % delete nonexistent bookmark
48 abort: a bookmark of this name does not exist
48 abort: a bookmark of this name does not exist
49 % bookmark name with spaces should be stripped
49 % bookmark name with spaces should be stripped
50 % list bookmarks
50 % list bookmarks
51 * X2 2:0316ce92851d
51 * X2 2:0316ce92851d
52 * Y 2:0316ce92851d
52 * Y 2:0316ce92851d
53 Z 0:f7b1eb17ad24
53 Z 0:f7b1eb17ad24
54 * x y 2:0316ce92851d
54 * x y 2:0316ce92851d
55 % look up stripped bookmark name
55 % look up stripped bookmark name
56 changeset: 2:0316ce92851d
56 changeset: 2:0316ce92851d
57 tag: X2
57 tag: X2
58 tag: Y
58 tag: Y
59 tag: tip
59 tag: tip
60 tag: x y
60 tag: x y
61 user: test
61 user: test
62 date: Thu Jan 01 00:00:00 1970 +0000
62 date: Thu Jan 01 00:00:00 1970 +0000
63 summary: 2
63 summary: 2
64
64
65 % reject bookmark name with newline
65 % reject bookmark name with newline
66 abort: bookmark name cannot contain newlines
66 abort: bookmark name cannot contain newlines
67 % bookmark with existing name
67 % bookmark with existing name
68 abort: a bookmark of the same name already exists
68 abort: a bookmark of the same name already exists
69 % force bookmark with existing name
69 % force bookmark with existing name
70 % list bookmarks
70 % list bookmarks
71 * X2 2:0316ce92851d
71 * X2 2:0316ce92851d
72 * Y 2:0316ce92851d
72 * Y 2:0316ce92851d
73 * Z 2:0316ce92851d
73 * Z 2:0316ce92851d
74 * x y 2:0316ce92851d
74 * x y 2:0316ce92851d
75 % revision but no bookmark name
75 % revision but no bookmark name
76 abort: bookmark name required
76 abort: bookmark name required
77 % bookmark name with whitespace only
78 abort: bookmark names cannot consist entirely of whitespace
@@ -1,37 +1,37 b''
1 1 files updated, 0 files merged, 2 files removed, 0 files unresolved
1 1 files updated, 0 files merged, 2 files removed, 0 files unresolved
2 searching for copies back to rev 1
2 searching for copies back to rev 1
3 unmatched files in other:
3 unmatched files in other:
4 b
4 b
5 c
5 c
6 all copies found (* = to merge, ! = divergent):
6 all copies found (* = to merge, ! = divergent):
7 c -> a *
7 c -> a *
8 b -> a *
8 b -> a *
9 checking for directory renames
9 checking for directory renames
10 resolving manifests
10 resolving manifests
11 overwrite None partial False
11 overwrite None partial False
12 ancestor 583c7b748052 local fb3948d97f07+ remote 7f1309517659
12 ancestor 583c7b748052 local fb3948d97f07+ remote 7f1309517659
13 a: remote moved to c -> m
13 a: remote moved to c -> m
14 a: remote moved to b -> m
14 a: remote moved to b -> m
15 preserving a for resolve of b
15 preserving a for resolve of b
16 preserving a for resolve of c
16 preserving a for resolve of c
17 removing a
17 removing a
18 update: a 1/2 files (50.00%)
18 updating: a 1/2 files (50.00%)
19 picked tool 'internal:merge' for b (binary False symlink False)
19 picked tool 'internal:merge' for b (binary False symlink False)
20 merging a and b to b
20 merging a and b to b
21 my b@fb3948d97f07+ other b@7f1309517659 ancestor a@583c7b748052
21 my b@fb3948d97f07+ other b@7f1309517659 ancestor a@583c7b748052
22 premerge successful
22 premerge successful
23 update: a 2/2 files (100.00%)
23 updating: a 2/2 files (100.00%)
24 picked tool 'internal:merge' for c (binary False symlink False)
24 picked tool 'internal:merge' for c (binary False symlink False)
25 merging a and c to c
25 merging a and c to c
26 my c@fb3948d97f07+ other c@7f1309517659 ancestor a@583c7b748052
26 my c@fb3948d97f07+ other c@7f1309517659 ancestor a@583c7b748052
27 premerge successful
27 premerge successful
28 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
28 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
29 (branch merge, don't forget to commit)
29 (branch merge, don't forget to commit)
30 -- b --
30 -- b --
31 0
31 0
32 1
32 1
33 2
33 2
34 -- c --
34 -- c --
35 0
35 0
36 1
36 1
37 2
37 2
@@ -1,27 +1,33 b''
1 #!/bin/sh
1 #!/bin/sh
2 # test command parsing and dispatch
2 # test command parsing and dispatch
3
3
4 "$TESTDIR/hghave" no-outer-repo || exit 80
4 "$TESTDIR/hghave" no-outer-repo || exit 80
5
5
6 dir=`pwd`
7
6 hg init a
8 hg init a
7 cd a
9 cd a
8 echo a > a
10 echo a > a
9 hg ci -Ama
11 hg ci -Ama
10
12
11 echo "# missing arg"
13 echo "# missing arg"
12 hg cat
14 hg cat
13
15
14 echo '% [defaults]'
16 echo '% [defaults]'
15 hg cat a
17 hg cat a
16 cat >> $HGRCPATH <<EOF
18 cat >> $HGRCPATH <<EOF
17 [defaults]
19 [defaults]
18 cat = -r null
20 cat = -r null
19 EOF
21 EOF
20 hg cat a
22 hg cat a
21
23
24 echo '% working directory removed'
25 rm -rf $dir/a
26 hg --version
27
22 echo '% no repo'
28 echo '% no repo'
23 cd ..
29 cd $dir
24 hg cat
30 hg cat
25
31
26 exit 0
32 exit 0
27
33
@@ -1,37 +1,39 b''
1 adding a
1 adding a
2 # missing arg
2 # missing arg
3 hg cat: invalid arguments
3 hg cat: invalid arguments
4 hg cat [OPTION]... FILE...
4 hg cat [OPTION]... FILE...
5
5
6 output the current or given revision of files
6 output the current or given revision of files
7
7
8 Print the specified files as they were at the given revision. If no
8 Print the specified files as they were at the given revision. If no
9 revision is given, the parent of the working directory is used, or tip if
9 revision is given, the parent of the working directory is used, or tip if
10 no revision is checked out.
10 no revision is checked out.
11
11
12 Output may be to a file, in which case the name of the file is given using
12 Output may be to a file, in which case the name of the file is given using
13 a format string. The formatting rules are the same as for the export
13 a format string. The formatting rules are the same as for the export
14 command, with the following additions:
14 command, with the following additions:
15
15
16 "%s" basename of file being printed
16 "%s" basename of file being printed
17 "%d" dirname of file being printed, or '.' if in repository root
17 "%d" dirname of file being printed, or '.' if in repository root
18 "%p" root-relative path name of file being printed
18 "%p" root-relative path name of file being printed
19
19
20 Returns 0 on success.
20 Returns 0 on success.
21
21
22 options:
22 options:
23
23
24 -o --output FORMAT print output to file with formatted name
24 -o --output FORMAT print output to file with formatted name
25 -r --rev REV print the given revision
25 -r --rev REV print the given revision
26 --decode apply any matching decode filter
26 --decode apply any matching decode filter
27 -I --include PATTERN [+] include names matching the given patterns
27 -I --include PATTERN [+] include names matching the given patterns
28 -X --exclude PATTERN [+] exclude names matching the given patterns
28 -X --exclude PATTERN [+] exclude names matching the given patterns
29
29
30 [+] marked option can be specified multiple times
30 [+] marked option can be specified multiple times
31
31
32 use "hg -v help cat" to show global options
32 use "hg -v help cat" to show global options
33 % [defaults]
33 % [defaults]
34 a
34 a
35 a: No such file in rev 000000000000
35 a: No such file in rev 000000000000
36 % working directory removed
37 abort: error getting current working directory: No such file or directory
36 % no repo
38 % no repo
37 abort: There is no Mercurial repository here (.hg not found)!
39 abort: There is no Mercurial repository here (.hg not found)!
@@ -1,39 +1,39 b''
1 created new head
1 created new head
2 changeset: 1:d9da848d0adf
2 changeset: 1:d9da848d0adf
3 user: test
3 user: test
4 date: Mon Jan 12 13:46:40 1970 +0000
4 date: Mon Jan 12 13:46:40 1970 +0000
5 summary: cp foo bar; change both
5 summary: cp foo bar; change both
6
6
7 searching for copies back to rev 1
7 searching for copies back to rev 1
8 unmatched files in other:
8 unmatched files in other:
9 bar
9 bar
10 all copies found (* = to merge, ! = divergent):
10 all copies found (* = to merge, ! = divergent):
11 bar -> foo *
11 bar -> foo *
12 checking for directory renames
12 checking for directory renames
13 resolving manifests
13 resolving manifests
14 overwrite None partial False
14 overwrite None partial False
15 ancestor 310fd17130da local 2092631ce82b+ remote d9da848d0adf
15 ancestor 310fd17130da local 2092631ce82b+ remote d9da848d0adf
16 foo: versions differ -> m
16 foo: versions differ -> m
17 foo: remote copied to bar -> m
17 foo: remote copied to bar -> m
18 preserving foo for resolve of bar
18 preserving foo for resolve of bar
19 preserving foo for resolve of foo
19 preserving foo for resolve of foo
20 update: foo 1/2 files (50.00%)
20 updating: foo 1/2 files (50.00%)
21 picked tool 'internal:merge' for bar (binary False symlink False)
21 picked tool 'internal:merge' for bar (binary False symlink False)
22 merging foo and bar to bar
22 merging foo and bar to bar
23 my bar@2092631ce82b+ other bar@d9da848d0adf ancestor foo@310fd17130da
23 my bar@2092631ce82b+ other bar@d9da848d0adf ancestor foo@310fd17130da
24 premerge successful
24 premerge successful
25 update: foo 2/2 files (100.00%)
25 updating: foo 2/2 files (100.00%)
26 picked tool 'internal:merge' for foo (binary False symlink False)
26 picked tool 'internal:merge' for foo (binary False symlink False)
27 merging foo
27 merging foo
28 my foo@2092631ce82b+ other foo@d9da848d0adf ancestor foo@310fd17130da
28 my foo@2092631ce82b+ other foo@d9da848d0adf ancestor foo@310fd17130da
29 premerge successful
29 premerge successful
30 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
30 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
31 (branch merge, don't forget to commit)
31 (branch merge, don't forget to commit)
32 -- foo --
32 -- foo --
33 line 0
33 line 0
34 line 1
34 line 1
35 line 2-1
35 line 2-1
36 -- bar --
36 -- bar --
37 line 0
37 line 0
38 line 1
38 line 1
39 line 2-2
39 line 2-2
@@ -1,123 +1,127 b''
1 #!/bin/sh
1 #!/bin/sh
2
2
3 ########################################
3 ########################################
4
4
5 HGENCODING=utf-8
5 HGENCODING=utf-8
6 export HGENCODING
6 export HGENCODING
7
7
8 hg init t
8 hg init t
9 cd t
9 cd t
10
10
11 python << EOF
11 python << EOF
12 # (byte, width) = (6, 4)
12 # (byte, width) = (6, 4)
13 s = "\xe7\x9f\xad\xe5\x90\x8d"
13 s = "\xe7\x9f\xad\xe5\x90\x8d"
14 # (byte, width) = (7, 7): odd width is good for alignment test
14 # (byte, width) = (7, 7): odd width is good for alignment test
15 m = "MIDDLE_"
15 m = "MIDDLE_"
16 # (byte, width) = (18, 12)
16 # (byte, width) = (18, 12)
17 l = "\xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d"
17 l = "\xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d"
18
18
19 f = file('s', 'w'); f.write(s); f.close()
19 f = file('s', 'w'); f.write(s); f.close()
20 f = file('m', 'w'); f.write(m); f.close()
20 f = file('m', 'w'); f.write(m); f.close()
21 f = file('l', 'w'); f.write(l); f.close()
21 f = file('l', 'w'); f.write(l); f.close()
22
22
23 # instant extension to show list of options
23 # instant extension to show list of options
24 f = file('showoptlist.py', 'w'); f.write("""# encoding: utf-8
24 f = file('showoptlist.py', 'w'); f.write("""# encoding: utf-8
25 def showoptlist(ui, repo, *pats, **opts):
25 def showoptlist(ui, repo, *pats, **opts):
26 '''dummy command to show option descriptions'''
26 '''dummy command to show option descriptions'''
27 return 0
27 return 0
28
28
29 cmdtable = {
29 cmdtable = {
30 'showoptlist':
30 'showoptlist':
31 (showoptlist,
31 (showoptlist,
32 [('s', 'opt1', '', 'short width', '""" + s + """'),
32 [('s', 'opt1', '', 'short width', '""" + s + """'),
33 ('m', 'opt2', '', 'middle width', '""" + m + """'),
33 ('m', 'opt2', '', 'middle width', '""" + m + """'),
34 ('l', 'opt3', '', 'long width', '""" + l + """')
34 ('l', 'opt3', '', 'long width', '""" + l + """')
35 ],
35 ],
36 ""
36 ""
37 )
37 )
38 }
38 }
39 """)
39 """)
40 f.close()
40 f.close()
41 EOF
41 EOF
42
42
43 S=`cat s`
43 S=`cat s`
44 M=`cat m`
44 M=`cat m`
45 L=`cat l`
45 L=`cat l`
46
46
47 ########################################
47 ########################################
48 #### alignment of:
48 #### alignment of:
49 #### - option descriptions in help
49 #### - option descriptions in help
50
50
51 cat <<EOF > .hg/hgrc
51 cat <<EOF > .hg/hgrc
52 [extensions]
52 [extensions]
53 ja_ext = `pwd`/showoptlist.py
53 ja_ext = `pwd`/showoptlist.py
54 EOF
54 EOF
55 echo '% check alignment of option descriptions in help'
55 echo '% check alignment of option descriptions in help'
56 hg help showoptlist
56 hg help showoptlist
57
57
58 ########################################
58 ########################################
59 #### alignment of:
59 #### alignment of:
60 #### - user names in annotate
60 #### - user names in annotate
61 #### - file names in diffstat
61 #### - file names in diffstat
62
62
63 rm -f s; touch s
64 rm -f m; touch m
65 rm -f l; touch l
66
63 #### add files
67 #### add files
64
68
65 touch $S
69 cp s $S
66 hg add $S
70 hg add $S
67 touch $M
71 cp m $M
68 hg add $M
72 hg add $M
69 touch $L
73 cp l $L
70 hg add $L
74 hg add $L
71
75
72 #### commit(1)
76 #### commit(1)
73
77
74 echo 'first line(1)' >> $S
78 echo 'first line(1)' >> s; cp s $S
75 echo 'first line(2)' >> $M
79 echo 'first line(2)' >> m; cp m $M
76 echo 'first line(3)' >> $L
80 echo 'first line(3)' >> l; cp l $L
77 hg commit -m 'first commit' -u $S -d "1000000 0"
81 hg commit -m 'first commit' -u $S -d "1000000 0"
78
82
79 #### commit(2)
83 #### commit(2)
80
84
81 echo 'second line(1)' >> $S
85 echo 'second line(1)' >> s; cp s $S
82 echo 'second line(2)' >> $M
86 echo 'second line(2)' >> m; cp m $M
83 echo 'second line(3)' >> $L
87 echo 'second line(3)' >> l; cp l $L
84 hg commit -m 'second commit' -u $M -d "1000000 0"
88 hg commit -m 'second commit' -u $M -d "1000000 0"
85
89
86 #### commit(3)
90 #### commit(3)
87
91
88 echo 'third line(1)' >> $S
92 echo 'third line(1)' >> s; cp s $S
89 echo 'third line(2)' >> $M
93 echo 'third line(2)' >> m; cp m $M
90 echo 'third line(3)' >> $L
94 echo 'third line(3)' >> l; cp l $L
91 hg commit -m 'third commit' -u $L -d "1000000 0"
95 hg commit -m 'third commit' -u $L -d "1000000 0"
92
96
93 #### check
97 #### check
94
98
95 echo '% check alignment of user names in annotate'
99 echo '% check alignment of user names in annotate'
96 hg annotate -u $M
100 hg annotate -u $M
97 echo '% check alignment of filenames in diffstat'
101 echo '% check alignment of filenames in diffstat'
98 hg diff -c tip --stat
102 hg diff -c tip --stat
99
103
100 ########################################
104 ########################################
101 #### alignment of:
105 #### alignment of:
102 #### - branch names in list
106 #### - branch names in list
103 #### - tag names in list
107 #### - tag names in list
104
108
105 #### add branches/tags
109 #### add branches/tags
106
110
107 hg branch $S
111 hg branch $S
108 hg tag -d "1000000 0" $S
112 hg tag -d "1000000 0" $S
109 hg branch $M
113 hg branch $M
110 hg tag -d "1000000 0" $M
114 hg tag -d "1000000 0" $M
111 hg branch $L
115 hg branch $L
112 hg tag -d "1000000 0" $L
116 hg tag -d "1000000 0" $L
113
117
114 #### check
118 #### check
115
119
116 echo '% check alignment of branches'
120 echo '% check alignment of branches'
117 hg tags
121 hg tags
118 echo '% check alignment of tags'
122 echo '% check alignment of tags'
119 hg tags
123 hg tags
120
124
121 ########################################
125 ########################################
122
126
123 exit 0
127 exit 0
@@ -1,161 +1,163 b''
1 #!/bin/sh
1 #!/bin/sh
2 # Tests some basic hgwebdir functionality. Tests setting up paths and
2 # Tests some basic hgwebdir functionality. Tests setting up paths and
3 # collection, different forms of 404s and the subdirectory support.
3 # collection, different forms of 404s and the subdirectory support.
4
4
5 mkdir webdir
5 mkdir webdir
6 cd webdir
6 cd webdir
7
7
8 hg init a
8 hg init a
9 echo a > a/a
9 echo a > a/a
10 hg --cwd a ci -Ama -d'1 0'
10 hg --cwd a ci -Ama -d'1 0'
11 # create a mercurial queue repository
11 # create a mercurial queue repository
12 hg --cwd a qinit --config extensions.hgext.mq= -c
12 hg --cwd a qinit --config extensions.hgext.mq= -c
13
13
14 hg init b
14 hg init b
15 echo b > b/b
15 echo b > b/b
16 hg --cwd b ci -Amb -d'2 0'
16 hg --cwd b ci -Amb -d'2 0'
17
17
18 # create a nested repository
18 # create a nested repository
19 cd b
19 cd b
20 hg init d
20 hg init d
21 echo d > d/d
21 echo d > d/d
22 hg --cwd d ci -Amd -d'3 0'
22 hg --cwd d ci -Amd -d'3 0'
23 cd ..
23 cd ..
24
24
25 hg init c
25 hg init c
26 echo c > c/c
26 echo c > c/c
27 hg --cwd c ci -Amc -d'3 0'
27 hg --cwd c ci -Amc -d'3 0'
28
28
29 root=`pwd`
29 root=`pwd`
30 cd ..
30 cd ..
31
31
32
32
33 cat > paths.conf <<EOF
33 cat > paths.conf <<EOF
34 [paths]
34 [paths]
35 a=$root/a
35 a=$root/a
36 b=$root/b
36 b=$root/b
37 EOF
37 EOF
38
38
39 hg serve -p $HGPORT -d --pid-file=hg.pid --webdir-conf paths.conf \
39 hg serve -p $HGPORT -d --pid-file=hg.pid --webdir-conf paths.conf \
40 -A access-paths.log -E error-paths-1.log
40 -A access-paths.log -E error-paths-1.log
41 cat hg.pid >> $DAEMON_PIDS
41 cat hg.pid >> $DAEMON_PIDS
42
42
43 echo % should give a 404 - file does not exist
43 echo % should give a 404 - file does not exist
44 "$TESTDIR/get-with-headers.py" localhost:$HGPORT '/a/file/tip/bork?style=raw'
44 "$TESTDIR/get-with-headers.py" localhost:$HGPORT '/a/file/tip/bork?style=raw'
45
45
46 echo % should succeed
46 echo % should succeed
47 "$TESTDIR/get-with-headers.py" localhost:$HGPORT '/?style=raw'
47 "$TESTDIR/get-with-headers.py" localhost:$HGPORT '/?style=raw'
48 "$TESTDIR/get-with-headers.py" localhost:$HGPORT '/a/file/tip/a?style=raw'
48 "$TESTDIR/get-with-headers.py" localhost:$HGPORT '/a/file/tip/a?style=raw'
49 "$TESTDIR/get-with-headers.py" localhost:$HGPORT '/b/file/tip/b?style=raw'
49 "$TESTDIR/get-with-headers.py" localhost:$HGPORT '/b/file/tip/b?style=raw'
50
50
51 echo % should give a 404 - repo is not published
51 echo % should give a 404 - repo is not published
52 "$TESTDIR/get-with-headers.py" localhost:$HGPORT '/c/file/tip/c?style=raw'
52 "$TESTDIR/get-with-headers.py" localhost:$HGPORT '/c/file/tip/c?style=raw'
53
53
54 echo % atom-log without basedir
54 echo % atom-log without basedir
55 "$TESTDIR/get-with-headers.py" localhost:$HGPORT '/a/atom-log' \
55 "$TESTDIR/get-with-headers.py" localhost:$HGPORT '/a/atom-log' \
56 | grep '<link' | sed 's|//[.a-zA-Z0-9_-]*:[0-9][0-9]*/|//example.com:8080/|'
56 | grep '<link' | sed 's|//[.a-zA-Z0-9_-]*:[0-9][0-9]*/|//example.com:8080/|'
57
57
58 echo % rss-log without basedir
58 echo % rss-log without basedir
59 "$TESTDIR/get-with-headers.py" localhost:$HGPORT '/a/rss-log' \
59 "$TESTDIR/get-with-headers.py" localhost:$HGPORT '/a/rss-log' \
60 | grep '<guid' | sed 's|//[.a-zA-Z0-9_-]*:[0-9][0-9]*/|//example.com:8080/|'
60 | grep '<guid' | sed 's|//[.a-zA-Z0-9_-]*:[0-9][0-9]*/|//example.com:8080/|'
61
61
62 cat > paths.conf <<EOF
62 cat > paths.conf <<EOF
63 [paths]
63 [paths]
64 t/a/=$root/a
64 t/a/=$root/a
65 b=$root/b
65 b=$root/b
66 coll=$root/*
66 coll=$root/*
67 rcoll=$root/**
67 rcoll=$root/**
68 star=*
69 starstar=**
68 EOF
70 EOF
69
71
70 hg serve -p $HGPORT1 -d --pid-file=hg.pid --webdir-conf paths.conf \
72 hg serve -p $HGPORT1 -d --pid-file=hg.pid --webdir-conf paths.conf \
71 -A access-paths.log -E error-paths-2.log
73 -A access-paths.log -E error-paths-2.log
72 cat hg.pid >> $DAEMON_PIDS
74 cat hg.pid >> $DAEMON_PIDS
73
75
74 echo % should succeed, slashy names
76 echo % should succeed, slashy names
75 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/?style=raw'
77 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/?style=raw'
76 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/?style=paper' \
78 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/?style=paper' \
77 | sed "s/[0-9]\{1,\} seconds\{0,1\} ago/seconds ago/"
79 | sed "s/[0-9]\{1,\} seconds\{0,1\} ago/seconds ago/"
78 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/t?style=raw'
80 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/t?style=raw'
79 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/t/?style=raw'
81 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/t/?style=raw'
80 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/t/?style=paper' \
82 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/t/?style=paper' \
81 | sed "s/[0-9]\{1,\} seconds\{0,1\} ago/seconds ago/"
83 | sed "s/[0-9]\{1,\} seconds\{0,1\} ago/seconds ago/"
82 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/t/a?style=atom' \
84 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/t/a?style=atom' \
83 | sed "s/http:\/\/[^/]*\//http:\/\/127.0.0.1\//"
85 | sed "s/http:\/\/[^/]*\//http:\/\/127.0.0.1\//"
84 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/t/a/?style=atom' \
86 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/t/a/?style=atom' \
85 | sed "s/http:\/\/[^/]*\//http:\/\/127.0.0.1\//"
87 | sed "s/http:\/\/[^/]*\//http:\/\/127.0.0.1\//"
86 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/t/a/file/tip/a?style=raw'
88 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/t/a/file/tip/a?style=raw'
87 # Test [paths] '*' extension
89 # Test [paths] '*' extension
88 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/coll/?style=raw'
90 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/coll/?style=raw'
89 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/coll/a/file/tip/a?style=raw'
91 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/coll/a/file/tip/a?style=raw'
90 #test [paths] '**' extension
92 #test [paths] '**' extension
91 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/rcoll/?style=raw'
93 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/rcoll/?style=raw'
92 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/rcoll/b/d/file/tip/d?style=raw'
94 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/rcoll/b/d/file/tip/d?style=raw'
93
95
94
96
95 "$TESTDIR/killdaemons.py"
97 "$TESTDIR/killdaemons.py"
96 cat > paths.conf <<EOF
98 cat > paths.conf <<EOF
97 [paths]
99 [paths]
98 t/a = $root/a
100 t/a = $root/a
99 t/b = $root/b
101 t/b = $root/b
100 c = $root/c
102 c = $root/c
101 [web]
103 [web]
102 descend=false
104 descend=false
103 EOF
105 EOF
104
106
105 hg serve -p $HGPORT1 -d --pid-file=hg.pid --webdir-conf paths.conf \
107 hg serve -p $HGPORT1 -d --pid-file=hg.pid --webdir-conf paths.conf \
106 -A access-paths.log -E error-paths-3.log
108 -A access-paths.log -E error-paths-3.log
107 cat hg.pid >> $DAEMON_PIDS
109 cat hg.pid >> $DAEMON_PIDS
108 echo % test descend = False
110 echo % test descend = False
109 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/?style=raw'
111 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/?style=raw'
110 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/t/?style=raw'
112 "$TESTDIR/get-with-headers.py" localhost:$HGPORT1 '/t/?style=raw'
111
113
112
114
113 cat > collections.conf <<EOF
115 cat > collections.conf <<EOF
114 [collections]
116 [collections]
115 $root=$root
117 $root=$root
116 EOF
118 EOF
117
119
118 hg serve --config web.baseurl=http://hg.example.com:8080/ -p $HGPORT2 -d \
120 hg serve --config web.baseurl=http://hg.example.com:8080/ -p $HGPORT2 -d \
119 --pid-file=hg.pid --webdir-conf collections.conf \
121 --pid-file=hg.pid --webdir-conf collections.conf \
120 -A access-collections.log -E error-collections.log
122 -A access-collections.log -E error-collections.log
121 cat hg.pid >> $DAEMON_PIDS
123 cat hg.pid >> $DAEMON_PIDS
122
124
123 echo % collections: should succeed
125 echo % collections: should succeed
124 "$TESTDIR/get-with-headers.py" localhost:$HGPORT2 '/?style=raw'
126 "$TESTDIR/get-with-headers.py" localhost:$HGPORT2 '/?style=raw'
125 "$TESTDIR/get-with-headers.py" localhost:$HGPORT2 '/a/file/tip/a?style=raw'
127 "$TESTDIR/get-with-headers.py" localhost:$HGPORT2 '/a/file/tip/a?style=raw'
126 "$TESTDIR/get-with-headers.py" localhost:$HGPORT2 '/b/file/tip/b?style=raw'
128 "$TESTDIR/get-with-headers.py" localhost:$HGPORT2 '/b/file/tip/b?style=raw'
127 "$TESTDIR/get-with-headers.py" localhost:$HGPORT2 '/c/file/tip/c?style=raw'
129 "$TESTDIR/get-with-headers.py" localhost:$HGPORT2 '/c/file/tip/c?style=raw'
128
130
129 echo % atom-log with basedir /
131 echo % atom-log with basedir /
130 "$TESTDIR/get-with-headers.py" localhost:$HGPORT2 '/a/atom-log' \
132 "$TESTDIR/get-with-headers.py" localhost:$HGPORT2 '/a/atom-log' \
131 | grep '<link' | sed 's|//[.a-zA-Z0-9_-]*:[0-9][0-9]*/|//example.com:8080/|'
133 | grep '<link' | sed 's|//[.a-zA-Z0-9_-]*:[0-9][0-9]*/|//example.com:8080/|'
132
134
133 echo % rss-log with basedir /
135 echo % rss-log with basedir /
134 "$TESTDIR/get-with-headers.py" localhost:$HGPORT2 '/a/rss-log' \
136 "$TESTDIR/get-with-headers.py" localhost:$HGPORT2 '/a/rss-log' \
135 | grep '<guid' | sed 's|//[.a-zA-Z0-9_-]*:[0-9][0-9]*/|//example.com:8080/|'
137 | grep '<guid' | sed 's|//[.a-zA-Z0-9_-]*:[0-9][0-9]*/|//example.com:8080/|'
136
138
137 "$TESTDIR/killdaemons.py"
139 "$TESTDIR/killdaemons.py"
138
140
139 hg serve --config web.baseurl=http://hg.example.com:8080/foo/ -p $HGPORT2 -d \
141 hg serve --config web.baseurl=http://hg.example.com:8080/foo/ -p $HGPORT2 -d \
140 --pid-file=hg.pid --webdir-conf collections.conf \
142 --pid-file=hg.pid --webdir-conf collections.conf \
141 -A access-collections-2.log -E error-collections-2.log
143 -A access-collections-2.log -E error-collections-2.log
142 cat hg.pid >> $DAEMON_PIDS
144 cat hg.pid >> $DAEMON_PIDS
143
145
144 echo % atom-log with basedir /foo/
146 echo % atom-log with basedir /foo/
145 "$TESTDIR/get-with-headers.py" localhost:$HGPORT2 '/a/atom-log' \
147 "$TESTDIR/get-with-headers.py" localhost:$HGPORT2 '/a/atom-log' \
146 | grep '<link' | sed 's|//[.a-zA-Z0-9_-]*:[0-9][0-9]*/|//example.com:8080/|'
148 | grep '<link' | sed 's|//[.a-zA-Z0-9_-]*:[0-9][0-9]*/|//example.com:8080/|'
147
149
148 echo % rss-log with basedir /foo/
150 echo % rss-log with basedir /foo/
149 "$TESTDIR/get-with-headers.py" localhost:$HGPORT2 '/a/rss-log' \
151 "$TESTDIR/get-with-headers.py" localhost:$HGPORT2 '/a/rss-log' \
150 | grep '<guid' | sed 's|//[.a-zA-Z0-9_-]*:[0-9][0-9]*/|//example.com:8080/|'
152 | grep '<guid' | sed 's|//[.a-zA-Z0-9_-]*:[0-9][0-9]*/|//example.com:8080/|'
151
153
152 echo % paths errors 1
154 echo % paths errors 1
153 cat error-paths-1.log
155 cat error-paths-1.log
154 echo % paths errors 2
156 echo % paths errors 2
155 cat error-paths-2.log
157 cat error-paths-2.log
156 echo % paths errors 3
158 echo % paths errors 3
157 cat error-paths-3.log
159 cat error-paths-3.log
158 echo % collections errors
160 echo % collections errors
159 cat error-collections.log
161 cat error-collections.log
160 echo % collections errors 2
162 echo % collections errors 2
161 cat error-collections-2.log
163 cat error-collections-2.log
@@ -1,362 +1,443 b''
1 adding a
1 adding a
2 adding b
2 adding b
3 adding d
3 adding d
4 adding c
4 adding c
5 % should give a 404 - file does not exist
5 % should give a 404 - file does not exist
6 404 Not Found
6 404 Not Found
7
7
8
8
9 error: bork@8580ff50825a: not found in manifest
9 error: bork@8580ff50825a: not found in manifest
10 % should succeed
10 % should succeed
11 200 Script output follows
11 200 Script output follows
12
12
13
13
14 /a/
14 /a/
15 /b/
15 /b/
16
16
17 200 Script output follows
17 200 Script output follows
18
18
19 a
19 a
20 200 Script output follows
20 200 Script output follows
21
21
22 b
22 b
23 % should give a 404 - repo is not published
23 % should give a 404 - repo is not published
24 404 Not Found
24 404 Not Found
25
25
26
26
27 error: repository c not found
27 error: repository c not found
28 % atom-log without basedir
28 % atom-log without basedir
29 <link rel="self" href="http://example.com:8080/a/atom-log"/>
29 <link rel="self" href="http://example.com:8080/a/atom-log"/>
30 <link rel="alternate" href="http://example.com:8080/a/"/>
30 <link rel="alternate" href="http://example.com:8080/a/"/>
31 <link href="http://example.com:8080/a/rev/8580ff50825a"/>
31 <link href="http://example.com:8080/a/rev/8580ff50825a"/>
32 % rss-log without basedir
32 % rss-log without basedir
33 <guid isPermaLink="true">http://example.com:8080/a/rev/8580ff50825a</guid>
33 <guid isPermaLink="true">http://example.com:8080/a/rev/8580ff50825a</guid>
34 % should succeed, slashy names
34 % should succeed, slashy names
35 200 Script output follows
35 200 Script output follows
36
36
37
37
38 /t/a/
38 /t/a/
39 /b/
39 /b/
40 /coll/a/
40 /coll/a/
41 /coll/a/.hg/patches/
41 /coll/a/.hg/patches/
42 /coll/b/
42 /coll/b/
43 /coll/c/
43 /coll/c/
44 /rcoll/a/
44 /rcoll/a/
45 /rcoll/a/.hg/patches/
45 /rcoll/a/.hg/patches/
46 /rcoll/b/
46 /rcoll/b/
47 /rcoll/b/d/
47 /rcoll/b/d/
48 /rcoll/c/
48 /rcoll/c/
49 /star/webdir/a/
50 /star/webdir/a/.hg/patches/
51 /star/webdir/b/
52 /star/webdir/c/
53 /starstar/webdir/a/
54 /starstar/webdir/a/.hg/patches/
55 /starstar/webdir/b/
56 /starstar/webdir/b/d/
57 /starstar/webdir/c/
49
58
50 200 Script output follows
59 200 Script output follows
51
60
52 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
61 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
53 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
62 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
54 <head>
63 <head>
55 <link rel="icon" href="/static/hgicon.png" type="image/png" />
64 <link rel="icon" href="/static/hgicon.png" type="image/png" />
56 <meta name="robots" content="index, nofollow" />
65 <meta name="robots" content="index, nofollow" />
57 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
66 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
58
67
59 <title>Mercurial repositories index</title>
68 <title>Mercurial repositories index</title>
60 </head>
69 </head>
61 <body>
70 <body>
62
71
63 <div class="container">
72 <div class="container">
64 <div class="menu">
73 <div class="menu">
65 <a href="http://mercurial.selenic.com/">
74 <a href="http://mercurial.selenic.com/">
66 <img src="/static/hglogo.png" width=75 height=90 border=0 alt="mercurial" /></a>
75 <img src="/static/hglogo.png" width=75 height=90 border=0 alt="mercurial" /></a>
67 </div>
76 </div>
68 <div class="main">
77 <div class="main">
69 <h2>Mercurial Repositories</h2>
78 <h2>Mercurial Repositories</h2>
70
79
71 <table class="bigtable">
80 <table class="bigtable">
72 <tr>
81 <tr>
73 <th><a href="?sort=name">Name</a></th>
82 <th><a href="?sort=name">Name</a></th>
74 <th><a href="?sort=description">Description</a></th>
83 <th><a href="?sort=description">Description</a></th>
75 <th><a href="?sort=contact">Contact</a></th>
84 <th><a href="?sort=contact">Contact</a></th>
76 <th><a href="?sort=lastchange">Last modified</a></th>
85 <th><a href="?sort=lastchange">Last modified</a></th>
77 <th>&nbsp;</th>
86 <th>&nbsp;</th>
78 </tr>
87 </tr>
79
88
80 <tr class="parity0">
89 <tr class="parity0">
81 <td><a href="/t/a/?style=paper">t/a</a></td>
90 <td><a href="/t/a/?style=paper">t/a</a></td>
82 <td>unknown</td>
91 <td>unknown</td>
83 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
92 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
84 <td class="age">seconds ago</td>
93 <td class="age">seconds ago</td>
85 <td class="indexlinks"></td>
94 <td class="indexlinks"></td>
86 </tr>
95 </tr>
87
96
88 <tr class="parity1">
97 <tr class="parity1">
89 <td><a href="/b/?style=paper">b</a></td>
98 <td><a href="/b/?style=paper">b</a></td>
90 <td>unknown</td>
99 <td>unknown</td>
91 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
100 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
92 <td class="age">seconds ago</td>
101 <td class="age">seconds ago</td>
93 <td class="indexlinks"></td>
102 <td class="indexlinks"></td>
94 </tr>
103 </tr>
95
104
96 <tr class="parity0">
105 <tr class="parity0">
97 <td><a href="/coll/a/?style=paper">coll/a</a></td>
106 <td><a href="/coll/a/?style=paper">coll/a</a></td>
98 <td>unknown</td>
107 <td>unknown</td>
99 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
108 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
100 <td class="age">seconds ago</td>
109 <td class="age">seconds ago</td>
101 <td class="indexlinks"></td>
110 <td class="indexlinks"></td>
102 </tr>
111 </tr>
103
112
104 <tr class="parity1">
113 <tr class="parity1">
105 <td><a href="/coll/a/.hg/patches/?style=paper">coll/a/.hg/patches</a></td>
114 <td><a href="/coll/a/.hg/patches/?style=paper">coll/a/.hg/patches</a></td>
106 <td>unknown</td>
115 <td>unknown</td>
107 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
116 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
108 <td class="age">seconds ago</td>
117 <td class="age">seconds ago</td>
109 <td class="indexlinks"></td>
118 <td class="indexlinks"></td>
110 </tr>
119 </tr>
111
120
112 <tr class="parity0">
121 <tr class="parity0">
113 <td><a href="/coll/b/?style=paper">coll/b</a></td>
122 <td><a href="/coll/b/?style=paper">coll/b</a></td>
114 <td>unknown</td>
123 <td>unknown</td>
115 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
124 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
116 <td class="age">seconds ago</td>
125 <td class="age">seconds ago</td>
117 <td class="indexlinks"></td>
126 <td class="indexlinks"></td>
118 </tr>
127 </tr>
119
128
120 <tr class="parity1">
129 <tr class="parity1">
121 <td><a href="/coll/c/?style=paper">coll/c</a></td>
130 <td><a href="/coll/c/?style=paper">coll/c</a></td>
122 <td>unknown</td>
131 <td>unknown</td>
123 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
132 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
124 <td class="age">seconds ago</td>
133 <td class="age">seconds ago</td>
125 <td class="indexlinks"></td>
134 <td class="indexlinks"></td>
126 </tr>
135 </tr>
127
136
128 <tr class="parity0">
137 <tr class="parity0">
129 <td><a href="/rcoll/a/?style=paper">rcoll/a</a></td>
138 <td><a href="/rcoll/a/?style=paper">rcoll/a</a></td>
130 <td>unknown</td>
139 <td>unknown</td>
131 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
140 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
132 <td class="age">seconds ago</td>
141 <td class="age">seconds ago</td>
133 <td class="indexlinks"></td>
142 <td class="indexlinks"></td>
134 </tr>
143 </tr>
135
144
136 <tr class="parity1">
145 <tr class="parity1">
137 <td><a href="/rcoll/a/.hg/patches/?style=paper">rcoll/a/.hg/patches</a></td>
146 <td><a href="/rcoll/a/.hg/patches/?style=paper">rcoll/a/.hg/patches</a></td>
138 <td>unknown</td>
147 <td>unknown</td>
139 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
148 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
140 <td class="age">seconds ago</td>
149 <td class="age">seconds ago</td>
141 <td class="indexlinks"></td>
150 <td class="indexlinks"></td>
142 </tr>
151 </tr>
143
152
144 <tr class="parity0">
153 <tr class="parity0">
145 <td><a href="/rcoll/b/?style=paper">rcoll/b</a></td>
154 <td><a href="/rcoll/b/?style=paper">rcoll/b</a></td>
146 <td>unknown</td>
155 <td>unknown</td>
147 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
156 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
148 <td class="age">seconds ago</td>
157 <td class="age">seconds ago</td>
149 <td class="indexlinks"></td>
158 <td class="indexlinks"></td>
150 </tr>
159 </tr>
151
160
152 <tr class="parity1">
161 <tr class="parity1">
153 <td><a href="/rcoll/b/d/?style=paper">rcoll/b/d</a></td>
162 <td><a href="/rcoll/b/d/?style=paper">rcoll/b/d</a></td>
154 <td>unknown</td>
163 <td>unknown</td>
155 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
164 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
156 <td class="age">seconds ago</td>
165 <td class="age">seconds ago</td>
157 <td class="indexlinks"></td>
166 <td class="indexlinks"></td>
158 </tr>
167 </tr>
159
168
160 <tr class="parity0">
169 <tr class="parity0">
161 <td><a href="/rcoll/c/?style=paper">rcoll/c</a></td>
170 <td><a href="/rcoll/c/?style=paper">rcoll/c</a></td>
162 <td>unknown</td>
171 <td>unknown</td>
163 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
172 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
164 <td class="age">seconds ago</td>
173 <td class="age">seconds ago</td>
165 <td class="indexlinks"></td>
174 <td class="indexlinks"></td>
166 </tr>
175 </tr>
167
176
177 <tr class="parity1">
178 <td><a href="/star/webdir/a/?style=paper">star/webdir/a</a></td>
179 <td>unknown</td>
180 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
181 <td class="age">seconds ago</td>
182 <td class="indexlinks"></td>
183 </tr>
184
185 <tr class="parity0">
186 <td><a href="/star/webdir/a/.hg/patches/?style=paper">star/webdir/a/.hg/patches</a></td>
187 <td>unknown</td>
188 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
189 <td class="age">seconds ago</td>
190 <td class="indexlinks"></td>
191 </tr>
192
193 <tr class="parity1">
194 <td><a href="/star/webdir/b/?style=paper">star/webdir/b</a></td>
195 <td>unknown</td>
196 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
197 <td class="age">seconds ago</td>
198 <td class="indexlinks"></td>
199 </tr>
200
201 <tr class="parity0">
202 <td><a href="/star/webdir/c/?style=paper">star/webdir/c</a></td>
203 <td>unknown</td>
204 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
205 <td class="age">seconds ago</td>
206 <td class="indexlinks"></td>
207 </tr>
208
209 <tr class="parity1">
210 <td><a href="/starstar/webdir/a/?style=paper">starstar/webdir/a</a></td>
211 <td>unknown</td>
212 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
213 <td class="age">seconds ago</td>
214 <td class="indexlinks"></td>
215 </tr>
216
217 <tr class="parity0">
218 <td><a href="/starstar/webdir/a/.hg/patches/?style=paper">starstar/webdir/a/.hg/patches</a></td>
219 <td>unknown</td>
220 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
221 <td class="age">seconds ago</td>
222 <td class="indexlinks"></td>
223 </tr>
224
225 <tr class="parity1">
226 <td><a href="/starstar/webdir/b/?style=paper">starstar/webdir/b</a></td>
227 <td>unknown</td>
228 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
229 <td class="age">seconds ago</td>
230 <td class="indexlinks"></td>
231 </tr>
232
233 <tr class="parity0">
234 <td><a href="/starstar/webdir/b/d/?style=paper">starstar/webdir/b/d</a></td>
235 <td>unknown</td>
236 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
237 <td class="age">seconds ago</td>
238 <td class="indexlinks"></td>
239 </tr>
240
241 <tr class="parity1">
242 <td><a href="/starstar/webdir/c/?style=paper">starstar/webdir/c</a></td>
243 <td>unknown</td>
244 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
245 <td class="age">seconds ago</td>
246 <td class="indexlinks"></td>
247 </tr>
248
168 </table>
249 </table>
169 </div>
250 </div>
170 </div>
251 </div>
171
252
172
253
173 </body>
254 </body>
174 </html>
255 </html>
175
256
176 200 Script output follows
257 200 Script output follows
177
258
178
259
179 /t/a/
260 /t/a/
180
261
181 200 Script output follows
262 200 Script output follows
182
263
183
264
184 /t/a/
265 /t/a/
185
266
186 200 Script output follows
267 200 Script output follows
187
268
188 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
269 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
189 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
270 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
190 <head>
271 <head>
191 <link rel="icon" href="/static/hgicon.png" type="image/png" />
272 <link rel="icon" href="/static/hgicon.png" type="image/png" />
192 <meta name="robots" content="index, nofollow" />
273 <meta name="robots" content="index, nofollow" />
193 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
274 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
194
275
195 <title>Mercurial repositories index</title>
276 <title>Mercurial repositories index</title>
196 </head>
277 </head>
197 <body>
278 <body>
198
279
199 <div class="container">
280 <div class="container">
200 <div class="menu">
281 <div class="menu">
201 <a href="http://mercurial.selenic.com/">
282 <a href="http://mercurial.selenic.com/">
202 <img src="/static/hglogo.png" width=75 height=90 border=0 alt="mercurial" /></a>
283 <img src="/static/hglogo.png" width=75 height=90 border=0 alt="mercurial" /></a>
203 </div>
284 </div>
204 <div class="main">
285 <div class="main">
205 <h2>Mercurial Repositories</h2>
286 <h2>Mercurial Repositories</h2>
206
287
207 <table class="bigtable">
288 <table class="bigtable">
208 <tr>
289 <tr>
209 <th><a href="?sort=name">Name</a></th>
290 <th><a href="?sort=name">Name</a></th>
210 <th><a href="?sort=description">Description</a></th>
291 <th><a href="?sort=description">Description</a></th>
211 <th><a href="?sort=contact">Contact</a></th>
292 <th><a href="?sort=contact">Contact</a></th>
212 <th><a href="?sort=lastchange">Last modified</a></th>
293 <th><a href="?sort=lastchange">Last modified</a></th>
213 <th>&nbsp;</th>
294 <th>&nbsp;</th>
214 </tr>
295 </tr>
215
296
216 <tr class="parity0">
297 <tr class="parity0">
217 <td><a href="/t/a/?style=paper">a</a></td>
298 <td><a href="/t/a/?style=paper">a</a></td>
218 <td>unknown</td>
299 <td>unknown</td>
219 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
300 <td>&#70;&#111;&#111;&#32;&#66;&#97;&#114;&#32;&#60;&#102;&#111;&#111;&#46;&#98;&#97;&#114;&#64;&#101;&#120;&#97;&#109;&#112;&#108;&#101;&#46;&#99;&#111;&#109;&#62;</td>
220 <td class="age">seconds ago</td>
301 <td class="age">seconds ago</td>
221 <td class="indexlinks"></td>
302 <td class="indexlinks"></td>
222 </tr>
303 </tr>
223
304
224 </table>
305 </table>
225 </div>
306 </div>
226 </div>
307 </div>
227
308
228
309
229 </body>
310 </body>
230 </html>
311 </html>
231
312
232 200 Script output follows
313 200 Script output follows
233
314
234 <?xml version="1.0" encoding="ascii"?>
315 <?xml version="1.0" encoding="ascii"?>
235 <feed xmlns="http://127.0.0.1/2005/Atom">
316 <feed xmlns="http://127.0.0.1/2005/Atom">
236 <!-- Changelog -->
317 <!-- Changelog -->
237 <id>http://127.0.0.1/t/a/</id>
318 <id>http://127.0.0.1/t/a/</id>
238 <link rel="self" href="http://127.0.0.1/t/a/atom-log"/>
319 <link rel="self" href="http://127.0.0.1/t/a/atom-log"/>
239 <link rel="alternate" href="http://127.0.0.1/t/a/"/>
320 <link rel="alternate" href="http://127.0.0.1/t/a/"/>
240 <title>t/a Changelog</title>
321 <title>t/a Changelog</title>
241 <updated>1970-01-01T00:00:01+00:00</updated>
322 <updated>1970-01-01T00:00:01+00:00</updated>
242
323
243 <entry>
324 <entry>
244 <title>a</title>
325 <title>a</title>
245 <id>http://127.0.0.1/t/a/#changeset-8580ff50825a50c8f716709acdf8de0deddcd6ab</id>
326 <id>http://127.0.0.1/t/a/#changeset-8580ff50825a50c8f716709acdf8de0deddcd6ab</id>
246 <link href="http://127.0.0.1/t/a/rev/8580ff50825a"/>
327 <link href="http://127.0.0.1/t/a/rev/8580ff50825a"/>
247 <author>
328 <author>
248 <name>test</name>
329 <name>test</name>
249 <email>&#116;&#101;&#115;&#116;</email>
330 <email>&#116;&#101;&#115;&#116;</email>
250 </author>
331 </author>
251 <updated>1970-01-01T00:00:01+00:00</updated>
332 <updated>1970-01-01T00:00:01+00:00</updated>
252 <published>1970-01-01T00:00:01+00:00</published>
333 <published>1970-01-01T00:00:01+00:00</published>
253 <content type="xhtml">
334 <content type="xhtml">
254 <div xmlns="http://127.0.0.1/1999/xhtml">
335 <div xmlns="http://127.0.0.1/1999/xhtml">
255 <pre xml:space="preserve">a</pre>
336 <pre xml:space="preserve">a</pre>
256 </div>
337 </div>
257 </content>
338 </content>
258 </entry>
339 </entry>
259
340
260 </feed>
341 </feed>
261 200 Script output follows
342 200 Script output follows
262
343
263 <?xml version="1.0" encoding="ascii"?>
344 <?xml version="1.0" encoding="ascii"?>
264 <feed xmlns="http://127.0.0.1/2005/Atom">
345 <feed xmlns="http://127.0.0.1/2005/Atom">
265 <!-- Changelog -->
346 <!-- Changelog -->
266 <id>http://127.0.0.1/t/a/</id>
347 <id>http://127.0.0.1/t/a/</id>
267 <link rel="self" href="http://127.0.0.1/t/a/atom-log"/>
348 <link rel="self" href="http://127.0.0.1/t/a/atom-log"/>
268 <link rel="alternate" href="http://127.0.0.1/t/a/"/>
349 <link rel="alternate" href="http://127.0.0.1/t/a/"/>
269 <title>t/a Changelog</title>
350 <title>t/a Changelog</title>
270 <updated>1970-01-01T00:00:01+00:00</updated>
351 <updated>1970-01-01T00:00:01+00:00</updated>
271
352
272 <entry>
353 <entry>
273 <title>a</title>
354 <title>a</title>
274 <id>http://127.0.0.1/t/a/#changeset-8580ff50825a50c8f716709acdf8de0deddcd6ab</id>
355 <id>http://127.0.0.1/t/a/#changeset-8580ff50825a50c8f716709acdf8de0deddcd6ab</id>
275 <link href="http://127.0.0.1/t/a/rev/8580ff50825a"/>
356 <link href="http://127.0.0.1/t/a/rev/8580ff50825a"/>
276 <author>
357 <author>
277 <name>test</name>
358 <name>test</name>
278 <email>&#116;&#101;&#115;&#116;</email>
359 <email>&#116;&#101;&#115;&#116;</email>
279 </author>
360 </author>
280 <updated>1970-01-01T00:00:01+00:00</updated>
361 <updated>1970-01-01T00:00:01+00:00</updated>
281 <published>1970-01-01T00:00:01+00:00</published>
362 <published>1970-01-01T00:00:01+00:00</published>
282 <content type="xhtml">
363 <content type="xhtml">
283 <div xmlns="http://127.0.0.1/1999/xhtml">
364 <div xmlns="http://127.0.0.1/1999/xhtml">
284 <pre xml:space="preserve">a</pre>
365 <pre xml:space="preserve">a</pre>
285 </div>
366 </div>
286 </content>
367 </content>
287 </entry>
368 </entry>
288
369
289 </feed>
370 </feed>
290 200 Script output follows
371 200 Script output follows
291
372
292 a
373 a
293 200 Script output follows
374 200 Script output follows
294
375
295
376
296 /coll/a/
377 /coll/a/
297 /coll/a/.hg/patches/
378 /coll/a/.hg/patches/
298 /coll/b/
379 /coll/b/
299 /coll/c/
380 /coll/c/
300
381
301 200 Script output follows
382 200 Script output follows
302
383
303 a
384 a
304 200 Script output follows
385 200 Script output follows
305
386
306
387
307 /rcoll/a/
388 /rcoll/a/
308 /rcoll/a/.hg/patches/
389 /rcoll/a/.hg/patches/
309 /rcoll/b/
390 /rcoll/b/
310 /rcoll/b/d/
391 /rcoll/b/d/
311 /rcoll/c/
392 /rcoll/c/
312
393
313 200 Script output follows
394 200 Script output follows
314
395
315 d
396 d
316 % test descend = False
397 % test descend = False
317 200 Script output follows
398 200 Script output follows
318
399
319
400
320 /c/
401 /c/
321
402
322 200 Script output follows
403 200 Script output follows
323
404
324
405
325 /t/a/
406 /t/a/
326 /t/b/
407 /t/b/
327
408
328 % collections: should succeed
409 % collections: should succeed
329 200 Script output follows
410 200 Script output follows
330
411
331
412
332 /a/
413 /a/
333 /a/.hg/patches/
414 /a/.hg/patches/
334 /b/
415 /b/
335 /c/
416 /c/
336
417
337 200 Script output follows
418 200 Script output follows
338
419
339 a
420 a
340 200 Script output follows
421 200 Script output follows
341
422
342 b
423 b
343 200 Script output follows
424 200 Script output follows
344
425
345 c
426 c
346 % atom-log with basedir /
427 % atom-log with basedir /
347 <link rel="self" href="http://example.com:8080/a/atom-log"/>
428 <link rel="self" href="http://example.com:8080/a/atom-log"/>
348 <link rel="alternate" href="http://example.com:8080/a/"/>
429 <link rel="alternate" href="http://example.com:8080/a/"/>
349 <link href="http://example.com:8080/a/rev/8580ff50825a"/>
430 <link href="http://example.com:8080/a/rev/8580ff50825a"/>
350 % rss-log with basedir /
431 % rss-log with basedir /
351 <guid isPermaLink="true">http://example.com:8080/a/rev/8580ff50825a</guid>
432 <guid isPermaLink="true">http://example.com:8080/a/rev/8580ff50825a</guid>
352 % atom-log with basedir /foo/
433 % atom-log with basedir /foo/
353 <link rel="self" href="http://example.com:8080/foo/a/atom-log"/>
434 <link rel="self" href="http://example.com:8080/foo/a/atom-log"/>
354 <link rel="alternate" href="http://example.com:8080/foo/a/"/>
435 <link rel="alternate" href="http://example.com:8080/foo/a/"/>
355 <link href="http://example.com:8080/foo/a/rev/8580ff50825a"/>
436 <link href="http://example.com:8080/foo/a/rev/8580ff50825a"/>
356 % rss-log with basedir /foo/
437 % rss-log with basedir /foo/
357 <guid isPermaLink="true">http://example.com:8080/foo/a/rev/8580ff50825a</guid>
438 <guid isPermaLink="true">http://example.com:8080/foo/a/rev/8580ff50825a</guid>
358 % paths errors 1
439 % paths errors 1
359 % paths errors 2
440 % paths errors 2
360 % paths errors 3
441 % paths errors 3
361 % collections errors
442 % collections errors
362 % collections errors 2
443 % collections errors 2
@@ -1,21 +1,21 b''
1 reverting foo
1 reverting foo
2 changeset 2:4d9e78aaceee backs out changeset 1:b515023e500e
2 changeset 2:4d9e78aaceee backs out changeset 1:b515023e500e
3 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
3 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
4 searching for copies back to rev 1
4 searching for copies back to rev 1
5 unmatched files in local:
5 unmatched files in local:
6 bar
6 bar
7 resolving manifests
7 resolving manifests
8 overwrite None partial False
8 overwrite None partial False
9 ancestor bbd179dfa0a7 local 71766447bdbb+ remote 4d9e78aaceee
9 ancestor bbd179dfa0a7 local 71766447bdbb+ remote 4d9e78aaceee
10 foo: remote is newer -> g
10 foo: remote is newer -> g
11 update: foo 1/1 files (100.00%)
11 updating: foo 1/1 files (100.00%)
12 getting foo
12 getting foo
13 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
13 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
14 (branch merge, don't forget to commit)
14 (branch merge, don't forget to commit)
15 n 0 -2 unset foo
15 n 0 -2 unset foo
16 M foo
16 M foo
17 c6fc755d7e68f49f880599da29f15add41f42f5a 644 foo
17 c6fc755d7e68f49f880599da29f15add41f42f5a 644 foo
18 rev offset length base linkrev nodeid p1 p2
18 rev offset length base linkrev nodeid p1 p2
19 0 0 5 0 0 2ed2a3912a0b 000000000000 000000000000
19 0 0 5 0 0 2ed2a3912a0b 000000000000 000000000000
20 1 5 9 1 1 6f4310b00b9a 2ed2a3912a0b 000000000000
20 1 5 9 1 1 6f4310b00b9a 2ed2a3912a0b 000000000000
21 2 14 5 2 2 c6fc755d7e68 6f4310b00b9a 000000000000
21 2 14 5 2 2 c6fc755d7e68 6f4310b00b9a 000000000000
@@ -1,62 +1,62 b''
1 adding 1
1 adding 1
2 adding 2
2 adding 2
3 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
3 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
4 created new head
4 created new head
5 searching for copies back to rev 1
5 searching for copies back to rev 1
6 unmatched files in other:
6 unmatched files in other:
7 1a
7 1a
8 all copies found (* = to merge, ! = divergent):
8 all copies found (* = to merge, ! = divergent):
9 1a -> 1
9 1a -> 1
10 checking for directory renames
10 checking for directory renames
11 resolving manifests
11 resolving manifests
12 overwrite None partial False
12 overwrite None partial False
13 ancestor 81f4b099af3d local c64f439569a9+ remote c12dcd37c90a
13 ancestor 81f4b099af3d local c64f439569a9+ remote c12dcd37c90a
14 1: other deleted -> r
14 1: other deleted -> r
15 1a: remote created -> g
15 1a: remote created -> g
16 update: 1 1/2 files (50.00%)
16 updating: 1 1/2 files (50.00%)
17 removing 1
17 removing 1
18 update: 1a 2/2 files (100.00%)
18 updating: 1a 2/2 files (100.00%)
19 getting 1a
19 getting 1a
20 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
20 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
21 (branch merge, don't forget to commit)
21 (branch merge, don't forget to commit)
22 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
22 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
23 created new head
23 created new head
24 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
24 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
25 searching for copies back to rev 1
25 searching for copies back to rev 1
26 unmatched files in local:
26 unmatched files in local:
27 1a
27 1a
28 all copies found (* = to merge, ! = divergent):
28 all copies found (* = to merge, ! = divergent):
29 1a -> 1 *
29 1a -> 1 *
30 checking for directory renames
30 checking for directory renames
31 resolving manifests
31 resolving manifests
32 overwrite None partial False
32 overwrite None partial False
33 ancestor c64f439569a9 local e327dca35ac8+ remote 746e9549ea96
33 ancestor c64f439569a9 local e327dca35ac8+ remote 746e9549ea96
34 1a: local copied/moved to 1 -> m
34 1a: local copied/moved to 1 -> m
35 preserving 1a for resolve of 1a
35 preserving 1a for resolve of 1a
36 update: 1a 1/1 files (100.00%)
36 updating: 1a 1/1 files (100.00%)
37 picked tool 'internal:merge' for 1a (binary False symlink False)
37 picked tool 'internal:merge' for 1a (binary False symlink False)
38 merging 1a and 1 to 1a
38 merging 1a and 1 to 1a
39 my 1a@e327dca35ac8+ other 1@746e9549ea96 ancestor 1@81f4b099af3d
39 my 1a@e327dca35ac8+ other 1@746e9549ea96 ancestor 1@81f4b099af3d
40 premerge successful
40 premerge successful
41 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
41 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
42 (branch merge, don't forget to commit)
42 (branch merge, don't forget to commit)
43 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
43 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
44 searching for copies back to rev 1
44 searching for copies back to rev 1
45 unmatched files in other:
45 unmatched files in other:
46 1a
46 1a
47 all copies found (* = to merge, ! = divergent):
47 all copies found (* = to merge, ! = divergent):
48 1a -> 1 *
48 1a -> 1 *
49 checking for directory renames
49 checking for directory renames
50 resolving manifests
50 resolving manifests
51 overwrite None partial False
51 overwrite None partial False
52 ancestor c64f439569a9 local 746e9549ea96+ remote e327dca35ac8
52 ancestor c64f439569a9 local 746e9549ea96+ remote e327dca35ac8
53 1: remote moved to 1a -> m
53 1: remote moved to 1a -> m
54 preserving 1 for resolve of 1a
54 preserving 1 for resolve of 1a
55 removing 1
55 removing 1
56 update: 1 1/1 files (100.00%)
56 updating: 1 1/1 files (100.00%)
57 picked tool 'internal:merge' for 1a (binary False symlink False)
57 picked tool 'internal:merge' for 1a (binary False symlink False)
58 merging 1 and 1a to 1a
58 merging 1 and 1a to 1a
59 my 1a@746e9549ea96+ other 1a@e327dca35ac8 ancestor 1@81f4b099af3d
59 my 1a@746e9549ea96+ other 1a@e327dca35ac8 ancestor 1@81f4b099af3d
60 premerge successful
60 premerge successful
61 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
61 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
62 (branch merge, don't forget to commit)
62 (branch merge, don't forget to commit)
@@ -1,409 +1,418 b''
1 #!/bin/sh
1 #!/bin/sh
2
2
3 cat <<EOF >> $HGRCPATH
3 cat <<EOF >> $HGRCPATH
4 [extensions]
4 [extensions]
5 keyword =
5 keyword =
6 mq =
6 mq =
7 notify =
7 notify =
8 record =
8 record =
9 transplant =
9 transplant =
10 [ui]
10 [ui]
11 interactive = true
11 interactive = true
12 EOF
12 EOF
13
13
14 # demo before [keyword] files are set up
14 # demo before [keyword] files are set up
15 # would succeed without uisetup otherwise
15 # would succeed without uisetup otherwise
16 echo % hg kwdemo
16 echo % hg kwdemo
17 hg --quiet kwdemo \
17 hg --quiet kwdemo \
18 | sed -e 's![^ ][^ ]*demo.txt,v!/TMP/demo.txt,v!' \
18 | sed -e 's![^ ][^ ]*demo.txt,v!/TMP/demo.txt,v!' \
19 -e 's/,v [a-z0-9][a-z0-9]* /,v xxxxxxxxxxxx /' \
19 -e 's/,v [a-z0-9][a-z0-9]* /,v xxxxxxxxxxxx /' \
20 -e '/[$]Revision/ s/: [a-z0-9][a-z0-9]* /: xxxxxxxxxxxx /' \
20 -e '/[$]Revision/ s/: [a-z0-9][a-z0-9]* /: xxxxxxxxxxxx /' \
21 -e 's! 20[0-9][0-9]/[01][0-9]/[0-3][0-9] [0-2][0-9]:[0-6][0-9]:[0-6][0-9]! 2000/00/00 00:00:00!'
21 -e 's! 20[0-9][0-9]/[01][0-9]/[0-3][0-9] [0-2][0-9]:[0-6][0-9]:[0-6][0-9]! 2000/00/00 00:00:00!'
22
22
23 hg --quiet kwdemo "Branch = {branches}"
23 hg --quiet kwdemo "Branch = {branches}"
24
24
25 cat <<EOF >> $HGRCPATH
25 cat <<EOF >> $HGRCPATH
26 [keyword]
26 [keyword]
27 ** =
27 ** =
28 b = ignore
28 b = ignore
29 [hooks]
29 [hooks]
30 commit=
30 commit=
31 commit.test=cp a hooktest
31 commit.test=cp a hooktest
32 EOF
32 EOF
33
33
34 hg init Test-bndl
34 hg init Test-bndl
35 cd Test-bndl
35 cd Test-bndl
36
36
37 echo % kwshrink should exit silently in empty/invalid repo
37 echo % kwshrink should exit silently in empty/invalid repo
38 hg kwshrink
38 hg kwshrink
39
39
40 # Symlinks cannot be created on Windows. The bundle was made with:
40 # Symlinks cannot be created on Windows. The bundle was made with:
41 #
41 #
42 # hg init t
42 # hg init t
43 # cd t
43 # cd t
44 # echo a > a
44 # echo a > a
45 # ln -s a sym
45 # ln -s a sym
46 # hg add sym
46 # hg add sym
47 # hg ci -m addsym -u mercurial
47 # hg ci -m addsym -u mercurial
48 # hg bundle --base null ../test-keyword.hg
48 # hg bundle --base null ../test-keyword.hg
49 #
49 #
50 hg pull -u "$TESTDIR/test-keyword.hg" \
50 hg pull -u "$TESTDIR/test-keyword.hg" \
51 | sed 's/pulling from.*test-keyword.hg/pulling from test-keyword.hg/'
51 | sed 's/pulling from.*test-keyword.hg/pulling from test-keyword.hg/'
52
52
53 echo 'expand $Id$' > a
53 echo 'expand $Id$' > a
54 echo 'do not process $Id:' >> a
54 echo 'do not process $Id:' >> a
55 echo 'xxx $' >> a
55 echo 'xxx $' >> a
56 echo 'ignore $Id$' > b
56 echo 'ignore $Id$' > b
57 echo % cat
57 echo % cat
58 cat a b
58 cat a b
59
59
60 echo % no kwfiles
60 echo % no kwfiles
61 hg kwfiles
61 hg kwfiles
62 echo % untracked candidates
62 echo % untracked candidates
63 hg -v kwfiles --unknown
63 hg -v kwfiles --unknown
64
64
65 echo % addremove
65 echo % addremove
66 hg addremove
66 hg addremove
67 echo % status
67 echo % status
68 hg status
68 hg status
69
69
70 echo % default keyword expansion including commit hook
70 echo % default keyword expansion including commit hook
71 echo % interrupted commit should not change state or run commit hook
71 echo % interrupted commit should not change state or run commit hook
72 hg --debug commit
72 hg --debug commit
73 echo % status
73 echo % status
74 hg status
74 hg status
75
75
76 echo % commit
76 echo % commit
77 hg --debug commit -mabsym -u 'User Name <user@example.com>'
77 hg --debug commit -mabsym -u 'User Name <user@example.com>'
78 echo % status
78 echo % status
79 hg status
79 hg status
80 echo % identify
80 echo % identify
81 hg debugrebuildstate
81 hg debugrebuildstate
82 hg --quiet identify
82 hg --quiet identify
83 echo % cat
83 echo % cat
84 cat a b
84 cat a b
85 echo % hg cat
85 echo % hg cat
86 hg cat sym a b
86 hg cat sym a b
87
87
88 echo
88 echo
89 echo % diff a hooktest
89 echo % diff a hooktest
90 diff a hooktest
90 diff a hooktest
91
91
92 echo % removing commit hook from config
92 echo % removing commit hook from config
93 sed -e '/\[hooks\]/,$ d' "$HGRCPATH" > $HGRCPATH.nohook
93 sed -e '/\[hooks\]/,$ d' "$HGRCPATH" > $HGRCPATH.nohook
94 mv "$HGRCPATH".nohook "$HGRCPATH"
94 mv "$HGRCPATH".nohook "$HGRCPATH"
95 rm hooktest
95 rm hooktest
96
96
97 echo % bundle
97 echo % bundle
98 hg bundle --base null ../kw.hg
98 hg bundle --base null ../kw.hg
99
99
100 cd ..
100 cd ..
101 hg init Test
101 hg init Test
102 cd Test
102 cd Test
103
103
104 echo % notify on pull to check whether keywords stay as is in email
104 echo % notify on pull to check whether keywords stay as is in email
105 echo % ie. if patch.diff wrapper acts as it should
105 echo % ie. if patch.diff wrapper acts as it should
106
106
107 cat <<EOF >> $HGRCPATH
107 cat <<EOF >> $HGRCPATH
108 [hooks]
108 [hooks]
109 incoming.notify = python:hgext.notify.hook
109 incoming.notify = python:hgext.notify.hook
110 [notify]
110 [notify]
111 sources = pull
111 sources = pull
112 diffstat = False
112 diffstat = False
113 [reposubs]
113 [reposubs]
114 * = Test
114 * = Test
115 EOF
115 EOF
116
116
117 echo % pull from bundle
117 echo % pull from bundle
118 hg pull -u ../kw.hg 2>&1 | sed -e '/^Content-Type:/,/^diffs (/ d'
118 hg pull -u ../kw.hg 2>&1 | sed -e '/^Content-Type:/,/^diffs (/ d'
119
119
120 echo % remove notify config
120 echo % remove notify config
121 sed -e '/\[hooks\]/,$ d' "$HGRCPATH" > $HGRCPATH.nonotify
121 sed -e '/\[hooks\]/,$ d' "$HGRCPATH" > $HGRCPATH.nonotify
122 mv "$HGRCPATH".nonotify "$HGRCPATH"
122 mv "$HGRCPATH".nonotify "$HGRCPATH"
123
123
124 echo % touch
124 echo % touch
125 touch a b
125 touch a b
126 echo % status
126 echo % status
127 hg status
127 hg status
128
128
129 rm sym a b
129 rm sym a b
130 echo % update
130 echo % update
131 hg update -C
131 hg update -C
132 echo % cat
132 echo % cat
133 cat a b
133 cat a b
134
134
135 echo % check whether expansion is filewise
135 echo % check whether expansion is filewise
136 echo '$Id$' > c
136 echo '$Id$' > c
137 echo 'tests for different changenodes' >> c
137 echo 'tests for different changenodes' >> c
138 echo % commit c
138 echo % commit c
139 hg commit -A -mcndiff -d '1 0' -u 'User Name <user@example.com>'
139 hg commit -A -mcndiff -d '1 0' -u 'User Name <user@example.com>'
140 echo % force expansion
140 echo % force expansion
141 hg -v kwexpand
141 hg -v kwexpand
142 echo % compare changenodes in a c
142 echo % compare changenodes in a c
143 cat a c
143 cat a c
144
144
145 echo % record chunk
145 echo % record chunk
146 python -c \
146 python -c \
147 'l=open("a").readlines();l.insert(1,"foo\n");l.append("bar\n");open("a","w").writelines(l);'
147 'l=open("a").readlines();l.insert(1,"foo\n");l.append("bar\n");open("a","w").writelines(l);'
148 hg record -d '1 10' -m rectest<<EOF
148 hg record -d '1 10' -m rectest<<EOF
149 y
149 y
150 y
150 y
151 n
151 n
152 EOF
152 EOF
153 echo
153 echo
154 hg identify
154 hg identify
155 hg status
155 hg status
156 echo % cat modified file
156 echo % cat modified file
157 cat a
157 cat a
158 hg diff | grep -v 'b/a'
158 hg diff | grep -v 'b/a'
159 hg rollback
159 hg rollback
160
160
161 echo % record file
161 echo % record file
162 echo foo > msg
162 echo foo > msg
163 # do not use "hg record -m" here!
163 # do not use "hg record -m" here!
164 hg record -l msg -d '1 11'<<EOF
164 hg record -l msg -d '1 11'<<EOF
165 y
165 y
166 y
166 y
167 y
167 y
168 EOF
168 EOF
169 echo % a should be clean
169 echo % a should be clean
170 hg status -A a
170 hg status -A a
171 rm msg
171 rm msg
172 hg rollback
172 hg rollback
173 hg update -C
173 hg update -C
174
174
175 echo % init --mq
175 echo % init --mq
176 hg init --mq
176 hg init --mq
177 echo % qimport
177 echo % qimport
178 hg qimport -r tip -n mqtest.diff
178 hg qimport -r tip -n mqtest.diff
179 echo % commit --mq
179 echo % commit --mq
180 hg commit --mq -m mqtest
180 hg commit --mq -m mqtest
181 echo % keywords should not be expanded in patch
181 echo % keywords should not be expanded in patch
182 cat .hg/patches/mqtest.diff
182 cat .hg/patches/mqtest.diff
183 echo % qpop
183 echo % qpop
184 hg qpop
184 hg qpop
185 echo % qgoto - should imply qpush
185 echo % qgoto - should imply qpush
186 hg qgoto mqtest.diff
186 hg qgoto mqtest.diff
187 echo % cat
187 echo % cat
188 cat c
188 cat c
189 echo % hg cat
189 echo % hg cat
190 hg cat c
190 hg cat c
191 echo % keyword should not be expanded in filelog
191 echo % keyword should not be expanded in filelog
192 hg --config 'extensions.keyword=!' cat c
192 hg --config 'extensions.keyword=!' cat c
193 echo % qpop and move on
193 echo % qpop and move on
194 hg qpop
194 hg qpop
195
195
196 echo % copy
196 echo % copy
197 hg cp a c
197 hg cp a c
198
198
199 echo % kwfiles added
199 echo % kwfiles added
200 hg kwfiles
200 hg kwfiles
201
201
202 echo % commit
202 echo % commit
203 hg --debug commit -ma2c -d '1 0' -u 'User Name <user@example.com>'
203 hg --debug commit -ma2c -d '1 0' -u 'User Name <user@example.com>'
204 echo % cat a c
204 echo % cat a c
205 cat a c
205 cat a c
206 echo % touch copied c
206 echo % touch copied c
207 touch c
207 touch c
208 echo % status
208 echo % status
209 hg status
209 hg status
210
210
211 echo % kwfiles
211 echo % kwfiles
212 hg kwfiles
212 hg kwfiles
213 echo % ignored files
213 echo % ignored files
214 hg -v kwfiles --ignore
214 hg -v kwfiles --ignore
215 echo % all files
215 echo % all files
216 hg kwfiles --all
216 hg kwfiles --all
217
217
218 echo % diff --rev
218 echo % diff --rev
219 hg diff --rev 1 | grep -v 'b/c'
219 hg diff --rev 1 | grep -v 'b/c'
220
220
221 echo % rollback
221 echo % rollback
222 hg rollback
222 hg rollback
223 echo % status
223 echo % status
224 hg status
224 hg status
225 echo % update -C
225 echo % update -C
226 hg update --clean
226 hg update --clean
227
227
228 echo % custom keyword expansion
228 echo % custom keyword expansion
229 echo % try with kwdemo
229 echo % try with kwdemo
230 hg --quiet kwdemo "Xinfo = {author}: {desc}"
230 hg --quiet kwdemo "Xinfo = {author}: {desc}"
231
231
232 cat <<EOF >>$HGRCPATH
232 cat <<EOF >>$HGRCPATH
233 [keywordmaps]
233 [keywordmaps]
234 Id = {file} {node|short} {date|rfc822date} {author|user}
234 Id = {file} {node|short} {date|rfc822date} {author|user}
235 Xinfo = {author}: {desc}
235 Xinfo = {author}: {desc}
236 EOF
236 EOF
237
237
238 echo % cat
238 echo % cat
239 cat a b
239 cat a b
240 echo % hg cat
240 echo % hg cat
241 hg cat sym a b
241 hg cat sym a b
242
242
243 echo
243 echo
244 echo '$Xinfo$' >> a
244 echo '$Xinfo$' >> a
245 cat <<EOF >> log
245 cat <<EOF >> log
246 firstline
246 firstline
247 secondline
247 secondline
248 EOF
248 EOF
249
249
250 echo % interrupted commit should not change state
250 echo % interrupted commit should not change state
251 hg commit
251 hg commit
252 echo % status
252 echo % status
253 hg status
253 hg status
254
254
255 echo % commit
255 echo % commit
256 hg --debug commit -l log -d '2 0' -u 'User Name <user@example.com>'
256 hg --debug commit -l log -d '2 0' -u 'User Name <user@example.com>'
257 rm log
257 rm log
258 echo % status
258 echo % status
259 hg status
259 hg status
260 echo % verify
260 echo % verify
261 hg verify
261 hg verify
262
262
263 echo % cat
263 echo % cat
264 cat a b
264 cat a b
265 echo % hg cat
265 echo % hg cat
266 hg cat sym a b
266 hg cat sym a b
267 echo
267 echo
268 echo % annotate
268 echo % annotate
269 hg annotate a
269 hg annotate a
270
270
271 echo % remove
271 echo % remove
272 hg debugrebuildstate
272 hg debugrebuildstate
273 hg remove a
273 hg remove a
274 hg --debug commit -m rma
274 hg --debug commit -m rma
275 echo % status
275 echo % status
276 hg status
276 hg status
277 echo % rollback
277 echo % rollback
278 hg rollback
278 hg rollback
279 echo % status
279 echo % status
280 hg status
280 hg status
281 echo % revert a
281 echo % revert a
282 hg revert --no-backup --rev tip a
282 hg revert --no-backup --rev tip a
283 echo % cat a
283 echo % cat a
284 cat a
284 cat a
285
285
286 echo % clone
287 cd ..
288
289 echo % expansion in dest
290 hg --quiet clone Test globalconf
291 cat globalconf/a
292 echo % no expansion in dest
293 hg --quiet --config 'keyword.**=ignore' clone Test localconf
294 cat localconf/a
295
286 echo % clone to test incoming
296 echo % clone to test incoming
287 cd ..
288 hg clone -r1 Test Test-a
297 hg clone -r1 Test Test-a
289 cd Test-a
298 cd Test-a
290 cat <<EOF >> .hg/hgrc
299 cat <<EOF >> .hg/hgrc
291 [paths]
300 [paths]
292 default = ../Test
301 default = ../Test
293 EOF
302 EOF
294 echo % incoming
303 echo % incoming
295 # remove path to temp dir
304 # remove path to temp dir
296 hg incoming | sed -e 's/^\(comparing with \).*\(test-keyword.*\)/\1\2/'
305 hg incoming | sed -e 's/^\(comparing with \).*\(test-keyword.*\)/\1\2/'
297
306
298 sed -e 's/Id.*/& rejecttest/' a > a.new
307 sed -e 's/Id.*/& rejecttest/' a > a.new
299 mv a.new a
308 mv a.new a
300 echo % commit rejecttest
309 echo % commit rejecttest
301 hg --debug commit -m'rejects?' -d '3 0' -u 'User Name <user@example.com>'
310 hg --debug commit -m'rejects?' -d '3 0' -u 'User Name <user@example.com>'
302 echo % export
311 echo % export
303 hg export -o ../rejecttest.diff tip
312 hg export -o ../rejecttest.diff tip
304
313
305 cd ../Test
314 cd ../Test
306 echo % import
315 echo % import
307 hg import ../rejecttest.diff
316 hg import ../rejecttest.diff
308 echo % cat
317 echo % cat
309 cat a b
318 cat a b
310 echo
319 echo
311 echo % rollback
320 echo % rollback
312 hg rollback
321 hg rollback
313 echo % clean update
322 echo % clean update
314 hg update --clean
323 hg update --clean
315
324
316 echo % kwexpand/kwshrink on selected files
325 echo % kwexpand/kwshrink on selected files
317 mkdir x
326 mkdir x
318 echo % copy a x/a
327 echo % copy a x/a
319 hg copy a x/a
328 hg copy a x/a
320 echo % kwexpand a
329 echo % kwexpand a
321 hg --verbose kwexpand a
330 hg --verbose kwexpand a
322 echo % kwexpand x/a should abort
331 echo % kwexpand x/a should abort
323 hg --verbose kwexpand x/a
332 hg --verbose kwexpand x/a
324 cd x
333 cd x
325 hg --debug commit -m xa -d '3 0' -u 'User Name <user@example.com>'
334 hg --debug commit -m xa -d '3 0' -u 'User Name <user@example.com>'
326 echo % cat a
335 echo % cat a
327 cat a
336 cat a
328 echo % kwshrink a inside directory x
337 echo % kwshrink a inside directory x
329 hg --verbose kwshrink a
338 hg --verbose kwshrink a
330 echo % cat a
339 echo % cat a
331 cat a
340 cat a
332 cd ..
341 cd ..
333
342
334 echo % kwexpand nonexistent
343 echo % kwexpand nonexistent
335 hg kwexpand nonexistent 2>&1 | sed 's/nonexistent:.*/nonexistent:/'
344 hg kwexpand nonexistent 2>&1 | sed 's/nonexistent:.*/nonexistent:/'
336
345
337 echo % hg serve
346 echo % hg serve
338 hg serve -p $HGPORT -d --pid-file=hg.pid -A access.log -E errors.log
347 hg serve -p $HGPORT -d --pid-file=hg.pid -A access.log -E errors.log
339 cat hg.pid >> $DAEMON_PIDS
348 cat hg.pid >> $DAEMON_PIDS
340 echo % expansion
349 echo % expansion
341 echo % hgweb file
350 echo % hgweb file
342 ("$TESTDIR/get-with-headers.py" localhost:$HGPORT '/file/tip/a/?style=raw')
351 ("$TESTDIR/get-with-headers.py" localhost:$HGPORT '/file/tip/a/?style=raw')
343 echo % no expansion
352 echo % no expansion
344 echo % hgweb annotate
353 echo % hgweb annotate
345 ("$TESTDIR/get-with-headers.py" localhost:$HGPORT '/annotate/tip/a/?style=raw')
354 ("$TESTDIR/get-with-headers.py" localhost:$HGPORT '/annotate/tip/a/?style=raw')
346 echo % hgweb changeset
355 echo % hgweb changeset
347 ("$TESTDIR/get-with-headers.py" localhost:$HGPORT '/rev/tip/?style=raw')
356 ("$TESTDIR/get-with-headers.py" localhost:$HGPORT '/rev/tip/?style=raw')
348 echo % hgweb filediff
357 echo % hgweb filediff
349 ("$TESTDIR/get-with-headers.py" localhost:$HGPORT '/diff/bb948857c743/a?style=raw')
358 ("$TESTDIR/get-with-headers.py" localhost:$HGPORT '/diff/bb948857c743/a?style=raw')
350 echo % errors encountered
359 echo % errors encountered
351 cat errors.log
360 cat errors.log
352
361
353 echo % merge/resolve
362 echo % merge/resolve
354 echo '$Id$' > m
363 echo '$Id$' > m
355 hg add m
364 hg add m
356 hg commit -m 4kw
365 hg commit -m 4kw
357 echo foo >> m
366 echo foo >> m
358 hg commit -m 5foo
367 hg commit -m 5foo
359 echo % simplemerge
368 echo % simplemerge
360 hg update 4
369 hg update 4
361 echo foo >> m
370 echo foo >> m
362 hg commit -m 6foo
371 hg commit -m 6foo
363 hg merge
372 hg merge
364 hg commit -m simplemerge
373 hg commit -m simplemerge
365 cat m
374 cat m
366 echo % conflict
375 echo % conflict
367 hg update 4
376 hg update 4
368 echo bar >> m
377 echo bar >> m
369 hg commit -m 8bar
378 hg commit -m 8bar
370 hg merge
379 hg merge
371 echo % keyword stays outside conflict zone
380 echo % keyword stays outside conflict zone
372 cat m
381 cat m
373 echo % resolve to local
382 echo % resolve to local
374 HGMERGE=internal:local hg resolve -a
383 HGMERGE=internal:local hg resolve -a
375 hg commit -m localresolve
384 hg commit -m localresolve
376 cat m
385 cat m
377
386
378 echo % test restricted mode with transplant -b
387 echo % test restricted mode with transplant -b
379 hg update 6
388 hg update 6
380 hg branch foo
389 hg branch foo
381 mv a a.bak
390 mv a a.bak
382 echo foobranch > a
391 echo foobranch > a
383 cat a.bak >> a
392 cat a.bak >> a
384 rm a.bak
393 rm a.bak
385 hg commit -m 9foobranch
394 hg commit -m 9foobranch
386 hg update default
395 hg update default
387 hg -y transplant -b foo tip
396 hg -y transplant -b foo tip
388 echo % no expansion in changeset
397 echo % no expansion in changeset
389 hg tip -p
398 hg tip -p
390 echo % expansion in file
399 echo % expansion in file
391 head -n 2 a
400 head -n 2 a
392 hg -q rollback
401 hg -q rollback
393 hg -q update -C
402 hg -q update -C
394
403
395 echo % switch off expansion
404 echo % switch off expansion
396 echo % kwshrink with unknown file u
405 echo % kwshrink with unknown file u
397 cp a u
406 cp a u
398 hg --verbose kwshrink
407 hg --verbose kwshrink
399 echo % cat
408 echo % cat
400 cat a b
409 cat a b
401 echo % hg cat
410 echo % hg cat
402 hg cat sym a b
411 hg cat sym a b
403 echo
412 echo
404 rm "$HGRCPATH"
413 rm "$HGRCPATH"
405 echo % cat
414 echo % cat
406 cat a b
415 cat a b
407 echo % hg cat
416 echo % hg cat
408 hg cat sym a b
417 hg cat sym a b
409 echo
418 echo
@@ -1,536 +1,547 b''
1 % hg kwdemo
1 % hg kwdemo
2 [extensions]
2 [extensions]
3 keyword =
3 keyword =
4 [keyword]
4 [keyword]
5 demo.txt =
5 demo.txt =
6 [keywordmaps]
6 [keywordmaps]
7 Author = {author|user}
7 Author = {author|user}
8 Date = {date|utcdate}
8 Date = {date|utcdate}
9 Header = {root}/{file},v {node|short} {date|utcdate} {author|user}
9 Header = {root}/{file},v {node|short} {date|utcdate} {author|user}
10 Id = {file|basename},v {node|short} {date|utcdate} {author|user}
10 Id = {file|basename},v {node|short} {date|utcdate} {author|user}
11 RCSFile = {file|basename},v
11 RCSFile = {file|basename},v
12 RCSfile = {file|basename},v
12 RCSfile = {file|basename},v
13 Revision = {node|short}
13 Revision = {node|short}
14 Source = {root}/{file},v
14 Source = {root}/{file},v
15 $Author: test $
15 $Author: test $
16 $Date: 2000/00/00 00:00:00 $
16 $Date: 2000/00/00 00:00:00 $
17 $Header: /TMP/demo.txt,v xxxxxxxxxxxx 2000/00/00 00:00:00 test $
17 $Header: /TMP/demo.txt,v xxxxxxxxxxxx 2000/00/00 00:00:00 test $
18 $Id: demo.txt,v xxxxxxxxxxxx 2000/00/00 00:00:00 test $
18 $Id: demo.txt,v xxxxxxxxxxxx 2000/00/00 00:00:00 test $
19 $RCSFile: demo.txt,v $
19 $RCSFile: demo.txt,v $
20 $RCSfile: demo.txt,v $
20 $RCSfile: demo.txt,v $
21 $Revision: xxxxxxxxxxxx $
21 $Revision: xxxxxxxxxxxx $
22 $Source: /TMP/demo.txt,v $
22 $Source: /TMP/demo.txt,v $
23 [extensions]
23 [extensions]
24 keyword =
24 keyword =
25 [keyword]
25 [keyword]
26 demo.txt =
26 demo.txt =
27 [keywordmaps]
27 [keywordmaps]
28 Branch = {branches}
28 Branch = {branches}
29 $Branch: demobranch $
29 $Branch: demobranch $
30 % kwshrink should exit silently in empty/invalid repo
30 % kwshrink should exit silently in empty/invalid repo
31 pulling from test-keyword.hg
31 pulling from test-keyword.hg
32 requesting all changes
32 requesting all changes
33 adding changesets
33 adding changesets
34 adding manifests
34 adding manifests
35 adding file changes
35 adding file changes
36 added 1 changesets with 1 changes to 1 files
36 added 1 changesets with 1 changes to 1 files
37 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
37 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
38 % cat
38 % cat
39 expand $Id$
39 expand $Id$
40 do not process $Id:
40 do not process $Id:
41 xxx $
41 xxx $
42 ignore $Id$
42 ignore $Id$
43 % no kwfiles
43 % no kwfiles
44 % untracked candidates
44 % untracked candidates
45 k a
45 k a
46 % addremove
46 % addremove
47 adding a
47 adding a
48 adding b
48 adding b
49 % status
49 % status
50 A a
50 A a
51 A b
51 A b
52 % default keyword expansion including commit hook
52 % default keyword expansion including commit hook
53 % interrupted commit should not change state or run commit hook
53 % interrupted commit should not change state or run commit hook
54 abort: empty commit message
54 abort: empty commit message
55 % status
55 % status
56 A a
56 A a
57 A b
57 A b
58 % commit
58 % commit
59 a
59 a
60 b
60 b
61 overwriting a expanding keywords
61 overwriting a expanding keywords
62 running hook commit.test: cp a hooktest
62 running hook commit.test: cp a hooktest
63 committed changeset 1:ef63ca68695bc9495032c6fda1350c71e6d256e9
63 committed changeset 1:ef63ca68695bc9495032c6fda1350c71e6d256e9
64 % status
64 % status
65 ? hooktest
65 ? hooktest
66 % identify
66 % identify
67 ef63ca68695b
67 ef63ca68695b
68 % cat
68 % cat
69 expand $Id: a,v ef63ca68695b 1970/01/01 00:00:00 user $
69 expand $Id: a,v ef63ca68695b 1970/01/01 00:00:00 user $
70 do not process $Id:
70 do not process $Id:
71 xxx $
71 xxx $
72 ignore $Id$
72 ignore $Id$
73 % hg cat
73 % hg cat
74 expand $Id: a,v ef63ca68695b 1970/01/01 00:00:00 user $
74 expand $Id: a,v ef63ca68695b 1970/01/01 00:00:00 user $
75 do not process $Id:
75 do not process $Id:
76 xxx $
76 xxx $
77 ignore $Id$
77 ignore $Id$
78 a
78 a
79 % diff a hooktest
79 % diff a hooktest
80 % removing commit hook from config
80 % removing commit hook from config
81 % bundle
81 % bundle
82 2 changesets found
82 2 changesets found
83 % notify on pull to check whether keywords stay as is in email
83 % notify on pull to check whether keywords stay as is in email
84 % ie. if patch.diff wrapper acts as it should
84 % ie. if patch.diff wrapper acts as it should
85 % pull from bundle
85 % pull from bundle
86 pulling from ../kw.hg
86 pulling from ../kw.hg
87 requesting all changes
87 requesting all changes
88 adding changesets
88 adding changesets
89 adding manifests
89 adding manifests
90 adding file changes
90 adding file changes
91 added 2 changesets with 3 changes to 3 files
91 added 2 changesets with 3 changes to 3 files
92
92
93 diff -r 000000000000 -r a2392c293916 sym
93 diff -r 000000000000 -r a2392c293916 sym
94 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
94 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
95 +++ b/sym Sat Feb 09 20:25:47 2008 +0100
95 +++ b/sym Sat Feb 09 20:25:47 2008 +0100
96 @@ -0,0 +1,1 @@
96 @@ -0,0 +1,1 @@
97 +a
97 +a
98 \ No newline at end of file
98 \ No newline at end of file
99
99
100 diff -r a2392c293916 -r ef63ca68695b a
100 diff -r a2392c293916 -r ef63ca68695b a
101 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
101 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
102 +++ b/a Thu Jan 01 00:00:00 1970 +0000
102 +++ b/a Thu Jan 01 00:00:00 1970 +0000
103 @@ -0,0 +1,3 @@
103 @@ -0,0 +1,3 @@
104 +expand $Id$
104 +expand $Id$
105 +do not process $Id:
105 +do not process $Id:
106 +xxx $
106 +xxx $
107 diff -r a2392c293916 -r ef63ca68695b b
107 diff -r a2392c293916 -r ef63ca68695b b
108 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
108 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
109 +++ b/b Thu Jan 01 00:00:00 1970 +0000
109 +++ b/b Thu Jan 01 00:00:00 1970 +0000
110 @@ -0,0 +1,1 @@
110 @@ -0,0 +1,1 @@
111 +ignore $Id$
111 +ignore $Id$
112 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
112 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
113 % remove notify config
113 % remove notify config
114 % touch
114 % touch
115 % status
115 % status
116 % update
116 % update
117 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
117 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
118 % cat
118 % cat
119 expand $Id: a,v ef63ca68695b 1970/01/01 00:00:00 user $
119 expand $Id: a,v ef63ca68695b 1970/01/01 00:00:00 user $
120 do not process $Id:
120 do not process $Id:
121 xxx $
121 xxx $
122 ignore $Id$
122 ignore $Id$
123 % check whether expansion is filewise
123 % check whether expansion is filewise
124 % commit c
124 % commit c
125 adding c
125 adding c
126 % force expansion
126 % force expansion
127 overwriting a expanding keywords
127 overwriting a expanding keywords
128 overwriting c expanding keywords
128 overwriting c expanding keywords
129 % compare changenodes in a c
129 % compare changenodes in a c
130 expand $Id: a,v ef63ca68695b 1970/01/01 00:00:00 user $
130 expand $Id: a,v ef63ca68695b 1970/01/01 00:00:00 user $
131 do not process $Id:
131 do not process $Id:
132 xxx $
132 xxx $
133 $Id: c,v 40a904bbbe4c 1970/01/01 00:00:01 user $
133 $Id: c,v 40a904bbbe4c 1970/01/01 00:00:01 user $
134 tests for different changenodes
134 tests for different changenodes
135 % record chunk
135 % record chunk
136 diff --git a/a b/a
136 diff --git a/a b/a
137 2 hunks, 2 lines changed
137 2 hunks, 2 lines changed
138 examine changes to 'a'? [Ynsfdaq?]
138 examine changes to 'a'? [Ynsfdaq?]
139 @@ -1,3 +1,4 @@
139 @@ -1,3 +1,4 @@
140 expand $Id$
140 expand $Id$
141 +foo
141 +foo
142 do not process $Id:
142 do not process $Id:
143 xxx $
143 xxx $
144 record change 1/2 to 'a'? [Ynsfdaq?]
144 record change 1/2 to 'a'? [Ynsfdaq?]
145 @@ -2,2 +3,3 @@
145 @@ -2,2 +3,3 @@
146 do not process $Id:
146 do not process $Id:
147 xxx $
147 xxx $
148 +bar
148 +bar
149 record change 2/2 to 'a'? [Ynsfdaq?]
149 record change 2/2 to 'a'? [Ynsfdaq?]
150
150
151 d17e03c92c97+ tip
151 d17e03c92c97+ tip
152 M a
152 M a
153 % cat modified file
153 % cat modified file
154 expand $Id: a,v d17e03c92c97 1970/01/01 00:00:01 test $
154 expand $Id: a,v d17e03c92c97 1970/01/01 00:00:01 test $
155 foo
155 foo
156 do not process $Id:
156 do not process $Id:
157 xxx $
157 xxx $
158 bar
158 bar
159 diff -r d17e03c92c97 a
159 diff -r d17e03c92c97 a
160 --- a/a Wed Dec 31 23:59:51 1969 -0000
160 --- a/a Wed Dec 31 23:59:51 1969 -0000
161 @@ -2,3 +2,4 @@
161 @@ -2,3 +2,4 @@
162 foo
162 foo
163 do not process $Id:
163 do not process $Id:
164 xxx $
164 xxx $
165 +bar
165 +bar
166 rolling back to revision 2 (undo commit)
166 rolling back to revision 2 (undo commit)
167 % record file
167 % record file
168 diff --git a/a b/a
168 diff --git a/a b/a
169 2 hunks, 2 lines changed
169 2 hunks, 2 lines changed
170 examine changes to 'a'? [Ynsfdaq?]
170 examine changes to 'a'? [Ynsfdaq?]
171 @@ -1,3 +1,4 @@
171 @@ -1,3 +1,4 @@
172 expand $Id$
172 expand $Id$
173 +foo
173 +foo
174 do not process $Id:
174 do not process $Id:
175 xxx $
175 xxx $
176 record change 1/2 to 'a'? [Ynsfdaq?]
176 record change 1/2 to 'a'? [Ynsfdaq?]
177 @@ -2,2 +3,3 @@
177 @@ -2,2 +3,3 @@
178 do not process $Id:
178 do not process $Id:
179 xxx $
179 xxx $
180 +bar
180 +bar
181 record change 2/2 to 'a'? [Ynsfdaq?]
181 record change 2/2 to 'a'? [Ynsfdaq?]
182 % a should be clean
182 % a should be clean
183 C a
183 C a
184 rolling back to revision 2 (undo commit)
184 rolling back to revision 2 (undo commit)
185 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
185 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
186 % init --mq
186 % init --mq
187 % qimport
187 % qimport
188 % commit --mq
188 % commit --mq
189 % keywords should not be expanded in patch
189 % keywords should not be expanded in patch
190 # HG changeset patch
190 # HG changeset patch
191 # User User Name <user@example.com>
191 # User User Name <user@example.com>
192 # Date 1 0
192 # Date 1 0
193 # Node ID 40a904bbbe4cd4ab0a1f28411e35db26341a40ad
193 # Node ID 40a904bbbe4cd4ab0a1f28411e35db26341a40ad
194 # Parent ef63ca68695bc9495032c6fda1350c71e6d256e9
194 # Parent ef63ca68695bc9495032c6fda1350c71e6d256e9
195 cndiff
195 cndiff
196
196
197 diff -r ef63ca68695b -r 40a904bbbe4c c
197 diff -r ef63ca68695b -r 40a904bbbe4c c
198 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
198 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
199 +++ b/c Thu Jan 01 00:00:01 1970 +0000
199 +++ b/c Thu Jan 01 00:00:01 1970 +0000
200 @@ -0,0 +1,2 @@
200 @@ -0,0 +1,2 @@
201 +$Id$
201 +$Id$
202 +tests for different changenodes
202 +tests for different changenodes
203 % qpop
203 % qpop
204 popping mqtest.diff
204 popping mqtest.diff
205 patch queue now empty
205 patch queue now empty
206 % qgoto - should imply qpush
206 % qgoto - should imply qpush
207 applying mqtest.diff
207 applying mqtest.diff
208 now at: mqtest.diff
208 now at: mqtest.diff
209 % cat
209 % cat
210 $Id: c,v 40a904bbbe4c 1970/01/01 00:00:01 user $
210 $Id: c,v 40a904bbbe4c 1970/01/01 00:00:01 user $
211 tests for different changenodes
211 tests for different changenodes
212 % hg cat
212 % hg cat
213 $Id: c,v 40a904bbbe4c 1970/01/01 00:00:01 user $
213 $Id: c,v 40a904bbbe4c 1970/01/01 00:00:01 user $
214 tests for different changenodes
214 tests for different changenodes
215 % keyword should not be expanded in filelog
215 % keyword should not be expanded in filelog
216 $Id$
216 $Id$
217 tests for different changenodes
217 tests for different changenodes
218 % qpop and move on
218 % qpop and move on
219 popping mqtest.diff
219 popping mqtest.diff
220 patch queue now empty
220 patch queue now empty
221 % copy
221 % copy
222 % kwfiles added
222 % kwfiles added
223 a
223 a
224 c
224 c
225 % commit
225 % commit
226 c
226 c
227 c: copy a:0045e12f6c5791aac80ca6cbfd97709a88307292
227 c: copy a:0045e12f6c5791aac80ca6cbfd97709a88307292
228 overwriting c expanding keywords
228 overwriting c expanding keywords
229 committed changeset 2:25736cf2f5cbe41f6be4e6784ef6ecf9f3bbcc7d
229 committed changeset 2:25736cf2f5cbe41f6be4e6784ef6ecf9f3bbcc7d
230 % cat a c
230 % cat a c
231 expand $Id: a,v ef63ca68695b 1970/01/01 00:00:00 user $
231 expand $Id: a,v ef63ca68695b 1970/01/01 00:00:00 user $
232 do not process $Id:
232 do not process $Id:
233 xxx $
233 xxx $
234 expand $Id: c,v 25736cf2f5cb 1970/01/01 00:00:01 user $
234 expand $Id: c,v 25736cf2f5cb 1970/01/01 00:00:01 user $
235 do not process $Id:
235 do not process $Id:
236 xxx $
236 xxx $
237 % touch copied c
237 % touch copied c
238 % status
238 % status
239 % kwfiles
239 % kwfiles
240 a
240 a
241 c
241 c
242 % ignored files
242 % ignored files
243 I b
243 I b
244 I sym
244 I sym
245 % all files
245 % all files
246 K a
246 K a
247 K c
247 K c
248 I b
248 I b
249 I sym
249 I sym
250 % diff --rev
250 % diff --rev
251 diff -r ef63ca68695b c
251 diff -r ef63ca68695b c
252 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
252 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
253 @@ -0,0 +1,3 @@
253 @@ -0,0 +1,3 @@
254 +expand $Id$
254 +expand $Id$
255 +do not process $Id:
255 +do not process $Id:
256 +xxx $
256 +xxx $
257 % rollback
257 % rollback
258 rolling back to revision 1 (undo commit)
258 rolling back to revision 1 (undo commit)
259 % status
259 % status
260 A c
260 A c
261 % update -C
261 % update -C
262 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
262 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
263 % custom keyword expansion
263 % custom keyword expansion
264 % try with kwdemo
264 % try with kwdemo
265 [extensions]
265 [extensions]
266 keyword =
266 keyword =
267 [keyword]
267 [keyword]
268 ** =
268 ** =
269 b = ignore
269 b = ignore
270 demo.txt =
270 demo.txt =
271 [keywordmaps]
271 [keywordmaps]
272 Xinfo = {author}: {desc}
272 Xinfo = {author}: {desc}
273 $Xinfo: test: hg keyword configuration and expansion example $
273 $Xinfo: test: hg keyword configuration and expansion example $
274 % cat
274 % cat
275 expand $Id: a,v ef63ca68695b 1970/01/01 00:00:00 user $
275 expand $Id: a,v ef63ca68695b 1970/01/01 00:00:00 user $
276 do not process $Id:
276 do not process $Id:
277 xxx $
277 xxx $
278 ignore $Id$
278 ignore $Id$
279 % hg cat
279 % hg cat
280 expand $Id: a ef63ca68695b Thu, 01 Jan 1970 00:00:00 +0000 user $
280 expand $Id: a ef63ca68695b Thu, 01 Jan 1970 00:00:00 +0000 user $
281 do not process $Id:
281 do not process $Id:
282 xxx $
282 xxx $
283 ignore $Id$
283 ignore $Id$
284 a
284 a
285 % interrupted commit should not change state
285 % interrupted commit should not change state
286 abort: empty commit message
286 abort: empty commit message
287 % status
287 % status
288 M a
288 M a
289 ? c
289 ? c
290 ? log
290 ? log
291 % commit
291 % commit
292 a
292 a
293 overwriting a expanding keywords
293 overwriting a expanding keywords
294 committed changeset 2:bb948857c743469b22bbf51f7ec8112279ca5d83
294 committed changeset 2:bb948857c743469b22bbf51f7ec8112279ca5d83
295 % status
295 % status
296 ? c
296 ? c
297 % verify
297 % verify
298 checking changesets
298 checking changesets
299 checking manifests
299 checking manifests
300 crosschecking files in changesets and manifests
300 crosschecking files in changesets and manifests
301 checking files
301 checking files
302 3 files, 3 changesets, 4 total revisions
302 3 files, 3 changesets, 4 total revisions
303 % cat
303 % cat
304 expand $Id: a bb948857c743 Thu, 01 Jan 1970 00:00:02 +0000 user $
304 expand $Id: a bb948857c743 Thu, 01 Jan 1970 00:00:02 +0000 user $
305 do not process $Id:
305 do not process $Id:
306 xxx $
306 xxx $
307 $Xinfo: User Name <user@example.com>: firstline $
307 $Xinfo: User Name <user@example.com>: firstline $
308 ignore $Id$
308 ignore $Id$
309 % hg cat
309 % hg cat
310 expand $Id: a bb948857c743 Thu, 01 Jan 1970 00:00:02 +0000 user $
310 expand $Id: a bb948857c743 Thu, 01 Jan 1970 00:00:02 +0000 user $
311 do not process $Id:
311 do not process $Id:
312 xxx $
312 xxx $
313 $Xinfo: User Name <user@example.com>: firstline $
313 $Xinfo: User Name <user@example.com>: firstline $
314 ignore $Id$
314 ignore $Id$
315 a
315 a
316 % annotate
316 % annotate
317 1: expand $Id$
317 1: expand $Id$
318 1: do not process $Id:
318 1: do not process $Id:
319 1: xxx $
319 1: xxx $
320 2: $Xinfo$
320 2: $Xinfo$
321 % remove
321 % remove
322 committed changeset 3:d14c712653769de926994cf7fbb06c8fbd68f012
322 committed changeset 3:d14c712653769de926994cf7fbb06c8fbd68f012
323 % status
323 % status
324 ? c
324 ? c
325 % rollback
325 % rollback
326 rolling back to revision 2 (undo commit)
326 rolling back to revision 2 (undo commit)
327 % status
327 % status
328 R a
328 R a
329 ? c
329 ? c
330 % revert a
330 % revert a
331 % cat a
331 % cat a
332 expand $Id: a bb948857c743 Thu, 01 Jan 1970 00:00:02 +0000 user $
332 expand $Id: a bb948857c743 Thu, 01 Jan 1970 00:00:02 +0000 user $
333 do not process $Id:
333 do not process $Id:
334 xxx $
334 xxx $
335 $Xinfo: User Name <user@example.com>: firstline $
335 $Xinfo: User Name <user@example.com>: firstline $
336 % clone
337 % expansion in dest
338 expand $Id: a bb948857c743 Thu, 01 Jan 1970 00:00:02 +0000 user $
339 do not process $Id:
340 xxx $
341 $Xinfo: User Name <user@example.com>: firstline $
342 % no expansion in dest
343 expand $Id$
344 do not process $Id:
345 xxx $
346 $Xinfo$
336 % clone to test incoming
347 % clone to test incoming
337 requesting all changes
348 requesting all changes
338 adding changesets
349 adding changesets
339 adding manifests
350 adding manifests
340 adding file changes
351 adding file changes
341 added 2 changesets with 3 changes to 3 files
352 added 2 changesets with 3 changes to 3 files
342 updating to branch default
353 updating to branch default
343 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
354 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
344 % incoming
355 % incoming
345 comparing with test-keyword/Test
356 comparing with test-keyword/Test
346 searching for changes
357 searching for changes
347 changeset: 2:bb948857c743
358 changeset: 2:bb948857c743
348 tag: tip
359 tag: tip
349 user: User Name <user@example.com>
360 user: User Name <user@example.com>
350 date: Thu Jan 01 00:00:02 1970 +0000
361 date: Thu Jan 01 00:00:02 1970 +0000
351 summary: firstline
362 summary: firstline
352
363
353 % commit rejecttest
364 % commit rejecttest
354 a
365 a
355 overwriting a expanding keywords
366 overwriting a expanding keywords
356 committed changeset 2:85e279d709ffc28c9fdd1b868570985fc3d87082
367 committed changeset 2:85e279d709ffc28c9fdd1b868570985fc3d87082
357 % export
368 % export
358 % import
369 % import
359 applying ../rejecttest.diff
370 applying ../rejecttest.diff
360 % cat
371 % cat
361 expand $Id: a 4e0994474d25 Thu, 01 Jan 1970 00:00:03 +0000 user $ rejecttest
372 expand $Id: a 4e0994474d25 Thu, 01 Jan 1970 00:00:03 +0000 user $ rejecttest
362 do not process $Id: rejecttest
373 do not process $Id: rejecttest
363 xxx $
374 xxx $
364 $Xinfo: User Name <user@example.com>: rejects? $
375 $Xinfo: User Name <user@example.com>: rejects? $
365 ignore $Id$
376 ignore $Id$
366
377
367 % rollback
378 % rollback
368 rolling back to revision 2 (undo commit)
379 rolling back to revision 2 (undo commit)
369 % clean update
380 % clean update
370 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
381 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
371 % kwexpand/kwshrink on selected files
382 % kwexpand/kwshrink on selected files
372 % copy a x/a
383 % copy a x/a
373 % kwexpand a
384 % kwexpand a
374 overwriting a expanding keywords
385 overwriting a expanding keywords
375 % kwexpand x/a should abort
386 % kwexpand x/a should abort
376 abort: outstanding uncommitted changes
387 abort: outstanding uncommitted changes
377 x/a
388 x/a
378 x/a: copy a:779c764182ce5d43e2b1eb66ce06d7b47bfe342e
389 x/a: copy a:779c764182ce5d43e2b1eb66ce06d7b47bfe342e
379 overwriting x/a expanding keywords
390 overwriting x/a expanding keywords
380 committed changeset 3:b4560182a3f9a358179fd2d835c15e9da379c1e4
391 committed changeset 3:b4560182a3f9a358179fd2d835c15e9da379c1e4
381 % cat a
392 % cat a
382 expand $Id: x/a b4560182a3f9 Thu, 01 Jan 1970 00:00:03 +0000 user $
393 expand $Id: x/a b4560182a3f9 Thu, 01 Jan 1970 00:00:03 +0000 user $
383 do not process $Id:
394 do not process $Id:
384 xxx $
395 xxx $
385 $Xinfo: User Name <user@example.com>: xa $
396 $Xinfo: User Name <user@example.com>: xa $
386 % kwshrink a inside directory x
397 % kwshrink a inside directory x
387 overwriting x/a shrinking keywords
398 overwriting x/a shrinking keywords
388 % cat a
399 % cat a
389 expand $Id$
400 expand $Id$
390 do not process $Id:
401 do not process $Id:
391 xxx $
402 xxx $
392 $Xinfo$
403 $Xinfo$
393 % kwexpand nonexistent
404 % kwexpand nonexistent
394 nonexistent:
405 nonexistent:
395 % hg serve
406 % hg serve
396 % expansion
407 % expansion
397 % hgweb file
408 % hgweb file
398 200 Script output follows
409 200 Script output follows
399
410
400 expand $Id: a bb948857c743 Thu, 01 Jan 1970 00:00:02 +0000 user $
411 expand $Id: a bb948857c743 Thu, 01 Jan 1970 00:00:02 +0000 user $
401 do not process $Id:
412 do not process $Id:
402 xxx $
413 xxx $
403 $Xinfo: User Name <user@example.com>: firstline $
414 $Xinfo: User Name <user@example.com>: firstline $
404 % no expansion
415 % no expansion
405 % hgweb annotate
416 % hgweb annotate
406 200 Script output follows
417 200 Script output follows
407
418
408
419
409 user@1: expand $Id$
420 user@1: expand $Id$
410 user@1: do not process $Id:
421 user@1: do not process $Id:
411 user@1: xxx $
422 user@1: xxx $
412 user@2: $Xinfo$
423 user@2: $Xinfo$
413
424
414
425
415
426
416
427
417 % hgweb changeset
428 % hgweb changeset
418 200 Script output follows
429 200 Script output follows
419
430
420
431
421 # HG changeset patch
432 # HG changeset patch
422 # User User Name <user@example.com>
433 # User User Name <user@example.com>
423 # Date 3 0
434 # Date 3 0
424 # Node ID b4560182a3f9a358179fd2d835c15e9da379c1e4
435 # Node ID b4560182a3f9a358179fd2d835c15e9da379c1e4
425 # Parent bb948857c743469b22bbf51f7ec8112279ca5d83
436 # Parent bb948857c743469b22bbf51f7ec8112279ca5d83
426 xa
437 xa
427
438
428 diff -r bb948857c743 -r b4560182a3f9 x/a
439 diff -r bb948857c743 -r b4560182a3f9 x/a
429 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
440 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
430 +++ b/x/a Thu Jan 01 00:00:03 1970 +0000
441 +++ b/x/a Thu Jan 01 00:00:03 1970 +0000
431 @@ -0,0 +1,4 @@
442 @@ -0,0 +1,4 @@
432 +expand $Id$
443 +expand $Id$
433 +do not process $Id:
444 +do not process $Id:
434 +xxx $
445 +xxx $
435 +$Xinfo$
446 +$Xinfo$
436
447
437 % hgweb filediff
448 % hgweb filediff
438 200 Script output follows
449 200 Script output follows
439
450
440
451
441 diff -r ef63ca68695b -r bb948857c743 a
452 diff -r ef63ca68695b -r bb948857c743 a
442 --- a/a Thu Jan 01 00:00:00 1970 +0000
453 --- a/a Thu Jan 01 00:00:00 1970 +0000
443 +++ b/a Thu Jan 01 00:00:02 1970 +0000
454 +++ b/a Thu Jan 01 00:00:02 1970 +0000
444 @@ -1,3 +1,4 @@
455 @@ -1,3 +1,4 @@
445 expand $Id$
456 expand $Id$
446 do not process $Id:
457 do not process $Id:
447 xxx $
458 xxx $
448 +$Xinfo$
459 +$Xinfo$
449
460
450
461
451
462
452
463
453 % errors encountered
464 % errors encountered
454 % merge/resolve
465 % merge/resolve
455 % simplemerge
466 % simplemerge
456 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
467 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
457 created new head
468 created new head
458 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
469 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
459 (branch merge, don't forget to commit)
470 (branch merge, don't forget to commit)
460 $Id: m 27d48ee14f67 Thu, 01 Jan 1970 00:00:00 +0000 test $
471 $Id: m 27d48ee14f67 Thu, 01 Jan 1970 00:00:00 +0000 test $
461 foo
472 foo
462 % conflict
473 % conflict
463 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
474 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
464 created new head
475 created new head
465 merging m
476 merging m
466 warning: conflicts during merge.
477 warning: conflicts during merge.
467 merging m failed!
478 merging m failed!
468 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
479 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
469 use 'hg resolve' to retry unresolved file merges or 'hg update -C' to abandon
480 use 'hg resolve' to retry unresolved file merges or 'hg update -C' to abandon
470 % keyword stays outside conflict zone
481 % keyword stays outside conflict zone
471 $Id$
482 $Id$
472 <<<<<<< local
483 <<<<<<< local
473 bar
484 bar
474 =======
485 =======
475 foo
486 foo
476 >>>>>>> other
487 >>>>>>> other
477 % resolve to local
488 % resolve to local
478 $Id: m 41efa6d38e9b Thu, 01 Jan 1970 00:00:00 +0000 test $
489 $Id: m 41efa6d38e9b Thu, 01 Jan 1970 00:00:00 +0000 test $
479 bar
490 bar
480 % test restricted mode with transplant -b
491 % test restricted mode with transplant -b
481 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
492 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
482 marked working directory as branch foo
493 marked working directory as branch foo
483 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
494 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
484 applying 4aa30d025d50
495 applying 4aa30d025d50
485 4aa30d025d50 transplanted to 5a4da427c162
496 4aa30d025d50 transplanted to 5a4da427c162
486 % no expansion in changeset
497 % no expansion in changeset
487 changeset: 11:5a4da427c162
498 changeset: 11:5a4da427c162
488 tag: tip
499 tag: tip
489 parent: 9:41efa6d38e9b
500 parent: 9:41efa6d38e9b
490 user: test
501 user: test
491 date: Thu Jan 01 00:00:00 1970 +0000
502 date: Thu Jan 01 00:00:00 1970 +0000
492 summary: 9foobranch
503 summary: 9foobranch
493
504
494 diff -r 41efa6d38e9b -r 5a4da427c162 a
505 diff -r 41efa6d38e9b -r 5a4da427c162 a
495 --- a/a Thu Jan 01 00:00:00 1970 +0000
506 --- a/a Thu Jan 01 00:00:00 1970 +0000
496 +++ b/a Thu Jan 01 00:00:00 1970 +0000
507 +++ b/a Thu Jan 01 00:00:00 1970 +0000
497 @@ -1,3 +1,4 @@
508 @@ -1,3 +1,4 @@
498 +foobranch
509 +foobranch
499 expand $Id$
510 expand $Id$
500 do not process $Id:
511 do not process $Id:
501 xxx $
512 xxx $
502
513
503 % expansion in file
514 % expansion in file
504 foobranch
515 foobranch
505 expand $Id: a 5a4da427c162 Thu, 01 Jan 1970 00:00:00 +0000 test $
516 expand $Id: a 5a4da427c162 Thu, 01 Jan 1970 00:00:00 +0000 test $
506 % switch off expansion
517 % switch off expansion
507 % kwshrink with unknown file u
518 % kwshrink with unknown file u
508 overwriting a shrinking keywords
519 overwriting a shrinking keywords
509 overwriting m shrinking keywords
520 overwriting m shrinking keywords
510 overwriting x/a shrinking keywords
521 overwriting x/a shrinking keywords
511 % cat
522 % cat
512 expand $Id$
523 expand $Id$
513 do not process $Id:
524 do not process $Id:
514 xxx $
525 xxx $
515 $Xinfo$
526 $Xinfo$
516 ignore $Id$
527 ignore $Id$
517 % hg cat
528 % hg cat
518 expand $Id: a bb948857c743 Thu, 01 Jan 1970 00:00:02 +0000 user $
529 expand $Id: a bb948857c743 Thu, 01 Jan 1970 00:00:02 +0000 user $
519 do not process $Id:
530 do not process $Id:
520 xxx $
531 xxx $
521 $Xinfo: User Name <user@example.com>: firstline $
532 $Xinfo: User Name <user@example.com>: firstline $
522 ignore $Id$
533 ignore $Id$
523 a
534 a
524 % cat
535 % cat
525 expand $Id$
536 expand $Id$
526 do not process $Id:
537 do not process $Id:
527 xxx $
538 xxx $
528 $Xinfo$
539 $Xinfo$
529 ignore $Id$
540 ignore $Id$
530 % hg cat
541 % hg cat
531 expand $Id$
542 expand $Id$
532 do not process $Id:
543 do not process $Id:
533 xxx $
544 xxx $
534 $Xinfo$
545 $Xinfo$
535 ignore $Id$
546 ignore $Id$
536 a
547 a
@@ -1,96 +1,96 b''
1 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
1 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
2 created new head
2 created new head
3 merging bar and foo to bar
3 merging bar and foo to bar
4 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
4 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
5 (branch merge, don't forget to commit)
5 (branch merge, don't forget to commit)
6 % contents of bar should be line0 line1 line2
6 % contents of bar should be line0 line1 line2
7 line0
7 line0
8 line1
8 line1
9 line2
9 line2
10 rev offset length base linkrev nodeid p1 p2
10 rev offset length base linkrev nodeid p1 p2
11 0 0 77 0 2 d35118874825 000000000000 000000000000
11 0 0 77 0 2 d35118874825 000000000000 000000000000
12 1 77 76 0 3 5345f5ab8abd 000000000000 d35118874825
12 1 77 76 0 3 5345f5ab8abd 000000000000 d35118874825
13 bar renamed from foo:9e25c27b87571a1edee5ae4dddee5687746cc8e2
13 bar renamed from foo:9e25c27b87571a1edee5ae4dddee5687746cc8e2
14 rev offset length base linkrev nodeid p1 p2
14 rev offset length base linkrev nodeid p1 p2
15 0 0 7 0 0 690b295714ae 000000000000 000000000000
15 0 0 7 0 0 690b295714ae 000000000000 000000000000
16 1 7 13 1 1 9e25c27b8757 690b295714ae 000000000000
16 1 7 13 1 1 9e25c27b8757 690b295714ae 000000000000
17 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
17 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
18 created new head
18 created new head
19 4:2263c1be0967 2:0f2ff26688b9
19 4:2263c1be0967 2:0f2ff26688b9
20 3:0555950ead28 2:0f2ff26688b9 1:5cd961e4045d
20 3:0555950ead28 2:0f2ff26688b9 1:5cd961e4045d
21 2:0f2ff26688b9 0:2665aaee66e9
21 2:0f2ff26688b9 0:2665aaee66e9
22 1:5cd961e4045d
22 1:5cd961e4045d
23 0:2665aaee66e9
23 0:2665aaee66e9
24 % this should use bar@rev2 as the ancestor
24 % this should use bar@rev2 as the ancestor
25 searching for copies back to rev 1
25 searching for copies back to rev 1
26 resolving manifests
26 resolving manifests
27 overwrite None partial False
27 overwrite None partial False
28 ancestor 0f2ff26688b9 local 2263c1be0967+ remote 0555950ead28
28 ancestor 0f2ff26688b9 local 2263c1be0967+ remote 0555950ead28
29 bar: versions differ -> m
29 bar: versions differ -> m
30 preserving bar for resolve of bar
30 preserving bar for resolve of bar
31 update: bar 1/1 files (100.00%)
31 updating: bar 1/1 files (100.00%)
32 picked tool 'internal:merge' for bar (binary False symlink False)
32 picked tool 'internal:merge' for bar (binary False symlink False)
33 merging bar
33 merging bar
34 my bar@2263c1be0967+ other bar@0555950ead28 ancestor bar@0f2ff26688b9
34 my bar@2263c1be0967+ other bar@0555950ead28 ancestor bar@0f2ff26688b9
35 premerge successful
35 premerge successful
36 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
36 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
37 (branch merge, don't forget to commit)
37 (branch merge, don't forget to commit)
38 % contents of bar should be line1 line2
38 % contents of bar should be line1 line2
39 line1
39 line1
40 line2
40 line2
41 rev offset length base linkrev nodeid p1 p2
41 rev offset length base linkrev nodeid p1 p2
42 0 0 77 0 2 d35118874825 000000000000 000000000000
42 0 0 77 0 2 d35118874825 000000000000 000000000000
43 1 77 76 0 3 5345f5ab8abd 000000000000 d35118874825
43 1 77 76 0 3 5345f5ab8abd 000000000000 d35118874825
44 2 153 7 2 4 ff4b45017382 d35118874825 000000000000
44 2 153 7 2 4 ff4b45017382 d35118874825 000000000000
45 3 160 13 3 5 3701b4893544 ff4b45017382 5345f5ab8abd
45 3 160 13 3 5 3701b4893544 ff4b45017382 5345f5ab8abd
46
46
47
47
48 requesting all changes
48 requesting all changes
49 adding changesets
49 adding changesets
50 adding manifests
50 adding manifests
51 adding file changes
51 adding file changes
52 added 3 changesets with 3 changes to 2 files (+1 heads)
52 added 3 changesets with 3 changes to 2 files (+1 heads)
53 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
53 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
54 merging foo and bar to bar
54 merging foo and bar to bar
55 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
55 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
56 (branch merge, don't forget to commit)
56 (branch merge, don't forget to commit)
57 % contents of bar should be line0 line1 line2
57 % contents of bar should be line0 line1 line2
58 line0
58 line0
59 line1
59 line1
60 line2
60 line2
61 rev offset length base linkrev nodeid p1 p2
61 rev offset length base linkrev nodeid p1 p2
62 0 0 77 0 2 d35118874825 000000000000 000000000000
62 0 0 77 0 2 d35118874825 000000000000 000000000000
63 1 77 76 0 3 5345f5ab8abd 000000000000 d35118874825
63 1 77 76 0 3 5345f5ab8abd 000000000000 d35118874825
64 bar renamed from foo:9e25c27b87571a1edee5ae4dddee5687746cc8e2
64 bar renamed from foo:9e25c27b87571a1edee5ae4dddee5687746cc8e2
65 rev offset length base linkrev nodeid p1 p2
65 rev offset length base linkrev nodeid p1 p2
66 0 0 7 0 0 690b295714ae 000000000000 000000000000
66 0 0 7 0 0 690b295714ae 000000000000 000000000000
67 1 7 13 1 1 9e25c27b8757 690b295714ae 000000000000
67 1 7 13 1 1 9e25c27b8757 690b295714ae 000000000000
68 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
68 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
69 created new head
69 created new head
70 4:2263c1be0967 2:0f2ff26688b9
70 4:2263c1be0967 2:0f2ff26688b9
71 3:3ffa6b9e35f0 1:5cd961e4045d 2:0f2ff26688b9
71 3:3ffa6b9e35f0 1:5cd961e4045d 2:0f2ff26688b9
72 2:0f2ff26688b9 0:2665aaee66e9
72 2:0f2ff26688b9 0:2665aaee66e9
73 1:5cd961e4045d
73 1:5cd961e4045d
74 0:2665aaee66e9
74 0:2665aaee66e9
75 % this should use bar@rev2 as the ancestor
75 % this should use bar@rev2 as the ancestor
76 searching for copies back to rev 1
76 searching for copies back to rev 1
77 resolving manifests
77 resolving manifests
78 overwrite None partial False
78 overwrite None partial False
79 ancestor 0f2ff26688b9 local 2263c1be0967+ remote 3ffa6b9e35f0
79 ancestor 0f2ff26688b9 local 2263c1be0967+ remote 3ffa6b9e35f0
80 bar: versions differ -> m
80 bar: versions differ -> m
81 preserving bar for resolve of bar
81 preserving bar for resolve of bar
82 update: bar 1/1 files (100.00%)
82 updating: bar 1/1 files (100.00%)
83 picked tool 'internal:merge' for bar (binary False symlink False)
83 picked tool 'internal:merge' for bar (binary False symlink False)
84 merging bar
84 merging bar
85 my bar@2263c1be0967+ other bar@3ffa6b9e35f0 ancestor bar@0f2ff26688b9
85 my bar@2263c1be0967+ other bar@3ffa6b9e35f0 ancestor bar@0f2ff26688b9
86 premerge successful
86 premerge successful
87 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
87 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
88 (branch merge, don't forget to commit)
88 (branch merge, don't forget to commit)
89 % contents of bar should be line1 line2
89 % contents of bar should be line1 line2
90 line1
90 line1
91 line2
91 line2
92 rev offset length base linkrev nodeid p1 p2
92 rev offset length base linkrev nodeid p1 p2
93 0 0 77 0 2 d35118874825 000000000000 000000000000
93 0 0 77 0 2 d35118874825 000000000000 000000000000
94 1 77 76 0 3 5345f5ab8abd 000000000000 d35118874825
94 1 77 76 0 3 5345f5ab8abd 000000000000 d35118874825
95 2 153 7 2 4 ff4b45017382 d35118874825 000000000000
95 2 153 7 2 4 ff4b45017382 d35118874825 000000000000
96 3 160 13 3 5 3701b4893544 ff4b45017382 5345f5ab8abd
96 3 160 13 3 5 3701b4893544 ff4b45017382 5345f5ab8abd
@@ -1,29 +1,29 b''
1 adding a
1 adding a
2 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
2 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
3 created new head
3 created new head
4 searching for copies back to rev 1
4 searching for copies back to rev 1
5 resolving manifests
5 resolving manifests
6 overwrite None partial False
6 overwrite None partial False
7 ancestor c334dc3be0da local 521a1e40188f+ remote 3574f3e69b1c
7 ancestor c334dc3be0da local 521a1e40188f+ remote 3574f3e69b1c
8 conflicting flags for a
8 conflicting flags for a
9 (n)one, e(x)ec or sym(l)ink? n
9 (n)one, e(x)ec or sym(l)ink? n
10 a: update permissions -> e
10 a: update permissions -> e
11 update: a 1/1 files (100.00%)
11 updating: a 1/1 files (100.00%)
12 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
12 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
13 (branch merge, don't forget to commit)
13 (branch merge, don't forget to commit)
14 % symlink is local parent, executable is other
14 % symlink is local parent, executable is other
15 a has no flags (default for conflicts)
15 a has no flags (default for conflicts)
16 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
16 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
17 searching for copies back to rev 1
17 searching for copies back to rev 1
18 resolving manifests
18 resolving manifests
19 overwrite None partial False
19 overwrite None partial False
20 ancestor c334dc3be0da local 3574f3e69b1c+ remote 521a1e40188f
20 ancestor c334dc3be0da local 3574f3e69b1c+ remote 521a1e40188f
21 conflicting flags for a
21 conflicting flags for a
22 (n)one, e(x)ec or sym(l)ink? n
22 (n)one, e(x)ec or sym(l)ink? n
23 a: remote is newer -> g
23 a: remote is newer -> g
24 update: a 1/1 files (100.00%)
24 updating: a 1/1 files (100.00%)
25 getting a
25 getting a
26 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
26 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
27 (branch merge, don't forget to commit)
27 (branch merge, don't forget to commit)
28 % symlink is other parent, executable is local
28 % symlink is other parent, executable is local
29 a has no flags (default for conflicts)
29 a has no flags (default for conflicts)
@@ -1,78 +1,78 b''
1 updating to branch default
1 updating to branch default
2 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
2 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
3 pulling from ../test-a
3 pulling from ../test-a
4 searching for changes
4 searching for changes
5 adding changesets
5 adding changesets
6 adding manifests
6 adding manifests
7 adding file changes
7 adding file changes
8 added 1 changesets with 1 changes to 1 files (+1 heads)
8 added 1 changesets with 1 changes to 1 files (+1 heads)
9 (run 'hg heads' to see heads, 'hg merge' to merge)
9 (run 'hg heads' to see heads, 'hg merge' to merge)
10 merging test.txt
10 merging test.txt
11 warning: conflicts during merge.
11 warning: conflicts during merge.
12 merging test.txt failed!
12 merging test.txt failed!
13 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
13 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
14 use 'hg resolve' to retry unresolved file merges or 'hg update -C' to abandon
14 use 'hg resolve' to retry unresolved file merges or 'hg update -C' to abandon
15 pulling from ../test-a
15 pulling from ../test-a
16 searching for changes
16 searching for changes
17 adding changesets
17 adding changesets
18 adding manifests
18 adding manifests
19 adding file changes
19 adding file changes
20 added 1 changesets with 1 changes to 1 files (+1 heads)
20 added 1 changesets with 1 changes to 1 files (+1 heads)
21 (run 'hg heads' to see heads, 'hg merge' to merge)
21 (run 'hg heads' to see heads, 'hg merge' to merge)
22 searching for copies back to rev 1
22 searching for copies back to rev 1
23 resolving manifests
23 resolving manifests
24 overwrite None partial False
24 overwrite None partial False
25 ancestor faaea63e63a9 local 451c744aabcc+ remote a070d41e8360
25 ancestor faaea63e63a9 local 451c744aabcc+ remote a070d41e8360
26 test.txt: versions differ -> m
26 test.txt: versions differ -> m
27 preserving test.txt for resolve of test.txt
27 preserving test.txt for resolve of test.txt
28 update: test.txt 1/1 files (100.00%)
28 updating: test.txt 1/1 files (100.00%)
29 picked tool 'internal:merge' for test.txt (binary False symlink False)
29 picked tool 'internal:merge' for test.txt (binary False symlink False)
30 merging test.txt
30 merging test.txt
31 my test.txt@451c744aabcc+ other test.txt@a070d41e8360 ancestor test.txt@faaea63e63a9
31 my test.txt@451c744aabcc+ other test.txt@a070d41e8360 ancestor test.txt@faaea63e63a9
32 warning: conflicts during merge.
32 warning: conflicts during merge.
33 merging test.txt failed!
33 merging test.txt failed!
34 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
34 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
35 use 'hg resolve' to retry unresolved file merges or 'hg update -C' to abandon
35 use 'hg resolve' to retry unresolved file merges or 'hg update -C' to abandon
36 one
36 one
37 <<<<<<< local
37 <<<<<<< local
38 two-point-five
38 two-point-five
39 =======
39 =======
40 two-point-one
40 two-point-one
41 >>>>>>> other
41 >>>>>>> other
42 three
42 three
43 rev offset length base linkrev nodeid p1 p2
43 rev offset length base linkrev nodeid p1 p2
44 0 0 7 0 0 01365c4cca56 000000000000 000000000000
44 0 0 7 0 0 01365c4cca56 000000000000 000000000000
45 1 7 9 1 1 7b013192566a 01365c4cca56 000000000000
45 1 7 9 1 1 7b013192566a 01365c4cca56 000000000000
46 2 16 15 2 2 8fe46a3eb557 01365c4cca56 000000000000
46 2 16 15 2 2 8fe46a3eb557 01365c4cca56 000000000000
47 3 31 27 2 3 fc3148072371 7b013192566a 8fe46a3eb557
47 3 31 27 2 3 fc3148072371 7b013192566a 8fe46a3eb557
48 4 58 25 4 4 d40249267ae3 8fe46a3eb557 000000000000
48 4 58 25 4 4 d40249267ae3 8fe46a3eb557 000000000000
49 changeset: 4:a070d41e8360
49 changeset: 4:a070d41e8360
50 tag: tip
50 tag: tip
51 parent: 2:faaea63e63a9
51 parent: 2:faaea63e63a9
52 user: test
52 user: test
53 date: Mon Jan 12 13:46:40 1970 +0000
53 date: Mon Jan 12 13:46:40 1970 +0000
54 summary: two -> two-point-one
54 summary: two -> two-point-one
55
55
56 changeset: 3:451c744aabcc
56 changeset: 3:451c744aabcc
57 parent: 1:e409be6afcc0
57 parent: 1:e409be6afcc0
58 parent: 2:faaea63e63a9
58 parent: 2:faaea63e63a9
59 user: test
59 user: test
60 date: Mon Jan 12 13:46:40 1970 +0000
60 date: Mon Jan 12 13:46:40 1970 +0000
61 summary: Merge 1
61 summary: Merge 1
62
62
63 changeset: 2:faaea63e63a9
63 changeset: 2:faaea63e63a9
64 parent: 0:095c92b91f1a
64 parent: 0:095c92b91f1a
65 user: test
65 user: test
66 date: Mon Jan 12 13:46:40 1970 +0000
66 date: Mon Jan 12 13:46:40 1970 +0000
67 summary: Numbers as words
67 summary: Numbers as words
68
68
69 changeset: 1:e409be6afcc0
69 changeset: 1:e409be6afcc0
70 user: test
70 user: test
71 date: Mon Jan 12 13:46:40 1970 +0000
71 date: Mon Jan 12 13:46:40 1970 +0000
72 summary: 2 -> 2.5
72 summary: 2 -> 2.5
73
73
74 changeset: 0:095c92b91f1a
74 changeset: 0:095c92b91f1a
75 user: test
75 user: test
76 date: Mon Jan 12 13:46:40 1970 +0000
76 date: Mon Jan 12 13:46:40 1970 +0000
77 summary: Initial
77 summary: Initial
78
78
@@ -1,625 +1,642 b''
1 #!/bin/sh
1 #!/bin/sh
2
2
3 . $TESTDIR/helpers.sh
3 . $TESTDIR/helpers.sh
4
4
5 checkundo()
5 checkundo()
6 {
6 {
7 if [ -f .hg/store/undo ]; then
7 if [ -f .hg/store/undo ]; then
8 echo ".hg/store/undo still exists after $1"
8 echo ".hg/store/undo still exists after $1"
9 fi
9 fi
10 }
10 }
11
11
12 echo "[extensions]" >> $HGRCPATH
12 echo "[extensions]" >> $HGRCPATH
13 echo "mq=" >> $HGRCPATH
13 echo "mq=" >> $HGRCPATH
14
14
15 echo "[mq]" >> $HGRCPATH
15 echo "[mq]" >> $HGRCPATH
16 echo "plain=true" >> $HGRCPATH
16 echo "plain=true" >> $HGRCPATH
17
17
18 echo % help
18 echo % help
19 hg help mq
19 hg help mq
20
20
21 hg init a
21 hg init a
22 cd a
22 cd a
23 echo a > a
23 echo a > a
24 hg ci -Ama
24 hg ci -Ama
25
25
26 hg clone . ../k
26 hg clone . ../k
27
27
28 mkdir b
28 mkdir b
29 echo z > b/z
29 echo z > b/z
30 hg ci -Ama
30 hg ci -Ama
31
31
32 echo % qinit
32 echo % qinit
33
33
34 hg qinit
34 hg qinit
35
35
36 cd ..
36 cd ..
37 hg init b
37 hg init b
38
38
39 echo % -R qinit
39 echo % -R qinit
40
40
41 hg -R b qinit
41 hg -R b qinit
42
42
43 hg init c
43 hg init c
44
44
45 echo % qinit -c
45 echo % qinit -c
46
46
47 hg --cwd c qinit -c
47 hg --cwd c qinit -c
48 hg -R c/.hg/patches st
48 hg -R c/.hg/patches st
49
49
50 echo '% qinit; qinit -c'
50 echo '% qinit; qinit -c'
51 hg init d
51 hg init d
52 cd d
52 cd d
53 hg qinit
53 hg qinit
54 hg qinit -c
54 hg qinit -c
55 # qinit -c should create both files if they don't exist
55 # qinit -c should create both files if they don't exist
56 echo ' .hgignore:'
56 echo ' .hgignore:'
57 cat .hg/patches/.hgignore
57 cat .hg/patches/.hgignore
58 echo ' series:'
58 echo ' series:'
59 cat .hg/patches/series
59 cat .hg/patches/series
60 hg qinit -c 2>&1 | sed -e 's/repository.*already/repository already/'
60 hg qinit -c 2>&1 | sed -e 's/repository.*already/repository already/'
61 cd ..
61 cd ..
62
62
63 echo '% qinit; <stuff>; qinit -c'
63 echo '% qinit; <stuff>; qinit -c'
64 hg init e
64 hg init e
65 cd e
65 cd e
66 hg qnew A
66 hg qnew A
67 checkundo qnew
67 checkundo qnew
68 echo foo > foo
68 echo foo > foo
69 hg add foo
69 hg add foo
70 hg qrefresh
70 hg qrefresh
71 hg qnew B
71 hg qnew B
72 echo >> foo
72 echo >> foo
73 hg qrefresh
73 hg qrefresh
74 echo status >> .hg/patches/.hgignore
74 echo status >> .hg/patches/.hgignore
75 echo bleh >> .hg/patches/.hgignore
75 echo bleh >> .hg/patches/.hgignore
76 hg qinit -c
76 hg qinit -c
77 hg -R .hg/patches status
77 hg -R .hg/patches status
78 # qinit -c shouldn't touch these files if they already exist
78 # qinit -c shouldn't touch these files if they already exist
79 echo ' .hgignore:'
79 echo ' .hgignore:'
80 cat .hg/patches/.hgignore
80 cat .hg/patches/.hgignore
81 echo ' series:'
81 echo ' series:'
82 cat .hg/patches/series
82 cat .hg/patches/series
83
83
84 echo '% status --mq with color (issue2096)'
84 echo '% status --mq with color (issue2096)'
85 hg status --mq --config extensions.color= --color=always
85 hg status --mq --config extensions.color= --color=always
86 cd ..
86 cd ..
87
87
88 echo '% init --mq without repo'
88 echo '% init --mq without repo'
89 mkdir f
89 mkdir f
90 cd f
90 cd f
91 hg init --mq
91 hg init --mq
92 cd ..
92 cd ..
93
93
94 echo '% init --mq with repo path'
94 echo '% init --mq with repo path'
95 hg init g
95 hg init g
96 hg init --mq g
96 hg init --mq g
97 test -d g/.hg/patches/.hg && echo "ok" || echo "failed"
97 test -d g/.hg/patches/.hg && echo "ok" || echo "failed"
98
98
99 echo '% init --mq with nonexistent directory'
99 echo '% init --mq with nonexistent directory'
100 hg init --mq nonexistentdir
100 hg init --mq nonexistentdir
101
101
102 echo '% init --mq with bundle (non "local")'
102 echo '% init --mq with bundle (non "local")'
103 hg -R a bundle --all a.bundle >/dev/null
103 hg -R a bundle --all a.bundle >/dev/null
104 hg init --mq a.bundle
104 hg init --mq a.bundle
105
105
106 cd a
106 cd a
107
107
108 hg qnew -m 'foo bar' test.patch
108 hg qnew -m 'foo bar' test.patch
109
109
110 echo '# comment' > .hg/patches/series.tmp
111 echo >> .hg/patches/series.tmp # empty line
112 cat .hg/patches/series >> .hg/patches/series.tmp
113 mv .hg/patches/series.tmp .hg/patches/series
114
110 echo % qrefresh
115 echo % qrefresh
111
116
112 echo a >> a
117 echo a >> a
113 hg qrefresh
118 hg qrefresh
114 sed -e "s/^\(diff -r \)\([a-f0-9]* \)/\1 x/" \
119 sed -e "s/^\(diff -r \)\([a-f0-9]* \)/\1 x/" \
115 -e "s/\(+++ [a-zA-Z0-9_/.-]*\).*/\1/" \
120 -e "s/\(+++ [a-zA-Z0-9_/.-]*\).*/\1/" \
116 -e "s/\(--- [a-zA-Z0-9_/.-]*\).*/\1/" .hg/patches/test.patch
121 -e "s/\(--- [a-zA-Z0-9_/.-]*\).*/\1/" .hg/patches/test.patch
117
122
118 echo % empty qrefresh
123 echo % empty qrefresh
119
124
120 hg qrefresh -X a
125 hg qrefresh -X a
121 echo 'revision:'
126 echo 'revision:'
122 hg diff -r -2 -r -1
127 hg diff -r -2 -r -1
123 echo 'patch:'
128 echo 'patch:'
124 cat .hg/patches/test.patch
129 cat .hg/patches/test.patch
125 echo 'working dir diff:'
130 echo 'working dir diff:'
126 hg diff --nodates -q
131 hg diff --nodates -q
127 # restore things
132 # restore things
128 hg qrefresh
133 hg qrefresh
129 checkundo qrefresh
134 checkundo qrefresh
130
135
131 echo % qpop
136 echo % qpop
132
137
133 hg qpop
138 hg qpop
134 checkundo qpop
139 checkundo qpop
135
140
136 echo % qpush with dump of tag cache
141 echo % qpush with dump of tag cache
137
142
138 # Dump the tag cache to ensure that it has exactly one head after qpush.
143 # Dump the tag cache to ensure that it has exactly one head after qpush.
139 rm -f .hg/tags.cache
144 rm -f .hg/tags.cache
140 hg tags > /dev/null
145 hg tags > /dev/null
141 echo ".hg/tags.cache (pre qpush):"
146 echo ".hg/tags.cache (pre qpush):"
142 sed 's/ [0-9a-f]*//' .hg/tags.cache
147 sed 's/ [0-9a-f]*//' .hg/tags.cache
143 hg qpush
148 hg qpush
144 hg tags > /dev/null
149 hg tags > /dev/null
145 echo ".hg/tags.cache (post qpush):"
150 echo ".hg/tags.cache (post qpush):"
146 sed 's/ [0-9a-f]*//' .hg/tags.cache
151 sed 's/ [0-9a-f]*//' .hg/tags.cache
147
152
148 checkundo qpush
153 checkundo qpush
149
154
150 cd ..
155 cd ..
151
156
152 echo % pop/push outside repo
157 echo % pop/push outside repo
153
158
154 hg -R a qpop
159 hg -R a qpop
155 hg -R a qpush
160 hg -R a qpush
156
161
157 cd a
162 cd a
158 hg qnew test2.patch
163 hg qnew test2.patch
159
164
160 echo % qrefresh in subdir
165 echo % qrefresh in subdir
161
166
162 cd b
167 cd b
163 echo a > a
168 echo a > a
164 hg add a
169 hg add a
165 hg qrefresh
170 hg qrefresh
166
171
167 echo % pop/push -a in subdir
172 echo % pop/push -a in subdir
168
173
169 hg qpop -a
174 hg qpop -a
170 hg --traceback qpush -a
175 hg --traceback qpush -a
171
176
172 # setting columns & formatted tests truncating (issue1912)
177 # setting columns & formatted tests truncating (issue1912)
173 echo % qseries
178 echo % qseries
174 COLUMNS=4 hg qseries --config ui.formatted=true
179 COLUMNS=4 hg qseries --config ui.formatted=true
175 COLUMNS=20 hg qseries --config ui.formatted=true -vs
180 COLUMNS=20 hg qseries --config ui.formatted=true -vs
176 hg qpop
181 hg qpop
177 hg qseries -vs
182 hg qseries -vs
178 hg sum | grep mq
183 hg sum | grep mq
179 hg qpush
184 hg qpush
180 hg sum | grep mq
185 hg sum | grep mq
181
186
182 echo % qapplied
187 echo % qapplied
183 hg qapplied
188 hg qapplied
184
189
185 echo % qtop
190 echo % qtop
186 hg qtop
191 hg qtop
187
192
188 echo % prev
193 echo % prev
189 hg qapp -1
194 hg qapp -1
190
195
191 echo % next
196 echo % next
192 hg qunapp -1
197 hg qunapp -1
193
198
194 hg qpop
199 hg qpop
195 echo % commit should fail
200 echo % commit should fail
196 hg commit
201 hg commit
197
202
198 echo % push should fail
203 echo % push should fail
199 hg push ../../k
204 hg push ../../k
200
205
201 echo % import should fail
206 echo % import should fail
202 hg st .
207 hg st .
203 echo foo >> ../a
208 echo foo >> ../a
204 hg diff > ../../import.diff
209 hg diff > ../../import.diff
205 hg revert --no-backup ../a
210 hg revert --no-backup ../a
206 hg import ../../import.diff
211 hg import ../../import.diff
207 hg st
212 hg st
208 echo % import --no-commit should succeed
213 echo % import --no-commit should succeed
209 hg import --no-commit ../../import.diff
214 hg import --no-commit ../../import.diff
210 hg st
215 hg st
211 hg revert --no-backup ../a
216 hg revert --no-backup ../a
212
217
213 echo % qunapplied
218 echo % qunapplied
214 hg qunapplied
219 hg qunapplied
215
220
216 echo % qpush/qpop with index
221 echo % qpush/qpop with index
217 hg qnew test1b.patch
222 hg qnew test1b.patch
218 echo 1b > 1b
223 echo 1b > 1b
219 hg add 1b
224 hg add 1b
220 hg qrefresh
225 hg qrefresh
221 hg qpush 2
226 hg qpush 2
222 hg qpop 0
227 hg qpop 0
223 hg qpush test.patch+1
228 hg qpush test.patch+1
224 hg qpush test.patch+2
229 hg qpush test.patch+2
225 hg qpop test2.patch-1
230 hg qpop test2.patch-1
226 hg qpop test2.patch-2
231 hg qpop test2.patch-2
227 hg qpush test1b.patch+1
232 hg qpush test1b.patch+1
228
233
229 echo % qpush --move
234 echo % qpush --move
230 hg qpop -a
235 hg qpop -a
236 hg qguard test1b.patch -- -negguard
237 hg qguard test2.patch -- +posguard
238 hg qpush --move test2.patch # can't move guarded patch
239 hg qselect posguard
231 hg qpush --move test2.patch # move to front
240 hg qpush --move test2.patch # move to front
232 hg qpush --move test1b.patch
241 hg qpush --move test1b.patch # negative guard unselected
233 hg qpush --move test.patch # noop move
242 hg qpush --move test.patch # noop move
234 hg qseries -v
243 hg qseries -v
235 hg qpop -a
244 hg qpop -a
236 hg qpush --move test.patch # cleaning up
245 # cleaning up
246 hg qselect --none
247 hg qguard --none test1b.patch
248 hg qguard --none test2.patch
249 hg qpush --move test.patch
237 hg qpush --move test1b.patch
250 hg qpush --move test1b.patch
238 hg qpush --move bogus # nonexistent patch
251 hg qpush --move bogus # nonexistent patch
252 hg qpush --move # no patch
239 hg qpush --move test.patch # already applied
253 hg qpush --move test.patch # already applied
240 hg qpush
254 hg qpush
241
255
256 echo % series after move
257 cat `hg root`/.hg/patches/series
258
242 echo % pop, qapplied, qunapplied
259 echo % pop, qapplied, qunapplied
243 hg qseries -v
260 hg qseries -v
244 echo % qapplied -1 test.patch
261 echo % qapplied -1 test.patch
245 hg qapplied -1 test.patch
262 hg qapplied -1 test.patch
246 echo % qapplied -1 test1b.patch
263 echo % qapplied -1 test1b.patch
247 hg qapplied -1 test1b.patch
264 hg qapplied -1 test1b.patch
248 echo % qapplied -1 test2.patch
265 echo % qapplied -1 test2.patch
249 hg qapplied -1 test2.patch
266 hg qapplied -1 test2.patch
250 echo % qapplied -1
267 echo % qapplied -1
251 hg qapplied -1
268 hg qapplied -1
252 echo % qapplied
269 echo % qapplied
253 hg qapplied
270 hg qapplied
254 echo % qapplied test1b.patch
271 echo % qapplied test1b.patch
255 hg qapplied test1b.patch
272 hg qapplied test1b.patch
256 echo % qunapplied -1
273 echo % qunapplied -1
257 hg qunapplied -1
274 hg qunapplied -1
258 echo % qunapplied
275 echo % qunapplied
259 hg qunapplied
276 hg qunapplied
260 echo % popping
277 echo % popping
261 hg qpop
278 hg qpop
262 echo % qunapplied -1
279 echo % qunapplied -1
263 hg qunapplied -1
280 hg qunapplied -1
264 echo % qunapplied
281 echo % qunapplied
265 hg qunapplied
282 hg qunapplied
266 echo % qunapplied test2.patch
283 echo % qunapplied test2.patch
267 hg qunapplied test2.patch
284 hg qunapplied test2.patch
268 echo % qunapplied -1 test2.patch
285 echo % qunapplied -1 test2.patch
269 hg qunapplied -1 test2.patch
286 hg qunapplied -1 test2.patch
270 echo % popping -a
287 echo % popping -a
271 hg qpop -a
288 hg qpop -a
272 echo % qapplied
289 echo % qapplied
273 hg qapplied
290 hg qapplied
274 echo % qapplied -1
291 echo % qapplied -1
275 hg qapplied -1
292 hg qapplied -1
276 hg qpush
293 hg qpush
277
294
278 echo % push should succeed
295 echo % push should succeed
279 hg qpop -a
296 hg qpop -a
280 hg push ../../k
297 hg push ../../k
281
298
282 echo % qpush/qpop error codes
299 echo % qpush/qpop error codes
283 errorcode()
300 errorcode()
284 {
301 {
285 hg "$@" && echo " $@ succeeds" || echo " $@ fails"
302 hg "$@" && echo " $@ succeeds" || echo " $@ fails"
286 }
303 }
287
304
288 # we want to start with some patches applied
305 # we want to start with some patches applied
289 hg qpush -a
306 hg qpush -a
290 echo " % pops all patches and succeeds"
307 echo " % pops all patches and succeeds"
291 errorcode qpop -a
308 errorcode qpop -a
292 echo " % does nothing and succeeds"
309 echo " % does nothing and succeeds"
293 errorcode qpop -a
310 errorcode qpop -a
294 echo " % fails - nothing else to pop"
311 echo " % fails - nothing else to pop"
295 errorcode qpop
312 errorcode qpop
296 echo " % pushes a patch and succeeds"
313 echo " % pushes a patch and succeeds"
297 errorcode qpush
314 errorcode qpush
298 echo " % pops a patch and succeeds"
315 echo " % pops a patch and succeeds"
299 errorcode qpop
316 errorcode qpop
300 echo " % pushes up to test1b.patch and succeeds"
317 echo " % pushes up to test1b.patch and succeeds"
301 errorcode qpush test1b.patch
318 errorcode qpush test1b.patch
302 echo " % does nothing and succeeds"
319 echo " % does nothing and succeeds"
303 errorcode qpush test1b.patch
320 errorcode qpush test1b.patch
304 echo " % does nothing and succeeds"
321 echo " % does nothing and succeeds"
305 errorcode qpop test1b.patch
322 errorcode qpop test1b.patch
306 echo " % fails - can't push to this patch"
323 echo " % fails - can't push to this patch"
307 errorcode qpush test.patch
324 errorcode qpush test.patch
308 echo " % fails - can't pop to this patch"
325 echo " % fails - can't pop to this patch"
309 errorcode qpop test2.patch
326 errorcode qpop test2.patch
310 echo " % pops up to test.patch and succeeds"
327 echo " % pops up to test.patch and succeeds"
311 errorcode qpop test.patch
328 errorcode qpop test.patch
312 echo " % pushes all patches and succeeds"
329 echo " % pushes all patches and succeeds"
313 errorcode qpush -a
330 errorcode qpush -a
314 echo " % does nothing and succeeds"
331 echo " % does nothing and succeeds"
315 errorcode qpush -a
332 errorcode qpush -a
316 echo " % fails - nothing else to push"
333 echo " % fails - nothing else to push"
317 errorcode qpush
334 errorcode qpush
318 echo " % does nothing and succeeds"
335 echo " % does nothing and succeeds"
319 errorcode qpush test2.patch
336 errorcode qpush test2.patch
320
337
321
338
322 echo % strip
339 echo % strip
323 cd ../../b
340 cd ../../b
324 echo x>x
341 echo x>x
325 hg ci -Ama
342 hg ci -Ama
326 hg strip tip | hidebackup
343 hg strip tip | hidebackup
327 hg unbundle .hg/strip-backup/*
344 hg unbundle .hg/strip-backup/*
328
345
329 echo % strip with local changes, should complain
346 echo % strip with local changes, should complain
330 hg up
347 hg up
331 echo y>y
348 echo y>y
332 hg add y
349 hg add y
333 hg strip tip | hidebackup
350 hg strip tip | hidebackup
334 echo % --force strip with local changes
351 echo % --force strip with local changes
335 hg strip -f tip | hidebackup
352 hg strip -f tip | hidebackup
336
353
337 echo '% cd b; hg qrefresh'
354 echo '% cd b; hg qrefresh'
338 hg init refresh
355 hg init refresh
339 cd refresh
356 cd refresh
340 echo a > a
357 echo a > a
341 hg ci -Ama
358 hg ci -Ama
342 hg qnew -mfoo foo
359 hg qnew -mfoo foo
343 echo a >> a
360 echo a >> a
344 hg qrefresh
361 hg qrefresh
345 mkdir b
362 mkdir b
346 cd b
363 cd b
347 echo f > f
364 echo f > f
348 hg add f
365 hg add f
349 hg qrefresh
366 hg qrefresh
350 sed -e "s/\(+++ [a-zA-Z0-9_/.-]*\).*/\1/" \
367 sed -e "s/\(+++ [a-zA-Z0-9_/.-]*\).*/\1/" \
351 -e "s/\(--- [a-zA-Z0-9_/.-]*\).*/\1/" ../.hg/patches/foo
368 -e "s/\(--- [a-zA-Z0-9_/.-]*\).*/\1/" ../.hg/patches/foo
352 echo % hg qrefresh .
369 echo % hg qrefresh .
353 hg qrefresh .
370 hg qrefresh .
354 sed -e "s/\(+++ [a-zA-Z0-9_/.-]*\).*/\1/" \
371 sed -e "s/\(+++ [a-zA-Z0-9_/.-]*\).*/\1/" \
355 -e "s/\(--- [a-zA-Z0-9_/.-]*\).*/\1/" ../.hg/patches/foo
372 -e "s/\(--- [a-zA-Z0-9_/.-]*\).*/\1/" ../.hg/patches/foo
356 hg status
373 hg status
357
374
358 echo % qpush failure
375 echo % qpush failure
359 cd ..
376 cd ..
360 hg qrefresh
377 hg qrefresh
361 hg qnew -mbar bar
378 hg qnew -mbar bar
362 echo foo > foo
379 echo foo > foo
363 echo bar > bar
380 echo bar > bar
364 hg add foo bar
381 hg add foo bar
365 hg qrefresh
382 hg qrefresh
366 hg qpop -a
383 hg qpop -a
367 echo bar > foo
384 echo bar > foo
368 hg qpush -a
385 hg qpush -a
369 hg st
386 hg st
370
387
371 echo % mq tags
388 echo % mq tags
372 hg log --template '{rev} {tags}\n' -r qparent:qtip
389 hg log --template '{rev} {tags}\n' -r qparent:qtip
373
390
374 echo % bad node in status
391 echo % bad node in status
375 hg qpop
392 hg qpop
376 hg strip -qn tip
393 hg strip -qn tip
377 hg tip 2>&1 | sed -e 's/unknown node .*/unknown node/'
394 hg tip 2>&1 | sed -e 's/unknown node .*/unknown node/'
378 hg branches 2>&1 | sed -e 's/unknown node .*/unknown node/'
395 hg branches 2>&1 | sed -e 's/unknown node .*/unknown node/'
379 hg qpop 2>&1 | sed -e 's/unknown node .*/unknown node/'
396 hg qpop 2>&1 | sed -e 's/unknown node .*/unknown node/'
380
397
381 cat >>$HGRCPATH <<EOF
398 cat >>$HGRCPATH <<EOF
382 [diff]
399 [diff]
383 git = True
400 git = True
384 EOF
401 EOF
385 cd ..
402 cd ..
386 hg init git
403 hg init git
387 cd git
404 cd git
388 hg qinit
405 hg qinit
389
406
390 hg qnew -m'new file' new
407 hg qnew -m'new file' new
391 echo foo > new
408 echo foo > new
392 chmod +x new
409 chmod +x new
393 hg add new
410 hg add new
394 hg qrefresh
411 hg qrefresh
395 sed -e "s/\(+++ [a-zA-Z0-9_/.-]*\).*/\1/" \
412 sed -e "s/\(+++ [a-zA-Z0-9_/.-]*\).*/\1/" \
396 -e "s/\(--- [a-zA-Z0-9_/.-]*\).*/\1/" .hg/patches/new
413 -e "s/\(--- [a-zA-Z0-9_/.-]*\).*/\1/" .hg/patches/new
397
414
398 hg qnew -m'copy file' copy
415 hg qnew -m'copy file' copy
399 hg cp new copy
416 hg cp new copy
400 hg qrefresh
417 hg qrefresh
401 sed -e "s/\(+++ [a-zA-Z0-9_/.-]*\).*/\1/" \
418 sed -e "s/\(+++ [a-zA-Z0-9_/.-]*\).*/\1/" \
402 -e "s/\(--- [a-zA-Z0-9_/.-]*\).*/\1/" .hg/patches/copy
419 -e "s/\(--- [a-zA-Z0-9_/.-]*\).*/\1/" .hg/patches/copy
403
420
404 hg qpop
421 hg qpop
405 hg qpush
422 hg qpush
406 hg qdiff
423 hg qdiff
407 cat >>$HGRCPATH <<EOF
424 cat >>$HGRCPATH <<EOF
408 [diff]
425 [diff]
409 git = False
426 git = False
410 EOF
427 EOF
411 hg qdiff --git
428 hg qdiff --git
412 cd ..
429 cd ..
413
430
414 echo % test file addition in slow path
431 echo % test file addition in slow path
415 hg init slow
432 hg init slow
416 cd slow
433 cd slow
417 hg qinit
434 hg qinit
418 echo foo > foo
435 echo foo > foo
419 hg add foo
436 hg add foo
420 hg ci -m 'add foo'
437 hg ci -m 'add foo'
421 hg qnew bar
438 hg qnew bar
422 echo bar > bar
439 echo bar > bar
423 hg add bar
440 hg add bar
424 hg mv foo baz
441 hg mv foo baz
425 hg qrefresh --git
442 hg qrefresh --git
426 hg up -C 0
443 hg up -C 0
427 echo >> foo
444 echo >> foo
428 hg ci -m 'change foo'
445 hg ci -m 'change foo'
429 hg up -C 1
446 hg up -C 1
430 hg qrefresh --git 2>&1 | grep -v 'saving bundle'
447 hg qrefresh --git 2>&1 | grep -v 'saving bundle'
431 cat .hg/patches/bar
448 cat .hg/patches/bar
432 hg log -v --template '{rev} {file_copies}\n' -r .
449 hg log -v --template '{rev} {file_copies}\n' -r .
433 hg qrefresh --git
450 hg qrefresh --git
434 cat .hg/patches/bar
451 cat .hg/patches/bar
435 hg log -v --template '{rev} {file_copies}\n' -r .
452 hg log -v --template '{rev} {file_copies}\n' -r .
436 hg qrefresh
453 hg qrefresh
437 grep 'diff --git' .hg/patches/bar
454 grep 'diff --git' .hg/patches/bar
438
455
439 echo % test file move chains in the slow path
456 echo % test file move chains in the slow path
440 hg up -C 1
457 hg up -C 1
441 echo >> foo
458 echo >> foo
442 hg ci -m 'change foo again'
459 hg ci -m 'change foo again'
443 hg up -C 2
460 hg up -C 2
444 hg mv bar quux
461 hg mv bar quux
445 hg mv baz bleh
462 hg mv baz bleh
446 hg qrefresh --git 2>&1 | grep -v 'saving bundle'
463 hg qrefresh --git 2>&1 | grep -v 'saving bundle'
447 cat .hg/patches/bar
464 cat .hg/patches/bar
448 hg log -v --template '{rev} {file_copies}\n' -r .
465 hg log -v --template '{rev} {file_copies}\n' -r .
449 hg mv quux fred
466 hg mv quux fred
450 hg mv bleh barney
467 hg mv bleh barney
451 hg qrefresh --git
468 hg qrefresh --git
452 cat .hg/patches/bar
469 cat .hg/patches/bar
453 hg log -v --template '{rev} {file_copies}\n' -r .
470 hg log -v --template '{rev} {file_copies}\n' -r .
454
471
455 echo % refresh omitting an added file
472 echo % refresh omitting an added file
456 hg qnew baz
473 hg qnew baz
457 echo newfile > newfile
474 echo newfile > newfile
458 hg add newfile
475 hg add newfile
459 hg qrefresh
476 hg qrefresh
460 hg st -A newfile
477 hg st -A newfile
461 hg qrefresh -X newfile
478 hg qrefresh -X newfile
462 hg st -A newfile
479 hg st -A newfile
463 hg revert newfile
480 hg revert newfile
464 rm newfile
481 rm newfile
465 hg qpop
482 hg qpop
466 hg qdel baz
483 hg qdel baz
467
484
468 echo % create a git patch
485 echo % create a git patch
469 echo a > alexander
486 echo a > alexander
470 hg add alexander
487 hg add alexander
471 hg qnew -f --git addalexander
488 hg qnew -f --git addalexander
472 grep diff .hg/patches/addalexander
489 grep diff .hg/patches/addalexander
473
490
474 echo % create a git binary patch
491 echo % create a git binary patch
475 cat > writebin.py <<EOF
492 cat > writebin.py <<EOF
476 import sys
493 import sys
477 path = sys.argv[1]
494 path = sys.argv[1]
478 open(path, 'wb').write('BIN\x00ARY')
495 open(path, 'wb').write('BIN\x00ARY')
479 EOF
496 EOF
480 python writebin.py bucephalus
497 python writebin.py bucephalus
481
498
482 python "$TESTDIR/md5sum.py" bucephalus
499 python "$TESTDIR/md5sum.py" bucephalus
483 hg add bucephalus
500 hg add bucephalus
484 hg qnew -f --git addbucephalus
501 hg qnew -f --git addbucephalus
485 grep diff .hg/patches/addbucephalus
502 grep diff .hg/patches/addbucephalus
486
503
487 echo % check binary patches can be popped and pushed
504 echo % check binary patches can be popped and pushed
488 hg qpop
505 hg qpop
489 test -f bucephalus && echo % bucephalus should not be there
506 test -f bucephalus && echo % bucephalus should not be there
490 hg qpush
507 hg qpush
491 test -f bucephalus || echo % bucephalus should be there
508 test -f bucephalus || echo % bucephalus should be there
492 python "$TESTDIR/md5sum.py" bucephalus
509 python "$TESTDIR/md5sum.py" bucephalus
493
510
494
511
495 echo '% strip again'
512 echo '% strip again'
496 cd ..
513 cd ..
497 hg init strip
514 hg init strip
498 cd strip
515 cd strip
499 touch foo
516 touch foo
500 hg add foo
517 hg add foo
501 hg ci -m 'add foo'
518 hg ci -m 'add foo'
502 echo >> foo
519 echo >> foo
503 hg ci -m 'change foo 1'
520 hg ci -m 'change foo 1'
504 hg up -C 0
521 hg up -C 0
505 echo 1 >> foo
522 echo 1 >> foo
506 hg ci -m 'change foo 2'
523 hg ci -m 'change foo 2'
507 HGMERGE=true hg merge
524 HGMERGE=true hg merge
508 hg ci -m merge
525 hg ci -m merge
509 hg log
526 hg log
510 hg strip 1 | hidebackup
527 hg strip 1 | hidebackup
511 checkundo strip
528 checkundo strip
512 hg log
529 hg log
513 cd ..
530 cd ..
514
531
515 echo '% qclone'
532 echo '% qclone'
516 qlog()
533 qlog()
517 {
534 {
518 echo 'main repo:'
535 echo 'main repo:'
519 hg log --template ' rev {rev}: {desc}\n'
536 hg log --template ' rev {rev}: {desc}\n'
520 echo 'patch repo:'
537 echo 'patch repo:'
521 hg -R .hg/patches log --template ' rev {rev}: {desc}\n'
538 hg -R .hg/patches log --template ' rev {rev}: {desc}\n'
522 }
539 }
523 hg init qclonesource
540 hg init qclonesource
524 cd qclonesource
541 cd qclonesource
525 echo foo > foo
542 echo foo > foo
526 hg add foo
543 hg add foo
527 hg ci -m 'add foo'
544 hg ci -m 'add foo'
528 hg qinit
545 hg qinit
529 hg qnew patch1
546 hg qnew patch1
530 echo bar >> foo
547 echo bar >> foo
531 hg qrefresh -m 'change foo'
548 hg qrefresh -m 'change foo'
532 cd ..
549 cd ..
533
550
534 # repo with unversioned patch dir
551 # repo with unversioned patch dir
535 hg qclone qclonesource failure
552 hg qclone qclonesource failure
536
553
537 cd qclonesource
554 cd qclonesource
538 hg qinit -c
555 hg qinit -c
539 hg qci -m checkpoint
556 hg qci -m checkpoint
540 qlog
557 qlog
541 cd ..
558 cd ..
542
559
543 # repo with patches applied
560 # repo with patches applied
544 hg qclone qclonesource qclonedest
561 hg qclone qclonesource qclonedest
545 cd qclonedest
562 cd qclonedest
546 qlog
563 qlog
547 cd ..
564 cd ..
548
565
549 # repo with patches unapplied
566 # repo with patches unapplied
550 cd qclonesource
567 cd qclonesource
551 hg qpop -a
568 hg qpop -a
552 qlog
569 qlog
553 cd ..
570 cd ..
554 hg qclone qclonesource qclonedest2
571 hg qclone qclonesource qclonedest2
555 cd qclonedest2
572 cd qclonedest2
556 qlog
573 qlog
557 cd ..
574 cd ..
558
575
559 echo % 'test applying on an empty file (issue 1033)'
576 echo % 'test applying on an empty file (issue 1033)'
560 hg init empty
577 hg init empty
561 cd empty
578 cd empty
562 touch a
579 touch a
563 hg ci -Am addempty
580 hg ci -Am addempty
564 echo a > a
581 echo a > a
565 hg qnew -f -e changea
582 hg qnew -f -e changea
566 hg qpop
583 hg qpop
567 hg qpush
584 hg qpush
568 cd ..
585 cd ..
569
586
570 echo % test qpush with --force, issue1087
587 echo % test qpush with --force, issue1087
571 hg init forcepush
588 hg init forcepush
572 cd forcepush
589 cd forcepush
573 echo hello > hello.txt
590 echo hello > hello.txt
574 echo bye > bye.txt
591 echo bye > bye.txt
575 hg ci -Ama
592 hg ci -Ama
576 hg qnew -d '0 0' empty
593 hg qnew -d '0 0' empty
577 hg qpop
594 hg qpop
578 echo world >> hello.txt
595 echo world >> hello.txt
579
596
580 echo % qpush should fail, local changes
597 echo % qpush should fail, local changes
581 hg qpush
598 hg qpush
582
599
583 echo % apply force, should not discard changes with empty patch
600 echo % apply force, should not discard changes with empty patch
584 hg qpush -f 2>&1 | sed 's,^.*/patch,patch,g'
601 hg qpush -f 2>&1 | sed 's,^.*/patch,patch,g'
585 hg diff --config diff.nodates=True
602 hg diff --config diff.nodates=True
586 hg qdiff --config diff.nodates=True
603 hg qdiff --config diff.nodates=True
587 hg log -l1 -p
604 hg log -l1 -p
588 hg qref -d '0 0'
605 hg qref -d '0 0'
589 hg qpop
606 hg qpop
590 echo universe >> hello.txt
607 echo universe >> hello.txt
591 echo universe >> bye.txt
608 echo universe >> bye.txt
592
609
593 echo % qpush should fail, local changes
610 echo % qpush should fail, local changes
594 hg qpush
611 hg qpush
595
612
596 echo % apply force, should discard changes in hello, but not bye
613 echo % apply force, should discard changes in hello, but not bye
597 hg qpush -f
614 hg qpush -f
598 hg st
615 hg st
599 hg diff --config diff.nodates=True
616 hg diff --config diff.nodates=True
600 hg qdiff --config diff.nodates=True
617 hg qdiff --config diff.nodates=True
601
618
602 echo % test popping revisions not in working dir ancestry
619 echo % test popping revisions not in working dir ancestry
603 hg qseries -v
620 hg qseries -v
604 hg up qparent
621 hg up qparent
605 hg qpop
622 hg qpop
606
623
607 cd ..
624 cd ..
608 hg init deletion-order
625 hg init deletion-order
609 cd deletion-order
626 cd deletion-order
610
627
611 touch a
628 touch a
612 hg ci -Aqm0
629 hg ci -Aqm0
613
630
614 hg qnew rename-dir
631 hg qnew rename-dir
615 hg rm a
632 hg rm a
616 hg qrefresh
633 hg qrefresh
617
634
618 mkdir a b
635 mkdir a b
619 touch a/a b/b
636 touch a/a b/b
620 hg add -q a b
637 hg add -q a b
621 hg qrefresh
638 hg qrefresh
622
639
623 echo % test popping must remove files added in subdirectories first
640 echo % test popping must remove files added in subdirectories first
624 hg qpop
641 hg qpop
625 cd ..
642 cd ..
@@ -1,10 +1,10 b''
1 adding a
1 adding a
2
2
3 #empty series
3 #empty series
4
4
5 #qimport valid patch followed by invalid patch
5 #qimport valid patch followed by invalid patch
6 adding b.patch to series file
6 adding b.patch to series file
7 abort: unable to read fakepatch
7 abort: unable to read file fakepatch
8
8
9 #valid patches before fail added to series
9 #valid patches before fail added to series
10 b.patch
10 b.patch
@@ -1,54 +1,54 b''
1 % qimport non-existing-file
1 % qimport non-existing-file
2 abort: unable to read non-existing-file
2 abort: unable to read file non-existing-file
3 % import email
3 % import email
4 adding email to series file
4 adding email to series file
5 applying email
5 applying email
6 now at: email
6 now at: email
7 % hg tip -v
7 % hg tip -v
8 changeset: 0:1a706973a7d8
8 changeset: 0:1a706973a7d8
9 tag: email
9 tag: email
10 tag: qbase
10 tag: qbase
11 tag: qtip
11 tag: qtip
12 tag: tip
12 tag: tip
13 user: Username in patch <test@example.net>
13 user: Username in patch <test@example.net>
14 date: Thu Jan 01 00:00:00 1970 +0000
14 date: Thu Jan 01 00:00:00 1970 +0000
15 files: x
15 files: x
16 description:
16 description:
17 First line of commit message.
17 First line of commit message.
18
18
19 More text in commit message.
19 More text in commit message.
20
20
21
21
22 popping email
22 popping email
23 patch queue now empty
23 patch queue now empty
24 % import URL
24 % import URL
25 adding url.diff to series file
25 adding url.diff to series file
26 url.diff
26 url.diff
27 % import patch that already exists
27 % import patch that already exists
28 abort: patch "url.diff" already exists
28 abort: patch "url.diff" already exists
29 applying url.diff
29 applying url.diff
30 now at: url.diff
30 now at: url.diff
31 foo
31 foo
32 popping url.diff
32 popping url.diff
33 patch queue now empty
33 patch queue now empty
34 % qimport -f
34 % qimport -f
35 adding url.diff to series file
35 adding url.diff to series file
36 applying url.diff
36 applying url.diff
37 now at: url.diff
37 now at: url.diff
38 foo2
38 foo2
39 popping url.diff
39 popping url.diff
40 patch queue now empty
40 patch queue now empty
41 % build diff with CRLF
41 % build diff with CRLF
42 adding b
42 adding b
43 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
43 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
44 % qimport CRLF diff
44 % qimport CRLF diff
45 adding b.diff to series file
45 adding b.diff to series file
46 applying b.diff
46 applying b.diff
47 now at: b.diff
47 now at: b.diff
48 % try to import --push
48 % try to import --push
49 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
49 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
50 adding another.diff to series file
50 adding another.diff to series file
51 applying another.diff
51 applying another.diff
52 now at: another.diff
52 now at: another.diff
53 patch b.diff finalized without changeset message
53 patch b.diff finalized without changeset message
54 patch another.diff finalized without changeset message
54 patch another.diff finalized without changeset message
@@ -1,642 +1,653 b''
1 % help
1 % help
2 mq extension - manage a stack of patches
2 mq extension - manage a stack of patches
3
3
4 This extension lets you work with a stack of patches in a Mercurial
4 This extension lets you work with a stack of patches in a Mercurial
5 repository. It manages two stacks of patches - all known patches, and applied
5 repository. It manages two stacks of patches - all known patches, and applied
6 patches (subset of known patches).
6 patches (subset of known patches).
7
7
8 Known patches are represented as patch files in the .hg/patches directory.
8 Known patches are represented as patch files in the .hg/patches directory.
9 Applied patches are both patch files and changesets.
9 Applied patches are both patch files and changesets.
10
10
11 Common tasks (use "hg help command" for more details):
11 Common tasks (use "hg help command" for more details):
12
12
13 create new patch qnew
13 create new patch qnew
14 import existing patch qimport
14 import existing patch qimport
15
15
16 print patch series qseries
16 print patch series qseries
17 print applied patches qapplied
17 print applied patches qapplied
18
18
19 add known patch to applied stack qpush
19 add known patch to applied stack qpush
20 remove patch from applied stack qpop
20 remove patch from applied stack qpop
21 refresh contents of top applied patch qrefresh
21 refresh contents of top applied patch qrefresh
22
22
23 By default, mq will automatically use git patches when required to avoid
23 By default, mq will automatically use git patches when required to avoid
24 losing file mode changes, copy records, binary files or empty files creations
24 losing file mode changes, copy records, binary files or empty files creations
25 or deletions. This behaviour can be configured with:
25 or deletions. This behaviour can be configured with:
26
26
27 [mq]
27 [mq]
28 git = auto/keep/yes/no
28 git = auto/keep/yes/no
29
29
30 If set to 'keep', mq will obey the [diff] section configuration while
30 If set to 'keep', mq will obey the [diff] section configuration while
31 preserving existing git patches upon qrefresh. If set to 'yes' or 'no', mq
31 preserving existing git patches upon qrefresh. If set to 'yes' or 'no', mq
32 will override the [diff] section and always generate git or regular patches,
32 will override the [diff] section and always generate git or regular patches,
33 possibly losing data in the second case.
33 possibly losing data in the second case.
34
34
35 You will by default be managing a patch queue named "patches". You can create
35 You will by default be managing a patch queue named "patches". You can create
36 other, independent patch queues with the "hg qqueue" command.
36 other, independent patch queues with the "hg qqueue" command.
37
37
38 list of commands:
38 list of commands:
39
39
40 qapplied print the patches already applied
40 qapplied print the patches already applied
41 qclone clone main and patch repository at same time
41 qclone clone main and patch repository at same time
42 qdelete remove patches from queue
42 qdelete remove patches from queue
43 qdiff diff of the current patch and subsequent modifications
43 qdiff diff of the current patch and subsequent modifications
44 qfinish move applied patches into repository history
44 qfinish move applied patches into repository history
45 qfold fold the named patches into the current patch
45 qfold fold the named patches into the current patch
46 qgoto push or pop patches until named patch is at top of stack
46 qgoto push or pop patches until named patch is at top of stack
47 qguard set or print guards for a patch
47 qguard set or print guards for a patch
48 qheader print the header of the topmost or specified patch
48 qheader print the header of the topmost or specified patch
49 qimport import a patch
49 qimport import a patch
50 qnew create a new patch
50 qnew create a new patch
51 qnext print the name of the next patch
51 qnext print the name of the next patch
52 qpop pop the current patch off the stack
52 qpop pop the current patch off the stack
53 qprev print the name of the previous patch
53 qprev print the name of the previous patch
54 qpush push the next patch onto the stack
54 qpush push the next patch onto the stack
55 qqueue manage multiple patch queues
55 qqueue manage multiple patch queues
56 qrefresh update the current patch
56 qrefresh update the current patch
57 qrename rename a patch
57 qrename rename a patch
58 qselect set or print guarded patches to push
58 qselect set or print guarded patches to push
59 qseries print the entire series file
59 qseries print the entire series file
60 qtop print the name of the current patch
60 qtop print the name of the current patch
61 qunapplied print the patches not yet applied
61 qunapplied print the patches not yet applied
62 strip strip a changeset and all its descendants from the repository
62 strip strip a changeset and all its descendants from the repository
63
63
64 use "hg -v help mq" to show aliases and global options
64 use "hg -v help mq" to show aliases and global options
65 adding a
65 adding a
66 updating to branch default
66 updating to branch default
67 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
67 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
68 adding b/z
68 adding b/z
69 % qinit
69 % qinit
70 % -R qinit
70 % -R qinit
71 % qinit -c
71 % qinit -c
72 A .hgignore
72 A .hgignore
73 A series
73 A series
74 % qinit; qinit -c
74 % qinit; qinit -c
75 .hgignore:
75 .hgignore:
76 ^\.hg
76 ^\.hg
77 ^\.mq
77 ^\.mq
78 syntax: glob
78 syntax: glob
79 status
79 status
80 guards
80 guards
81 series:
81 series:
82 abort: repository already exists!
82 abort: repository already exists!
83 % qinit; <stuff>; qinit -c
83 % qinit; <stuff>; qinit -c
84 adding .hg/patches/A
84 adding .hg/patches/A
85 adding .hg/patches/B
85 adding .hg/patches/B
86 A .hgignore
86 A .hgignore
87 A A
87 A A
88 A B
88 A B
89 A series
89 A series
90 .hgignore:
90 .hgignore:
91 status
91 status
92 bleh
92 bleh
93 series:
93 series:
94 A
94 A
95 B
95 B
96 % status --mq with color (issue2096)
96 % status --mq with color (issue2096)
97 A .hgignore
97 A .hgignore
98 A A
98 A A
99 A B
99 A B
100 A series
100 A series
101 % init --mq without repo
101 % init --mq without repo
102 abort: There is no Mercurial repository here (.hg not found)
102 abort: There is no Mercurial repository here (.hg not found)
103 % init --mq with repo path
103 % init --mq with repo path
104 ok
104 ok
105 % init --mq with nonexistent directory
105 % init --mq with nonexistent directory
106 abort: repository nonexistentdir not found!
106 abort: repository nonexistentdir not found!
107 % init --mq with bundle (non "local")
107 % init --mq with bundle (non "local")
108 abort: only a local queue repository may be initialized
108 abort: only a local queue repository may be initialized
109 % qrefresh
109 % qrefresh
110 foo bar
110 foo bar
111
111
112 diff -r xa
112 diff -r xa
113 --- a/a
113 --- a/a
114 +++ b/a
114 +++ b/a
115 @@ -1,1 +1,2 @@
115 @@ -1,1 +1,2 @@
116 a
116 a
117 +a
117 +a
118 % empty qrefresh
118 % empty qrefresh
119 revision:
119 revision:
120 patch:
120 patch:
121 foo bar
121 foo bar
122
122
123 working dir diff:
123 working dir diff:
124 --- a/a
124 --- a/a
125 +++ b/a
125 +++ b/a
126 @@ -1,1 +1,2 @@
126 @@ -1,1 +1,2 @@
127 a
127 a
128 +a
128 +a
129 % qpop
129 % qpop
130 popping test.patch
130 popping test.patch
131 patch queue now empty
131 patch queue now empty
132 % qpush with dump of tag cache
132 % qpush with dump of tag cache
133 .hg/tags.cache (pre qpush):
133 .hg/tags.cache (pre qpush):
134 1
134 1
135
135
136 applying test.patch
136 applying test.patch
137 now at: test.patch
137 now at: test.patch
138 .hg/tags.cache (post qpush):
138 .hg/tags.cache (post qpush):
139 2
139 2
140
140
141 % pop/push outside repo
141 % pop/push outside repo
142 popping test.patch
142 popping test.patch
143 patch queue now empty
143 patch queue now empty
144 applying test.patch
144 applying test.patch
145 now at: test.patch
145 now at: test.patch
146 % qrefresh in subdir
146 % qrefresh in subdir
147 % pop/push -a in subdir
147 % pop/push -a in subdir
148 popping test2.patch
148 popping test2.patch
149 popping test.patch
149 popping test.patch
150 patch queue now empty
150 patch queue now empty
151 applying test.patch
151 applying test.patch
152 applying test2.patch
152 applying test2.patch
153 now at: test2.patch
153 now at: test2.patch
154 % qseries
154 % qseries
155 test.patch
155 test.patch
156 test2.patch
156 test2.patch
157 0 A test.patch: f...
157 0 A test.patch: f...
158 1 A test2.patch:
158 1 A test2.patch:
159 popping test2.patch
159 popping test2.patch
160 now at: test.patch
160 now at: test.patch
161 0 A test.patch: foo bar
161 0 A test.patch: foo bar
162 1 U test2.patch:
162 1 U test2.patch:
163 mq: 1 applied, 1 unapplied
163 mq: 1 applied, 1 unapplied
164 applying test2.patch
164 applying test2.patch
165 now at: test2.patch
165 now at: test2.patch
166 mq: 2 applied
166 mq: 2 applied
167 % qapplied
167 % qapplied
168 test.patch
168 test.patch
169 test2.patch
169 test2.patch
170 % qtop
170 % qtop
171 test2.patch
171 test2.patch
172 % prev
172 % prev
173 test.patch
173 test.patch
174 % next
174 % next
175 all patches applied
175 all patches applied
176 popping test2.patch
176 popping test2.patch
177 now at: test.patch
177 now at: test.patch
178 % commit should fail
178 % commit should fail
179 abort: cannot commit over an applied mq patch
179 abort: cannot commit over an applied mq patch
180 % push should fail
180 % push should fail
181 pushing to ../../k
181 pushing to ../../k
182 abort: source has mq patches applied
182 abort: source has mq patches applied
183 % import should fail
183 % import should fail
184 abort: cannot import over an applied patch
184 abort: cannot import over an applied patch
185 % import --no-commit should succeed
185 % import --no-commit should succeed
186 applying ../../import.diff
186 applying ../../import.diff
187 M a
187 M a
188 % qunapplied
188 % qunapplied
189 test2.patch
189 test2.patch
190 % qpush/qpop with index
190 % qpush/qpop with index
191 applying test2.patch
191 applying test2.patch
192 now at: test2.patch
192 now at: test2.patch
193 popping test2.patch
193 popping test2.patch
194 popping test1b.patch
194 popping test1b.patch
195 now at: test.patch
195 now at: test.patch
196 applying test1b.patch
196 applying test1b.patch
197 now at: test1b.patch
197 now at: test1b.patch
198 applying test2.patch
198 applying test2.patch
199 now at: test2.patch
199 now at: test2.patch
200 popping test2.patch
200 popping test2.patch
201 now at: test1b.patch
201 now at: test1b.patch
202 popping test1b.patch
202 popping test1b.patch
203 now at: test.patch
203 now at: test.patch
204 applying test1b.patch
204 applying test1b.patch
205 applying test2.patch
205 applying test2.patch
206 now at: test2.patch
206 now at: test2.patch
207 % qpush --move
207 % qpush --move
208 popping test2.patch
208 popping test2.patch
209 popping test1b.patch
209 popping test1b.patch
210 popping test.patch
210 popping test.patch
211 patch queue now empty
211 patch queue now empty
212 cannot push 'test2.patch' - guarded by ['+posguard']
213 number of unguarded, unapplied patches has changed from 2 to 3
212 applying test2.patch
214 applying test2.patch
213 now at: test2.patch
215 now at: test2.patch
214 applying test1b.patch
216 applying test1b.patch
215 now at: test1b.patch
217 now at: test1b.patch
216 applying test.patch
218 applying test.patch
217 now at: test.patch
219 now at: test.patch
218 0 A test2.patch
220 0 A test2.patch
219 1 A test1b.patch
221 1 A test1b.patch
220 2 A test.patch
222 2 A test.patch
221 popping test.patch
223 popping test.patch
222 popping test1b.patch
224 popping test1b.patch
223 popping test2.patch
225 popping test2.patch
224 patch queue now empty
226 patch queue now empty
227 guards deactivated
228 number of unguarded, unapplied patches has changed from 3 to 2
225 applying test.patch
229 applying test.patch
226 now at: test.patch
230 now at: test.patch
227 applying test1b.patch
231 applying test1b.patch
228 now at: test1b.patch
232 now at: test1b.patch
229 abort: patch bogus not in series
233 abort: patch bogus not in series
234 abort: please specify the patch to move
230 abort: cannot push to a previous patch: test.patch
235 abort: cannot push to a previous patch: test.patch
231 applying test2.patch
236 applying test2.patch
232 now at: test2.patch
237 now at: test2.patch
238 % series after move
239 test.patch
240 test1b.patch
241 test2.patch
242 # comment
243
233 % pop, qapplied, qunapplied
244 % pop, qapplied, qunapplied
234 0 A test.patch
245 0 A test.patch
235 1 A test1b.patch
246 1 A test1b.patch
236 2 A test2.patch
247 2 A test2.patch
237 % qapplied -1 test.patch
248 % qapplied -1 test.patch
238 only one patch applied
249 only one patch applied
239 % qapplied -1 test1b.patch
250 % qapplied -1 test1b.patch
240 test.patch
251 test.patch
241 % qapplied -1 test2.patch
252 % qapplied -1 test2.patch
242 test1b.patch
253 test1b.patch
243 % qapplied -1
254 % qapplied -1
244 test1b.patch
255 test1b.patch
245 % qapplied
256 % qapplied
246 test.patch
257 test.patch
247 test1b.patch
258 test1b.patch
248 test2.patch
259 test2.patch
249 % qapplied test1b.patch
260 % qapplied test1b.patch
250 test.patch
261 test.patch
251 test1b.patch
262 test1b.patch
252 % qunapplied -1
263 % qunapplied -1
253 all patches applied
264 all patches applied
254 % qunapplied
265 % qunapplied
255 % popping
266 % popping
256 popping test2.patch
267 popping test2.patch
257 now at: test1b.patch
268 now at: test1b.patch
258 % qunapplied -1
269 % qunapplied -1
259 test2.patch
270 test2.patch
260 % qunapplied
271 % qunapplied
261 test2.patch
272 test2.patch
262 % qunapplied test2.patch
273 % qunapplied test2.patch
263 % qunapplied -1 test2.patch
274 % qunapplied -1 test2.patch
264 all patches applied
275 all patches applied
265 % popping -a
276 % popping -a
266 popping test1b.patch
277 popping test1b.patch
267 popping test.patch
278 popping test.patch
268 patch queue now empty
279 patch queue now empty
269 % qapplied
280 % qapplied
270 % qapplied -1
281 % qapplied -1
271 no patches applied
282 no patches applied
272 applying test.patch
283 applying test.patch
273 now at: test.patch
284 now at: test.patch
274 % push should succeed
285 % push should succeed
275 popping test.patch
286 popping test.patch
276 patch queue now empty
287 patch queue now empty
277 pushing to ../../k
288 pushing to ../../k
278 searching for changes
289 searching for changes
279 adding changesets
290 adding changesets
280 adding manifests
291 adding manifests
281 adding file changes
292 adding file changes
282 added 1 changesets with 1 changes to 1 files
293 added 1 changesets with 1 changes to 1 files
283 % qpush/qpop error codes
294 % qpush/qpop error codes
284 applying test.patch
295 applying test.patch
285 applying test1b.patch
296 applying test1b.patch
286 applying test2.patch
297 applying test2.patch
287 now at: test2.patch
298 now at: test2.patch
288 % pops all patches and succeeds
299 % pops all patches and succeeds
289 popping test2.patch
300 popping test2.patch
290 popping test1b.patch
301 popping test1b.patch
291 popping test.patch
302 popping test.patch
292 patch queue now empty
303 patch queue now empty
293 qpop -a succeeds
304 qpop -a succeeds
294 % does nothing and succeeds
305 % does nothing and succeeds
295 no patches applied
306 no patches applied
296 qpop -a succeeds
307 qpop -a succeeds
297 % fails - nothing else to pop
308 % fails - nothing else to pop
298 no patches applied
309 no patches applied
299 qpop fails
310 qpop fails
300 % pushes a patch and succeeds
311 % pushes a patch and succeeds
301 applying test.patch
312 applying test.patch
302 now at: test.patch
313 now at: test.patch
303 qpush succeeds
314 qpush succeeds
304 % pops a patch and succeeds
315 % pops a patch and succeeds
305 popping test.patch
316 popping test.patch
306 patch queue now empty
317 patch queue now empty
307 qpop succeeds
318 qpop succeeds
308 % pushes up to test1b.patch and succeeds
319 % pushes up to test1b.patch and succeeds
309 applying test.patch
320 applying test.patch
310 applying test1b.patch
321 applying test1b.patch
311 now at: test1b.patch
322 now at: test1b.patch
312 qpush test1b.patch succeeds
323 qpush test1b.patch succeeds
313 % does nothing and succeeds
324 % does nothing and succeeds
314 qpush: test1b.patch is already at the top
325 qpush: test1b.patch is already at the top
315 qpush test1b.patch succeeds
326 qpush test1b.patch succeeds
316 % does nothing and succeeds
327 % does nothing and succeeds
317 qpop: test1b.patch is already at the top
328 qpop: test1b.patch is already at the top
318 qpop test1b.patch succeeds
329 qpop test1b.patch succeeds
319 % fails - can't push to this patch
330 % fails - can't push to this patch
320 abort: cannot push to a previous patch: test.patch
331 abort: cannot push to a previous patch: test.patch
321 qpush test.patch fails
332 qpush test.patch fails
322 % fails - can't pop to this patch
333 % fails - can't pop to this patch
323 abort: patch test2.patch is not applied
334 abort: patch test2.patch is not applied
324 qpop test2.patch fails
335 qpop test2.patch fails
325 % pops up to test.patch and succeeds
336 % pops up to test.patch and succeeds
326 popping test1b.patch
337 popping test1b.patch
327 now at: test.patch
338 now at: test.patch
328 qpop test.patch succeeds
339 qpop test.patch succeeds
329 % pushes all patches and succeeds
340 % pushes all patches and succeeds
330 applying test1b.patch
341 applying test1b.patch
331 applying test2.patch
342 applying test2.patch
332 now at: test2.patch
343 now at: test2.patch
333 qpush -a succeeds
344 qpush -a succeeds
334 % does nothing and succeeds
345 % does nothing and succeeds
335 all patches are currently applied
346 all patches are currently applied
336 qpush -a succeeds
347 qpush -a succeeds
337 % fails - nothing else to push
348 % fails - nothing else to push
338 patch series already fully applied
349 patch series already fully applied
339 qpush fails
350 qpush fails
340 % does nothing and succeeds
351 % does nothing and succeeds
341 qpush: test2.patch is already at the top
352 qpush: test2.patch is already at the top
342 qpush test2.patch succeeds
353 qpush test2.patch succeeds
343 % strip
354 % strip
344 adding x
355 adding x
345 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
356 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
346 saved backup bundle to
357 saved backup bundle to
347 adding changesets
358 adding changesets
348 adding manifests
359 adding manifests
349 adding file changes
360 adding file changes
350 added 1 changesets with 1 changes to 1 files
361 added 1 changesets with 1 changes to 1 files
351 (run 'hg update' to get a working copy)
362 (run 'hg update' to get a working copy)
352 % strip with local changes, should complain
363 % strip with local changes, should complain
353 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
364 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
354 abort: local changes found
365 abort: local changes found
355 % --force strip with local changes
366 % --force strip with local changes
356 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
367 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
357 saved backup bundle to
368 saved backup bundle to
358 % cd b; hg qrefresh
369 % cd b; hg qrefresh
359 adding a
370 adding a
360 foo
371 foo
361
372
362 diff -r cb9a9f314b8b a
373 diff -r cb9a9f314b8b a
363 --- a/a
374 --- a/a
364 +++ b/a
375 +++ b/a
365 @@ -1,1 +1,2 @@
376 @@ -1,1 +1,2 @@
366 a
377 a
367 +a
378 +a
368 diff -r cb9a9f314b8b b/f
379 diff -r cb9a9f314b8b b/f
369 --- /dev/null
380 --- /dev/null
370 +++ b/b/f
381 +++ b/b/f
371 @@ -0,0 +1,1 @@
382 @@ -0,0 +1,1 @@
372 +f
383 +f
373 % hg qrefresh .
384 % hg qrefresh .
374 foo
385 foo
375
386
376 diff -r cb9a9f314b8b b/f
387 diff -r cb9a9f314b8b b/f
377 --- /dev/null
388 --- /dev/null
378 +++ b/b/f
389 +++ b/b/f
379 @@ -0,0 +1,1 @@
390 @@ -0,0 +1,1 @@
380 +f
391 +f
381 M a
392 M a
382 % qpush failure
393 % qpush failure
383 popping bar
394 popping bar
384 popping foo
395 popping foo
385 patch queue now empty
396 patch queue now empty
386 applying foo
397 applying foo
387 applying bar
398 applying bar
388 file foo already exists
399 file foo already exists
389 1 out of 1 hunks FAILED -- saving rejects to file foo.rej
400 1 out of 1 hunks FAILED -- saving rejects to file foo.rej
390 patch failed, unable to continue (try -v)
401 patch failed, unable to continue (try -v)
391 patch failed, rejects left in working dir
402 patch failed, rejects left in working dir
392 errors during apply, please fix and refresh bar
403 errors during apply, please fix and refresh bar
393 ? foo
404 ? foo
394 ? foo.rej
405 ? foo.rej
395 % mq tags
406 % mq tags
396 0 qparent
407 0 qparent
397 1 foo qbase
408 1 foo qbase
398 2 bar qtip tip
409 2 bar qtip tip
399 % bad node in status
410 % bad node in status
400 popping bar
411 popping bar
401 now at: foo
412 now at: foo
402 changeset: 0:cb9a9f314b8b
413 changeset: 0:cb9a9f314b8b
403 tag: tip
414 tag: tip
404 user: test
415 user: test
405 date: Thu Jan 01 00:00:00 1970 +0000
416 date: Thu Jan 01 00:00:00 1970 +0000
406 summary: a
417 summary: a
407
418
408 default 0:cb9a9f314b8b
419 default 0:cb9a9f314b8b
409 no patches applied
420 no patches applied
410 new file
421 new file
411
422
412 diff --git a/new b/new
423 diff --git a/new b/new
413 new file mode 100755
424 new file mode 100755
414 --- /dev/null
425 --- /dev/null
415 +++ b/new
426 +++ b/new
416 @@ -0,0 +1,1 @@
427 @@ -0,0 +1,1 @@
417 +foo
428 +foo
418 copy file
429 copy file
419
430
420 diff --git a/new b/copy
431 diff --git a/new b/copy
421 copy from new
432 copy from new
422 copy to copy
433 copy to copy
423 popping copy
434 popping copy
424 now at: new
435 now at: new
425 applying copy
436 applying copy
426 now at: copy
437 now at: copy
427 diff --git a/new b/copy
438 diff --git a/new b/copy
428 copy from new
439 copy from new
429 copy to copy
440 copy to copy
430 diff --git a/new b/copy
441 diff --git a/new b/copy
431 copy from new
442 copy from new
432 copy to copy
443 copy to copy
433 % test file addition in slow path
444 % test file addition in slow path
434 1 files updated, 0 files merged, 2 files removed, 0 files unresolved
445 1 files updated, 0 files merged, 2 files removed, 0 files unresolved
435 created new head
446 created new head
436 2 files updated, 0 files merged, 1 files removed, 0 files unresolved
447 2 files updated, 0 files merged, 1 files removed, 0 files unresolved
437 diff --git a/bar b/bar
448 diff --git a/bar b/bar
438 new file mode 100644
449 new file mode 100644
439 --- /dev/null
450 --- /dev/null
440 +++ b/bar
451 +++ b/bar
441 @@ -0,0 +1,1 @@
452 @@ -0,0 +1,1 @@
442 +bar
453 +bar
443 diff --git a/foo b/baz
454 diff --git a/foo b/baz
444 rename from foo
455 rename from foo
445 rename to baz
456 rename to baz
446 2 baz (foo)
457 2 baz (foo)
447 diff --git a/bar b/bar
458 diff --git a/bar b/bar
448 new file mode 100644
459 new file mode 100644
449 --- /dev/null
460 --- /dev/null
450 +++ b/bar
461 +++ b/bar
451 @@ -0,0 +1,1 @@
462 @@ -0,0 +1,1 @@
452 +bar
463 +bar
453 diff --git a/foo b/baz
464 diff --git a/foo b/baz
454 rename from foo
465 rename from foo
455 rename to baz
466 rename to baz
456 2 baz (foo)
467 2 baz (foo)
457 diff --git a/bar b/bar
468 diff --git a/bar b/bar
458 diff --git a/foo b/baz
469 diff --git a/foo b/baz
459 % test file move chains in the slow path
470 % test file move chains in the slow path
460 1 files updated, 0 files merged, 2 files removed, 0 files unresolved
471 1 files updated, 0 files merged, 2 files removed, 0 files unresolved
461 2 files updated, 0 files merged, 1 files removed, 0 files unresolved
472 2 files updated, 0 files merged, 1 files removed, 0 files unresolved
462 diff --git a/foo b/bleh
473 diff --git a/foo b/bleh
463 rename from foo
474 rename from foo
464 rename to bleh
475 rename to bleh
465 diff --git a/quux b/quux
476 diff --git a/quux b/quux
466 new file mode 100644
477 new file mode 100644
467 --- /dev/null
478 --- /dev/null
468 +++ b/quux
479 +++ b/quux
469 @@ -0,0 +1,1 @@
480 @@ -0,0 +1,1 @@
470 +bar
481 +bar
471 3 bleh (foo)
482 3 bleh (foo)
472 diff --git a/foo b/barney
483 diff --git a/foo b/barney
473 rename from foo
484 rename from foo
474 rename to barney
485 rename to barney
475 diff --git a/fred b/fred
486 diff --git a/fred b/fred
476 new file mode 100644
487 new file mode 100644
477 --- /dev/null
488 --- /dev/null
478 +++ b/fred
489 +++ b/fred
479 @@ -0,0 +1,1 @@
490 @@ -0,0 +1,1 @@
480 +bar
491 +bar
481 3 barney (foo)
492 3 barney (foo)
482 % refresh omitting an added file
493 % refresh omitting an added file
483 C newfile
494 C newfile
484 A newfile
495 A newfile
485 popping baz
496 popping baz
486 now at: bar
497 now at: bar
487 % create a git patch
498 % create a git patch
488 diff --git a/alexander b/alexander
499 diff --git a/alexander b/alexander
489 % create a git binary patch
500 % create a git binary patch
490 8ba2a2f3e77b55d03051ff9c24ad65e7 bucephalus
501 8ba2a2f3e77b55d03051ff9c24ad65e7 bucephalus
491 diff --git a/bucephalus b/bucephalus
502 diff --git a/bucephalus b/bucephalus
492 % check binary patches can be popped and pushed
503 % check binary patches can be popped and pushed
493 popping addbucephalus
504 popping addbucephalus
494 now at: addalexander
505 now at: addalexander
495 applying addbucephalus
506 applying addbucephalus
496 now at: addbucephalus
507 now at: addbucephalus
497 8ba2a2f3e77b55d03051ff9c24ad65e7 bucephalus
508 8ba2a2f3e77b55d03051ff9c24ad65e7 bucephalus
498 % strip again
509 % strip again
499 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
510 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
500 created new head
511 created new head
501 merging foo
512 merging foo
502 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
513 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
503 (branch merge, don't forget to commit)
514 (branch merge, don't forget to commit)
504 changeset: 3:99615015637b
515 changeset: 3:99615015637b
505 tag: tip
516 tag: tip
506 parent: 2:20cbbe65cff7
517 parent: 2:20cbbe65cff7
507 parent: 1:d2871fc282d4
518 parent: 1:d2871fc282d4
508 user: test
519 user: test
509 date: Thu Jan 01 00:00:00 1970 +0000
520 date: Thu Jan 01 00:00:00 1970 +0000
510 summary: merge
521 summary: merge
511
522
512 changeset: 2:20cbbe65cff7
523 changeset: 2:20cbbe65cff7
513 parent: 0:53245c60e682
524 parent: 0:53245c60e682
514 user: test
525 user: test
515 date: Thu Jan 01 00:00:00 1970 +0000
526 date: Thu Jan 01 00:00:00 1970 +0000
516 summary: change foo 2
527 summary: change foo 2
517
528
518 changeset: 1:d2871fc282d4
529 changeset: 1:d2871fc282d4
519 user: test
530 user: test
520 date: Thu Jan 01 00:00:00 1970 +0000
531 date: Thu Jan 01 00:00:00 1970 +0000
521 summary: change foo 1
532 summary: change foo 1
522
533
523 changeset: 0:53245c60e682
534 changeset: 0:53245c60e682
524 user: test
535 user: test
525 date: Thu Jan 01 00:00:00 1970 +0000
536 date: Thu Jan 01 00:00:00 1970 +0000
526 summary: add foo
537 summary: add foo
527
538
528 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
539 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
529 saved backup bundle to
540 saved backup bundle to
530 changeset: 1:20cbbe65cff7
541 changeset: 1:20cbbe65cff7
531 tag: tip
542 tag: tip
532 user: test
543 user: test
533 date: Thu Jan 01 00:00:00 1970 +0000
544 date: Thu Jan 01 00:00:00 1970 +0000
534 summary: change foo 2
545 summary: change foo 2
535
546
536 changeset: 0:53245c60e682
547 changeset: 0:53245c60e682
537 user: test
548 user: test
538 date: Thu Jan 01 00:00:00 1970 +0000
549 date: Thu Jan 01 00:00:00 1970 +0000
539 summary: add foo
550 summary: add foo
540
551
541 % qclone
552 % qclone
542 abort: versioned patch repository not found (see init --mq)
553 abort: versioned patch repository not found (see init --mq)
543 adding .hg/patches/patch1
554 adding .hg/patches/patch1
544 main repo:
555 main repo:
545 rev 1: change foo
556 rev 1: change foo
546 rev 0: add foo
557 rev 0: add foo
547 patch repo:
558 patch repo:
548 rev 0: checkpoint
559 rev 0: checkpoint
549 updating to branch default
560 updating to branch default
550 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
561 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
551 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
562 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
552 main repo:
563 main repo:
553 rev 0: add foo
564 rev 0: add foo
554 patch repo:
565 patch repo:
555 rev 0: checkpoint
566 rev 0: checkpoint
556 popping patch1
567 popping patch1
557 patch queue now empty
568 patch queue now empty
558 main repo:
569 main repo:
559 rev 0: add foo
570 rev 0: add foo
560 patch repo:
571 patch repo:
561 rev 0: checkpoint
572 rev 0: checkpoint
562 updating to branch default
573 updating to branch default
563 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
574 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
564 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
575 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
565 main repo:
576 main repo:
566 rev 0: add foo
577 rev 0: add foo
567 patch repo:
578 patch repo:
568 rev 0: checkpoint
579 rev 0: checkpoint
569 % test applying on an empty file (issue 1033)
580 % test applying on an empty file (issue 1033)
570 adding a
581 adding a
571 popping changea
582 popping changea
572 patch queue now empty
583 patch queue now empty
573 applying changea
584 applying changea
574 now at: changea
585 now at: changea
575 % test qpush with --force, issue1087
586 % test qpush with --force, issue1087
576 adding bye.txt
587 adding bye.txt
577 adding hello.txt
588 adding hello.txt
578 popping empty
589 popping empty
579 patch queue now empty
590 patch queue now empty
580 % qpush should fail, local changes
591 % qpush should fail, local changes
581 abort: local changes found, refresh first
592 abort: local changes found, refresh first
582 % apply force, should not discard changes with empty patch
593 % apply force, should not discard changes with empty patch
583 applying empty
594 applying empty
584 patch empty is empty
595 patch empty is empty
585 now at: empty
596 now at: empty
586 diff -r bf5fc3f07a0a hello.txt
597 diff -r bf5fc3f07a0a hello.txt
587 --- a/hello.txt
598 --- a/hello.txt
588 +++ b/hello.txt
599 +++ b/hello.txt
589 @@ -1,1 +1,2 @@
600 @@ -1,1 +1,2 @@
590 hello
601 hello
591 +world
602 +world
592 diff -r 9ecee4f634e3 hello.txt
603 diff -r 9ecee4f634e3 hello.txt
593 --- a/hello.txt
604 --- a/hello.txt
594 +++ b/hello.txt
605 +++ b/hello.txt
595 @@ -1,1 +1,2 @@
606 @@ -1,1 +1,2 @@
596 hello
607 hello
597 +world
608 +world
598 changeset: 1:bf5fc3f07a0a
609 changeset: 1:bf5fc3f07a0a
599 tag: empty
610 tag: empty
600 tag: qbase
611 tag: qbase
601 tag: qtip
612 tag: qtip
602 tag: tip
613 tag: tip
603 user: test
614 user: test
604 date: Thu Jan 01 00:00:00 1970 +0000
615 date: Thu Jan 01 00:00:00 1970 +0000
605 summary: imported patch empty
616 summary: imported patch empty
606
617
607
618
608 popping empty
619 popping empty
609 patch queue now empty
620 patch queue now empty
610 % qpush should fail, local changes
621 % qpush should fail, local changes
611 abort: local changes found, refresh first
622 abort: local changes found, refresh first
612 % apply force, should discard changes in hello, but not bye
623 % apply force, should discard changes in hello, but not bye
613 applying empty
624 applying empty
614 now at: empty
625 now at: empty
615 M bye.txt
626 M bye.txt
616 diff -r ba252371dbc1 bye.txt
627 diff -r ba252371dbc1 bye.txt
617 --- a/bye.txt
628 --- a/bye.txt
618 +++ b/bye.txt
629 +++ b/bye.txt
619 @@ -1,1 +1,2 @@
630 @@ -1,1 +1,2 @@
620 bye
631 bye
621 +universe
632 +universe
622 diff -r 9ecee4f634e3 bye.txt
633 diff -r 9ecee4f634e3 bye.txt
623 --- a/bye.txt
634 --- a/bye.txt
624 +++ b/bye.txt
635 +++ b/bye.txt
625 @@ -1,1 +1,2 @@
636 @@ -1,1 +1,2 @@
626 bye
637 bye
627 +universe
638 +universe
628 diff -r 9ecee4f634e3 hello.txt
639 diff -r 9ecee4f634e3 hello.txt
629 --- a/hello.txt
640 --- a/hello.txt
630 +++ b/hello.txt
641 +++ b/hello.txt
631 @@ -1,1 +1,3 @@
642 @@ -1,1 +1,3 @@
632 hello
643 hello
633 +world
644 +world
634 +universe
645 +universe
635 % test popping revisions not in working dir ancestry
646 % test popping revisions not in working dir ancestry
636 0 A empty
647 0 A empty
637 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
648 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
638 popping empty
649 popping empty
639 patch queue now empty
650 patch queue now empty
640 % test popping must remove files added in subdirectories first
651 % test popping must remove files added in subdirectories first
641 popping rename-dir
652 popping rename-dir
642 patch queue now empty
653 patch queue now empty
@@ -1,82 +1,82 b''
1 adding a/a
1 adding a/a
2 adding a/b
2 adding a/b
3 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
3 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
4 moving a/a to b/a
4 moving a/a to b/a
5 moving a/b to b/b
5 moving a/b to b/b
6 2 files updated, 0 files merged, 2 files removed, 0 files unresolved
6 2 files updated, 0 files merged, 2 files removed, 0 files unresolved
7 created new head
7 created new head
8 searching for copies back to rev 1
8 searching for copies back to rev 1
9 unmatched files in local:
9 unmatched files in local:
10 a/c
10 a/c
11 a/d
11 a/d
12 unmatched files in other:
12 unmatched files in other:
13 b/a
13 b/a
14 b/b
14 b/b
15 all copies found (* = to merge, ! = divergent):
15 all copies found (* = to merge, ! = divergent):
16 b/a -> a/a
16 b/a -> a/a
17 b/b -> a/b
17 b/b -> a/b
18 checking for directory renames
18 checking for directory renames
19 dir a/ -> b/
19 dir a/ -> b/
20 file a/c -> b/c
20 file a/c -> b/c
21 file a/d -> b/d
21 file a/d -> b/d
22 resolving manifests
22 resolving manifests
23 overwrite None partial False
23 overwrite None partial False
24 ancestor f9b20c0d4c51 local ce36d17b18fb+ remote 397f8b00a740
24 ancestor f9b20c0d4c51 local ce36d17b18fb+ remote 397f8b00a740
25 a/d: remote renamed directory to b/d -> d
25 a/d: remote renamed directory to b/d -> d
26 a/c: remote renamed directory to b/c -> d
26 a/c: remote renamed directory to b/c -> d
27 a/b: other deleted -> r
27 a/b: other deleted -> r
28 a/a: other deleted -> r
28 a/a: other deleted -> r
29 b/a: remote created -> g
29 b/a: remote created -> g
30 b/b: remote created -> g
30 b/b: remote created -> g
31 update: a/a 1/6 files (16.67%)
31 updating: a/a 1/6 files (16.67%)
32 removing a/a
32 removing a/a
33 update: a/b 2/6 files (33.33%)
33 updating: a/b 2/6 files (33.33%)
34 removing a/b
34 removing a/b
35 update: a/c 3/6 files (50.00%)
35 updating: a/c 3/6 files (50.00%)
36 moving a/c to b/c
36 moving a/c to b/c
37 update: a/d 4/6 files (66.67%)
37 updating: a/d 4/6 files (66.67%)
38 moving a/d to b/d
38 moving a/d to b/d
39 update: b/a 5/6 files (83.33%)
39 updating: b/a 5/6 files (83.33%)
40 getting b/a
40 getting b/a
41 update: b/b 6/6 files (100.00%)
41 updating: b/b 6/6 files (100.00%)
42 getting b/b
42 getting b/b
43 4 files updated, 0 files merged, 2 files removed, 0 files unresolved
43 4 files updated, 0 files merged, 2 files removed, 0 files unresolved
44 (branch merge, don't forget to commit)
44 (branch merge, don't forget to commit)
45 a/* b/a b/b b/c b/d
45 a/* b/a b/b b/c b/d
46 M b/a
46 M b/a
47 M b/b
47 M b/b
48 A b/c
48 A b/c
49 a/c
49 a/c
50 R a/a
50 R a/a
51 R a/b
51 R a/b
52 R a/c
52 R a/c
53 ? b/d
53 ? b/d
54 b/c renamed from a/c:354ae8da6e890359ef49ade27b68bbc361f3ca88
54 b/c renamed from a/c:354ae8da6e890359ef49ade27b68bbc361f3ca88
55 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
55 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
56 searching for copies back to rev 1
56 searching for copies back to rev 1
57 unmatched files in local:
57 unmatched files in local:
58 b/a
58 b/a
59 b/b
59 b/b
60 b/d
60 b/d
61 unmatched files in other:
61 unmatched files in other:
62 a/c
62 a/c
63 all copies found (* = to merge, ! = divergent):
63 all copies found (* = to merge, ! = divergent):
64 b/a -> a/a
64 b/a -> a/a
65 b/b -> a/b
65 b/b -> a/b
66 checking for directory renames
66 checking for directory renames
67 dir a/ -> b/
67 dir a/ -> b/
68 file a/c -> b/c
68 file a/c -> b/c
69 resolving manifests
69 resolving manifests
70 overwrite None partial False
70 overwrite None partial False
71 ancestor f9b20c0d4c51 local 397f8b00a740+ remote ce36d17b18fb
71 ancestor f9b20c0d4c51 local 397f8b00a740+ remote ce36d17b18fb
72 None: local renamed directory to b/c -> d
72 None: local renamed directory to b/c -> d
73 update:None 1/1 files (100.00%)
73 updating:None 1/1 files (100.00%)
74 getting a/c to b/c
74 getting a/c to b/c
75 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
75 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
76 (branch merge, don't forget to commit)
76 (branch merge, don't forget to commit)
77 a/* b/a b/b b/c b/d
77 a/* b/a b/b b/c b/d
78 A b/c
78 A b/c
79 a/c
79 a/c
80 ? b/d
80 ? b/d
81 created new head
81 created new head
82 b/c renamed from a/c:354ae8da6e890359ef49ade27b68bbc361f3ca88
82 b/c renamed from a/c:354ae8da6e890359ef49ade27b68bbc361f3ca88
@@ -1,46 +1,46 b''
1 checkout
1 checkout
2 2 files updated, 0 files merged, 2 files removed, 0 files unresolved
2 2 files updated, 0 files merged, 2 files removed, 0 files unresolved
3 created new head
3 created new head
4 merge
4 merge
5 searching for copies back to rev 1
5 searching for copies back to rev 1
6 unmatched files in local:
6 unmatched files in local:
7 c2
7 c2
8 unmatched files in other:
8 unmatched files in other:
9 b
9 b
10 b2
10 b2
11 all copies found (* = to merge, ! = divergent):
11 all copies found (* = to merge, ! = divergent):
12 c2 -> a2 !
12 c2 -> a2 !
13 b -> a *
13 b -> a *
14 b2 -> a2 !
14 b2 -> a2 !
15 checking for directory renames
15 checking for directory renames
16 a2: divergent renames -> dr
16 a2: divergent renames -> dr
17 resolving manifests
17 resolving manifests
18 overwrite None partial False
18 overwrite None partial False
19 ancestor af1939970a1c local 044f8520aeeb+ remote 85c198ef2f6c
19 ancestor af1939970a1c local 044f8520aeeb+ remote 85c198ef2f6c
20 a: remote moved to b -> m
20 a: remote moved to b -> m
21 b2: remote created -> g
21 b2: remote created -> g
22 preserving a for resolve of b
22 preserving a for resolve of b
23 removing a
23 removing a
24 update: a 1/3 files (33.33%)
24 updating: a 1/3 files (33.33%)
25 picked tool 'internal:merge' for b (binary False symlink False)
25 picked tool 'internal:merge' for b (binary False symlink False)
26 merging a and b to b
26 merging a and b to b
27 my b@044f8520aeeb+ other b@85c198ef2f6c ancestor a@af1939970a1c
27 my b@044f8520aeeb+ other b@85c198ef2f6c ancestor a@af1939970a1c
28 premerge successful
28 premerge successful
29 update: a2 2/3 files (66.67%)
29 updating: a2 2/3 files (66.67%)
30 warning: detected divergent renames of a2 to:
30 warning: detected divergent renames of a2 to:
31 c2
31 c2
32 b2
32 b2
33 update: b2 3/3 files (100.00%)
33 updating: b2 3/3 files (100.00%)
34 getting b2
34 getting b2
35 1 files updated, 1 files merged, 0 files removed, 0 files unresolved
35 1 files updated, 1 files merged, 0 files removed, 0 files unresolved
36 (branch merge, don't forget to commit)
36 (branch merge, don't forget to commit)
37 M b
37 M b
38 a
38 a
39 M b2
39 M b2
40 R a
40 R a
41 C c2
41 C c2
42 blahblah
42 blahblah
43 rev offset length base linkrev nodeid p1 p2
43 rev offset length base linkrev nodeid p1 p2
44 0 0 67 0 1 57eacc201a7f 000000000000 000000000000
44 0 0 67 0 1 57eacc201a7f 000000000000 000000000000
45 1 67 72 1 3 4727ba907962 000000000000 57eacc201a7f
45 1 67 72 1 3 4727ba907962 000000000000 57eacc201a7f
46 b renamed from a:dd03b83622e78778b403775d0d074b9ac7387a66
46 b renamed from a:dd03b83622e78778b403775d0d074b9ac7387a66
@@ -1,651 +1,651 b''
1 created new head
1 created new head
2 --------------
2 --------------
3 test L:up a R:nc a b W: - 1 get local a to b
3 test L:up a R:nc a b W: - 1 get local a to b
4 --------------
4 --------------
5 searching for copies back to rev 1
5 searching for copies back to rev 1
6 unmatched files in other:
6 unmatched files in other:
7 b
7 b
8 all copies found (* = to merge, ! = divergent):
8 all copies found (* = to merge, ! = divergent):
9 b -> a *
9 b -> a *
10 checking for directory renames
10 checking for directory renames
11 resolving manifests
11 resolving manifests
12 overwrite None partial False
12 overwrite None partial False
13 ancestor 924404dff337 local e300d1c794ec+ remote 4ce40f5aca24
13 ancestor 924404dff337 local e300d1c794ec+ remote 4ce40f5aca24
14 rev: versions differ -> m
14 rev: versions differ -> m
15 a: remote copied to b -> m
15 a: remote copied to b -> m
16 preserving a for resolve of b
16 preserving a for resolve of b
17 preserving rev for resolve of rev
17 preserving rev for resolve of rev
18 update: a 1/2 files (50.00%)
18 updating: a 1/2 files (50.00%)
19 picked tool 'python ../merge' for b (binary False symlink False)
19 picked tool 'python ../merge' for b (binary False symlink False)
20 merging a and b to b
20 merging a and b to b
21 my b@e300d1c794ec+ other b@4ce40f5aca24 ancestor a@924404dff337
21 my b@e300d1c794ec+ other b@4ce40f5aca24 ancestor a@924404dff337
22 premerge successful
22 premerge successful
23 update: rev 2/2 files (100.00%)
23 updating: rev 2/2 files (100.00%)
24 picked tool 'python ../merge' for rev (binary False symlink False)
24 picked tool 'python ../merge' for rev (binary False symlink False)
25 merging rev
25 merging rev
26 my rev@e300d1c794ec+ other rev@4ce40f5aca24 ancestor rev@924404dff337
26 my rev@e300d1c794ec+ other rev@4ce40f5aca24 ancestor rev@924404dff337
27 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
27 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
28 (branch merge, don't forget to commit)
28 (branch merge, don't forget to commit)
29 --------------
29 --------------
30 M b
30 M b
31 a
31 a
32 C a
32 C a
33 --------------
33 --------------
34
34
35 created new head
35 created new head
36 --------------
36 --------------
37 test L:nc a b R:up a W: - 2 get rem change to a and b
37 test L:nc a b R:up a W: - 2 get rem change to a and b
38 --------------
38 --------------
39 searching for copies back to rev 1
39 searching for copies back to rev 1
40 unmatched files in local:
40 unmatched files in local:
41 b
41 b
42 all copies found (* = to merge, ! = divergent):
42 all copies found (* = to merge, ! = divergent):
43 b -> a *
43 b -> a *
44 checking for directory renames
44 checking for directory renames
45 resolving manifests
45 resolving manifests
46 overwrite None partial False
46 overwrite None partial False
47 ancestor 924404dff337 local 86a2aa42fc76+ remote f4db7e329e71
47 ancestor 924404dff337 local 86a2aa42fc76+ remote f4db7e329e71
48 a: remote is newer -> g
48 a: remote is newer -> g
49 b: local copied/moved to a -> m
49 b: local copied/moved to a -> m
50 rev: versions differ -> m
50 rev: versions differ -> m
51 preserving b for resolve of b
51 preserving b for resolve of b
52 preserving rev for resolve of rev
52 preserving rev for resolve of rev
53 update: a 1/3 files (33.33%)
53 updating: a 1/3 files (33.33%)
54 getting a
54 getting a
55 update: b 2/3 files (66.67%)
55 updating: b 2/3 files (66.67%)
56 picked tool 'python ../merge' for b (binary False symlink False)
56 picked tool 'python ../merge' for b (binary False symlink False)
57 merging b and a to b
57 merging b and a to b
58 my b@86a2aa42fc76+ other a@f4db7e329e71 ancestor a@924404dff337
58 my b@86a2aa42fc76+ other a@f4db7e329e71 ancestor a@924404dff337
59 premerge successful
59 premerge successful
60 update: rev 3/3 files (100.00%)
60 updating: rev 3/3 files (100.00%)
61 picked tool 'python ../merge' for rev (binary False symlink False)
61 picked tool 'python ../merge' for rev (binary False symlink False)
62 merging rev
62 merging rev
63 my rev@86a2aa42fc76+ other rev@f4db7e329e71 ancestor rev@924404dff337
63 my rev@86a2aa42fc76+ other rev@f4db7e329e71 ancestor rev@924404dff337
64 1 files updated, 2 files merged, 0 files removed, 0 files unresolved
64 1 files updated, 2 files merged, 0 files removed, 0 files unresolved
65 (branch merge, don't forget to commit)
65 (branch merge, don't forget to commit)
66 --------------
66 --------------
67 M a
67 M a
68 M b
68 M b
69 a
69 a
70 --------------
70 --------------
71
71
72 created new head
72 created new head
73 --------------
73 --------------
74 test L:up a R:nm a b W: - 3 get local a change to b, remove a
74 test L:up a R:nm a b W: - 3 get local a change to b, remove a
75 --------------
75 --------------
76 searching for copies back to rev 1
76 searching for copies back to rev 1
77 unmatched files in other:
77 unmatched files in other:
78 b
78 b
79 all copies found (* = to merge, ! = divergent):
79 all copies found (* = to merge, ! = divergent):
80 b -> a *
80 b -> a *
81 checking for directory renames
81 checking for directory renames
82 resolving manifests
82 resolving manifests
83 overwrite None partial False
83 overwrite None partial False
84 ancestor 924404dff337 local e300d1c794ec+ remote bdb19105162a
84 ancestor 924404dff337 local e300d1c794ec+ remote bdb19105162a
85 rev: versions differ -> m
85 rev: versions differ -> m
86 a: remote moved to b -> m
86 a: remote moved to b -> m
87 preserving a for resolve of b
87 preserving a for resolve of b
88 preserving rev for resolve of rev
88 preserving rev for resolve of rev
89 removing a
89 removing a
90 update: a 1/2 files (50.00%)
90 updating: a 1/2 files (50.00%)
91 picked tool 'python ../merge' for b (binary False symlink False)
91 picked tool 'python ../merge' for b (binary False symlink False)
92 merging a and b to b
92 merging a and b to b
93 my b@e300d1c794ec+ other b@bdb19105162a ancestor a@924404dff337
93 my b@e300d1c794ec+ other b@bdb19105162a ancestor a@924404dff337
94 premerge successful
94 premerge successful
95 update: rev 2/2 files (100.00%)
95 updating: rev 2/2 files (100.00%)
96 picked tool 'python ../merge' for rev (binary False symlink False)
96 picked tool 'python ../merge' for rev (binary False symlink False)
97 merging rev
97 merging rev
98 my rev@e300d1c794ec+ other rev@bdb19105162a ancestor rev@924404dff337
98 my rev@e300d1c794ec+ other rev@bdb19105162a ancestor rev@924404dff337
99 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
99 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
100 (branch merge, don't forget to commit)
100 (branch merge, don't forget to commit)
101 --------------
101 --------------
102 M b
102 M b
103 a
103 a
104 --------------
104 --------------
105
105
106 created new head
106 created new head
107 --------------
107 --------------
108 test L:nm a b R:up a W: - 4 get remote change to b
108 test L:nm a b R:up a W: - 4 get remote change to b
109 --------------
109 --------------
110 searching for copies back to rev 1
110 searching for copies back to rev 1
111 unmatched files in local:
111 unmatched files in local:
112 b
112 b
113 all copies found (* = to merge, ! = divergent):
113 all copies found (* = to merge, ! = divergent):
114 b -> a *
114 b -> a *
115 checking for directory renames
115 checking for directory renames
116 resolving manifests
116 resolving manifests
117 overwrite None partial False
117 overwrite None partial False
118 ancestor 924404dff337 local 02963e448370+ remote f4db7e329e71
118 ancestor 924404dff337 local 02963e448370+ remote f4db7e329e71
119 b: local copied/moved to a -> m
119 b: local copied/moved to a -> m
120 rev: versions differ -> m
120 rev: versions differ -> m
121 preserving b for resolve of b
121 preserving b for resolve of b
122 preserving rev for resolve of rev
122 preserving rev for resolve of rev
123 update: b 1/2 files (50.00%)
123 updating: b 1/2 files (50.00%)
124 picked tool 'python ../merge' for b (binary False symlink False)
124 picked tool 'python ../merge' for b (binary False symlink False)
125 merging b and a to b
125 merging b and a to b
126 my b@02963e448370+ other a@f4db7e329e71 ancestor a@924404dff337
126 my b@02963e448370+ other a@f4db7e329e71 ancestor a@924404dff337
127 premerge successful
127 premerge successful
128 update: rev 2/2 files (100.00%)
128 updating: rev 2/2 files (100.00%)
129 picked tool 'python ../merge' for rev (binary False symlink False)
129 picked tool 'python ../merge' for rev (binary False symlink False)
130 merging rev
130 merging rev
131 my rev@02963e448370+ other rev@f4db7e329e71 ancestor rev@924404dff337
131 my rev@02963e448370+ other rev@f4db7e329e71 ancestor rev@924404dff337
132 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
132 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
133 (branch merge, don't forget to commit)
133 (branch merge, don't forget to commit)
134 --------------
134 --------------
135 M b
135 M b
136 a
136 a
137 --------------
137 --------------
138
138
139 created new head
139 created new head
140 --------------
140 --------------
141 test L: R:nc a b W: - 5 get b
141 test L: R:nc a b W: - 5 get b
142 --------------
142 --------------
143 searching for copies back to rev 1
143 searching for copies back to rev 1
144 unmatched files in other:
144 unmatched files in other:
145 b
145 b
146 all copies found (* = to merge, ! = divergent):
146 all copies found (* = to merge, ! = divergent):
147 b -> a
147 b -> a
148 checking for directory renames
148 checking for directory renames
149 resolving manifests
149 resolving manifests
150 overwrite None partial False
150 overwrite None partial False
151 ancestor 924404dff337 local 94b33a1b7f2d+ remote 4ce40f5aca24
151 ancestor 924404dff337 local 94b33a1b7f2d+ remote 4ce40f5aca24
152 rev: versions differ -> m
152 rev: versions differ -> m
153 b: remote created -> g
153 b: remote created -> g
154 preserving rev for resolve of rev
154 preserving rev for resolve of rev
155 update: b 1/2 files (50.00%)
155 updating: b 1/2 files (50.00%)
156 getting b
156 getting b
157 update: rev 2/2 files (100.00%)
157 updating: rev 2/2 files (100.00%)
158 picked tool 'python ../merge' for rev (binary False symlink False)
158 picked tool 'python ../merge' for rev (binary False symlink False)
159 merging rev
159 merging rev
160 my rev@94b33a1b7f2d+ other rev@4ce40f5aca24 ancestor rev@924404dff337
160 my rev@94b33a1b7f2d+ other rev@4ce40f5aca24 ancestor rev@924404dff337
161 1 files updated, 1 files merged, 0 files removed, 0 files unresolved
161 1 files updated, 1 files merged, 0 files removed, 0 files unresolved
162 (branch merge, don't forget to commit)
162 (branch merge, don't forget to commit)
163 --------------
163 --------------
164 M b
164 M b
165 C a
165 C a
166 --------------
166 --------------
167
167
168 created new head
168 created new head
169 --------------
169 --------------
170 test L:nc a b R: W: - 6 nothing
170 test L:nc a b R: W: - 6 nothing
171 --------------
171 --------------
172 searching for copies back to rev 1
172 searching for copies back to rev 1
173 unmatched files in local:
173 unmatched files in local:
174 b
174 b
175 all copies found (* = to merge, ! = divergent):
175 all copies found (* = to merge, ! = divergent):
176 b -> a
176 b -> a
177 checking for directory renames
177 checking for directory renames
178 resolving manifests
178 resolving manifests
179 overwrite None partial False
179 overwrite None partial False
180 ancestor 924404dff337 local 86a2aa42fc76+ remote 97c705ade336
180 ancestor 924404dff337 local 86a2aa42fc76+ remote 97c705ade336
181 rev: versions differ -> m
181 rev: versions differ -> m
182 preserving rev for resolve of rev
182 preserving rev for resolve of rev
183 update: rev 1/1 files (100.00%)
183 updating: rev 1/1 files (100.00%)
184 picked tool 'python ../merge' for rev (binary False symlink False)
184 picked tool 'python ../merge' for rev (binary False symlink False)
185 merging rev
185 merging rev
186 my rev@86a2aa42fc76+ other rev@97c705ade336 ancestor rev@924404dff337
186 my rev@86a2aa42fc76+ other rev@97c705ade336 ancestor rev@924404dff337
187 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
187 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
188 (branch merge, don't forget to commit)
188 (branch merge, don't forget to commit)
189 --------------
189 --------------
190 C a
190 C a
191 C b
191 C b
192 --------------
192 --------------
193
193
194 created new head
194 created new head
195 --------------
195 --------------
196 test L: R:nm a b W: - 7 get b
196 test L: R:nm a b W: - 7 get b
197 --------------
197 --------------
198 searching for copies back to rev 1
198 searching for copies back to rev 1
199 unmatched files in other:
199 unmatched files in other:
200 b
200 b
201 all copies found (* = to merge, ! = divergent):
201 all copies found (* = to merge, ! = divergent):
202 b -> a
202 b -> a
203 checking for directory renames
203 checking for directory renames
204 resolving manifests
204 resolving manifests
205 overwrite None partial False
205 overwrite None partial False
206 ancestor 924404dff337 local 94b33a1b7f2d+ remote bdb19105162a
206 ancestor 924404dff337 local 94b33a1b7f2d+ remote bdb19105162a
207 a: other deleted -> r
207 a: other deleted -> r
208 rev: versions differ -> m
208 rev: versions differ -> m
209 b: remote created -> g
209 b: remote created -> g
210 preserving rev for resolve of rev
210 preserving rev for resolve of rev
211 update: a 1/3 files (33.33%)
211 updating: a 1/3 files (33.33%)
212 removing a
212 removing a
213 update: b 2/3 files (66.67%)
213 updating: b 2/3 files (66.67%)
214 getting b
214 getting b
215 update: rev 3/3 files (100.00%)
215 updating: rev 3/3 files (100.00%)
216 picked tool 'python ../merge' for rev (binary False symlink False)
216 picked tool 'python ../merge' for rev (binary False symlink False)
217 merging rev
217 merging rev
218 my rev@94b33a1b7f2d+ other rev@bdb19105162a ancestor rev@924404dff337
218 my rev@94b33a1b7f2d+ other rev@bdb19105162a ancestor rev@924404dff337
219 1 files updated, 1 files merged, 1 files removed, 0 files unresolved
219 1 files updated, 1 files merged, 1 files removed, 0 files unresolved
220 (branch merge, don't forget to commit)
220 (branch merge, don't forget to commit)
221 --------------
221 --------------
222 M b
222 M b
223 --------------
223 --------------
224
224
225 created new head
225 created new head
226 --------------
226 --------------
227 test L:nm a b R: W: - 8 nothing
227 test L:nm a b R: W: - 8 nothing
228 --------------
228 --------------
229 searching for copies back to rev 1
229 searching for copies back to rev 1
230 unmatched files in local:
230 unmatched files in local:
231 b
231 b
232 all copies found (* = to merge, ! = divergent):
232 all copies found (* = to merge, ! = divergent):
233 b -> a
233 b -> a
234 checking for directory renames
234 checking for directory renames
235 resolving manifests
235 resolving manifests
236 overwrite None partial False
236 overwrite None partial False
237 ancestor 924404dff337 local 02963e448370+ remote 97c705ade336
237 ancestor 924404dff337 local 02963e448370+ remote 97c705ade336
238 rev: versions differ -> m
238 rev: versions differ -> m
239 preserving rev for resolve of rev
239 preserving rev for resolve of rev
240 update: rev 1/1 files (100.00%)
240 updating: rev 1/1 files (100.00%)
241 picked tool 'python ../merge' for rev (binary False symlink False)
241 picked tool 'python ../merge' for rev (binary False symlink False)
242 merging rev
242 merging rev
243 my rev@02963e448370+ other rev@97c705ade336 ancestor rev@924404dff337
243 my rev@02963e448370+ other rev@97c705ade336 ancestor rev@924404dff337
244 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
244 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
245 (branch merge, don't forget to commit)
245 (branch merge, don't forget to commit)
246 --------------
246 --------------
247 C b
247 C b
248 --------------
248 --------------
249
249
250 created new head
250 created new head
251 --------------
251 --------------
252 test L:um a b R:um a b W: - 9 do merge with ancestor in a
252 test L:um a b R:um a b W: - 9 do merge with ancestor in a
253 --------------
253 --------------
254 searching for copies back to rev 1
254 searching for copies back to rev 1
255 resolving manifests
255 resolving manifests
256 overwrite None partial False
256 overwrite None partial False
257 ancestor 924404dff337 local 62e7bf090eba+ remote 49b6d8032493
257 ancestor 924404dff337 local 62e7bf090eba+ remote 49b6d8032493
258 b: versions differ -> m
258 b: versions differ -> m
259 rev: versions differ -> m
259 rev: versions differ -> m
260 preserving b for resolve of b
260 preserving b for resolve of b
261 preserving rev for resolve of rev
261 preserving rev for resolve of rev
262 update: b 1/2 files (50.00%)
262 updating: b 1/2 files (50.00%)
263 picked tool 'python ../merge' for b (binary False symlink False)
263 picked tool 'python ../merge' for b (binary False symlink False)
264 merging b
264 merging b
265 my b@62e7bf090eba+ other b@49b6d8032493 ancestor a@924404dff337
265 my b@62e7bf090eba+ other b@49b6d8032493 ancestor a@924404dff337
266 update: rev 2/2 files (100.00%)
266 updating: rev 2/2 files (100.00%)
267 picked tool 'python ../merge' for rev (binary False symlink False)
267 picked tool 'python ../merge' for rev (binary False symlink False)
268 merging rev
268 merging rev
269 my rev@62e7bf090eba+ other rev@49b6d8032493 ancestor rev@924404dff337
269 my rev@62e7bf090eba+ other rev@49b6d8032493 ancestor rev@924404dff337
270 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
270 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
271 (branch merge, don't forget to commit)
271 (branch merge, don't forget to commit)
272 --------------
272 --------------
273 M b
273 M b
274 --------------
274 --------------
275
275
276 created new head
276 created new head
277 --------------
277 --------------
278 test L:nm a b R:nm a c W: - 11 get c, keep b
278 test L:nm a b R:nm a c W: - 11 get c, keep b
279 --------------
279 --------------
280 searching for copies back to rev 1
280 searching for copies back to rev 1
281 unmatched files in local:
281 unmatched files in local:
282 b
282 b
283 unmatched files in other:
283 unmatched files in other:
284 c
284 c
285 all copies found (* = to merge, ! = divergent):
285 all copies found (* = to merge, ! = divergent):
286 c -> a !
286 c -> a !
287 b -> a !
287 b -> a !
288 checking for directory renames
288 checking for directory renames
289 a: divergent renames -> dr
289 a: divergent renames -> dr
290 resolving manifests
290 resolving manifests
291 overwrite None partial False
291 overwrite None partial False
292 ancestor 924404dff337 local 02963e448370+ remote fe905ef2c33e
292 ancestor 924404dff337 local 02963e448370+ remote fe905ef2c33e
293 rev: versions differ -> m
293 rev: versions differ -> m
294 c: remote created -> g
294 c: remote created -> g
295 preserving rev for resolve of rev
295 preserving rev for resolve of rev
296 update: a 1/3 files (33.33%)
296 updating: a 1/3 files (33.33%)
297 warning: detected divergent renames of a to:
297 warning: detected divergent renames of a to:
298 b
298 b
299 c
299 c
300 update: c 2/3 files (66.67%)
300 updating: c 2/3 files (66.67%)
301 getting c
301 getting c
302 update: rev 3/3 files (100.00%)
302 updating: rev 3/3 files (100.00%)
303 picked tool 'python ../merge' for rev (binary False symlink False)
303 picked tool 'python ../merge' for rev (binary False symlink False)
304 merging rev
304 merging rev
305 my rev@02963e448370+ other rev@fe905ef2c33e ancestor rev@924404dff337
305 my rev@02963e448370+ other rev@fe905ef2c33e ancestor rev@924404dff337
306 1 files updated, 1 files merged, 0 files removed, 0 files unresolved
306 1 files updated, 1 files merged, 0 files removed, 0 files unresolved
307 (branch merge, don't forget to commit)
307 (branch merge, don't forget to commit)
308 --------------
308 --------------
309 M c
309 M c
310 C b
310 C b
311 --------------
311 --------------
312
312
313 created new head
313 created new head
314 --------------
314 --------------
315 test L:nc a b R:up b W: - 12 merge b no ancestor
315 test L:nc a b R:up b W: - 12 merge b no ancestor
316 --------------
316 --------------
317 searching for copies back to rev 1
317 searching for copies back to rev 1
318 resolving manifests
318 resolving manifests
319 overwrite None partial False
319 overwrite None partial False
320 ancestor 924404dff337 local 86a2aa42fc76+ remote af30c7647fc7
320 ancestor 924404dff337 local 86a2aa42fc76+ remote af30c7647fc7
321 b: versions differ -> m
321 b: versions differ -> m
322 rev: versions differ -> m
322 rev: versions differ -> m
323 preserving b for resolve of b
323 preserving b for resolve of b
324 preserving rev for resolve of rev
324 preserving rev for resolve of rev
325 update: b 1/2 files (50.00%)
325 updating: b 1/2 files (50.00%)
326 picked tool 'python ../merge' for b (binary False symlink False)
326 picked tool 'python ../merge' for b (binary False symlink False)
327 merging b
327 merging b
328 my b@86a2aa42fc76+ other b@af30c7647fc7 ancestor b@000000000000
328 my b@86a2aa42fc76+ other b@af30c7647fc7 ancestor b@000000000000
329 update: rev 2/2 files (100.00%)
329 updating: rev 2/2 files (100.00%)
330 picked tool 'python ../merge' for rev (binary False symlink False)
330 picked tool 'python ../merge' for rev (binary False symlink False)
331 merging rev
331 merging rev
332 my rev@86a2aa42fc76+ other rev@af30c7647fc7 ancestor rev@924404dff337
332 my rev@86a2aa42fc76+ other rev@af30c7647fc7 ancestor rev@924404dff337
333 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
333 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
334 (branch merge, don't forget to commit)
334 (branch merge, don't forget to commit)
335 --------------
335 --------------
336 M b
336 M b
337 C a
337 C a
338 --------------
338 --------------
339
339
340 created new head
340 created new head
341 --------------
341 --------------
342 test L:up b R:nm a b W: - 13 merge b no ancestor
342 test L:up b R:nm a b W: - 13 merge b no ancestor
343 --------------
343 --------------
344 searching for copies back to rev 1
344 searching for copies back to rev 1
345 resolving manifests
345 resolving manifests
346 overwrite None partial False
346 overwrite None partial False
347 ancestor 924404dff337 local 59318016310c+ remote bdb19105162a
347 ancestor 924404dff337 local 59318016310c+ remote bdb19105162a
348 a: other deleted -> r
348 a: other deleted -> r
349 b: versions differ -> m
349 b: versions differ -> m
350 rev: versions differ -> m
350 rev: versions differ -> m
351 preserving b for resolve of b
351 preserving b for resolve of b
352 preserving rev for resolve of rev
352 preserving rev for resolve of rev
353 update: a 1/3 files (33.33%)
353 updating: a 1/3 files (33.33%)
354 removing a
354 removing a
355 update: b 2/3 files (66.67%)
355 updating: b 2/3 files (66.67%)
356 picked tool 'python ../merge' for b (binary False symlink False)
356 picked tool 'python ../merge' for b (binary False symlink False)
357 merging b
357 merging b
358 my b@59318016310c+ other b@bdb19105162a ancestor b@000000000000
358 my b@59318016310c+ other b@bdb19105162a ancestor b@000000000000
359 update: rev 3/3 files (100.00%)
359 updating: rev 3/3 files (100.00%)
360 picked tool 'python ../merge' for rev (binary False symlink False)
360 picked tool 'python ../merge' for rev (binary False symlink False)
361 merging rev
361 merging rev
362 my rev@59318016310c+ other rev@bdb19105162a ancestor rev@924404dff337
362 my rev@59318016310c+ other rev@bdb19105162a ancestor rev@924404dff337
363 0 files updated, 2 files merged, 1 files removed, 0 files unresolved
363 0 files updated, 2 files merged, 1 files removed, 0 files unresolved
364 (branch merge, don't forget to commit)
364 (branch merge, don't forget to commit)
365 --------------
365 --------------
366 M b
366 M b
367 --------------
367 --------------
368
368
369 created new head
369 created new head
370 --------------
370 --------------
371 test L:nc a b R:up a b W: - 14 merge b no ancestor
371 test L:nc a b R:up a b W: - 14 merge b no ancestor
372 --------------
372 --------------
373 searching for copies back to rev 1
373 searching for copies back to rev 1
374 resolving manifests
374 resolving manifests
375 overwrite None partial False
375 overwrite None partial False
376 ancestor 924404dff337 local 86a2aa42fc76+ remote 8dbce441892a
376 ancestor 924404dff337 local 86a2aa42fc76+ remote 8dbce441892a
377 a: remote is newer -> g
377 a: remote is newer -> g
378 b: versions differ -> m
378 b: versions differ -> m
379 rev: versions differ -> m
379 rev: versions differ -> m
380 preserving b for resolve of b
380 preserving b for resolve of b
381 preserving rev for resolve of rev
381 preserving rev for resolve of rev
382 update: a 1/3 files (33.33%)
382 updating: a 1/3 files (33.33%)
383 getting a
383 getting a
384 update: b 2/3 files (66.67%)
384 updating: b 2/3 files (66.67%)
385 picked tool 'python ../merge' for b (binary False symlink False)
385 picked tool 'python ../merge' for b (binary False symlink False)
386 merging b
386 merging b
387 my b@86a2aa42fc76+ other b@8dbce441892a ancestor b@000000000000
387 my b@86a2aa42fc76+ other b@8dbce441892a ancestor b@000000000000
388 update: rev 3/3 files (100.00%)
388 updating: rev 3/3 files (100.00%)
389 picked tool 'python ../merge' for rev (binary False symlink False)
389 picked tool 'python ../merge' for rev (binary False symlink False)
390 merging rev
390 merging rev
391 my rev@86a2aa42fc76+ other rev@8dbce441892a ancestor rev@924404dff337
391 my rev@86a2aa42fc76+ other rev@8dbce441892a ancestor rev@924404dff337
392 1 files updated, 2 files merged, 0 files removed, 0 files unresolved
392 1 files updated, 2 files merged, 0 files removed, 0 files unresolved
393 (branch merge, don't forget to commit)
393 (branch merge, don't forget to commit)
394 --------------
394 --------------
395 M a
395 M a
396 M b
396 M b
397 --------------
397 --------------
398
398
399 created new head
399 created new head
400 --------------
400 --------------
401 test L:up b R:nm a b W: - 15 merge b no ancestor, remove a
401 test L:up b R:nm a b W: - 15 merge b no ancestor, remove a
402 --------------
402 --------------
403 searching for copies back to rev 1
403 searching for copies back to rev 1
404 resolving manifests
404 resolving manifests
405 overwrite None partial False
405 overwrite None partial False
406 ancestor 924404dff337 local 59318016310c+ remote bdb19105162a
406 ancestor 924404dff337 local 59318016310c+ remote bdb19105162a
407 a: other deleted -> r
407 a: other deleted -> r
408 b: versions differ -> m
408 b: versions differ -> m
409 rev: versions differ -> m
409 rev: versions differ -> m
410 preserving b for resolve of b
410 preserving b for resolve of b
411 preserving rev for resolve of rev
411 preserving rev for resolve of rev
412 update: a 1/3 files (33.33%)
412 updating: a 1/3 files (33.33%)
413 removing a
413 removing a
414 update: b 2/3 files (66.67%)
414 updating: b 2/3 files (66.67%)
415 picked tool 'python ../merge' for b (binary False symlink False)
415 picked tool 'python ../merge' for b (binary False symlink False)
416 merging b
416 merging b
417 my b@59318016310c+ other b@bdb19105162a ancestor b@000000000000
417 my b@59318016310c+ other b@bdb19105162a ancestor b@000000000000
418 update: rev 3/3 files (100.00%)
418 updating: rev 3/3 files (100.00%)
419 picked tool 'python ../merge' for rev (binary False symlink False)
419 picked tool 'python ../merge' for rev (binary False symlink False)
420 merging rev
420 merging rev
421 my rev@59318016310c+ other rev@bdb19105162a ancestor rev@924404dff337
421 my rev@59318016310c+ other rev@bdb19105162a ancestor rev@924404dff337
422 0 files updated, 2 files merged, 1 files removed, 0 files unresolved
422 0 files updated, 2 files merged, 1 files removed, 0 files unresolved
423 (branch merge, don't forget to commit)
423 (branch merge, don't forget to commit)
424 --------------
424 --------------
425 M b
425 M b
426 --------------
426 --------------
427
427
428 created new head
428 created new head
429 --------------
429 --------------
430 test L:nc a b R:up a b W: - 16 get a, merge b no ancestor
430 test L:nc a b R:up a b W: - 16 get a, merge b no ancestor
431 --------------
431 --------------
432 searching for copies back to rev 1
432 searching for copies back to rev 1
433 resolving manifests
433 resolving manifests
434 overwrite None partial False
434 overwrite None partial False
435 ancestor 924404dff337 local 86a2aa42fc76+ remote 8dbce441892a
435 ancestor 924404dff337 local 86a2aa42fc76+ remote 8dbce441892a
436 a: remote is newer -> g
436 a: remote is newer -> g
437 b: versions differ -> m
437 b: versions differ -> m
438 rev: versions differ -> m
438 rev: versions differ -> m
439 preserving b for resolve of b
439 preserving b for resolve of b
440 preserving rev for resolve of rev
440 preserving rev for resolve of rev
441 update: a 1/3 files (33.33%)
441 updating: a 1/3 files (33.33%)
442 getting a
442 getting a
443 update: b 2/3 files (66.67%)
443 updating: b 2/3 files (66.67%)
444 picked tool 'python ../merge' for b (binary False symlink False)
444 picked tool 'python ../merge' for b (binary False symlink False)
445 merging b
445 merging b
446 my b@86a2aa42fc76+ other b@8dbce441892a ancestor b@000000000000
446 my b@86a2aa42fc76+ other b@8dbce441892a ancestor b@000000000000
447 update: rev 3/3 files (100.00%)
447 updating: rev 3/3 files (100.00%)
448 picked tool 'python ../merge' for rev (binary False symlink False)
448 picked tool 'python ../merge' for rev (binary False symlink False)
449 merging rev
449 merging rev
450 my rev@86a2aa42fc76+ other rev@8dbce441892a ancestor rev@924404dff337
450 my rev@86a2aa42fc76+ other rev@8dbce441892a ancestor rev@924404dff337
451 1 files updated, 2 files merged, 0 files removed, 0 files unresolved
451 1 files updated, 2 files merged, 0 files removed, 0 files unresolved
452 (branch merge, don't forget to commit)
452 (branch merge, don't forget to commit)
453 --------------
453 --------------
454 M a
454 M a
455 M b
455 M b
456 --------------
456 --------------
457
457
458 created new head
458 created new head
459 --------------
459 --------------
460 test L:up a b R:nc a b W: - 17 keep a, merge b no ancestor
460 test L:up a b R:nc a b W: - 17 keep a, merge b no ancestor
461 --------------
461 --------------
462 searching for copies back to rev 1
462 searching for copies back to rev 1
463 resolving manifests
463 resolving manifests
464 overwrite None partial False
464 overwrite None partial False
465 ancestor 924404dff337 local 0b76e65c8289+ remote 4ce40f5aca24
465 ancestor 924404dff337 local 0b76e65c8289+ remote 4ce40f5aca24
466 b: versions differ -> m
466 b: versions differ -> m
467 rev: versions differ -> m
467 rev: versions differ -> m
468 preserving b for resolve of b
468 preserving b for resolve of b
469 preserving rev for resolve of rev
469 preserving rev for resolve of rev
470 update: b 1/2 files (50.00%)
470 updating: b 1/2 files (50.00%)
471 picked tool 'python ../merge' for b (binary False symlink False)
471 picked tool 'python ../merge' for b (binary False symlink False)
472 merging b
472 merging b
473 my b@0b76e65c8289+ other b@4ce40f5aca24 ancestor b@000000000000
473 my b@0b76e65c8289+ other b@4ce40f5aca24 ancestor b@000000000000
474 update: rev 2/2 files (100.00%)
474 updating: rev 2/2 files (100.00%)
475 picked tool 'python ../merge' for rev (binary False symlink False)
475 picked tool 'python ../merge' for rev (binary False symlink False)
476 merging rev
476 merging rev
477 my rev@0b76e65c8289+ other rev@4ce40f5aca24 ancestor rev@924404dff337
477 my rev@0b76e65c8289+ other rev@4ce40f5aca24 ancestor rev@924404dff337
478 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
478 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
479 (branch merge, don't forget to commit)
479 (branch merge, don't forget to commit)
480 --------------
480 --------------
481 M b
481 M b
482 C a
482 C a
483 --------------
483 --------------
484
484
485 created new head
485 created new head
486 --------------
486 --------------
487 test L:nm a b R:up a b W: - 18 merge b no ancestor
487 test L:nm a b R:up a b W: - 18 merge b no ancestor
488 --------------
488 --------------
489 searching for copies back to rev 1
489 searching for copies back to rev 1
490 resolving manifests
490 resolving manifests
491 overwrite None partial False
491 overwrite None partial False
492 ancestor 924404dff337 local 02963e448370+ remote 8dbce441892a
492 ancestor 924404dff337 local 02963e448370+ remote 8dbce441892a
493 b: versions differ -> m
493 b: versions differ -> m
494 rev: versions differ -> m
494 rev: versions differ -> m
495 remote changed a which local deleted
495 remote changed a which local deleted
496 use (c)hanged version or leave (d)eleted? c
496 use (c)hanged version or leave (d)eleted? c
497 a: prompt recreating -> g
497 a: prompt recreating -> g
498 preserving b for resolve of b
498 preserving b for resolve of b
499 preserving rev for resolve of rev
499 preserving rev for resolve of rev
500 update: a 1/3 files (33.33%)
500 updating: a 1/3 files (33.33%)
501 getting a
501 getting a
502 update: b 2/3 files (66.67%)
502 updating: b 2/3 files (66.67%)
503 picked tool 'python ../merge' for b (binary False symlink False)
503 picked tool 'python ../merge' for b (binary False symlink False)
504 merging b
504 merging b
505 my b@02963e448370+ other b@8dbce441892a ancestor b@000000000000
505 my b@02963e448370+ other b@8dbce441892a ancestor b@000000000000
506 update: rev 3/3 files (100.00%)
506 updating: rev 3/3 files (100.00%)
507 picked tool 'python ../merge' for rev (binary False symlink False)
507 picked tool 'python ../merge' for rev (binary False symlink False)
508 merging rev
508 merging rev
509 my rev@02963e448370+ other rev@8dbce441892a ancestor rev@924404dff337
509 my rev@02963e448370+ other rev@8dbce441892a ancestor rev@924404dff337
510 1 files updated, 2 files merged, 0 files removed, 0 files unresolved
510 1 files updated, 2 files merged, 0 files removed, 0 files unresolved
511 (branch merge, don't forget to commit)
511 (branch merge, don't forget to commit)
512 --------------
512 --------------
513 M a
513 M a
514 M b
514 M b
515 --------------
515 --------------
516
516
517 created new head
517 created new head
518 --------------
518 --------------
519 test L:up a b R:nm a b W: - 19 merge b no ancestor, prompt remove a
519 test L:up a b R:nm a b W: - 19 merge b no ancestor, prompt remove a
520 --------------
520 --------------
521 searching for copies back to rev 1
521 searching for copies back to rev 1
522 resolving manifests
522 resolving manifests
523 overwrite None partial False
523 overwrite None partial False
524 ancestor 924404dff337 local 0b76e65c8289+ remote bdb19105162a
524 ancestor 924404dff337 local 0b76e65c8289+ remote bdb19105162a
525 local changed a which remote deleted
525 local changed a which remote deleted
526 use (c)hanged version or (d)elete? c
526 use (c)hanged version or (d)elete? c
527 a: prompt keep -> a
527 a: prompt keep -> a
528 b: versions differ -> m
528 b: versions differ -> m
529 rev: versions differ -> m
529 rev: versions differ -> m
530 preserving b for resolve of b
530 preserving b for resolve of b
531 preserving rev for resolve of rev
531 preserving rev for resolve of rev
532 update: a 1/3 files (33.33%)
532 updating: a 1/3 files (33.33%)
533 update: b 2/3 files (66.67%)
533 updating: b 2/3 files (66.67%)
534 picked tool 'python ../merge' for b (binary False symlink False)
534 picked tool 'python ../merge' for b (binary False symlink False)
535 merging b
535 merging b
536 my b@0b76e65c8289+ other b@bdb19105162a ancestor b@000000000000
536 my b@0b76e65c8289+ other b@bdb19105162a ancestor b@000000000000
537 update: rev 3/3 files (100.00%)
537 updating: rev 3/3 files (100.00%)
538 picked tool 'python ../merge' for rev (binary False symlink False)
538 picked tool 'python ../merge' for rev (binary False symlink False)
539 merging rev
539 merging rev
540 my rev@0b76e65c8289+ other rev@bdb19105162a ancestor rev@924404dff337
540 my rev@0b76e65c8289+ other rev@bdb19105162a ancestor rev@924404dff337
541 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
541 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
542 (branch merge, don't forget to commit)
542 (branch merge, don't forget to commit)
543 --------------
543 --------------
544 M b
544 M b
545 C a
545 C a
546 --------------
546 --------------
547
547
548 created new head
548 created new head
549 --------------
549 --------------
550 test L:up a R:um a b W: - 20 merge a and b to b, remove a
550 test L:up a R:um a b W: - 20 merge a and b to b, remove a
551 --------------
551 --------------
552 searching for copies back to rev 1
552 searching for copies back to rev 1
553 unmatched files in other:
553 unmatched files in other:
554 b
554 b
555 all copies found (* = to merge, ! = divergent):
555 all copies found (* = to merge, ! = divergent):
556 b -> a *
556 b -> a *
557 checking for directory renames
557 checking for directory renames
558 resolving manifests
558 resolving manifests
559 overwrite None partial False
559 overwrite None partial False
560 ancestor 924404dff337 local e300d1c794ec+ remote 49b6d8032493
560 ancestor 924404dff337 local e300d1c794ec+ remote 49b6d8032493
561 rev: versions differ -> m
561 rev: versions differ -> m
562 a: remote moved to b -> m
562 a: remote moved to b -> m
563 preserving a for resolve of b
563 preserving a for resolve of b
564 preserving rev for resolve of rev
564 preserving rev for resolve of rev
565 removing a
565 removing a
566 update: a 1/2 files (50.00%)
566 updating: a 1/2 files (50.00%)
567 picked tool 'python ../merge' for b (binary False symlink False)
567 picked tool 'python ../merge' for b (binary False symlink False)
568 merging a and b to b
568 merging a and b to b
569 my b@e300d1c794ec+ other b@49b6d8032493 ancestor a@924404dff337
569 my b@e300d1c794ec+ other b@49b6d8032493 ancestor a@924404dff337
570 update: rev 2/2 files (100.00%)
570 updating: rev 2/2 files (100.00%)
571 picked tool 'python ../merge' for rev (binary False symlink False)
571 picked tool 'python ../merge' for rev (binary False symlink False)
572 merging rev
572 merging rev
573 my rev@e300d1c794ec+ other rev@49b6d8032493 ancestor rev@924404dff337
573 my rev@e300d1c794ec+ other rev@49b6d8032493 ancestor rev@924404dff337
574 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
574 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
575 (branch merge, don't forget to commit)
575 (branch merge, don't forget to commit)
576 --------------
576 --------------
577 M b
577 M b
578 a
578 a
579 --------------
579 --------------
580
580
581 created new head
581 created new head
582 --------------
582 --------------
583 test L:um a b R:up a W: - 21 merge a and b to b
583 test L:um a b R:up a W: - 21 merge a and b to b
584 --------------
584 --------------
585 searching for copies back to rev 1
585 searching for copies back to rev 1
586 unmatched files in local:
586 unmatched files in local:
587 b
587 b
588 all copies found (* = to merge, ! = divergent):
588 all copies found (* = to merge, ! = divergent):
589 b -> a *
589 b -> a *
590 checking for directory renames
590 checking for directory renames
591 resolving manifests
591 resolving manifests
592 overwrite None partial False
592 overwrite None partial False
593 ancestor 924404dff337 local 62e7bf090eba+ remote f4db7e329e71
593 ancestor 924404dff337 local 62e7bf090eba+ remote f4db7e329e71
594 b: local copied/moved to a -> m
594 b: local copied/moved to a -> m
595 rev: versions differ -> m
595 rev: versions differ -> m
596 preserving b for resolve of b
596 preserving b for resolve of b
597 preserving rev for resolve of rev
597 preserving rev for resolve of rev
598 update: b 1/2 files (50.00%)
598 updating: b 1/2 files (50.00%)
599 picked tool 'python ../merge' for b (binary False symlink False)
599 picked tool 'python ../merge' for b (binary False symlink False)
600 merging b and a to b
600 merging b and a to b
601 my b@62e7bf090eba+ other a@f4db7e329e71 ancestor a@924404dff337
601 my b@62e7bf090eba+ other a@f4db7e329e71 ancestor a@924404dff337
602 update: rev 2/2 files (100.00%)
602 updating: rev 2/2 files (100.00%)
603 picked tool 'python ../merge' for rev (binary False symlink False)
603 picked tool 'python ../merge' for rev (binary False symlink False)
604 merging rev
604 merging rev
605 my rev@62e7bf090eba+ other rev@f4db7e329e71 ancestor rev@924404dff337
605 my rev@62e7bf090eba+ other rev@f4db7e329e71 ancestor rev@924404dff337
606 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
606 0 files updated, 2 files merged, 0 files removed, 0 files unresolved
607 (branch merge, don't forget to commit)
607 (branch merge, don't forget to commit)
608 --------------
608 --------------
609 M b
609 M b
610 a
610 a
611 --------------
611 --------------
612
612
613 created new head
613 created new head
614 --------------
614 --------------
615 test L:nm a b R:up a c W: - 23 get c, keep b
615 test L:nm a b R:up a c W: - 23 get c, keep b
616 --------------
616 --------------
617 searching for copies back to rev 1
617 searching for copies back to rev 1
618 unmatched files in local:
618 unmatched files in local:
619 b
619 b
620 unmatched files in other:
620 unmatched files in other:
621 c
621 c
622 all copies found (* = to merge, ! = divergent):
622 all copies found (* = to merge, ! = divergent):
623 b -> a *
623 b -> a *
624 checking for directory renames
624 checking for directory renames
625 resolving manifests
625 resolving manifests
626 overwrite None partial False
626 overwrite None partial False
627 ancestor 924404dff337 local 02963e448370+ remote 2b958612230f
627 ancestor 924404dff337 local 02963e448370+ remote 2b958612230f
628 b: local copied/moved to a -> m
628 b: local copied/moved to a -> m
629 rev: versions differ -> m
629 rev: versions differ -> m
630 c: remote created -> g
630 c: remote created -> g
631 preserving b for resolve of b
631 preserving b for resolve of b
632 preserving rev for resolve of rev
632 preserving rev for resolve of rev
633 update: b 1/3 files (33.33%)
633 updating: b 1/3 files (33.33%)
634 picked tool 'python ../merge' for b (binary False symlink False)
634 picked tool 'python ../merge' for b (binary False symlink False)
635 merging b and a to b
635 merging b and a to b
636 my b@02963e448370+ other a@2b958612230f ancestor a@924404dff337
636 my b@02963e448370+ other a@2b958612230f ancestor a@924404dff337
637 premerge successful
637 premerge successful
638 update: c 2/3 files (66.67%)
638 updating: c 2/3 files (66.67%)
639 getting c
639 getting c
640 update: rev 3/3 files (100.00%)
640 updating: rev 3/3 files (100.00%)
641 picked tool 'python ../merge' for rev (binary False symlink False)
641 picked tool 'python ../merge' for rev (binary False symlink False)
642 merging rev
642 merging rev
643 my rev@02963e448370+ other rev@2b958612230f ancestor rev@924404dff337
643 my rev@02963e448370+ other rev@2b958612230f ancestor rev@924404dff337
644 1 files updated, 2 files merged, 0 files removed, 0 files unresolved
644 1 files updated, 2 files merged, 0 files removed, 0 files unresolved
645 (branch merge, don't forget to commit)
645 (branch merge, don't forget to commit)
646 --------------
646 --------------
647 M b
647 M b
648 a
648 a
649 M c
649 M c
650 --------------
650 --------------
651
651
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now