##// END OF EJS Templates
move discovery methods from localrepo into new discovery module
Dirkjan Ochtman -
r11301:3d0591a6 default
parent child Browse files
Show More
@@ -1,377 +1,378
1 1 # ASCII graph log extension for Mercurial
2 2 #
3 3 # Copyright 2007 Joel Rosdahl <joel@rosdahl.net>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 '''command to view revision graphs from a shell
9 9
10 10 This extension adds a --graph option to the incoming, outgoing and log
11 11 commands. When this options is given, an ASCII representation of the
12 12 revision graph is also shown.
13 13 '''
14 14
15 15 import os
16 16 from mercurial.cmdutil import revrange, show_changeset
17 17 from mercurial.commands import templateopts
18 18 from mercurial.i18n import _
19 19 from mercurial.node import nullrev
20 20 from mercurial import bundlerepo, changegroup, cmdutil, commands, extensions
21 from mercurial import hg, url, util, graphmod
21 from mercurial import hg, url, util, graphmod, discovery
22 22
23 23 ASCIIDATA = 'ASC'
24 24
25 25 def asciiedges(seen, rev, parents):
26 26 """adds edge info to changelog DAG walk suitable for ascii()"""
27 27 if rev not in seen:
28 28 seen.append(rev)
29 29 nodeidx = seen.index(rev)
30 30
31 31 knownparents = []
32 32 newparents = []
33 33 for parent in parents:
34 34 if parent in seen:
35 35 knownparents.append(parent)
36 36 else:
37 37 newparents.append(parent)
38 38
39 39 ncols = len(seen)
40 40 seen[nodeidx:nodeidx + 1] = newparents
41 41 edges = [(nodeidx, seen.index(p)) for p in knownparents]
42 42
43 43 if len(newparents) > 0:
44 44 edges.append((nodeidx, nodeidx))
45 45 if len(newparents) > 1:
46 46 edges.append((nodeidx, nodeidx + 1))
47 47
48 48 nmorecols = len(seen) - ncols
49 49 return nodeidx, edges, ncols, nmorecols
50 50
51 51 def fix_long_right_edges(edges):
52 52 for (i, (start, end)) in enumerate(edges):
53 53 if end > start:
54 54 edges[i] = (start, end + 1)
55 55
56 56 def get_nodeline_edges_tail(
57 57 node_index, p_node_index, n_columns, n_columns_diff, p_diff, fix_tail):
58 58 if fix_tail and n_columns_diff == p_diff and n_columns_diff != 0:
59 59 # Still going in the same non-vertical direction.
60 60 if n_columns_diff == -1:
61 61 start = max(node_index + 1, p_node_index)
62 62 tail = ["|", " "] * (start - node_index - 1)
63 63 tail.extend(["/", " "] * (n_columns - start))
64 64 return tail
65 65 else:
66 66 return ["\\", " "] * (n_columns - node_index - 1)
67 67 else:
68 68 return ["|", " "] * (n_columns - node_index - 1)
69 69
70 70 def draw_edges(edges, nodeline, interline):
71 71 for (start, end) in edges:
72 72 if start == end + 1:
73 73 interline[2 * end + 1] = "/"
74 74 elif start == end - 1:
75 75 interline[2 * start + 1] = "\\"
76 76 elif start == end:
77 77 interline[2 * start] = "|"
78 78 else:
79 79 nodeline[2 * end] = "+"
80 80 if start > end:
81 81 (start, end) = (end, start)
82 82 for i in range(2 * start + 1, 2 * end):
83 83 if nodeline[i] != "+":
84 84 nodeline[i] = "-"
85 85
86 86 def get_padding_line(ni, n_columns, edges):
87 87 line = []
88 88 line.extend(["|", " "] * ni)
89 89 if (ni, ni - 1) in edges or (ni, ni) in edges:
90 90 # (ni, ni - 1) (ni, ni)
91 91 # | | | | | | | |
92 92 # +---o | | o---+
93 93 # | | c | | c | |
94 94 # | |/ / | |/ /
95 95 # | | | | | |
96 96 c = "|"
97 97 else:
98 98 c = " "
99 99 line.extend([c, " "])
100 100 line.extend(["|", " "] * (n_columns - ni - 1))
101 101 return line
102 102
103 103 def asciistate():
104 104 """returns the initial value for the "state" argument to ascii()"""
105 105 return [0, 0]
106 106
107 107 def ascii(ui, state, type, char, text, coldata):
108 108 """prints an ASCII graph of the DAG
109 109
110 110 takes the following arguments (one call per node in the graph):
111 111
112 112 - ui to write to
113 113 - Somewhere to keep the needed state in (init to asciistate())
114 114 - Column of the current node in the set of ongoing edges.
115 115 - Type indicator of node data == ASCIIDATA.
116 116 - Payload: (char, lines):
117 117 - Character to use as node's symbol.
118 118 - List of lines to display as the node's text.
119 119 - Edges; a list of (col, next_col) indicating the edges between
120 120 the current node and its parents.
121 121 - Number of columns (ongoing edges) in the current revision.
122 122 - The difference between the number of columns (ongoing edges)
123 123 in the next revision and the number of columns (ongoing edges)
124 124 in the current revision. That is: -1 means one column removed;
125 125 0 means no columns added or removed; 1 means one column added.
126 126 """
127 127
128 128 idx, edges, ncols, coldiff = coldata
129 129 assert -2 < coldiff < 2
130 130 if coldiff == -1:
131 131 # Transform
132 132 #
133 133 # | | | | | |
134 134 # o | | into o---+
135 135 # |X / |/ /
136 136 # | | | |
137 137 fix_long_right_edges(edges)
138 138
139 139 # add_padding_line says whether to rewrite
140 140 #
141 141 # | | | | | | | |
142 142 # | o---+ into | o---+
143 143 # | / / | | | # <--- padding line
144 144 # o | | | / /
145 145 # o | |
146 146 add_padding_line = (len(text) > 2 and coldiff == -1 and
147 147 [x for (x, y) in edges if x + 1 < y])
148 148
149 149 # fix_nodeline_tail says whether to rewrite
150 150 #
151 151 # | | o | | | | o | |
152 152 # | | |/ / | | |/ /
153 153 # | o | | into | o / / # <--- fixed nodeline tail
154 154 # | |/ / | |/ /
155 155 # o | | o | |
156 156 fix_nodeline_tail = len(text) <= 2 and not add_padding_line
157 157
158 158 # nodeline is the line containing the node character (typically o)
159 159 nodeline = ["|", " "] * idx
160 160 nodeline.extend([char, " "])
161 161
162 162 nodeline.extend(
163 163 get_nodeline_edges_tail(idx, state[1], ncols, coldiff,
164 164 state[0], fix_nodeline_tail))
165 165
166 166 # shift_interline is the line containing the non-vertical
167 167 # edges between this entry and the next
168 168 shift_interline = ["|", " "] * idx
169 169 if coldiff == -1:
170 170 n_spaces = 1
171 171 edge_ch = "/"
172 172 elif coldiff == 0:
173 173 n_spaces = 2
174 174 edge_ch = "|"
175 175 else:
176 176 n_spaces = 3
177 177 edge_ch = "\\"
178 178 shift_interline.extend(n_spaces * [" "])
179 179 shift_interline.extend([edge_ch, " "] * (ncols - idx - 1))
180 180
181 181 # draw edges from the current node to its parents
182 182 draw_edges(edges, nodeline, shift_interline)
183 183
184 184 # lines is the list of all graph lines to print
185 185 lines = [nodeline]
186 186 if add_padding_line:
187 187 lines.append(get_padding_line(idx, ncols, edges))
188 188 lines.append(shift_interline)
189 189
190 190 # make sure that there are as many graph lines as there are
191 191 # log strings
192 192 while len(text) < len(lines):
193 193 text.append("")
194 194 if len(lines) < len(text):
195 195 extra_interline = ["|", " "] * (ncols + coldiff)
196 196 while len(lines) < len(text):
197 197 lines.append(extra_interline)
198 198
199 199 # print lines
200 200 indentation_level = max(ncols, ncols + coldiff)
201 201 for (line, logstr) in zip(lines, text):
202 202 ln = "%-*s %s" % (2 * indentation_level, "".join(line), logstr)
203 203 ui.write(ln.rstrip() + '\n')
204 204
205 205 # ... and start over
206 206 state[0] = coldiff
207 207 state[1] = idx
208 208
209 209 def get_revs(repo, rev_opt):
210 210 if rev_opt:
211 211 revs = revrange(repo, rev_opt)
212 212 return (max(revs), min(revs))
213 213 else:
214 214 return (len(repo) - 1, 0)
215 215
216 216 def check_unsupported_flags(opts):
217 217 for op in ["follow", "follow_first", "date", "copies", "keyword", "remove",
218 218 "only_merges", "user", "only_branch", "prune", "newest_first",
219 219 "no_merges", "include", "exclude"]:
220 220 if op in opts and opts[op]:
221 221 raise util.Abort(_("--graph option is incompatible with --%s")
222 222 % op.replace("_", "-"))
223 223
224 224 def generate(ui, dag, displayer, showparents, edgefn):
225 225 seen, state = [], asciistate()
226 226 for rev, type, ctx, parents in dag:
227 227 char = ctx.node() in showparents and '@' or 'o'
228 228 displayer.show(ctx)
229 229 lines = displayer.hunk.pop(rev).split('\n')[:-1]
230 230 ascii(ui, state, type, char, lines, edgefn(seen, rev, parents))
231 231
232 232 def graphlog(ui, repo, path=None, **opts):
233 233 """show revision history alongside an ASCII revision graph
234 234
235 235 Print a revision history alongside a revision graph drawn with
236 236 ASCII characters.
237 237
238 238 Nodes printed as an @ character are parents of the working
239 239 directory.
240 240 """
241 241
242 242 check_unsupported_flags(opts)
243 243 limit = cmdutil.loglimit(opts)
244 244 start, stop = get_revs(repo, opts["rev"])
245 245 if start == nullrev:
246 246 return
247 247
248 248 if path:
249 249 path = util.canonpath(repo.root, os.getcwd(), path)
250 250 if path: # could be reset in canonpath
251 251 revdag = graphmod.filerevs(repo, path, start, stop, limit)
252 252 else:
253 253 if limit is not None:
254 254 stop = max(stop, start - limit + 1)
255 255 revdag = graphmod.revisions(repo, start, stop)
256 256
257 257 displayer = show_changeset(ui, repo, opts, buffered=True)
258 258 showparents = [ctx.node() for ctx in repo[None].parents()]
259 259 generate(ui, revdag, displayer, showparents, asciiedges)
260 260
261 261 def graphrevs(repo, nodes, opts):
262 262 limit = cmdutil.loglimit(opts)
263 263 nodes.reverse()
264 264 if limit is not None:
265 265 nodes = nodes[:limit]
266 266 return graphmod.nodes(repo, nodes)
267 267
268 268 def goutgoing(ui, repo, dest=None, **opts):
269 269 """show the outgoing changesets alongside an ASCII revision graph
270 270
271 271 Print the outgoing changesets alongside a revision graph drawn with
272 272 ASCII characters.
273 273
274 274 Nodes printed as an @ character are parents of the working
275 275 directory.
276 276 """
277 277
278 278 check_unsupported_flags(opts)
279 279 dest = ui.expandpath(dest or 'default-push', dest or 'default')
280 280 dest, branches = hg.parseurl(dest, opts.get('branch'))
281 281 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
282 282 other = hg.repository(hg.remoteui(ui, opts), dest)
283 283 if revs:
284 284 revs = [repo.lookup(rev) for rev in revs]
285 285 ui.status(_('comparing with %s\n') % url.hidepassword(dest))
286 o = repo.findoutgoing(other, force=opts.get('force'))
286 o = discovery.findoutgoing(repo, other, force=opts.get('force'))
287 287 if not o:
288 288 ui.status(_("no changes found\n"))
289 289 return
290 290
291 291 o = repo.changelog.nodesbetween(o, revs)[0]
292 292 revdag = graphrevs(repo, o, opts)
293 293 displayer = show_changeset(ui, repo, opts, buffered=True)
294 294 showparents = [ctx.node() for ctx in repo[None].parents()]
295 295 generate(ui, revdag, displayer, showparents, asciiedges)
296 296
297 297 def gincoming(ui, repo, source="default", **opts):
298 298 """show the incoming changesets alongside an ASCII revision graph
299 299
300 300 Print the incoming changesets alongside a revision graph drawn with
301 301 ASCII characters.
302 302
303 303 Nodes printed as an @ character are parents of the working
304 304 directory.
305 305 """
306 306
307 307 check_unsupported_flags(opts)
308 308 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
309 309 other = hg.repository(hg.remoteui(repo, opts), source)
310 310 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
311 311 ui.status(_('comparing with %s\n') % url.hidepassword(source))
312 312 if revs:
313 313 revs = [other.lookup(rev) for rev in revs]
314 incoming = repo.findincoming(other, heads=revs, force=opts["force"])
314 incoming = discovery.findincoming(repo, other, heads=revs,
315 force=opts["force"])
315 316 if not incoming:
316 317 try:
317 318 os.unlink(opts["bundle"])
318 319 except:
319 320 pass
320 321 ui.status(_("no changes found\n"))
321 322 return
322 323
323 324 cleanup = None
324 325 try:
325 326
326 327 fname = opts["bundle"]
327 328 if fname or not other.local():
328 329 # create a bundle (uncompressed if other repo is not local)
329 330 if revs is None:
330 331 cg = other.changegroup(incoming, "incoming")
331 332 else:
332 333 cg = other.changegroupsubset(incoming, revs, 'incoming')
333 334 bundletype = other.local() and "HG10BZ" or "HG10UN"
334 335 fname = cleanup = changegroup.writebundle(cg, fname, bundletype)
335 336 # keep written bundle?
336 337 if opts["bundle"]:
337 338 cleanup = None
338 339 if not other.local():
339 340 # use the created uncompressed bundlerepo
340 341 other = bundlerepo.bundlerepository(ui, repo.root, fname)
341 342
342 343 chlist = other.changelog.nodesbetween(incoming, revs)[0]
343 344 revdag = graphrevs(other, chlist, opts)
344 345 displayer = show_changeset(ui, other, opts, buffered=True)
345 346 showparents = [ctx.node() for ctx in repo[None].parents()]
346 347 generate(ui, revdag, displayer, showparents, asciiedges)
347 348
348 349 finally:
349 350 if hasattr(other, 'close'):
350 351 other.close()
351 352 if cleanup:
352 353 os.unlink(cleanup)
353 354
354 355 def uisetup(ui):
355 356 '''Initialize the extension.'''
356 357 _wrapcmd(ui, 'log', commands.table, graphlog)
357 358 _wrapcmd(ui, 'incoming', commands.table, gincoming)
358 359 _wrapcmd(ui, 'outgoing', commands.table, goutgoing)
359 360
360 361 def _wrapcmd(ui, cmd, table, wrapfn):
361 362 '''wrap the command'''
362 363 def graph(orig, *args, **kwargs):
363 364 if kwargs['graph']:
364 365 return wrapfn(*args, **kwargs)
365 366 return orig(*args, **kwargs)
366 367 entry = extensions.wrapcommand(table, cmd, graph)
367 368 entry[1].append(('G', 'graph', None, _("show the revision DAG")))
368 369
369 370 cmdtable = {
370 371 "glog":
371 372 (graphlog,
372 373 [('l', 'limit', '', _('limit number of changes displayed')),
373 374 ('p', 'patch', False, _('show patch')),
374 375 ('r', 'rev', [], _('show the specified revision or range')),
375 376 ] + templateopts,
376 377 _('hg glog [OPTION]... [FILE]')),
377 378 }
@@ -1,533 +1,533
1 1 # patchbomb.py - sending Mercurial changesets as patch emails
2 2 #
3 3 # Copyright 2005-2009 Matt Mackall <mpm@selenic.com> and others
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 '''command to send changesets as (a series of) patch emails
9 9
10 10 The series is started off with a "[PATCH 0 of N]" introduction, which
11 11 describes the series as a whole.
12 12
13 13 Each patch email has a Subject line of "[PATCH M of N] ...", using the
14 14 first line of the changeset description as the subject text. The
15 15 message contains two or three body parts:
16 16
17 17 - The changeset description.
18 18 - [Optional] The result of running diffstat on the patch.
19 19 - The patch itself, as generated by :hg:`export`.
20 20
21 21 Each message refers to the first in the series using the In-Reply-To
22 22 and References headers, so they will show up as a sequence in threaded
23 23 mail and news readers, and in mail archives.
24 24
25 25 With the -d/--diffstat option, you will be prompted for each changeset
26 26 with a diffstat summary and the changeset summary, so you can be sure
27 27 you are sending the right changes.
28 28
29 29 To configure other defaults, add a section like this to your hgrc
30 30 file::
31 31
32 32 [email]
33 33 from = My Name <my@email>
34 34 to = recipient1, recipient2, ...
35 35 cc = cc1, cc2, ...
36 36 bcc = bcc1, bcc2, ...
37 37 reply-to = address1, address2, ...
38 38
39 39 Use ``[patchbomb]`` as configuration section name if you need to
40 40 override global ``[email]`` address settings.
41 41
42 42 Then you can use the :hg:`email` command to mail a series of
43 43 changesets as a patchbomb.
44 44
45 45 To avoid sending patches prematurely, it is a good idea to first run
46 46 the :hg:`email` command with the "-n" option (test only). You will be
47 47 prompted for an email recipient address, a subject and an introductory
48 48 message describing the patches of your patchbomb. Then when all is
49 49 done, patchbomb messages are displayed. If the PAGER environment
50 50 variable is set, your pager will be fired up once for each patchbomb
51 51 message, so you can verify everything is alright.
52 52
53 53 The -m/--mbox option is also very useful. Instead of previewing each
54 54 patchbomb message in a pager or sending the messages directly, it will
55 55 create a UNIX mailbox file with the patch emails. This mailbox file
56 56 can be previewed with any mail user agent which supports UNIX mbox
57 57 files, e.g. with mutt::
58 58
59 59 % mutt -R -f mbox
60 60
61 61 When you are previewing the patchbomb messages, you can use ``formail``
62 62 (a utility that is commonly installed as part of the procmail
63 63 package), to send each message out::
64 64
65 65 % formail -s sendmail -bm -t < mbox
66 66
67 67 That should be all. Now your patchbomb is on its way out.
68 68
69 69 You can also either configure the method option in the email section
70 70 to be a sendmail compatible mailer or fill out the [smtp] section so
71 71 that the patchbomb extension can automatically send patchbombs
72 72 directly from the commandline. See the [email] and [smtp] sections in
73 73 hgrc(5) for details.
74 74 '''
75 75
76 76 import os, errno, socket, tempfile, cStringIO, time
77 77 import email.MIMEMultipart, email.MIMEBase
78 78 import email.Utils, email.Encoders, email.Generator
79 from mercurial import cmdutil, commands, hg, mail, patch, util
79 from mercurial import cmdutil, commands, hg, mail, patch, util, discovery
80 80 from mercurial.i18n import _
81 81 from mercurial.node import bin
82 82
83 83 def prompt(ui, prompt, default=None, rest=':'):
84 84 if not ui.interactive():
85 85 if default is not None:
86 86 return default
87 87 raise util.Abort(_("%s Please enter a valid value" % (prompt + rest)))
88 88 if default:
89 89 prompt += ' [%s]' % default
90 90 prompt += rest
91 91 while True:
92 92 r = ui.prompt(prompt, default=default)
93 93 if r:
94 94 return r
95 95 if default is not None:
96 96 return default
97 97 ui.warn(_('Please enter a valid value.\n'))
98 98
99 99 def cdiffstat(ui, summary, patchlines):
100 100 s = patch.diffstat(patchlines)
101 101 if summary:
102 102 ui.write(summary, '\n')
103 103 ui.write(s, '\n')
104 104 ans = prompt(ui, _('does the diffstat above look okay?'), 'y')
105 105 if not ans.lower().startswith('y'):
106 106 raise util.Abort(_('diffstat rejected'))
107 107 return s
108 108
109 109 def introneeded(opts, number):
110 110 '''is an introductory message required?'''
111 111 return number > 1 or opts.get('intro') or opts.get('desc')
112 112
113 113 def makepatch(ui, repo, patch, opts, _charsets, idx, total, patchname=None):
114 114
115 115 desc = []
116 116 node = None
117 117 body = ''
118 118
119 119 for line in patch:
120 120 if line.startswith('#'):
121 121 if line.startswith('# Node ID'):
122 122 node = line.split()[-1]
123 123 continue
124 124 if line.startswith('diff -r') or line.startswith('diff --git'):
125 125 break
126 126 desc.append(line)
127 127
128 128 if not patchname and not node:
129 129 raise ValueError
130 130
131 131 if opts.get('attach'):
132 132 body = ('\n'.join(desc[1:]).strip() or
133 133 'Patch subject is complete summary.')
134 134 body += '\n\n\n'
135 135
136 136 if opts.get('plain'):
137 137 while patch and patch[0].startswith('# '):
138 138 patch.pop(0)
139 139 if patch:
140 140 patch.pop(0)
141 141 while patch and not patch[0].strip():
142 142 patch.pop(0)
143 143
144 144 if opts.get('diffstat'):
145 145 body += cdiffstat(ui, '\n'.join(desc), patch) + '\n\n'
146 146
147 147 if opts.get('attach') or opts.get('inline'):
148 148 msg = email.MIMEMultipart.MIMEMultipart()
149 149 if body:
150 150 msg.attach(mail.mimeencode(ui, body, _charsets, opts.get('test')))
151 151 p = mail.mimetextpatch('\n'.join(patch), 'x-patch', opts.get('test'))
152 152 binnode = bin(node)
153 153 # if node is mq patch, it will have the patch file's name as a tag
154 154 if not patchname:
155 155 patchtags = [t for t in repo.nodetags(binnode)
156 156 if t.endswith('.patch') or t.endswith('.diff')]
157 157 if patchtags:
158 158 patchname = patchtags[0]
159 159 elif total > 1:
160 160 patchname = cmdutil.make_filename(repo, '%b-%n.patch',
161 161 binnode, seqno=idx, total=total)
162 162 else:
163 163 patchname = cmdutil.make_filename(repo, '%b.patch', binnode)
164 164 disposition = 'inline'
165 165 if opts.get('attach'):
166 166 disposition = 'attachment'
167 167 p['Content-Disposition'] = disposition + '; filename=' + patchname
168 168 msg.attach(p)
169 169 else:
170 170 body += '\n'.join(patch)
171 171 msg = mail.mimetextpatch(body, display=opts.get('test'))
172 172
173 173 flag = ' '.join(opts.get('flag'))
174 174 if flag:
175 175 flag = ' ' + flag
176 176
177 177 subj = desc[0].strip().rstrip('. ')
178 178 if not introneeded(opts, total):
179 179 subj = '[PATCH%s] %s' % (flag, opts.get('subject') or subj)
180 180 else:
181 181 tlen = len(str(total))
182 182 subj = '[PATCH %0*d of %d%s] %s' % (tlen, idx, total, flag, subj)
183 183 msg['Subject'] = mail.headencode(ui, subj, _charsets, opts.get('test'))
184 184 msg['X-Mercurial-Node'] = node
185 185 return msg, subj
186 186
187 187 def patchbomb(ui, repo, *revs, **opts):
188 188 '''send changesets by email
189 189
190 190 By default, diffs are sent in the format generated by
191 191 :hg:`export`, one per message. The series starts with a "[PATCH 0
192 192 of N]" introduction, which describes the series as a whole.
193 193
194 194 Each patch email has a Subject line of "[PATCH M of N] ...", using
195 195 the first line of the changeset description as the subject text.
196 196 The message contains two or three parts. First, the changeset
197 197 description. Next, (optionally) if the diffstat program is
198 198 installed and -d/--diffstat is used, the result of running
199 199 diffstat on the patch. Finally, the patch itself, as generated by
200 200 :hg:`export`.
201 201
202 202 By default the patch is included as text in the email body for
203 203 easy reviewing. Using the -a/--attach option will instead create
204 204 an attachment for the patch. With -i/--inline an inline attachment
205 205 will be created.
206 206
207 207 With -o/--outgoing, emails will be generated for patches not found
208 208 in the destination repository (or only those which are ancestors
209 209 of the specified revisions if any are provided)
210 210
211 211 With -b/--bundle, changesets are selected as for --outgoing, but a
212 212 single email containing a binary Mercurial bundle as an attachment
213 213 will be sent.
214 214
215 215 Examples::
216 216
217 217 hg email -r 3000 # send patch 3000 only
218 218 hg email -r 3000 -r 3001 # send patches 3000 and 3001
219 219 hg email -r 3000:3005 # send patches 3000 through 3005
220 220 hg email 3000 # send patch 3000 (deprecated)
221 221
222 222 hg email -o # send all patches not in default
223 223 hg email -o DEST # send all patches not in DEST
224 224 hg email -o -r 3000 # send all ancestors of 3000 not in default
225 225 hg email -o -r 3000 DEST # send all ancestors of 3000 not in DEST
226 226
227 227 hg email -b # send bundle of all patches not in default
228 228 hg email -b DEST # send bundle of all patches not in DEST
229 229 hg email -b -r 3000 # bundle of all ancestors of 3000 not in default
230 230 hg email -b -r 3000 DEST # bundle of all ancestors of 3000 not in DEST
231 231
232 232 Before using this command, you will need to enable email in your
233 233 hgrc. See the [email] section in hgrc(5) for details.
234 234 '''
235 235
236 236 _charsets = mail._charsets(ui)
237 237
238 238 def outgoing(dest, revs):
239 239 '''Return the revisions present locally but not in dest'''
240 240 dest = ui.expandpath(dest or 'default-push', dest or 'default')
241 241 dest, branches = hg.parseurl(dest)
242 242 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
243 243 if revs:
244 244 revs = [repo.lookup(rev) for rev in revs]
245 245 other = hg.repository(hg.remoteui(repo, opts), dest)
246 246 ui.status(_('comparing with %s\n') % dest)
247 o = repo.findoutgoing(other)
247 o = discovery.findoutgoing(repo, other)
248 248 if not o:
249 249 ui.status(_("no changes found\n"))
250 250 return []
251 251 o = repo.changelog.nodesbetween(o, revs)[0]
252 252 return [str(repo.changelog.rev(r)) for r in o]
253 253
254 254 def getpatches(revs):
255 255 for r in cmdutil.revrange(repo, revs):
256 256 output = cStringIO.StringIO()
257 257 cmdutil.export(repo, [r], fp=output,
258 258 opts=patch.diffopts(ui, opts))
259 259 yield output.getvalue().split('\n')
260 260
261 261 def getbundle(dest):
262 262 tmpdir = tempfile.mkdtemp(prefix='hg-email-bundle-')
263 263 tmpfn = os.path.join(tmpdir, 'bundle')
264 264 try:
265 265 commands.bundle(ui, repo, tmpfn, dest, **opts)
266 266 return open(tmpfn, 'rb').read()
267 267 finally:
268 268 try:
269 269 os.unlink(tmpfn)
270 270 except:
271 271 pass
272 272 os.rmdir(tmpdir)
273 273
274 274 if not (opts.get('test') or opts.get('mbox')):
275 275 # really sending
276 276 mail.validateconfig(ui)
277 277
278 278 if not (revs or opts.get('rev')
279 279 or opts.get('outgoing') or opts.get('bundle')
280 280 or opts.get('patches')):
281 281 raise util.Abort(_('specify at least one changeset with -r or -o'))
282 282
283 283 if opts.get('outgoing') and opts.get('bundle'):
284 284 raise util.Abort(_("--outgoing mode always on with --bundle;"
285 285 " do not re-specify --outgoing"))
286 286
287 287 if opts.get('outgoing') or opts.get('bundle'):
288 288 if len(revs) > 1:
289 289 raise util.Abort(_("too many destinations"))
290 290 dest = revs and revs[0] or None
291 291 revs = []
292 292
293 293 if opts.get('rev'):
294 294 if revs:
295 295 raise util.Abort(_('use only one form to specify the revision'))
296 296 revs = opts.get('rev')
297 297
298 298 if opts.get('outgoing'):
299 299 revs = outgoing(dest, opts.get('rev'))
300 300 if opts.get('bundle'):
301 301 opts['revs'] = revs
302 302
303 303 # start
304 304 if opts.get('date'):
305 305 start_time = util.parsedate(opts.get('date'))
306 306 else:
307 307 start_time = util.makedate()
308 308
309 309 def genmsgid(id):
310 310 return '<%s.%s@%s>' % (id[:20], int(start_time[0]), socket.getfqdn())
311 311
312 312 def getdescription(body, sender):
313 313 if opts.get('desc'):
314 314 body = open(opts.get('desc')).read()
315 315 else:
316 316 ui.write(_('\nWrite the introductory message for the '
317 317 'patch series.\n\n'))
318 318 body = ui.edit(body, sender)
319 319 return body
320 320
321 321 def getpatchmsgs(patches, patchnames=None):
322 322 jumbo = []
323 323 msgs = []
324 324
325 325 ui.write(_('This patch series consists of %d patches.\n\n')
326 326 % len(patches))
327 327
328 328 name = None
329 329 for i, p in enumerate(patches):
330 330 jumbo.extend(p)
331 331 if patchnames:
332 332 name = patchnames[i]
333 333 msg = makepatch(ui, repo, p, opts, _charsets, i + 1,
334 334 len(patches), name)
335 335 msgs.append(msg)
336 336
337 337 if introneeded(opts, len(patches)):
338 338 tlen = len(str(len(patches)))
339 339
340 340 flag = ' '.join(opts.get('flag'))
341 341 if flag:
342 342 subj = '[PATCH %0*d of %d %s]' % (tlen, 0, len(patches), flag)
343 343 else:
344 344 subj = '[PATCH %0*d of %d]' % (tlen, 0, len(patches))
345 345 subj += ' ' + (opts.get('subject') or
346 346 prompt(ui, 'Subject: ', rest=subj))
347 347
348 348 body = ''
349 349 if opts.get('diffstat'):
350 350 d = cdiffstat(ui, _('Final summary:\n'), jumbo)
351 351 if d:
352 352 body = '\n' + d
353 353
354 354 body = getdescription(body, sender)
355 355 msg = mail.mimeencode(ui, body, _charsets, opts.get('test'))
356 356 msg['Subject'] = mail.headencode(ui, subj, _charsets,
357 357 opts.get('test'))
358 358
359 359 msgs.insert(0, (msg, subj))
360 360 return msgs
361 361
362 362 def getbundlemsgs(bundle):
363 363 subj = (opts.get('subject')
364 364 or prompt(ui, 'Subject:', 'A bundle for your repository'))
365 365
366 366 body = getdescription('', sender)
367 367 msg = email.MIMEMultipart.MIMEMultipart()
368 368 if body:
369 369 msg.attach(mail.mimeencode(ui, body, _charsets, opts.get('test')))
370 370 datapart = email.MIMEBase.MIMEBase('application', 'x-mercurial-bundle')
371 371 datapart.set_payload(bundle)
372 372 bundlename = '%s.hg' % opts.get('bundlename', 'bundle')
373 373 datapart.add_header('Content-Disposition', 'attachment',
374 374 filename=bundlename)
375 375 email.Encoders.encode_base64(datapart)
376 376 msg.attach(datapart)
377 377 msg['Subject'] = mail.headencode(ui, subj, _charsets, opts.get('test'))
378 378 return [(msg, subj)]
379 379
380 380 sender = (opts.get('from') or ui.config('email', 'from') or
381 381 ui.config('patchbomb', 'from') or
382 382 prompt(ui, 'From', ui.username()))
383 383
384 384 # internal option used by pbranches
385 385 patches = opts.get('patches')
386 386 if patches:
387 387 msgs = getpatchmsgs(patches, opts.get('patchnames'))
388 388 elif opts.get('bundle'):
389 389 msgs = getbundlemsgs(getbundle(dest))
390 390 else:
391 391 msgs = getpatchmsgs(list(getpatches(revs)))
392 392
393 393 def getaddrs(opt, prpt=None, default=None):
394 394 addrs = opts.get(opt.replace('-', '_'))
395 395 if addrs:
396 396 return mail.addrlistencode(ui, addrs, _charsets,
397 397 opts.get('test'))
398 398
399 399 addrs = (ui.config('email', opt) or
400 400 ui.config('patchbomb', opt) or '')
401 401 if not addrs and prpt:
402 402 addrs = prompt(ui, prpt, default)
403 403
404 404 return mail.addrlistencode(ui, [addrs], _charsets, opts.get('test'))
405 405
406 406 to = getaddrs('to', 'To')
407 407 cc = getaddrs('cc', 'Cc', '')
408 408 bcc = getaddrs('bcc')
409 409 replyto = getaddrs('reply-to')
410 410
411 411 ui.write('\n')
412 412
413 413 parent = opts.get('in_reply_to') or None
414 414 # angle brackets may be omitted, they're not semantically part of the msg-id
415 415 if parent is not None:
416 416 if not parent.startswith('<'):
417 417 parent = '<' + parent
418 418 if not parent.endswith('>'):
419 419 parent += '>'
420 420
421 421 first = True
422 422
423 423 sender_addr = email.Utils.parseaddr(sender)[1]
424 424 sender = mail.addressencode(ui, sender, _charsets, opts.get('test'))
425 425 sendmail = None
426 426 for m, subj in msgs:
427 427 try:
428 428 m['Message-Id'] = genmsgid(m['X-Mercurial-Node'])
429 429 except TypeError:
430 430 m['Message-Id'] = genmsgid('patchbomb')
431 431 if parent:
432 432 m['In-Reply-To'] = parent
433 433 m['References'] = parent
434 434 if first:
435 435 parent = m['Message-Id']
436 436 first = False
437 437
438 438 m['User-Agent'] = 'Mercurial-patchbomb/%s' % util.version()
439 439 m['Date'] = email.Utils.formatdate(start_time[0], localtime=True)
440 440
441 441 start_time = (start_time[0] + 1, start_time[1])
442 442 m['From'] = sender
443 443 m['To'] = ', '.join(to)
444 444 if cc:
445 445 m['Cc'] = ', '.join(cc)
446 446 if bcc:
447 447 m['Bcc'] = ', '.join(bcc)
448 448 if replyto:
449 449 m['Reply-To'] = ', '.join(replyto)
450 450 if opts.get('test'):
451 451 ui.status(_('Displaying '), subj, ' ...\n')
452 452 ui.flush()
453 453 if 'PAGER' in os.environ and not ui.plain():
454 454 fp = util.popen(os.environ['PAGER'], 'w')
455 455 else:
456 456 fp = ui
457 457 generator = email.Generator.Generator(fp, mangle_from_=False)
458 458 try:
459 459 generator.flatten(m, 0)
460 460 fp.write('\n')
461 461 except IOError, inst:
462 462 if inst.errno != errno.EPIPE:
463 463 raise
464 464 if fp is not ui:
465 465 fp.close()
466 466 elif opts.get('mbox'):
467 467 ui.status(_('Writing '), subj, ' ...\n')
468 468 fp = open(opts.get('mbox'), 'In-Reply-To' in m and 'ab+' or 'wb+')
469 469 generator = email.Generator.Generator(fp, mangle_from_=True)
470 470 # Should be time.asctime(), but Windows prints 2-characters day
471 471 # of month instead of one. Make them print the same thing.
472 472 date = time.strftime('%a %b %d %H:%M:%S %Y',
473 473 time.localtime(start_time[0]))
474 474 fp.write('From %s %s\n' % (sender_addr, date))
475 475 generator.flatten(m, 0)
476 476 fp.write('\n\n')
477 477 fp.close()
478 478 else:
479 479 if not sendmail:
480 480 sendmail = mail.connect(ui)
481 481 ui.status(_('Sending '), subj, ' ...\n')
482 482 # Exim does not remove the Bcc field
483 483 del m['Bcc']
484 484 fp = cStringIO.StringIO()
485 485 generator = email.Generator.Generator(fp, mangle_from_=False)
486 486 generator.flatten(m, 0)
487 487 sendmail(sender, to + bcc + cc, fp.getvalue())
488 488
489 489 emailopts = [
490 490 ('a', 'attach', None, _('send patches as attachments')),
491 491 ('i', 'inline', None, _('send patches as inline attachments')),
492 492 ('', 'bcc', [], _('email addresses of blind carbon copy recipients')),
493 493 ('c', 'cc', [], _('email addresses of copy recipients')),
494 494 ('d', 'diffstat', None, _('add diffstat output to messages')),
495 495 ('', 'date', '', _('use the given date as the sending date')),
496 496 ('', 'desc', '', _('use the given file as the series description')),
497 497 ('f', 'from', '', _('email address of sender')),
498 498 ('n', 'test', None, _('print messages that would be sent')),
499 499 ('m', 'mbox', '',
500 500 _('write messages to mbox file instead of sending them')),
501 501 ('', 'reply-to', [], _('email addresses replies should be sent to')),
502 502 ('s', 'subject', '',
503 503 _('subject of first message (intro or single patch)')),
504 504 ('', 'in-reply-to', '',
505 505 _('message identifier to reply to')),
506 506 ('', 'flag', [], _('flags to add in subject prefixes')),
507 507 ('t', 'to', [], _('email addresses of recipients')),
508 508 ]
509 509
510 510
511 511 cmdtable = {
512 512 "email":
513 513 (patchbomb,
514 514 [('g', 'git', None, _('use git extended diff format')),
515 515 ('', 'plain', None, _('omit hg patch header')),
516 516 ('o', 'outgoing', None,
517 517 _('send changes not found in the target repository')),
518 518 ('b', 'bundle', None,
519 519 _('send changes not in target as a binary bundle')),
520 520 ('', 'bundlename', 'bundle',
521 521 _('name of the bundle attachment file')),
522 522 ('r', 'rev', [], _('a revision to send')),
523 523 ('', 'force', None,
524 524 _('run even when remote repository is unrelated '
525 525 '(with -b/--bundle)')),
526 526 ('', 'base', [],
527 527 _('a base changeset to specify instead of a destination '
528 528 '(with -b/--bundle)')),
529 529 ('', 'intro', None,
530 530 _('send an introduction email for a single patch')),
531 531 ] + emailopts + commands.remoteopts,
532 532 _('hg email [OPTION]... [DEST]...'))
533 533 }
@@ -1,605 +1,606
1 1 # Patch transplanting extension for Mercurial
2 2 #
3 3 # Copyright 2006, 2007 Brendan Cully <brendan@kublai.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 '''command to transplant changesets from another branch
9 9
10 10 This extension allows you to transplant patches from another branch.
11 11
12 12 Transplanted patches are recorded in .hg/transplant/transplants, as a
13 13 map from a changeset hash to its hash in the source repository.
14 14 '''
15 15
16 16 from mercurial.i18n import _
17 17 import os, tempfile
18 18 from mercurial import bundlerepo, changegroup, cmdutil, hg, merge, match
19 from mercurial import patch, revlog, util, error
19 from mercurial import patch, revlog, util, error, discovery
20 20
21 21 class transplantentry(object):
22 22 def __init__(self, lnode, rnode):
23 23 self.lnode = lnode
24 24 self.rnode = rnode
25 25
26 26 class transplants(object):
27 27 def __init__(self, path=None, transplantfile=None, opener=None):
28 28 self.path = path
29 29 self.transplantfile = transplantfile
30 30 self.opener = opener
31 31
32 32 if not opener:
33 33 self.opener = util.opener(self.path)
34 34 self.transplants = []
35 35 self.dirty = False
36 36 self.read()
37 37
38 38 def read(self):
39 39 abspath = os.path.join(self.path, self.transplantfile)
40 40 if self.transplantfile and os.path.exists(abspath):
41 41 for line in self.opener(self.transplantfile).read().splitlines():
42 42 lnode, rnode = map(revlog.bin, line.split(':'))
43 43 self.transplants.append(transplantentry(lnode, rnode))
44 44
45 45 def write(self):
46 46 if self.dirty and self.transplantfile:
47 47 if not os.path.isdir(self.path):
48 48 os.mkdir(self.path)
49 49 fp = self.opener(self.transplantfile, 'w')
50 50 for c in self.transplants:
51 51 l, r = map(revlog.hex, (c.lnode, c.rnode))
52 52 fp.write(l + ':' + r + '\n')
53 53 fp.close()
54 54 self.dirty = False
55 55
56 56 def get(self, rnode):
57 57 return [t for t in self.transplants if t.rnode == rnode]
58 58
59 59 def set(self, lnode, rnode):
60 60 self.transplants.append(transplantentry(lnode, rnode))
61 61 self.dirty = True
62 62
63 63 def remove(self, transplant):
64 64 del self.transplants[self.transplants.index(transplant)]
65 65 self.dirty = True
66 66
67 67 class transplanter(object):
68 68 def __init__(self, ui, repo):
69 69 self.ui = ui
70 70 self.path = repo.join('transplant')
71 71 self.opener = util.opener(self.path)
72 72 self.transplants = transplants(self.path, 'transplants',
73 73 opener=self.opener)
74 74
75 75 def applied(self, repo, node, parent):
76 76 '''returns True if a node is already an ancestor of parent
77 77 or has already been transplanted'''
78 78 if hasnode(repo, node):
79 79 if node in repo.changelog.reachable(parent, stop=node):
80 80 return True
81 81 for t in self.transplants.get(node):
82 82 # it might have been stripped
83 83 if not hasnode(repo, t.lnode):
84 84 self.transplants.remove(t)
85 85 return False
86 86 if t.lnode in repo.changelog.reachable(parent, stop=t.lnode):
87 87 return True
88 88 return False
89 89
90 90 def apply(self, repo, source, revmap, merges, opts={}):
91 91 '''apply the revisions in revmap one by one in revision order'''
92 92 revs = sorted(revmap)
93 93 p1, p2 = repo.dirstate.parents()
94 94 pulls = []
95 95 diffopts = patch.diffopts(self.ui, opts)
96 96 diffopts.git = True
97 97
98 98 lock = wlock = None
99 99 try:
100 100 wlock = repo.wlock()
101 101 lock = repo.lock()
102 102 for rev in revs:
103 103 node = revmap[rev]
104 104 revstr = '%s:%s' % (rev, revlog.short(node))
105 105
106 106 if self.applied(repo, node, p1):
107 107 self.ui.warn(_('skipping already applied revision %s\n') %
108 108 revstr)
109 109 continue
110 110
111 111 parents = source.changelog.parents(node)
112 112 if not opts.get('filter'):
113 113 # If the changeset parent is the same as the
114 114 # wdir's parent, just pull it.
115 115 if parents[0] == p1:
116 116 pulls.append(node)
117 117 p1 = node
118 118 continue
119 119 if pulls:
120 120 if source != repo:
121 121 repo.pull(source, heads=pulls)
122 122 merge.update(repo, pulls[-1], False, False, None)
123 123 p1, p2 = repo.dirstate.parents()
124 124 pulls = []
125 125
126 126 domerge = False
127 127 if node in merges:
128 128 # pulling all the merge revs at once would mean we
129 129 # couldn't transplant after the latest even if
130 130 # transplants before them fail.
131 131 domerge = True
132 132 if not hasnode(repo, node):
133 133 repo.pull(source, heads=[node])
134 134
135 135 if parents[1] != revlog.nullid:
136 136 self.ui.note(_('skipping merge changeset %s:%s\n')
137 137 % (rev, revlog.short(node)))
138 138 patchfile = None
139 139 else:
140 140 fd, patchfile = tempfile.mkstemp(prefix='hg-transplant-')
141 141 fp = os.fdopen(fd, 'w')
142 142 gen = patch.diff(source, parents[0], node, opts=diffopts)
143 143 for chunk in gen:
144 144 fp.write(chunk)
145 145 fp.close()
146 146
147 147 del revmap[rev]
148 148 if patchfile or domerge:
149 149 try:
150 150 n = self.applyone(repo, node,
151 151 source.changelog.read(node),
152 152 patchfile, merge=domerge,
153 153 log=opts.get('log'),
154 154 filter=opts.get('filter'))
155 155 if n and domerge:
156 156 self.ui.status(_('%s merged at %s\n') % (revstr,
157 157 revlog.short(n)))
158 158 elif n:
159 159 self.ui.status(_('%s transplanted to %s\n')
160 160 % (revlog.short(node),
161 161 revlog.short(n)))
162 162 finally:
163 163 if patchfile:
164 164 os.unlink(patchfile)
165 165 if pulls:
166 166 repo.pull(source, heads=pulls)
167 167 merge.update(repo, pulls[-1], False, False, None)
168 168 finally:
169 169 self.saveseries(revmap, merges)
170 170 self.transplants.write()
171 171 lock.release()
172 172 wlock.release()
173 173
174 174 def filter(self, filter, changelog, patchfile):
175 175 '''arbitrarily rewrite changeset before applying it'''
176 176
177 177 self.ui.status(_('filtering %s\n') % patchfile)
178 178 user, date, msg = (changelog[1], changelog[2], changelog[4])
179 179
180 180 fd, headerfile = tempfile.mkstemp(prefix='hg-transplant-')
181 181 fp = os.fdopen(fd, 'w')
182 182 fp.write("# HG changeset patch\n")
183 183 fp.write("# User %s\n" % user)
184 184 fp.write("# Date %d %d\n" % date)
185 185 fp.write(msg + '\n')
186 186 fp.close()
187 187
188 188 try:
189 189 util.system('%s %s %s' % (filter, util.shellquote(headerfile),
190 190 util.shellquote(patchfile)),
191 191 environ={'HGUSER': changelog[1]},
192 192 onerr=util.Abort, errprefix=_('filter failed'))
193 193 user, date, msg = self.parselog(file(headerfile))[1:4]
194 194 finally:
195 195 os.unlink(headerfile)
196 196
197 197 return (user, date, msg)
198 198
199 199 def applyone(self, repo, node, cl, patchfile, merge=False, log=False,
200 200 filter=None):
201 201 '''apply the patch in patchfile to the repository as a transplant'''
202 202 (manifest, user, (time, timezone), files, message) = cl[:5]
203 203 date = "%d %d" % (time, timezone)
204 204 extra = {'transplant_source': node}
205 205 if filter:
206 206 (user, date, message) = self.filter(filter, cl, patchfile)
207 207
208 208 if log:
209 209 # we don't translate messages inserted into commits
210 210 message += '\n(transplanted from %s)' % revlog.hex(node)
211 211
212 212 self.ui.status(_('applying %s\n') % revlog.short(node))
213 213 self.ui.note('%s %s\n%s\n' % (user, date, message))
214 214
215 215 if not patchfile and not merge:
216 216 raise util.Abort(_('can only omit patchfile if merging'))
217 217 if patchfile:
218 218 try:
219 219 files = {}
220 220 try:
221 221 patch.patch(patchfile, self.ui, cwd=repo.root,
222 222 files=files, eolmode=None)
223 223 if not files:
224 224 self.ui.warn(_('%s: empty changeset')
225 225 % revlog.hex(node))
226 226 return None
227 227 finally:
228 228 files = patch.updatedir(self.ui, repo, files)
229 229 except Exception, inst:
230 230 seriespath = os.path.join(self.path, 'series')
231 231 if os.path.exists(seriespath):
232 232 os.unlink(seriespath)
233 233 p1 = repo.dirstate.parents()[0]
234 234 p2 = node
235 235 self.log(user, date, message, p1, p2, merge=merge)
236 236 self.ui.write(str(inst) + '\n')
237 237 raise util.Abort(_('Fix up the merge and run '
238 238 'hg transplant --continue'))
239 239 else:
240 240 files = None
241 241 if merge:
242 242 p1, p2 = repo.dirstate.parents()
243 243 repo.dirstate.setparents(p1, node)
244 244 m = match.always(repo.root, '')
245 245 else:
246 246 m = match.exact(repo.root, '', files)
247 247
248 248 n = repo.commit(message, user, date, extra=extra, match=m)
249 249 if not merge:
250 250 self.transplants.set(n, node)
251 251
252 252 return n
253 253
254 254 def resume(self, repo, source, opts=None):
255 255 '''recover last transaction and apply remaining changesets'''
256 256 if os.path.exists(os.path.join(self.path, 'journal')):
257 257 n, node = self.recover(repo)
258 258 self.ui.status(_('%s transplanted as %s\n') % (revlog.short(node),
259 259 revlog.short(n)))
260 260 seriespath = os.path.join(self.path, 'series')
261 261 if not os.path.exists(seriespath):
262 262 self.transplants.write()
263 263 return
264 264 nodes, merges = self.readseries()
265 265 revmap = {}
266 266 for n in nodes:
267 267 revmap[source.changelog.rev(n)] = n
268 268 os.unlink(seriespath)
269 269
270 270 self.apply(repo, source, revmap, merges, opts)
271 271
272 272 def recover(self, repo):
273 273 '''commit working directory using journal metadata'''
274 274 node, user, date, message, parents = self.readlog()
275 275 merge = len(parents) == 2
276 276
277 277 if not user or not date or not message or not parents[0]:
278 278 raise util.Abort(_('transplant log file is corrupt'))
279 279
280 280 extra = {'transplant_source': node}
281 281 wlock = repo.wlock()
282 282 try:
283 283 p1, p2 = repo.dirstate.parents()
284 284 if p1 != parents[0]:
285 285 raise util.Abort(
286 286 _('working dir not at transplant parent %s') %
287 287 revlog.hex(parents[0]))
288 288 if merge:
289 289 repo.dirstate.setparents(p1, parents[1])
290 290 n = repo.commit(message, user, date, extra=extra)
291 291 if not n:
292 292 raise util.Abort(_('commit failed'))
293 293 if not merge:
294 294 self.transplants.set(n, node)
295 295 self.unlog()
296 296
297 297 return n, node
298 298 finally:
299 299 wlock.release()
300 300
301 301 def readseries(self):
302 302 nodes = []
303 303 merges = []
304 304 cur = nodes
305 305 for line in self.opener('series').read().splitlines():
306 306 if line.startswith('# Merges'):
307 307 cur = merges
308 308 continue
309 309 cur.append(revlog.bin(line))
310 310
311 311 return (nodes, merges)
312 312
313 313 def saveseries(self, revmap, merges):
314 314 if not revmap:
315 315 return
316 316
317 317 if not os.path.isdir(self.path):
318 318 os.mkdir(self.path)
319 319 series = self.opener('series', 'w')
320 320 for rev in sorted(revmap):
321 321 series.write(revlog.hex(revmap[rev]) + '\n')
322 322 if merges:
323 323 series.write('# Merges\n')
324 324 for m in merges:
325 325 series.write(revlog.hex(m) + '\n')
326 326 series.close()
327 327
328 328 def parselog(self, fp):
329 329 parents = []
330 330 message = []
331 331 node = revlog.nullid
332 332 inmsg = False
333 333 for line in fp.read().splitlines():
334 334 if inmsg:
335 335 message.append(line)
336 336 elif line.startswith('# User '):
337 337 user = line[7:]
338 338 elif line.startswith('# Date '):
339 339 date = line[7:]
340 340 elif line.startswith('# Node ID '):
341 341 node = revlog.bin(line[10:])
342 342 elif line.startswith('# Parent '):
343 343 parents.append(revlog.bin(line[9:]))
344 344 elif not line.startswith('#'):
345 345 inmsg = True
346 346 message.append(line)
347 347 return (node, user, date, '\n'.join(message), parents)
348 348
349 349 def log(self, user, date, message, p1, p2, merge=False):
350 350 '''journal changelog metadata for later recover'''
351 351
352 352 if not os.path.isdir(self.path):
353 353 os.mkdir(self.path)
354 354 fp = self.opener('journal', 'w')
355 355 fp.write('# User %s\n' % user)
356 356 fp.write('# Date %s\n' % date)
357 357 fp.write('# Node ID %s\n' % revlog.hex(p2))
358 358 fp.write('# Parent ' + revlog.hex(p1) + '\n')
359 359 if merge:
360 360 fp.write('# Parent ' + revlog.hex(p2) + '\n')
361 361 fp.write(message.rstrip() + '\n')
362 362 fp.close()
363 363
364 364 def readlog(self):
365 365 return self.parselog(self.opener('journal'))
366 366
367 367 def unlog(self):
368 368 '''remove changelog journal'''
369 369 absdst = os.path.join(self.path, 'journal')
370 370 if os.path.exists(absdst):
371 371 os.unlink(absdst)
372 372
373 373 def transplantfilter(self, repo, source, root):
374 374 def matchfn(node):
375 375 if self.applied(repo, node, root):
376 376 return False
377 377 if source.changelog.parents(node)[1] != revlog.nullid:
378 378 return False
379 379 extra = source.changelog.read(node)[5]
380 380 cnode = extra.get('transplant_source')
381 381 if cnode and self.applied(repo, cnode, root):
382 382 return False
383 383 return True
384 384
385 385 return matchfn
386 386
387 387 def hasnode(repo, node):
388 388 try:
389 389 return repo.changelog.rev(node) != None
390 390 except error.RevlogError:
391 391 return False
392 392
393 393 def browserevs(ui, repo, nodes, opts):
394 394 '''interactively transplant changesets'''
395 395 def browsehelp(ui):
396 396 ui.write(_('y: transplant this changeset\n'
397 397 'n: skip this changeset\n'
398 398 'm: merge at this changeset\n'
399 399 'p: show patch\n'
400 400 'c: commit selected changesets\n'
401 401 'q: cancel transplant\n'
402 402 '?: show this help\n'))
403 403
404 404 displayer = cmdutil.show_changeset(ui, repo, opts)
405 405 transplants = []
406 406 merges = []
407 407 for node in nodes:
408 408 displayer.show(repo[node])
409 409 action = None
410 410 while not action:
411 411 action = ui.prompt(_('apply changeset? [ynmpcq?]:'))
412 412 if action == '?':
413 413 browsehelp(ui)
414 414 action = None
415 415 elif action == 'p':
416 416 parent = repo.changelog.parents(node)[0]
417 417 for chunk in patch.diff(repo, parent, node):
418 418 ui.write(chunk)
419 419 action = None
420 420 elif action not in ('y', 'n', 'm', 'c', 'q'):
421 421 ui.write(_('no such option\n'))
422 422 action = None
423 423 if action == 'y':
424 424 transplants.append(node)
425 425 elif action == 'm':
426 426 merges.append(node)
427 427 elif action == 'c':
428 428 break
429 429 elif action == 'q':
430 430 transplants = ()
431 431 merges = ()
432 432 break
433 433 displayer.close()
434 434 return (transplants, merges)
435 435
436 436 def transplant(ui, repo, *revs, **opts):
437 437 '''transplant changesets from another branch
438 438
439 439 Selected changesets will be applied on top of the current working
440 440 directory with the log of the original changeset. If --log is
441 441 specified, log messages will have a comment appended of the form::
442 442
443 443 (transplanted from CHANGESETHASH)
444 444
445 445 You can rewrite the changelog message with the --filter option.
446 446 Its argument will be invoked with the current changelog message as
447 447 $1 and the patch as $2.
448 448
449 449 If --source/-s is specified, selects changesets from the named
450 450 repository. If --branch/-b is specified, selects changesets from
451 451 the branch holding the named revision, up to that revision. If
452 452 --all/-a is specified, all changesets on the branch will be
453 453 transplanted, otherwise you will be prompted to select the
454 454 changesets you want.
455 455
456 456 :hg:`transplant --branch REVISION --all` will rebase the selected
457 457 branch (up to the named revision) onto your current working
458 458 directory.
459 459
460 460 You can optionally mark selected transplanted changesets as merge
461 461 changesets. You will not be prompted to transplant any ancestors
462 462 of a merged transplant, and you can merge descendants of them
463 463 normally instead of transplanting them.
464 464
465 465 If no merges or revisions are provided, :hg:`transplant` will
466 466 start an interactive changeset browser.
467 467
468 468 If a changeset application fails, you can fix the merge by hand
469 469 and then resume where you left off by calling :hg:`transplant
470 470 --continue/-c`.
471 471 '''
472 472 def getremotechanges(repo, url):
473 473 sourcerepo = ui.expandpath(url)
474 474 source = hg.repository(ui, sourcerepo)
475 common, incoming, rheads = repo.findcommonincoming(source, force=True)
475 tmp = discovery.findcommonincoming(repo, source, force=True)
476 common, incoming, rheads = tmp
476 477 if not incoming:
477 478 return (source, None, None)
478 479
479 480 bundle = None
480 481 if not source.local():
481 482 if source.capable('changegroupsubset'):
482 483 cg = source.changegroupsubset(incoming, rheads, 'incoming')
483 484 else:
484 485 cg = source.changegroup(incoming, 'incoming')
485 486 bundle = changegroup.writebundle(cg, None, 'HG10UN')
486 487 source = bundlerepo.bundlerepository(ui, repo.root, bundle)
487 488
488 489 return (source, incoming, bundle)
489 490
490 491 def incwalk(repo, incoming, branches, match=util.always):
491 492 if not branches:
492 493 branches = None
493 494 for node in repo.changelog.nodesbetween(incoming, branches)[0]:
494 495 if match(node):
495 496 yield node
496 497
497 498 def transplantwalk(repo, root, branches, match=util.always):
498 499 if not branches:
499 500 branches = repo.heads()
500 501 ancestors = []
501 502 for branch in branches:
502 503 ancestors.append(repo.changelog.ancestor(root, branch))
503 504 for node in repo.changelog.nodesbetween(ancestors, branches)[0]:
504 505 if match(node):
505 506 yield node
506 507
507 508 def checkopts(opts, revs):
508 509 if opts.get('continue'):
509 510 if opts.get('branch') or opts.get('all') or opts.get('merge'):
510 511 raise util.Abort(_('--continue is incompatible with '
511 512 'branch, all or merge'))
512 513 return
513 514 if not (opts.get('source') or revs or
514 515 opts.get('merge') or opts.get('branch')):
515 516 raise util.Abort(_('no source URL, branch tag or revision '
516 517 'list provided'))
517 518 if opts.get('all'):
518 519 if not opts.get('branch'):
519 520 raise util.Abort(_('--all requires a branch revision'))
520 521 if revs:
521 522 raise util.Abort(_('--all is incompatible with a '
522 523 'revision list'))
523 524
524 525 checkopts(opts, revs)
525 526
526 527 if not opts.get('log'):
527 528 opts['log'] = ui.config('transplant', 'log')
528 529 if not opts.get('filter'):
529 530 opts['filter'] = ui.config('transplant', 'filter')
530 531
531 532 tp = transplanter(ui, repo)
532 533
533 534 p1, p2 = repo.dirstate.parents()
534 535 if len(repo) > 0 and p1 == revlog.nullid:
535 536 raise util.Abort(_('no revision checked out'))
536 537 if not opts.get('continue'):
537 538 if p2 != revlog.nullid:
538 539 raise util.Abort(_('outstanding uncommitted merges'))
539 540 m, a, r, d = repo.status()[:4]
540 541 if m or a or r or d:
541 542 raise util.Abort(_('outstanding local changes'))
542 543
543 544 bundle = None
544 545 source = opts.get('source')
545 546 if source:
546 547 (source, incoming, bundle) = getremotechanges(repo, source)
547 548 else:
548 549 source = repo
549 550
550 551 try:
551 552 if opts.get('continue'):
552 553 tp.resume(repo, source, opts)
553 554 return
554 555
555 556 tf = tp.transplantfilter(repo, source, p1)
556 557 if opts.get('prune'):
557 558 prune = [source.lookup(r)
558 559 for r in cmdutil.revrange(source, opts.get('prune'))]
559 560 matchfn = lambda x: tf(x) and x not in prune
560 561 else:
561 562 matchfn = tf
562 563 branches = map(source.lookup, opts.get('branch', ()))
563 564 merges = map(source.lookup, opts.get('merge', ()))
564 565 revmap = {}
565 566 if revs:
566 567 for r in cmdutil.revrange(source, revs):
567 568 revmap[int(r)] = source.lookup(r)
568 569 elif opts.get('all') or not merges:
569 570 if source != repo:
570 571 alltransplants = incwalk(source, incoming, branches,
571 572 match=matchfn)
572 573 else:
573 574 alltransplants = transplantwalk(source, p1, branches,
574 575 match=matchfn)
575 576 if opts.get('all'):
576 577 revs = alltransplants
577 578 else:
578 579 revs, newmerges = browserevs(ui, source, alltransplants, opts)
579 580 merges.extend(newmerges)
580 581 for r in revs:
581 582 revmap[source.changelog.rev(r)] = r
582 583 for r in merges:
583 584 revmap[source.changelog.rev(r)] = r
584 585
585 586 tp.apply(repo, source, revmap, merges, opts)
586 587 finally:
587 588 if bundle:
588 589 source.close()
589 590 os.unlink(bundle)
590 591
591 592 cmdtable = {
592 593 "transplant":
593 594 (transplant,
594 595 [('s', 'source', '', _('pull patches from REPOSITORY')),
595 596 ('b', 'branch', [], _('pull patches from branch BRANCH')),
596 597 ('a', 'all', None, _('pull all changesets up to BRANCH')),
597 598 ('p', 'prune', [], _('skip over REV')),
598 599 ('m', 'merge', [], _('merge at REV')),
599 600 ('', 'log', None, _('append transplant info to log message')),
600 601 ('c', 'continue', None, _('continue last transplant session '
601 602 'after repair')),
602 603 ('', 'filter', '', _('filter changesets through FILTER'))],
603 604 _('hg transplant [-s REPOSITORY] [-b BRANCH [-a]] [-p REV] '
604 605 '[-m REV] [REV]...'))
605 606 }
@@ -1,4098 +1,4100
1 1 # commands.py - command processing for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from node import hex, nullid, nullrev, short
9 9 from lock import release
10 10 from i18n import _, gettext
11 11 import os, re, sys, difflib, time, tempfile
12 12 import hg, util, revlog, bundlerepo, extensions, copies, error
13 import patch, help, mdiff, url, encoding, templatekw
13 import patch, help, mdiff, url, encoding, templatekw, discovery
14 14 import archival, changegroup, cmdutil, sshserver, hbisect, hgweb, hgweb.server
15 15 import merge as mergemod
16 16 import minirst, revset
17 17
18 18 # Commands start here, listed alphabetically
19 19
20 20 def add(ui, repo, *pats, **opts):
21 21 """add the specified files on the next commit
22 22
23 23 Schedule files to be version controlled and added to the
24 24 repository.
25 25
26 26 The files will be added to the repository at the next commit. To
27 27 undo an add before that, see :hg:`forget`.
28 28
29 29 If no names are given, add all files to the repository.
30 30
31 31 .. container:: verbose
32 32
33 33 An example showing how new (unknown) files are added
34 34 automatically by :hg:`add`::
35 35
36 36 $ ls
37 37 foo.c
38 38 $ hg status
39 39 ? foo.c
40 40 $ hg add
41 41 adding foo.c
42 42 $ hg status
43 43 A foo.c
44 44 """
45 45
46 46 bad = []
47 47 names = []
48 48 m = cmdutil.match(repo, pats, opts)
49 49 oldbad = m.bad
50 50 m.bad = lambda x, y: bad.append(x) or oldbad(x, y)
51 51
52 52 for f in repo.walk(m):
53 53 exact = m.exact(f)
54 54 if exact or f not in repo.dirstate:
55 55 names.append(f)
56 56 if ui.verbose or not exact:
57 57 ui.status(_('adding %s\n') % m.rel(f))
58 58 if not opts.get('dry_run'):
59 59 bad += [f for f in repo.add(names) if f in m.files()]
60 60 return bad and 1 or 0
61 61
62 62 def addremove(ui, repo, *pats, **opts):
63 63 """add all new files, delete all missing files
64 64
65 65 Add all new files and remove all missing files from the
66 66 repository.
67 67
68 68 New files are ignored if they match any of the patterns in
69 69 .hgignore. As with add, these changes take effect at the next
70 70 commit.
71 71
72 72 Use the -s/--similarity option to detect renamed files. With a
73 73 parameter greater than 0, this compares every removed file with
74 74 every added file and records those similar enough as renames. This
75 75 option takes a percentage between 0 (disabled) and 100 (files must
76 76 be identical) as its parameter. Detecting renamed files this way
77 77 can be expensive.
78 78
79 79 Returns 0 if all files are successfully added.
80 80 """
81 81 try:
82 82 sim = float(opts.get('similarity') or 0)
83 83 except ValueError:
84 84 raise util.Abort(_('similarity must be a number'))
85 85 if sim < 0 or sim > 100:
86 86 raise util.Abort(_('similarity must be between 0 and 100'))
87 87 return cmdutil.addremove(repo, pats, opts, similarity=sim / 100.0)
88 88
89 89 def annotate(ui, repo, *pats, **opts):
90 90 """show changeset information by line for each file
91 91
92 92 List changes in files, showing the revision id responsible for
93 93 each line
94 94
95 95 This command is useful for discovering when a change was made and
96 96 by whom.
97 97
98 98 Without the -a/--text option, annotate will avoid processing files
99 99 it detects as binary. With -a, annotate will annotate the file
100 100 anyway, although the results will probably be neither useful
101 101 nor desirable.
102 102
103 103 Returns 0 on success.
104 104 """
105 105 if opts.get('follow'):
106 106 # --follow is deprecated and now just an alias for -f/--file
107 107 # to mimic the behavior of Mercurial before version 1.5
108 108 opts['file'] = 1
109 109
110 110 datefunc = ui.quiet and util.shortdate or util.datestr
111 111 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
112 112
113 113 if not pats:
114 114 raise util.Abort(_('at least one filename or pattern is required'))
115 115
116 116 opmap = [('user', lambda x: ui.shortuser(x[0].user())),
117 117 ('number', lambda x: str(x[0].rev())),
118 118 ('changeset', lambda x: short(x[0].node())),
119 119 ('date', getdate),
120 120 ('file', lambda x: x[0].path()),
121 121 ]
122 122
123 123 if (not opts.get('user') and not opts.get('changeset')
124 124 and not opts.get('date') and not opts.get('file')):
125 125 opts['number'] = 1
126 126
127 127 linenumber = opts.get('line_number') is not None
128 128 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
129 129 raise util.Abort(_('at least one of -n/-c is required for -l'))
130 130
131 131 funcmap = [func for op, func in opmap if opts.get(op)]
132 132 if linenumber:
133 133 lastfunc = funcmap[-1]
134 134 funcmap[-1] = lambda x: "%s:%s" % (lastfunc(x), x[1])
135 135
136 136 ctx = repo[opts.get('rev')]
137 137 m = cmdutil.match(repo, pats, opts)
138 138 follow = not opts.get('no_follow')
139 139 for abs in ctx.walk(m):
140 140 fctx = ctx[abs]
141 141 if not opts.get('text') and util.binary(fctx.data()):
142 142 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
143 143 continue
144 144
145 145 lines = fctx.annotate(follow=follow, linenumber=linenumber)
146 146 pieces = []
147 147
148 148 for f in funcmap:
149 149 l = [f(n) for n, dummy in lines]
150 150 if l:
151 151 ml = max(map(len, l))
152 152 pieces.append(["%*s" % (ml, x) for x in l])
153 153
154 154 if pieces:
155 155 for p, l in zip(zip(*pieces), lines):
156 156 ui.write("%s: %s" % (" ".join(p), l[1]))
157 157
158 158 def archive(ui, repo, dest, **opts):
159 159 '''create an unversioned archive of a repository revision
160 160
161 161 By default, the revision used is the parent of the working
162 162 directory; use -r/--rev to specify a different revision.
163 163
164 164 The archive type is automatically detected based on file
165 165 extension (or override using -t/--type).
166 166
167 167 Valid types are:
168 168
169 169 :``files``: a directory full of files (default)
170 170 :``tar``: tar archive, uncompressed
171 171 :``tbz2``: tar archive, compressed using bzip2
172 172 :``tgz``: tar archive, compressed using gzip
173 173 :``uzip``: zip archive, uncompressed
174 174 :``zip``: zip archive, compressed using deflate
175 175
176 176 The exact name of the destination archive or directory is given
177 177 using a format string; see :hg:`help export` for details.
178 178
179 179 Each member added to an archive file has a directory prefix
180 180 prepended. Use -p/--prefix to specify a format string for the
181 181 prefix. The default is the basename of the archive, with suffixes
182 182 removed.
183 183
184 184 Returns 0 on success.
185 185 '''
186 186
187 187 ctx = repo[opts.get('rev')]
188 188 if not ctx:
189 189 raise util.Abort(_('no working directory: please specify a revision'))
190 190 node = ctx.node()
191 191 dest = cmdutil.make_filename(repo, dest, node)
192 192 if os.path.realpath(dest) == repo.root:
193 193 raise util.Abort(_('repository root cannot be destination'))
194 194
195 195 def guess_type():
196 196 exttypes = {
197 197 'tar': ['.tar'],
198 198 'tbz2': ['.tbz2', '.tar.bz2'],
199 199 'tgz': ['.tgz', '.tar.gz'],
200 200 'zip': ['.zip'],
201 201 }
202 202
203 203 for type, extensions in exttypes.items():
204 204 if util.any(dest.endswith(ext) for ext in extensions):
205 205 return type
206 206 return None
207 207
208 208 kind = opts.get('type') or guess_type() or 'files'
209 209 prefix = opts.get('prefix')
210 210
211 211 if dest == '-':
212 212 if kind == 'files':
213 213 raise util.Abort(_('cannot archive plain files to stdout'))
214 214 dest = sys.stdout
215 215 if not prefix:
216 216 prefix = os.path.basename(repo.root) + '-%h'
217 217
218 218 prefix = cmdutil.make_filename(repo, prefix, node)
219 219 matchfn = cmdutil.match(repo, [], opts)
220 220 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
221 221 matchfn, prefix)
222 222
223 223 def backout(ui, repo, node=None, rev=None, **opts):
224 224 '''reverse effect of earlier changeset
225 225
226 226 Commit the backed out changes as a new changeset. The new
227 227 changeset is a child of the backed out changeset.
228 228
229 229 If you backout a changeset other than the tip, a new head is
230 230 created. This head will be the new tip and you should merge this
231 231 backout changeset with another head.
232 232
233 233 The --merge option remembers the parent of the working directory
234 234 before starting the backout, then merges the new head with that
235 235 changeset afterwards. This saves you from doing the merge by hand.
236 236 The result of this merge is not committed, as with a normal merge.
237 237
238 238 See :hg:`help dates` for a list of formats valid for -d/--date.
239 239
240 240 Returns 0 on success.
241 241 '''
242 242 if rev and node:
243 243 raise util.Abort(_("please specify just one revision"))
244 244
245 245 if not rev:
246 246 rev = node
247 247
248 248 if not rev:
249 249 raise util.Abort(_("please specify a revision to backout"))
250 250
251 251 date = opts.get('date')
252 252 if date:
253 253 opts['date'] = util.parsedate(date)
254 254
255 255 cmdutil.bail_if_changed(repo)
256 256 node = repo.lookup(rev)
257 257
258 258 op1, op2 = repo.dirstate.parents()
259 259 a = repo.changelog.ancestor(op1, node)
260 260 if a != node:
261 261 raise util.Abort(_('cannot backout change on a different branch'))
262 262
263 263 p1, p2 = repo.changelog.parents(node)
264 264 if p1 == nullid:
265 265 raise util.Abort(_('cannot backout a change with no parents'))
266 266 if p2 != nullid:
267 267 if not opts.get('parent'):
268 268 raise util.Abort(_('cannot backout a merge changeset without '
269 269 '--parent'))
270 270 p = repo.lookup(opts['parent'])
271 271 if p not in (p1, p2):
272 272 raise util.Abort(_('%s is not a parent of %s') %
273 273 (short(p), short(node)))
274 274 parent = p
275 275 else:
276 276 if opts.get('parent'):
277 277 raise util.Abort(_('cannot use --parent on non-merge changeset'))
278 278 parent = p1
279 279
280 280 # the backout should appear on the same branch
281 281 branch = repo.dirstate.branch()
282 282 hg.clean(repo, node, show_stats=False)
283 283 repo.dirstate.setbranch(branch)
284 284 revert_opts = opts.copy()
285 285 revert_opts['date'] = None
286 286 revert_opts['all'] = True
287 287 revert_opts['rev'] = hex(parent)
288 288 revert_opts['no_backup'] = None
289 289 revert(ui, repo, **revert_opts)
290 290 commit_opts = opts.copy()
291 291 commit_opts['addremove'] = False
292 292 if not commit_opts['message'] and not commit_opts['logfile']:
293 293 # we don't translate commit messages
294 294 commit_opts['message'] = "Backed out changeset %s" % short(node)
295 295 commit_opts['force_editor'] = True
296 296 commit(ui, repo, **commit_opts)
297 297 def nice(node):
298 298 return '%d:%s' % (repo.changelog.rev(node), short(node))
299 299 ui.status(_('changeset %s backs out changeset %s\n') %
300 300 (nice(repo.changelog.tip()), nice(node)))
301 301 if op1 != node:
302 302 hg.clean(repo, op1, show_stats=False)
303 303 if opts.get('merge'):
304 304 ui.status(_('merging with changeset %s\n')
305 305 % nice(repo.changelog.tip()))
306 306 hg.merge(repo, hex(repo.changelog.tip()))
307 307 else:
308 308 ui.status(_('the backout changeset is a new head - '
309 309 'do not forget to merge\n'))
310 310 ui.status(_('(use "backout --merge" '
311 311 'if you want to auto-merge)\n'))
312 312
313 313 def bisect(ui, repo, rev=None, extra=None, command=None,
314 314 reset=None, good=None, bad=None, skip=None, noupdate=None):
315 315 """subdivision search of changesets
316 316
317 317 This command helps to find changesets which introduce problems. To
318 318 use, mark the earliest changeset you know exhibits the problem as
319 319 bad, then mark the latest changeset which is free from the problem
320 320 as good. Bisect will update your working directory to a revision
321 321 for testing (unless the -U/--noupdate option is specified). Once
322 322 you have performed tests, mark the working directory as good or
323 323 bad, and bisect will either update to another candidate changeset
324 324 or announce that it has found the bad revision.
325 325
326 326 As a shortcut, you can also use the revision argument to mark a
327 327 revision as good or bad without checking it out first.
328 328
329 329 If you supply a command, it will be used for automatic bisection.
330 330 Its exit status will be used to mark revisions as good or bad:
331 331 status 0 means good, 125 means to skip the revision, 127
332 332 (command not found) will abort the bisection, and any other
333 333 non-zero exit status means the revision is bad.
334 334
335 335 Returns 0 on success.
336 336 """
337 337 def print_result(nodes, good):
338 338 displayer = cmdutil.show_changeset(ui, repo, {})
339 339 if len(nodes) == 1:
340 340 # narrowed it down to a single revision
341 341 if good:
342 342 ui.write(_("The first good revision is:\n"))
343 343 else:
344 344 ui.write(_("The first bad revision is:\n"))
345 345 displayer.show(repo[nodes[0]])
346 346 else:
347 347 # multiple possible revisions
348 348 if good:
349 349 ui.write(_("Due to skipped revisions, the first "
350 350 "good revision could be any of:\n"))
351 351 else:
352 352 ui.write(_("Due to skipped revisions, the first "
353 353 "bad revision could be any of:\n"))
354 354 for n in nodes:
355 355 displayer.show(repo[n])
356 356 displayer.close()
357 357
358 358 def check_state(state, interactive=True):
359 359 if not state['good'] or not state['bad']:
360 360 if (good or bad or skip or reset) and interactive:
361 361 return
362 362 if not state['good']:
363 363 raise util.Abort(_('cannot bisect (no known good revisions)'))
364 364 else:
365 365 raise util.Abort(_('cannot bisect (no known bad revisions)'))
366 366 return True
367 367
368 368 # backward compatibility
369 369 if rev in "good bad reset init".split():
370 370 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
371 371 cmd, rev, extra = rev, extra, None
372 372 if cmd == "good":
373 373 good = True
374 374 elif cmd == "bad":
375 375 bad = True
376 376 else:
377 377 reset = True
378 378 elif extra or good + bad + skip + reset + bool(command) > 1:
379 379 raise util.Abort(_('incompatible arguments'))
380 380
381 381 if reset:
382 382 p = repo.join("bisect.state")
383 383 if os.path.exists(p):
384 384 os.unlink(p)
385 385 return
386 386
387 387 state = hbisect.load_state(repo)
388 388
389 389 if command:
390 390 changesets = 1
391 391 try:
392 392 while changesets:
393 393 # update state
394 394 status = util.system(command)
395 395 if status == 125:
396 396 transition = "skip"
397 397 elif status == 0:
398 398 transition = "good"
399 399 # status < 0 means process was killed
400 400 elif status == 127:
401 401 raise util.Abort(_("failed to execute %s") % command)
402 402 elif status < 0:
403 403 raise util.Abort(_("%s killed") % command)
404 404 else:
405 405 transition = "bad"
406 406 ctx = repo[rev or '.']
407 407 state[transition].append(ctx.node())
408 408 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
409 409 check_state(state, interactive=False)
410 410 # bisect
411 411 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
412 412 # update to next check
413 413 cmdutil.bail_if_changed(repo)
414 414 hg.clean(repo, nodes[0], show_stats=False)
415 415 finally:
416 416 hbisect.save_state(repo, state)
417 417 print_result(nodes, good)
418 418 return
419 419
420 420 # update state
421 421 node = repo.lookup(rev or '.')
422 422 if good or bad or skip:
423 423 if good:
424 424 state['good'].append(node)
425 425 elif bad:
426 426 state['bad'].append(node)
427 427 elif skip:
428 428 state['skip'].append(node)
429 429 hbisect.save_state(repo, state)
430 430
431 431 if not check_state(state):
432 432 return
433 433
434 434 # actually bisect
435 435 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
436 436 if changesets == 0:
437 437 print_result(nodes, good)
438 438 else:
439 439 assert len(nodes) == 1 # only a single node can be tested next
440 440 node = nodes[0]
441 441 # compute the approximate number of remaining tests
442 442 tests, size = 0, 2
443 443 while size <= changesets:
444 444 tests, size = tests + 1, size * 2
445 445 rev = repo.changelog.rev(node)
446 446 ui.write(_("Testing changeset %d:%s "
447 447 "(%d changesets remaining, ~%d tests)\n")
448 448 % (rev, short(node), changesets, tests))
449 449 if not noupdate:
450 450 cmdutil.bail_if_changed(repo)
451 451 return hg.clean(repo, node)
452 452
453 453 def branch(ui, repo, label=None, **opts):
454 454 """set or show the current branch name
455 455
456 456 With no argument, show the current branch name. With one argument,
457 457 set the working directory branch name (the branch will not exist
458 458 in the repository until the next commit). Standard practice
459 459 recommends that primary development take place on the 'default'
460 460 branch.
461 461
462 462 Unless -f/--force is specified, branch will not let you set a
463 463 branch name that already exists, even if it's inactive.
464 464
465 465 Use -C/--clean to reset the working directory branch to that of
466 466 the parent of the working directory, negating a previous branch
467 467 change.
468 468
469 469 Use the command :hg:`update` to switch to an existing branch. Use
470 470 :hg:`commit --close-branch` to mark this branch as closed.
471 471
472 472 Returns 0 on success.
473 473 """
474 474
475 475 if opts.get('clean'):
476 476 label = repo[None].parents()[0].branch()
477 477 repo.dirstate.setbranch(label)
478 478 ui.status(_('reset working directory to branch %s\n') % label)
479 479 elif label:
480 480 utflabel = encoding.fromlocal(label)
481 481 if not opts.get('force') and utflabel in repo.branchtags():
482 482 if label not in [p.branch() for p in repo.parents()]:
483 483 raise util.Abort(_('a branch of the same name already exists'
484 484 " (use 'hg update' to switch to it)"))
485 485 repo.dirstate.setbranch(utflabel)
486 486 ui.status(_('marked working directory as branch %s\n') % label)
487 487 else:
488 488 ui.write("%s\n" % encoding.tolocal(repo.dirstate.branch()))
489 489
490 490 def branches(ui, repo, active=False, closed=False):
491 491 """list repository named branches
492 492
493 493 List the repository's named branches, indicating which ones are
494 494 inactive. If -c/--closed is specified, also list branches which have
495 495 been marked closed (see :hg:`commit --close-branch`).
496 496
497 497 If -a/--active is specified, only show active branches. A branch
498 498 is considered active if it contains repository heads.
499 499
500 500 Use the command :hg:`update` to switch to an existing branch.
501 501
502 502 Returns 0.
503 503 """
504 504
505 505 hexfunc = ui.debugflag and hex or short
506 506 activebranches = [repo[n].branch() for n in repo.heads()]
507 507 def testactive(tag, node):
508 508 realhead = tag in activebranches
509 509 open = node in repo.branchheads(tag, closed=False)
510 510 return realhead and open
511 511 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
512 512 for tag, node in repo.branchtags().items()],
513 513 reverse=True)
514 514
515 515 for isactive, node, tag in branches:
516 516 if (not active) or isactive:
517 517 encodedtag = encoding.tolocal(tag)
518 518 if ui.quiet:
519 519 ui.write("%s\n" % encodedtag)
520 520 else:
521 521 hn = repo.lookup(node)
522 522 if isactive:
523 523 notice = ''
524 524 elif hn not in repo.branchheads(tag, closed=False):
525 525 if not closed:
526 526 continue
527 527 notice = _(' (closed)')
528 528 else:
529 529 notice = _(' (inactive)')
530 530 rev = str(node).rjust(31 - encoding.colwidth(encodedtag))
531 531 data = encodedtag, rev, hexfunc(hn), notice
532 532 ui.write("%s %s:%s%s\n" % data)
533 533
534 534 def bundle(ui, repo, fname, dest=None, **opts):
535 535 """create a changegroup file
536 536
537 537 Generate a compressed changegroup file collecting changesets not
538 538 known to be in another repository.
539 539
540 540 If you omit the destination repository, then hg assumes the
541 541 destination will have all the nodes you specify with --base
542 542 parameters. To create a bundle containing all changesets, use
543 543 -a/--all (or --base null).
544 544
545 545 You can change compression method with the -t/--type option.
546 546 The available compression methods are: none, bzip2, and
547 547 gzip (by default, bundles are compressed using bzip2).
548 548
549 549 The bundle file can then be transferred using conventional means
550 550 and applied to another repository with the unbundle or pull
551 551 command. This is useful when direct push and pull are not
552 552 available or when exporting an entire repository is undesirable.
553 553
554 554 Applying bundles preserves all changeset contents including
555 555 permissions, copy/rename information, and revision history.
556 556
557 557 Returns 0 on success, 1 if no changes found.
558 558 """
559 559 revs = opts.get('rev') or None
560 560 if revs:
561 561 revs = [repo.lookup(rev) for rev in revs]
562 562 if opts.get('all'):
563 563 base = ['null']
564 564 else:
565 565 base = opts.get('base')
566 566 if base:
567 567 if dest:
568 568 raise util.Abort(_("--base is incompatible with specifying "
569 569 "a destination"))
570 570 base = [repo.lookup(rev) for rev in base]
571 571 # create the right base
572 572 # XXX: nodesbetween / changegroup* should be "fixed" instead
573 573 o = []
574 574 has = set((nullid,))
575 575 for n in base:
576 576 has.update(repo.changelog.reachable(n))
577 577 if revs:
578 578 visit = list(revs)
579 579 has.difference_update(revs)
580 580 else:
581 581 visit = repo.changelog.heads()
582 582 seen = {}
583 583 while visit:
584 584 n = visit.pop(0)
585 585 parents = [p for p in repo.changelog.parents(n) if p not in has]
586 586 if len(parents) == 0:
587 587 if n not in has:
588 588 o.append(n)
589 589 else:
590 590 for p in parents:
591 591 if p not in seen:
592 592 seen[p] = 1
593 593 visit.append(p)
594 594 else:
595 595 dest = ui.expandpath(dest or 'default-push', dest or 'default')
596 596 dest, branches = hg.parseurl(dest, opts.get('branch'))
597 597 other = hg.repository(hg.remoteui(repo, opts), dest)
598 598 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
599 o = repo.findoutgoing(other, force=opts.get('force'))
599 o = discovery.findoutgoing(repo, other, force=opts.get('force'))
600 600
601 601 if not o:
602 602 ui.status(_("no changes found\n"))
603 603 return 1
604 604
605 605 if revs:
606 606 cg = repo.changegroupsubset(o, revs, 'bundle')
607 607 else:
608 608 cg = repo.changegroup(o, 'bundle')
609 609
610 610 bundletype = opts.get('type', 'bzip2').lower()
611 611 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
612 612 bundletype = btypes.get(bundletype)
613 613 if bundletype not in changegroup.bundletypes:
614 614 raise util.Abort(_('unknown bundle type specified with --type'))
615 615
616 616 changegroup.writebundle(cg, fname, bundletype)
617 617
618 618 def cat(ui, repo, file1, *pats, **opts):
619 619 """output the current or given revision of files
620 620
621 621 Print the specified files as they were at the given revision. If
622 622 no revision is given, the parent of the working directory is used,
623 623 or tip if no revision is checked out.
624 624
625 625 Output may be to a file, in which case the name of the file is
626 626 given using a format string. The formatting rules are the same as
627 627 for the export command, with the following additions:
628 628
629 629 :``%s``: basename of file being printed
630 630 :``%d``: dirname of file being printed, or '.' if in repository root
631 631 :``%p``: root-relative path name of file being printed
632 632
633 633 Returns 0 on success.
634 634 """
635 635 ctx = repo[opts.get('rev')]
636 636 err = 1
637 637 m = cmdutil.match(repo, (file1,) + pats, opts)
638 638 for abs in ctx.walk(m):
639 639 fp = cmdutil.make_file(repo, opts.get('output'), ctx.node(), pathname=abs)
640 640 data = ctx[abs].data()
641 641 if opts.get('decode'):
642 642 data = repo.wwritedata(abs, data)
643 643 fp.write(data)
644 644 err = 0
645 645 return err
646 646
647 647 def clone(ui, source, dest=None, **opts):
648 648 """make a copy of an existing repository
649 649
650 650 Create a copy of an existing repository in a new directory.
651 651
652 652 If no destination directory name is specified, it defaults to the
653 653 basename of the source.
654 654
655 655 The location of the source is added to the new repository's
656 656 .hg/hgrc file, as the default to be used for future pulls.
657 657
658 658 See :hg:`help urls` for valid source format details.
659 659
660 660 It is possible to specify an ``ssh://`` URL as the destination, but no
661 661 .hg/hgrc and working directory will be created on the remote side.
662 662 Please see :hg:`help urls` for important details about ``ssh://`` URLs.
663 663
664 664 A set of changesets (tags, or branch names) to pull may be specified
665 665 by listing each changeset (tag, or branch name) with -r/--rev.
666 666 If -r/--rev is used, the cloned repository will contain only a subset
667 667 of the changesets of the source repository. Only the set of changesets
668 668 defined by all -r/--rev options (including all their ancestors)
669 669 will be pulled into the destination repository.
670 670 No subsequent changesets (including subsequent tags) will be present
671 671 in the destination.
672 672
673 673 Using -r/--rev (or 'clone src#rev dest') implies --pull, even for
674 674 local source repositories.
675 675
676 676 For efficiency, hardlinks are used for cloning whenever the source
677 677 and destination are on the same filesystem (note this applies only
678 678 to the repository data, not to the working directory). Some
679 679 filesystems, such as AFS, implement hardlinking incorrectly, but
680 680 do not report errors. In these cases, use the --pull option to
681 681 avoid hardlinking.
682 682
683 683 In some cases, you can clone repositories and the working directory
684 684 using full hardlinks with ::
685 685
686 686 $ cp -al REPO REPOCLONE
687 687
688 688 This is the fastest way to clone, but it is not always safe. The
689 689 operation is not atomic (making sure REPO is not modified during
690 690 the operation is up to you) and you have to make sure your editor
691 691 breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
692 692 this is not compatible with certain extensions that place their
693 693 metadata under the .hg directory, such as mq.
694 694
695 695 Mercurial will update the working directory to the first applicable
696 696 revision from this list:
697 697
698 698 a) null if -U or the source repository has no changesets
699 699 b) if -u . and the source repository is local, the first parent of
700 700 the source repository's working directory
701 701 c) the changeset specified with -u (if a branch name, this means the
702 702 latest head of that branch)
703 703 d) the changeset specified with -r
704 704 e) the tipmost head specified with -b
705 705 f) the tipmost head specified with the url#branch source syntax
706 706 g) the tipmost head of the default branch
707 707 h) tip
708 708
709 709 Returns 0 on success.
710 710 """
711 711 if opts.get('noupdate') and opts.get('updaterev'):
712 712 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
713 713
714 714 r = hg.clone(hg.remoteui(ui, opts), source, dest,
715 715 pull=opts.get('pull'),
716 716 stream=opts.get('uncompressed'),
717 717 rev=opts.get('rev'),
718 718 update=opts.get('updaterev') or not opts.get('noupdate'),
719 719 branch=opts.get('branch'))
720 720
721 721 return r is None
722 722
723 723 def commit(ui, repo, *pats, **opts):
724 724 """commit the specified files or all outstanding changes
725 725
726 726 Commit changes to the given files into the repository. Unlike a
727 727 centralized RCS, this operation is a local operation. See
728 728 :hg:`push` for a way to actively distribute your changes.
729 729
730 730 If a list of files is omitted, all changes reported by :hg:`status`
731 731 will be committed.
732 732
733 733 If you are committing the result of a merge, do not provide any
734 734 filenames or -I/-X filters.
735 735
736 736 If no commit message is specified, the configured editor is
737 737 started to prompt you for a message.
738 738
739 739 See :hg:`help dates` for a list of formats valid for -d/--date.
740 740
741 741 Returns 0 on success, 1 if nothing changed.
742 742 """
743 743 extra = {}
744 744 if opts.get('close_branch'):
745 745 if repo['.'].node() not in repo.branchheads():
746 746 # The topo heads set is included in the branch heads set of the
747 747 # current branch, so it's sufficient to test branchheads
748 748 raise util.Abort(_('can only close branch heads'))
749 749 extra['close'] = 1
750 750 e = cmdutil.commiteditor
751 751 if opts.get('force_editor'):
752 752 e = cmdutil.commitforceeditor
753 753
754 754 def commitfunc(ui, repo, message, match, opts):
755 755 return repo.commit(message, opts.get('user'), opts.get('date'), match,
756 756 editor=e, extra=extra)
757 757
758 758 branch = repo[None].branch()
759 759 bheads = repo.branchheads(branch)
760 760
761 761 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
762 762 if not node:
763 763 ui.status(_("nothing changed\n"))
764 764 return 1
765 765
766 766 ctx = repo[node]
767 767 parents = ctx.parents()
768 768
769 769 if bheads and [x for x in parents
770 770 if x.node() not in bheads and x.branch() == branch]:
771 771 ui.status(_('created new head\n'))
772 772
773 773 if not opts.get('close_branch'):
774 774 for r in parents:
775 775 if r.extra().get('close'):
776 776 ui.status(_('reopening closed branch head %d\n') % r)
777 777
778 778 if ui.debugflag:
779 779 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
780 780 elif ui.verbose:
781 781 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
782 782
783 783 def copy(ui, repo, *pats, **opts):
784 784 """mark files as copied for the next commit
785 785
786 786 Mark dest as having copies of source files. If dest is a
787 787 directory, copies are put in that directory. If dest is a file,
788 788 the source must be a single file.
789 789
790 790 By default, this command copies the contents of files as they
791 791 exist in the working directory. If invoked with -A/--after, the
792 792 operation is recorded, but no copying is performed.
793 793
794 794 This command takes effect with the next commit. To undo a copy
795 795 before that, see :hg:`revert`.
796 796
797 797 Returns 0 on success, 1 if errors are encountered.
798 798 """
799 799 wlock = repo.wlock(False)
800 800 try:
801 801 return cmdutil.copy(ui, repo, pats, opts)
802 802 finally:
803 803 wlock.release()
804 804
805 805 def debugancestor(ui, repo, *args):
806 806 """find the ancestor revision of two revisions in a given index"""
807 807 if len(args) == 3:
808 808 index, rev1, rev2 = args
809 809 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index)
810 810 lookup = r.lookup
811 811 elif len(args) == 2:
812 812 if not repo:
813 813 raise util.Abort(_("There is no Mercurial repository here "
814 814 "(.hg not found)"))
815 815 rev1, rev2 = args
816 816 r = repo.changelog
817 817 lookup = repo.lookup
818 818 else:
819 819 raise util.Abort(_('either two or three arguments required'))
820 820 a = r.ancestor(lookup(rev1), lookup(rev2))
821 821 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
822 822
823 823 def debugcommands(ui, cmd='', *args):
824 824 """list all available commands and options"""
825 825 for cmd, vals in sorted(table.iteritems()):
826 826 cmd = cmd.split('|')[0].strip('^')
827 827 opts = ', '.join([i[1] for i in vals[1]])
828 828 ui.write('%s: %s\n' % (cmd, opts))
829 829
830 830 def debugcomplete(ui, cmd='', **opts):
831 831 """returns the completion list associated with the given command"""
832 832
833 833 if opts.get('options'):
834 834 options = []
835 835 otables = [globalopts]
836 836 if cmd:
837 837 aliases, entry = cmdutil.findcmd(cmd, table, False)
838 838 otables.append(entry[1])
839 839 for t in otables:
840 840 for o in t:
841 841 if "(DEPRECATED)" in o[3]:
842 842 continue
843 843 if o[0]:
844 844 options.append('-%s' % o[0])
845 845 options.append('--%s' % o[1])
846 846 ui.write("%s\n" % "\n".join(options))
847 847 return
848 848
849 849 cmdlist = cmdutil.findpossible(cmd, table)
850 850 if ui.verbose:
851 851 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
852 852 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
853 853
854 854 def debugfsinfo(ui, path = "."):
855 855 """show information detected about current filesystem"""
856 856 open('.debugfsinfo', 'w').write('')
857 857 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
858 858 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
859 859 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
860 860 and 'yes' or 'no'))
861 861 os.unlink('.debugfsinfo')
862 862
863 863 def debugrebuildstate(ui, repo, rev="tip"):
864 864 """rebuild the dirstate as it would look like for the given revision"""
865 865 ctx = repo[rev]
866 866 wlock = repo.wlock()
867 867 try:
868 868 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
869 869 finally:
870 870 wlock.release()
871 871
872 872 def debugcheckstate(ui, repo):
873 873 """validate the correctness of the current dirstate"""
874 874 parent1, parent2 = repo.dirstate.parents()
875 875 m1 = repo[parent1].manifest()
876 876 m2 = repo[parent2].manifest()
877 877 errors = 0
878 878 for f in repo.dirstate:
879 879 state = repo.dirstate[f]
880 880 if state in "nr" and f not in m1:
881 881 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
882 882 errors += 1
883 883 if state in "a" and f in m1:
884 884 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
885 885 errors += 1
886 886 if state in "m" and f not in m1 and f not in m2:
887 887 ui.warn(_("%s in state %s, but not in either manifest\n") %
888 888 (f, state))
889 889 errors += 1
890 890 for f in m1:
891 891 state = repo.dirstate[f]
892 892 if state not in "nrm":
893 893 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
894 894 errors += 1
895 895 if errors:
896 896 error = _(".hg/dirstate inconsistent with current parent's manifest")
897 897 raise util.Abort(error)
898 898
899 899 def showconfig(ui, repo, *values, **opts):
900 900 """show combined config settings from all hgrc files
901 901
902 902 With no arguments, print names and values of all config items.
903 903
904 904 With one argument of the form section.name, print just the value
905 905 of that config item.
906 906
907 907 With multiple arguments, print names and values of all config
908 908 items with matching section names.
909 909
910 910 With --debug, the source (filename and line number) is printed
911 911 for each config item.
912 912
913 913 Returns 0 on success.
914 914 """
915 915
916 916 for f in util.rcpath():
917 917 ui.debug(_('read config from: %s\n') % f)
918 918 untrusted = bool(opts.get('untrusted'))
919 919 if values:
920 920 if len([v for v in values if '.' in v]) > 1:
921 921 raise util.Abort(_('only one config item permitted'))
922 922 for section, name, value in ui.walkconfig(untrusted=untrusted):
923 923 sectname = section + '.' + name
924 924 if values:
925 925 for v in values:
926 926 if v == section:
927 927 ui.debug('%s: ' %
928 928 ui.configsource(section, name, untrusted))
929 929 ui.write('%s=%s\n' % (sectname, value))
930 930 elif v == sectname:
931 931 ui.debug('%s: ' %
932 932 ui.configsource(section, name, untrusted))
933 933 ui.write(value, '\n')
934 934 else:
935 935 ui.debug('%s: ' %
936 936 ui.configsource(section, name, untrusted))
937 937 ui.write('%s=%s\n' % (sectname, value))
938 938
939 939 def debugrevspec(ui, repo, expr):
940 940 '''parse and apply a revision specification'''
941 941 if ui.verbose:
942 942 tree = revset.parse(expr)
943 943 ui.note(tree, "\n")
944 944 func = revset.match(expr)
945 945 for c in func(repo, range(len(repo))):
946 946 ui.write("%s\n" % c)
947 947
948 948 def debugsetparents(ui, repo, rev1, rev2=None):
949 949 """manually set the parents of the current working directory
950 950
951 951 This is useful for writing repository conversion tools, but should
952 952 be used with care.
953 953
954 954 Returns 0 on success.
955 955 """
956 956
957 957 if not rev2:
958 958 rev2 = hex(nullid)
959 959
960 960 wlock = repo.wlock()
961 961 try:
962 962 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
963 963 finally:
964 964 wlock.release()
965 965
966 966 def debugstate(ui, repo, nodates=None):
967 967 """show the contents of the current dirstate"""
968 968 timestr = ""
969 969 showdate = not nodates
970 970 for file_, ent in sorted(repo.dirstate._map.iteritems()):
971 971 if showdate:
972 972 if ent[3] == -1:
973 973 # Pad or slice to locale representation
974 974 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
975 975 time.localtime(0)))
976 976 timestr = 'unset'
977 977 timestr = (timestr[:locale_len] +
978 978 ' ' * (locale_len - len(timestr)))
979 979 else:
980 980 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
981 981 time.localtime(ent[3]))
982 982 if ent[1] & 020000:
983 983 mode = 'lnk'
984 984 else:
985 985 mode = '%3o' % (ent[1] & 0777)
986 986 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
987 987 for f in repo.dirstate.copies():
988 988 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
989 989
990 990 def debugsub(ui, repo, rev=None):
991 991 if rev == '':
992 992 rev = None
993 993 for k, v in sorted(repo[rev].substate.items()):
994 994 ui.write('path %s\n' % k)
995 995 ui.write(' source %s\n' % v[0])
996 996 ui.write(' revision %s\n' % v[1])
997 997
998 998 def debugdata(ui, file_, rev):
999 999 """dump the contents of a data file revision"""
1000 1000 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_[:-2] + ".i")
1001 1001 try:
1002 1002 ui.write(r.revision(r.lookup(rev)))
1003 1003 except KeyError:
1004 1004 raise util.Abort(_('invalid revision identifier %s') % rev)
1005 1005
1006 1006 def debugdate(ui, date, range=None, **opts):
1007 1007 """parse and display a date"""
1008 1008 if opts["extended"]:
1009 1009 d = util.parsedate(date, util.extendeddateformats)
1010 1010 else:
1011 1011 d = util.parsedate(date)
1012 1012 ui.write("internal: %s %s\n" % d)
1013 1013 ui.write("standard: %s\n" % util.datestr(d))
1014 1014 if range:
1015 1015 m = util.matchdate(range)
1016 1016 ui.write("match: %s\n" % m(d[0]))
1017 1017
1018 1018 def debugindex(ui, file_):
1019 1019 """dump the contents of an index file"""
1020 1020 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
1021 1021 ui.write(" rev offset length base linkrev"
1022 1022 " nodeid p1 p2\n")
1023 1023 for i in r:
1024 1024 node = r.node(i)
1025 1025 try:
1026 1026 pp = r.parents(node)
1027 1027 except:
1028 1028 pp = [nullid, nullid]
1029 1029 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1030 1030 i, r.start(i), r.length(i), r.base(i), r.linkrev(i),
1031 1031 short(node), short(pp[0]), short(pp[1])))
1032 1032
1033 1033 def debugindexdot(ui, file_):
1034 1034 """dump an index DAG as a graphviz dot file"""
1035 1035 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
1036 1036 ui.write("digraph G {\n")
1037 1037 for i in r:
1038 1038 node = r.node(i)
1039 1039 pp = r.parents(node)
1040 1040 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1041 1041 if pp[1] != nullid:
1042 1042 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1043 1043 ui.write("}\n")
1044 1044
1045 1045 def debuginstall(ui):
1046 1046 '''test Mercurial installation
1047 1047
1048 1048 Returns 0 on success.
1049 1049 '''
1050 1050
1051 1051 def writetemp(contents):
1052 1052 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1053 1053 f = os.fdopen(fd, "wb")
1054 1054 f.write(contents)
1055 1055 f.close()
1056 1056 return name
1057 1057
1058 1058 problems = 0
1059 1059
1060 1060 # encoding
1061 1061 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1062 1062 try:
1063 1063 encoding.fromlocal("test")
1064 1064 except util.Abort, inst:
1065 1065 ui.write(" %s\n" % inst)
1066 1066 ui.write(_(" (check that your locale is properly set)\n"))
1067 1067 problems += 1
1068 1068
1069 1069 # compiled modules
1070 1070 ui.status(_("Checking extensions...\n"))
1071 1071 try:
1072 1072 import bdiff, mpatch, base85
1073 1073 except Exception, inst:
1074 1074 ui.write(" %s\n" % inst)
1075 1075 ui.write(_(" One or more extensions could not be found"))
1076 1076 ui.write(_(" (check that you compiled the extensions)\n"))
1077 1077 problems += 1
1078 1078
1079 1079 # templates
1080 1080 ui.status(_("Checking templates...\n"))
1081 1081 try:
1082 1082 import templater
1083 1083 templater.templater(templater.templatepath("map-cmdline.default"))
1084 1084 except Exception, inst:
1085 1085 ui.write(" %s\n" % inst)
1086 1086 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1087 1087 problems += 1
1088 1088
1089 1089 # patch
1090 1090 ui.status(_("Checking patch...\n"))
1091 1091 patchproblems = 0
1092 1092 a = "1\n2\n3\n4\n"
1093 1093 b = "1\n2\n3\ninsert\n4\n"
1094 1094 fa = writetemp(a)
1095 1095 d = mdiff.unidiff(a, None, b, None, os.path.basename(fa),
1096 1096 os.path.basename(fa))
1097 1097 fd = writetemp(d)
1098 1098
1099 1099 files = {}
1100 1100 try:
1101 1101 patch.patch(fd, ui, cwd=os.path.dirname(fa), files=files)
1102 1102 except util.Abort, e:
1103 1103 ui.write(_(" patch call failed:\n"))
1104 1104 ui.write(" " + str(e) + "\n")
1105 1105 patchproblems += 1
1106 1106 else:
1107 1107 if list(files) != [os.path.basename(fa)]:
1108 1108 ui.write(_(" unexpected patch output!\n"))
1109 1109 patchproblems += 1
1110 1110 a = open(fa).read()
1111 1111 if a != b:
1112 1112 ui.write(_(" patch test failed!\n"))
1113 1113 patchproblems += 1
1114 1114
1115 1115 if patchproblems:
1116 1116 if ui.config('ui', 'patch'):
1117 1117 ui.write(_(" (Current patch tool may be incompatible with patch,"
1118 1118 " or misconfigured. Please check your .hgrc file)\n"))
1119 1119 else:
1120 1120 ui.write(_(" Internal patcher failure, please report this error"
1121 1121 " to http://mercurial.selenic.com/bts/\n"))
1122 1122 problems += patchproblems
1123 1123
1124 1124 os.unlink(fa)
1125 1125 os.unlink(fd)
1126 1126
1127 1127 # editor
1128 1128 ui.status(_("Checking commit editor...\n"))
1129 1129 editor = ui.geteditor()
1130 1130 cmdpath = util.find_exe(editor) or util.find_exe(editor.split()[0])
1131 1131 if not cmdpath:
1132 1132 if editor == 'vi':
1133 1133 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1134 1134 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
1135 1135 else:
1136 1136 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1137 1137 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
1138 1138 problems += 1
1139 1139
1140 1140 # check username
1141 1141 ui.status(_("Checking username...\n"))
1142 1142 try:
1143 1143 user = ui.username()
1144 1144 except util.Abort, e:
1145 1145 ui.write(" %s\n" % e)
1146 1146 ui.write(_(" (specify a username in your .hgrc file)\n"))
1147 1147 problems += 1
1148 1148
1149 1149 if not problems:
1150 1150 ui.status(_("No problems detected\n"))
1151 1151 else:
1152 1152 ui.write(_("%s problems detected,"
1153 1153 " please check your install!\n") % problems)
1154 1154
1155 1155 return problems
1156 1156
1157 1157 def debugrename(ui, repo, file1, *pats, **opts):
1158 1158 """dump rename information"""
1159 1159
1160 1160 ctx = repo[opts.get('rev')]
1161 1161 m = cmdutil.match(repo, (file1,) + pats, opts)
1162 1162 for abs in ctx.walk(m):
1163 1163 fctx = ctx[abs]
1164 1164 o = fctx.filelog().renamed(fctx.filenode())
1165 1165 rel = m.rel(abs)
1166 1166 if o:
1167 1167 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1168 1168 else:
1169 1169 ui.write(_("%s not renamed\n") % rel)
1170 1170
1171 1171 def debugwalk(ui, repo, *pats, **opts):
1172 1172 """show how files match on given patterns"""
1173 1173 m = cmdutil.match(repo, pats, opts)
1174 1174 items = list(repo.walk(m))
1175 1175 if not items:
1176 1176 return
1177 1177 fmt = 'f %%-%ds %%-%ds %%s' % (
1178 1178 max([len(abs) for abs in items]),
1179 1179 max([len(m.rel(abs)) for abs in items]))
1180 1180 for abs in items:
1181 1181 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
1182 1182 ui.write("%s\n" % line.rstrip())
1183 1183
1184 1184 def diff(ui, repo, *pats, **opts):
1185 1185 """diff repository (or selected files)
1186 1186
1187 1187 Show differences between revisions for the specified files.
1188 1188
1189 1189 Differences between files are shown using the unified diff format.
1190 1190
1191 1191 NOTE: diff may generate unexpected results for merges, as it will
1192 1192 default to comparing against the working directory's first parent
1193 1193 changeset if no revisions are specified.
1194 1194
1195 1195 When two revision arguments are given, then changes are shown
1196 1196 between those revisions. If only one revision is specified then
1197 1197 that revision is compared to the working directory, and, when no
1198 1198 revisions are specified, the working directory files are compared
1199 1199 to its parent.
1200 1200
1201 1201 Alternatively you can specify -c/--change with a revision to see
1202 1202 the changes in that changeset relative to its first parent.
1203 1203
1204 1204 Without the -a/--text option, diff will avoid generating diffs of
1205 1205 files it detects as binary. With -a, diff will generate a diff
1206 1206 anyway, probably with undesirable results.
1207 1207
1208 1208 Use the -g/--git option to generate diffs in the git extended diff
1209 1209 format. For more information, read :hg:`help diffs`.
1210 1210
1211 1211 Returns 0 on success.
1212 1212 """
1213 1213
1214 1214 revs = opts.get('rev')
1215 1215 change = opts.get('change')
1216 1216 stat = opts.get('stat')
1217 1217 reverse = opts.get('reverse')
1218 1218
1219 1219 if revs and change:
1220 1220 msg = _('cannot specify --rev and --change at the same time')
1221 1221 raise util.Abort(msg)
1222 1222 elif change:
1223 1223 node2 = repo.lookup(change)
1224 1224 node1 = repo[node2].parents()[0].node()
1225 1225 else:
1226 1226 node1, node2 = cmdutil.revpair(repo, revs)
1227 1227
1228 1228 if reverse:
1229 1229 node1, node2 = node2, node1
1230 1230
1231 1231 diffopts = patch.diffopts(ui, opts)
1232 1232 m = cmdutil.match(repo, pats, opts)
1233 1233 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat)
1234 1234
1235 1235 def export(ui, repo, *changesets, **opts):
1236 1236 """dump the header and diffs for one or more changesets
1237 1237
1238 1238 Print the changeset header and diffs for one or more revisions.
1239 1239
1240 1240 The information shown in the changeset header is: author, date,
1241 1241 branch name (if non-default), changeset hash, parent(s) and commit
1242 1242 comment.
1243 1243
1244 1244 NOTE: export may generate unexpected diff output for merge
1245 1245 changesets, as it will compare the merge changeset against its
1246 1246 first parent only.
1247 1247
1248 1248 Output may be to a file, in which case the name of the file is
1249 1249 given using a format string. The formatting rules are as follows:
1250 1250
1251 1251 :``%%``: literal "%" character
1252 1252 :``%H``: changeset hash (40 bytes of hexadecimal)
1253 1253 :``%N``: number of patches being generated
1254 1254 :``%R``: changeset revision number
1255 1255 :``%b``: basename of the exporting repository
1256 1256 :``%h``: short-form changeset hash (12 bytes of hexadecimal)
1257 1257 :``%n``: zero-padded sequence number, starting at 1
1258 1258 :``%r``: zero-padded changeset revision number
1259 1259
1260 1260 Without the -a/--text option, export will avoid generating diffs
1261 1261 of files it detects as binary. With -a, export will generate a
1262 1262 diff anyway, probably with undesirable results.
1263 1263
1264 1264 Use the -g/--git option to generate diffs in the git extended diff
1265 1265 format. See :hg:`help diffs` for more information.
1266 1266
1267 1267 With the --switch-parent option, the diff will be against the
1268 1268 second parent. It can be useful to review a merge.
1269 1269
1270 1270 Returns 0 on success.
1271 1271 """
1272 1272 changesets += tuple(opts.get('rev', []))
1273 1273 if not changesets:
1274 1274 raise util.Abort(_("export requires at least one changeset"))
1275 1275 revs = cmdutil.revrange(repo, changesets)
1276 1276 if len(revs) > 1:
1277 1277 ui.note(_('exporting patches:\n'))
1278 1278 else:
1279 1279 ui.note(_('exporting patch:\n'))
1280 1280 cmdutil.export(repo, revs, template=opts.get('output'),
1281 1281 switch_parent=opts.get('switch_parent'),
1282 1282 opts=patch.diffopts(ui, opts))
1283 1283
1284 1284 def forget(ui, repo, *pats, **opts):
1285 1285 """forget the specified files on the next commit
1286 1286
1287 1287 Mark the specified files so they will no longer be tracked
1288 1288 after the next commit.
1289 1289
1290 1290 This only removes files from the current branch, not from the
1291 1291 entire project history, and it does not delete them from the
1292 1292 working directory.
1293 1293
1294 1294 To undo a forget before the next commit, see :hg:`add`.
1295 1295
1296 1296 Returns 0 on success.
1297 1297 """
1298 1298
1299 1299 if not pats:
1300 1300 raise util.Abort(_('no files specified'))
1301 1301
1302 1302 m = cmdutil.match(repo, pats, opts)
1303 1303 s = repo.status(match=m, clean=True)
1304 1304 forget = sorted(s[0] + s[1] + s[3] + s[6])
1305 1305 errs = 0
1306 1306
1307 1307 for f in m.files():
1308 1308 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
1309 1309 ui.warn(_('not removing %s: file is already untracked\n')
1310 1310 % m.rel(f))
1311 1311 errs = 1
1312 1312
1313 1313 for f in forget:
1314 1314 if ui.verbose or not m.exact(f):
1315 1315 ui.status(_('removing %s\n') % m.rel(f))
1316 1316
1317 1317 repo.remove(forget, unlink=False)
1318 1318 return errs
1319 1319
1320 1320 def grep(ui, repo, pattern, *pats, **opts):
1321 1321 """search for a pattern in specified files and revisions
1322 1322
1323 1323 Search revisions of files for a regular expression.
1324 1324
1325 1325 This command behaves differently than Unix grep. It only accepts
1326 1326 Python/Perl regexps. It searches repository history, not the
1327 1327 working directory. It always prints the revision number in which a
1328 1328 match appears.
1329 1329
1330 1330 By default, grep only prints output for the first revision of a
1331 1331 file in which it finds a match. To get it to print every revision
1332 1332 that contains a change in match status ("-" for a match that
1333 1333 becomes a non-match, or "+" for a non-match that becomes a match),
1334 1334 use the --all flag.
1335 1335
1336 1336 Returns 0 if a match is found, 1 otherwise.
1337 1337 """
1338 1338 reflags = 0
1339 1339 if opts.get('ignore_case'):
1340 1340 reflags |= re.I
1341 1341 try:
1342 1342 regexp = re.compile(pattern, reflags)
1343 1343 except Exception, inst:
1344 1344 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
1345 1345 return 1
1346 1346 sep, eol = ':', '\n'
1347 1347 if opts.get('print0'):
1348 1348 sep = eol = '\0'
1349 1349
1350 1350 getfile = util.lrucachefunc(repo.file)
1351 1351
1352 1352 def matchlines(body):
1353 1353 begin = 0
1354 1354 linenum = 0
1355 1355 while True:
1356 1356 match = regexp.search(body, begin)
1357 1357 if not match:
1358 1358 break
1359 1359 mstart, mend = match.span()
1360 1360 linenum += body.count('\n', begin, mstart) + 1
1361 1361 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1362 1362 begin = body.find('\n', mend) + 1 or len(body)
1363 1363 lend = begin - 1
1364 1364 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1365 1365
1366 1366 class linestate(object):
1367 1367 def __init__(self, line, linenum, colstart, colend):
1368 1368 self.line = line
1369 1369 self.linenum = linenum
1370 1370 self.colstart = colstart
1371 1371 self.colend = colend
1372 1372
1373 1373 def __hash__(self):
1374 1374 return hash((self.linenum, self.line))
1375 1375
1376 1376 def __eq__(self, other):
1377 1377 return self.line == other.line
1378 1378
1379 1379 matches = {}
1380 1380 copies = {}
1381 1381 def grepbody(fn, rev, body):
1382 1382 matches[rev].setdefault(fn, [])
1383 1383 m = matches[rev][fn]
1384 1384 for lnum, cstart, cend, line in matchlines(body):
1385 1385 s = linestate(line, lnum, cstart, cend)
1386 1386 m.append(s)
1387 1387
1388 1388 def difflinestates(a, b):
1389 1389 sm = difflib.SequenceMatcher(None, a, b)
1390 1390 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
1391 1391 if tag == 'insert':
1392 1392 for i in xrange(blo, bhi):
1393 1393 yield ('+', b[i])
1394 1394 elif tag == 'delete':
1395 1395 for i in xrange(alo, ahi):
1396 1396 yield ('-', a[i])
1397 1397 elif tag == 'replace':
1398 1398 for i in xrange(alo, ahi):
1399 1399 yield ('-', a[i])
1400 1400 for i in xrange(blo, bhi):
1401 1401 yield ('+', b[i])
1402 1402
1403 1403 def display(fn, ctx, pstates, states):
1404 1404 rev = ctx.rev()
1405 1405 datefunc = ui.quiet and util.shortdate or util.datestr
1406 1406 found = False
1407 1407 filerevmatches = {}
1408 1408 if opts.get('all'):
1409 1409 iter = difflinestates(pstates, states)
1410 1410 else:
1411 1411 iter = [('', l) for l in states]
1412 1412 for change, l in iter:
1413 1413 cols = [fn, str(rev)]
1414 1414 before, match, after = None, None, None
1415 1415 if opts.get('line_number'):
1416 1416 cols.append(str(l.linenum))
1417 1417 if opts.get('all'):
1418 1418 cols.append(change)
1419 1419 if opts.get('user'):
1420 1420 cols.append(ui.shortuser(ctx.user()))
1421 1421 if opts.get('date'):
1422 1422 cols.append(datefunc(ctx.date()))
1423 1423 if opts.get('files_with_matches'):
1424 1424 c = (fn, rev)
1425 1425 if c in filerevmatches:
1426 1426 continue
1427 1427 filerevmatches[c] = 1
1428 1428 else:
1429 1429 before = l.line[:l.colstart]
1430 1430 match = l.line[l.colstart:l.colend]
1431 1431 after = l.line[l.colend:]
1432 1432 ui.write(sep.join(cols))
1433 1433 if before is not None:
1434 1434 ui.write(sep + before)
1435 1435 ui.write(match, label='grep.match')
1436 1436 ui.write(after)
1437 1437 ui.write(eol)
1438 1438 found = True
1439 1439 return found
1440 1440
1441 1441 skip = {}
1442 1442 revfiles = {}
1443 1443 matchfn = cmdutil.match(repo, pats, opts)
1444 1444 found = False
1445 1445 follow = opts.get('follow')
1446 1446
1447 1447 def prep(ctx, fns):
1448 1448 rev = ctx.rev()
1449 1449 pctx = ctx.parents()[0]
1450 1450 parent = pctx.rev()
1451 1451 matches.setdefault(rev, {})
1452 1452 matches.setdefault(parent, {})
1453 1453 files = revfiles.setdefault(rev, [])
1454 1454 for fn in fns:
1455 1455 flog = getfile(fn)
1456 1456 try:
1457 1457 fnode = ctx.filenode(fn)
1458 1458 except error.LookupError:
1459 1459 continue
1460 1460
1461 1461 copied = flog.renamed(fnode)
1462 1462 copy = follow and copied and copied[0]
1463 1463 if copy:
1464 1464 copies.setdefault(rev, {})[fn] = copy
1465 1465 if fn in skip:
1466 1466 if copy:
1467 1467 skip[copy] = True
1468 1468 continue
1469 1469 files.append(fn)
1470 1470
1471 1471 if fn not in matches[rev]:
1472 1472 grepbody(fn, rev, flog.read(fnode))
1473 1473
1474 1474 pfn = copy or fn
1475 1475 if pfn not in matches[parent]:
1476 1476 try:
1477 1477 fnode = pctx.filenode(pfn)
1478 1478 grepbody(pfn, parent, flog.read(fnode))
1479 1479 except error.LookupError:
1480 1480 pass
1481 1481
1482 1482 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
1483 1483 rev = ctx.rev()
1484 1484 parent = ctx.parents()[0].rev()
1485 1485 for fn in sorted(revfiles.get(rev, [])):
1486 1486 states = matches[rev][fn]
1487 1487 copy = copies.get(rev, {}).get(fn)
1488 1488 if fn in skip:
1489 1489 if copy:
1490 1490 skip[copy] = True
1491 1491 continue
1492 1492 pstates = matches.get(parent, {}).get(copy or fn, [])
1493 1493 if pstates or states:
1494 1494 r = display(fn, ctx, pstates, states)
1495 1495 found = found or r
1496 1496 if r and not opts.get('all'):
1497 1497 skip[fn] = True
1498 1498 if copy:
1499 1499 skip[copy] = True
1500 1500 del matches[rev]
1501 1501 del revfiles[rev]
1502 1502
1503 1503 return not found
1504 1504
1505 1505 def heads(ui, repo, *branchrevs, **opts):
1506 1506 """show current repository heads or show branch heads
1507 1507
1508 1508 With no arguments, show all repository branch heads.
1509 1509
1510 1510 Repository "heads" are changesets with no child changesets. They are
1511 1511 where development generally takes place and are the usual targets
1512 1512 for update and merge operations. Branch heads are changesets that have
1513 1513 no child changeset on the same branch.
1514 1514
1515 1515 If one or more REVs are given, only branch heads on the branches
1516 1516 associated with the specified changesets are shown.
1517 1517
1518 1518 If -c/--closed is specified, also show branch heads marked closed
1519 1519 (see :hg:`commit --close-branch`).
1520 1520
1521 1521 If STARTREV is specified, only those heads that are descendants of
1522 1522 STARTREV will be displayed.
1523 1523
1524 1524 If -t/--topo is specified, named branch mechanics will be ignored and only
1525 1525 changesets without children will be shown.
1526 1526
1527 1527 Returns 0 if matching heads are found, 1 if not.
1528 1528 """
1529 1529
1530 1530 if opts.get('rev'):
1531 1531 start = repo.lookup(opts['rev'])
1532 1532 else:
1533 1533 start = None
1534 1534
1535 1535 if opts.get('topo'):
1536 1536 heads = [repo[h] for h in repo.heads(start)]
1537 1537 else:
1538 1538 heads = []
1539 1539 for b, ls in repo.branchmap().iteritems():
1540 1540 if start is None:
1541 1541 heads += [repo[h] for h in ls]
1542 1542 continue
1543 1543 startrev = repo.changelog.rev(start)
1544 1544 descendants = set(repo.changelog.descendants(startrev))
1545 1545 descendants.add(startrev)
1546 1546 rev = repo.changelog.rev
1547 1547 heads += [repo[h] for h in ls if rev(h) in descendants]
1548 1548
1549 1549 if branchrevs:
1550 1550 decode, encode = encoding.fromlocal, encoding.tolocal
1551 1551 branches = set(repo[decode(br)].branch() for br in branchrevs)
1552 1552 heads = [h for h in heads if h.branch() in branches]
1553 1553
1554 1554 if not opts.get('closed'):
1555 1555 heads = [h for h in heads if not h.extra().get('close')]
1556 1556
1557 1557 if opts.get('active') and branchrevs:
1558 1558 dagheads = repo.heads(start)
1559 1559 heads = [h for h in heads if h.node() in dagheads]
1560 1560
1561 1561 if branchrevs:
1562 1562 haveheads = set(h.branch() for h in heads)
1563 1563 if branches - haveheads:
1564 1564 headless = ', '.join(encode(b) for b in branches - haveheads)
1565 1565 msg = _('no open branch heads found on branches %s')
1566 1566 if opts.get('rev'):
1567 1567 msg += _(' (started at %s)' % opts['rev'])
1568 1568 ui.warn((msg + '\n') % headless)
1569 1569
1570 1570 if not heads:
1571 1571 return 1
1572 1572
1573 1573 heads = sorted(heads, key=lambda x: -x.rev())
1574 1574 displayer = cmdutil.show_changeset(ui, repo, opts)
1575 1575 for ctx in heads:
1576 1576 displayer.show(ctx)
1577 1577 displayer.close()
1578 1578
1579 1579 def help_(ui, name=None, with_version=False, unknowncmd=False):
1580 1580 """show help for a given topic or a help overview
1581 1581
1582 1582 With no arguments, print a list of commands with short help messages.
1583 1583
1584 1584 Given a topic, extension, or command name, print help for that
1585 1585 topic.
1586 1586
1587 1587 Returns 0 if successful.
1588 1588 """
1589 1589 option_lists = []
1590 1590 textwidth = util.termwidth() - 2
1591 1591
1592 1592 def addglobalopts(aliases):
1593 1593 if ui.verbose:
1594 1594 option_lists.append((_("global options:"), globalopts))
1595 1595 if name == 'shortlist':
1596 1596 option_lists.append((_('use "hg help" for the full list '
1597 1597 'of commands'), ()))
1598 1598 else:
1599 1599 if name == 'shortlist':
1600 1600 msg = _('use "hg help" for the full list of commands '
1601 1601 'or "hg -v" for details')
1602 1602 elif aliases:
1603 1603 msg = _('use "hg -v help%s" to show aliases and '
1604 1604 'global options') % (name and " " + name or "")
1605 1605 else:
1606 1606 msg = _('use "hg -v help %s" to show global options') % name
1607 1607 option_lists.append((msg, ()))
1608 1608
1609 1609 def helpcmd(name):
1610 1610 if with_version:
1611 1611 version_(ui)
1612 1612 ui.write('\n')
1613 1613
1614 1614 try:
1615 1615 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
1616 1616 except error.AmbiguousCommand, inst:
1617 1617 # py3k fix: except vars can't be used outside the scope of the
1618 1618 # except block, nor can be used inside a lambda. python issue4617
1619 1619 prefix = inst.args[0]
1620 1620 select = lambda c: c.lstrip('^').startswith(prefix)
1621 1621 helplist(_('list of commands:\n\n'), select)
1622 1622 return
1623 1623
1624 1624 # check if it's an invalid alias and display its error if it is
1625 1625 if getattr(entry[0], 'badalias', False):
1626 1626 if not unknowncmd:
1627 1627 entry[0](ui)
1628 1628 return
1629 1629
1630 1630 # synopsis
1631 1631 if len(entry) > 2:
1632 1632 if entry[2].startswith('hg'):
1633 1633 ui.write("%s\n" % entry[2])
1634 1634 else:
1635 1635 ui.write('hg %s %s\n' % (aliases[0], entry[2]))
1636 1636 else:
1637 1637 ui.write('hg %s\n' % aliases[0])
1638 1638
1639 1639 # aliases
1640 1640 if not ui.quiet and len(aliases) > 1:
1641 1641 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
1642 1642
1643 1643 # description
1644 1644 doc = gettext(entry[0].__doc__)
1645 1645 if not doc:
1646 1646 doc = _("(no help text available)")
1647 1647 if hasattr(entry[0], 'definition'): # aliased command
1648 1648 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
1649 1649 if ui.quiet:
1650 1650 doc = doc.splitlines()[0]
1651 1651 keep = ui.verbose and ['verbose'] or []
1652 1652 formatted, pruned = minirst.format(doc, textwidth, keep=keep)
1653 1653 ui.write("\n%s\n" % formatted)
1654 1654 if pruned:
1655 1655 ui.write(_('\nuse "hg -v help %s" to show verbose help\n') % name)
1656 1656
1657 1657 if not ui.quiet:
1658 1658 # options
1659 1659 if entry[1]:
1660 1660 option_lists.append((_("options:\n"), entry[1]))
1661 1661
1662 1662 addglobalopts(False)
1663 1663
1664 1664 def helplist(header, select=None):
1665 1665 h = {}
1666 1666 cmds = {}
1667 1667 for c, e in table.iteritems():
1668 1668 f = c.split("|", 1)[0]
1669 1669 if select and not select(f):
1670 1670 continue
1671 1671 if (not select and name != 'shortlist' and
1672 1672 e[0].__module__ != __name__):
1673 1673 continue
1674 1674 if name == "shortlist" and not f.startswith("^"):
1675 1675 continue
1676 1676 f = f.lstrip("^")
1677 1677 if not ui.debugflag and f.startswith("debug"):
1678 1678 continue
1679 1679 doc = e[0].__doc__
1680 1680 if doc and 'DEPRECATED' in doc and not ui.verbose:
1681 1681 continue
1682 1682 doc = gettext(doc)
1683 1683 if not doc:
1684 1684 doc = _("(no help text available)")
1685 1685 h[f] = doc.splitlines()[0].rstrip()
1686 1686 cmds[f] = c.lstrip("^")
1687 1687
1688 1688 if not h:
1689 1689 ui.status(_('no commands defined\n'))
1690 1690 return
1691 1691
1692 1692 ui.status(header)
1693 1693 fns = sorted(h)
1694 1694 m = max(map(len, fns))
1695 1695 for f in fns:
1696 1696 if ui.verbose:
1697 1697 commands = cmds[f].replace("|",", ")
1698 1698 ui.write(" %s:\n %s\n"%(commands, h[f]))
1699 1699 else:
1700 1700 ui.write('%s\n' % (util.wrap(h[f],
1701 1701 initindent=' %-*s ' % (m, f),
1702 1702 hangindent=' ' * (m + 4))))
1703 1703
1704 1704 if not ui.quiet:
1705 1705 addglobalopts(True)
1706 1706
1707 1707 def helptopic(name):
1708 1708 for names, header, doc in help.helptable:
1709 1709 if name in names:
1710 1710 break
1711 1711 else:
1712 1712 raise error.UnknownCommand(name)
1713 1713
1714 1714 # description
1715 1715 if not doc:
1716 1716 doc = _("(no help text available)")
1717 1717 if hasattr(doc, '__call__'):
1718 1718 doc = doc()
1719 1719
1720 1720 ui.write("%s\n\n" % header)
1721 1721 ui.write("%s\n" % minirst.format(doc, textwidth, indent=4))
1722 1722
1723 1723 def helpext(name):
1724 1724 try:
1725 1725 mod = extensions.find(name)
1726 1726 doc = gettext(mod.__doc__) or _('no help text available')
1727 1727 except KeyError:
1728 1728 mod = None
1729 1729 doc = extensions.disabledext(name)
1730 1730 if not doc:
1731 1731 raise error.UnknownCommand(name)
1732 1732
1733 1733 if '\n' not in doc:
1734 1734 head, tail = doc, ""
1735 1735 else:
1736 1736 head, tail = doc.split('\n', 1)
1737 1737 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
1738 1738 if tail:
1739 1739 ui.write(minirst.format(tail, textwidth))
1740 1740 ui.status('\n\n')
1741 1741
1742 1742 if mod:
1743 1743 try:
1744 1744 ct = mod.cmdtable
1745 1745 except AttributeError:
1746 1746 ct = {}
1747 1747 modcmds = set([c.split('|', 1)[0] for c in ct])
1748 1748 helplist(_('list of commands:\n\n'), modcmds.__contains__)
1749 1749 else:
1750 1750 ui.write(_('use "hg help extensions" for information on enabling '
1751 1751 'extensions\n'))
1752 1752
1753 1753 def helpextcmd(name):
1754 1754 cmd, ext, mod = extensions.disabledcmd(name, ui.config('ui', 'strict'))
1755 1755 doc = gettext(mod.__doc__).splitlines()[0]
1756 1756
1757 1757 msg = help.listexts(_("'%s' is provided by the following "
1758 1758 "extension:") % cmd, {ext: doc}, len(ext),
1759 1759 indent=4)
1760 1760 ui.write(minirst.format(msg, textwidth))
1761 1761 ui.write('\n\n')
1762 1762 ui.write(_('use "hg help extensions" for information on enabling '
1763 1763 'extensions\n'))
1764 1764
1765 1765 if name and name != 'shortlist':
1766 1766 i = None
1767 1767 if unknowncmd:
1768 1768 queries = (helpextcmd,)
1769 1769 else:
1770 1770 queries = (helptopic, helpcmd, helpext, helpextcmd)
1771 1771 for f in queries:
1772 1772 try:
1773 1773 f(name)
1774 1774 i = None
1775 1775 break
1776 1776 except error.UnknownCommand, inst:
1777 1777 i = inst
1778 1778 if i:
1779 1779 raise i
1780 1780
1781 1781 else:
1782 1782 # program name
1783 1783 if ui.verbose or with_version:
1784 1784 version_(ui)
1785 1785 else:
1786 1786 ui.status(_("Mercurial Distributed SCM\n"))
1787 1787 ui.status('\n')
1788 1788
1789 1789 # list of commands
1790 1790 if name == "shortlist":
1791 1791 header = _('basic commands:\n\n')
1792 1792 else:
1793 1793 header = _('list of commands:\n\n')
1794 1794
1795 1795 helplist(header)
1796 1796 if name != 'shortlist':
1797 1797 exts, maxlength = extensions.enabled()
1798 1798 text = help.listexts(_('enabled extensions:'), exts, maxlength)
1799 1799 if text:
1800 1800 ui.write("\n%s\n" % minirst.format(text, textwidth))
1801 1801
1802 1802 # list all option lists
1803 1803 opt_output = []
1804 1804 for title, options in option_lists:
1805 1805 opt_output.append(("\n%s" % title, None))
1806 1806 for shortopt, longopt, default, desc in options:
1807 1807 if _("DEPRECATED") in desc and not ui.verbose:
1808 1808 continue
1809 1809 opt_output.append(("%2s%s" % (shortopt and "-%s" % shortopt,
1810 1810 longopt and " --%s" % longopt),
1811 1811 "%s%s" % (desc,
1812 1812 default
1813 1813 and _(" (default: %s)") % default
1814 1814 or "")))
1815 1815
1816 1816 if not name:
1817 1817 ui.write(_("\nadditional help topics:\n\n"))
1818 1818 topics = []
1819 1819 for names, header, doc in help.helptable:
1820 1820 topics.append((sorted(names, key=len, reverse=True)[0], header))
1821 1821 topics_len = max([len(s[0]) for s in topics])
1822 1822 for t, desc in topics:
1823 1823 ui.write(" %-*s %s\n" % (topics_len, t, desc))
1824 1824
1825 1825 if opt_output:
1826 1826 opts_len = max([len(line[0]) for line in opt_output if line[1]] or [0])
1827 1827 for first, second in opt_output:
1828 1828 if second:
1829 1829 initindent = ' %-*s ' % (opts_len, first)
1830 1830 hangindent = ' ' * (opts_len + 3)
1831 1831 ui.write('%s\n' % (util.wrap(second,
1832 1832 initindent=initindent,
1833 1833 hangindent=hangindent)))
1834 1834 else:
1835 1835 ui.write("%s\n" % first)
1836 1836
1837 1837 def identify(ui, repo, source=None,
1838 1838 rev=None, num=None, id=None, branch=None, tags=None):
1839 1839 """identify the working copy or specified revision
1840 1840
1841 1841 With no revision, print a summary of the current state of the
1842 1842 repository.
1843 1843
1844 1844 Specifying a path to a repository root or Mercurial bundle will
1845 1845 cause lookup to operate on that repository/bundle.
1846 1846
1847 1847 This summary identifies the repository state using one or two
1848 1848 parent hash identifiers, followed by a "+" if there are
1849 1849 uncommitted changes in the working directory, a list of tags for
1850 1850 this revision and a branch name for non-default branches.
1851 1851
1852 1852 Returns 0 if successful.
1853 1853 """
1854 1854
1855 1855 if not repo and not source:
1856 1856 raise util.Abort(_("There is no Mercurial repository here "
1857 1857 "(.hg not found)"))
1858 1858
1859 1859 hexfunc = ui.debugflag and hex or short
1860 1860 default = not (num or id or branch or tags)
1861 1861 output = []
1862 1862
1863 1863 revs = []
1864 1864 if source:
1865 1865 source, branches = hg.parseurl(ui.expandpath(source))
1866 1866 repo = hg.repository(ui, source)
1867 1867 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
1868 1868
1869 1869 if not repo.local():
1870 1870 if not rev and revs:
1871 1871 rev = revs[0]
1872 1872 if not rev:
1873 1873 rev = "tip"
1874 1874 if num or branch or tags:
1875 1875 raise util.Abort(
1876 1876 "can't query remote revision number, branch, or tags")
1877 1877 output = [hexfunc(repo.lookup(rev))]
1878 1878 elif not rev:
1879 1879 ctx = repo[None]
1880 1880 parents = ctx.parents()
1881 1881 changed = False
1882 1882 if default or id or num:
1883 1883 changed = util.any(repo.status())
1884 1884 if default or id:
1885 1885 output = ["%s%s" % ('+'.join([hexfunc(p.node()) for p in parents]),
1886 1886 (changed) and "+" or "")]
1887 1887 if num:
1888 1888 output.append("%s%s" % ('+'.join([str(p.rev()) for p in parents]),
1889 1889 (changed) and "+" or ""))
1890 1890 else:
1891 1891 ctx = repo[rev]
1892 1892 if default or id:
1893 1893 output = [hexfunc(ctx.node())]
1894 1894 if num:
1895 1895 output.append(str(ctx.rev()))
1896 1896
1897 1897 if repo.local() and default and not ui.quiet:
1898 1898 b = encoding.tolocal(ctx.branch())
1899 1899 if b != 'default':
1900 1900 output.append("(%s)" % b)
1901 1901
1902 1902 # multiple tags for a single parent separated by '/'
1903 1903 t = "/".join(ctx.tags())
1904 1904 if t:
1905 1905 output.append(t)
1906 1906
1907 1907 if branch:
1908 1908 output.append(encoding.tolocal(ctx.branch()))
1909 1909
1910 1910 if tags:
1911 1911 output.extend(ctx.tags())
1912 1912
1913 1913 ui.write("%s\n" % ' '.join(output))
1914 1914
1915 1915 def import_(ui, repo, patch1, *patches, **opts):
1916 1916 """import an ordered set of patches
1917 1917
1918 1918 Import a list of patches and commit them individually (unless
1919 1919 --no-commit is specified).
1920 1920
1921 1921 If there are outstanding changes in the working directory, import
1922 1922 will abort unless given the -f/--force flag.
1923 1923
1924 1924 You can import a patch straight from a mail message. Even patches
1925 1925 as attachments work (to use the body part, it must have type
1926 1926 text/plain or text/x-patch). From and Subject headers of email
1927 1927 message are used as default committer and commit message. All
1928 1928 text/plain body parts before first diff are added to commit
1929 1929 message.
1930 1930
1931 1931 If the imported patch was generated by :hg:`export`, user and
1932 1932 description from patch override values from message headers and
1933 1933 body. Values given on command line with -m/--message and -u/--user
1934 1934 override these.
1935 1935
1936 1936 If --exact is specified, import will set the working directory to
1937 1937 the parent of each patch before applying it, and will abort if the
1938 1938 resulting changeset has a different ID than the one recorded in
1939 1939 the patch. This may happen due to character set problems or other
1940 1940 deficiencies in the text patch format.
1941 1941
1942 1942 With -s/--similarity, hg will attempt to discover renames and
1943 1943 copies in the patch in the same way as 'addremove'.
1944 1944
1945 1945 To read a patch from standard input, use "-" as the patch name. If
1946 1946 a URL is specified, the patch will be downloaded from it.
1947 1947 See :hg:`help dates` for a list of formats valid for -d/--date.
1948 1948
1949 1949 Returns 0 on success.
1950 1950 """
1951 1951 patches = (patch1,) + patches
1952 1952
1953 1953 date = opts.get('date')
1954 1954 if date:
1955 1955 opts['date'] = util.parsedate(date)
1956 1956
1957 1957 try:
1958 1958 sim = float(opts.get('similarity') or 0)
1959 1959 except ValueError:
1960 1960 raise util.Abort(_('similarity must be a number'))
1961 1961 if sim < 0 or sim > 100:
1962 1962 raise util.Abort(_('similarity must be between 0 and 100'))
1963 1963
1964 1964 if opts.get('exact') or not opts.get('force'):
1965 1965 cmdutil.bail_if_changed(repo)
1966 1966
1967 1967 d = opts["base"]
1968 1968 strip = opts["strip"]
1969 1969 wlock = lock = None
1970 1970
1971 1971 def tryone(ui, hunk):
1972 1972 tmpname, message, user, date, branch, nodeid, p1, p2 = \
1973 1973 patch.extract(ui, hunk)
1974 1974
1975 1975 if not tmpname:
1976 1976 return None
1977 1977 commitid = _('to working directory')
1978 1978
1979 1979 try:
1980 1980 cmdline_message = cmdutil.logmessage(opts)
1981 1981 if cmdline_message:
1982 1982 # pickup the cmdline msg
1983 1983 message = cmdline_message
1984 1984 elif message:
1985 1985 # pickup the patch msg
1986 1986 message = message.strip()
1987 1987 else:
1988 1988 # launch the editor
1989 1989 message = None
1990 1990 ui.debug('message:\n%s\n' % message)
1991 1991
1992 1992 wp = repo.parents()
1993 1993 if opts.get('exact'):
1994 1994 if not nodeid or not p1:
1995 1995 raise util.Abort(_('not a Mercurial patch'))
1996 1996 p1 = repo.lookup(p1)
1997 1997 p2 = repo.lookup(p2 or hex(nullid))
1998 1998
1999 1999 if p1 != wp[0].node():
2000 2000 hg.clean(repo, p1)
2001 2001 repo.dirstate.setparents(p1, p2)
2002 2002 elif p2:
2003 2003 try:
2004 2004 p1 = repo.lookup(p1)
2005 2005 p2 = repo.lookup(p2)
2006 2006 if p1 == wp[0].node():
2007 2007 repo.dirstate.setparents(p1, p2)
2008 2008 except error.RepoError:
2009 2009 pass
2010 2010 if opts.get('exact') or opts.get('import_branch'):
2011 2011 repo.dirstate.setbranch(branch or 'default')
2012 2012
2013 2013 files = {}
2014 2014 try:
2015 2015 patch.patch(tmpname, ui, strip=strip, cwd=repo.root,
2016 2016 files=files, eolmode=None)
2017 2017 finally:
2018 2018 files = patch.updatedir(ui, repo, files,
2019 2019 similarity=sim / 100.0)
2020 2020 if not opts.get('no_commit'):
2021 2021 if opts.get('exact'):
2022 2022 m = None
2023 2023 else:
2024 2024 m = cmdutil.matchfiles(repo, files or [])
2025 2025 n = repo.commit(message, opts.get('user') or user,
2026 2026 opts.get('date') or date, match=m,
2027 2027 editor=cmdutil.commiteditor)
2028 2028 if opts.get('exact'):
2029 2029 if hex(n) != nodeid:
2030 2030 repo.rollback()
2031 2031 raise util.Abort(_('patch is damaged'
2032 2032 ' or loses information'))
2033 2033 # Force a dirstate write so that the next transaction
2034 2034 # backups an up-do-date file.
2035 2035 repo.dirstate.write()
2036 2036 if n:
2037 2037 commitid = short(n)
2038 2038
2039 2039 return commitid
2040 2040 finally:
2041 2041 os.unlink(tmpname)
2042 2042
2043 2043 try:
2044 2044 wlock = repo.wlock()
2045 2045 lock = repo.lock()
2046 2046 lastcommit = None
2047 2047 for p in patches:
2048 2048 pf = os.path.join(d, p)
2049 2049
2050 2050 if pf == '-':
2051 2051 ui.status(_("applying patch from stdin\n"))
2052 2052 pf = sys.stdin
2053 2053 else:
2054 2054 ui.status(_("applying %s\n") % p)
2055 2055 pf = url.open(ui, pf)
2056 2056
2057 2057 haspatch = False
2058 2058 for hunk in patch.split(pf):
2059 2059 commitid = tryone(ui, hunk)
2060 2060 if commitid:
2061 2061 haspatch = True
2062 2062 if lastcommit:
2063 2063 ui.status(_('applied %s\n') % lastcommit)
2064 2064 lastcommit = commitid
2065 2065
2066 2066 if not haspatch:
2067 2067 raise util.Abort(_('no diffs found'))
2068 2068
2069 2069 finally:
2070 2070 release(lock, wlock)
2071 2071
2072 2072 def incoming(ui, repo, source="default", **opts):
2073 2073 """show new changesets found in source
2074 2074
2075 2075 Show new changesets found in the specified path/URL or the default
2076 2076 pull location. These are the changesets that would have been pulled
2077 2077 if a pull at the time you issued this command.
2078 2078
2079 2079 For remote repository, using --bundle avoids downloading the
2080 2080 changesets twice if the incoming is followed by a pull.
2081 2081
2082 2082 See pull for valid source format details.
2083 2083
2084 2084 Returns 0 if there are incoming changes, 1 otherwise.
2085 2085 """
2086 2086 limit = cmdutil.loglimit(opts)
2087 2087 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
2088 2088 other = hg.repository(hg.remoteui(repo, opts), source)
2089 2089 ui.status(_('comparing with %s\n') % url.hidepassword(source))
2090 2090 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
2091 2091 if revs:
2092 2092 revs = [other.lookup(rev) for rev in revs]
2093 common, incoming, rheads = repo.findcommonincoming(other, heads=revs,
2094 force=opts["force"])
2093
2094 tmp = discovery.findcommonincoming(repo, other, heads=revs,
2095 force=opts.get('force'))
2096 common, incoming, rheads = tmp
2095 2097 if not incoming:
2096 2098 try:
2097 2099 os.unlink(opts["bundle"])
2098 2100 except:
2099 2101 pass
2100 2102 ui.status(_("no changes found\n"))
2101 2103 return 1
2102 2104
2103 2105 cleanup = None
2104 2106 try:
2105 2107 fname = opts["bundle"]
2106 2108 if fname or not other.local():
2107 2109 # create a bundle (uncompressed if other repo is not local)
2108 2110
2109 2111 if revs is None and other.capable('changegroupsubset'):
2110 2112 revs = rheads
2111 2113
2112 2114 if revs is None:
2113 2115 cg = other.changegroup(incoming, "incoming")
2114 2116 else:
2115 2117 cg = other.changegroupsubset(incoming, revs, 'incoming')
2116 2118 bundletype = other.local() and "HG10BZ" or "HG10UN"
2117 2119 fname = cleanup = changegroup.writebundle(cg, fname, bundletype)
2118 2120 # keep written bundle?
2119 2121 if opts["bundle"]:
2120 2122 cleanup = None
2121 2123 if not other.local():
2122 2124 # use the created uncompressed bundlerepo
2123 2125 other = bundlerepo.bundlerepository(ui, repo.root, fname)
2124 2126
2125 2127 o = other.changelog.nodesbetween(incoming, revs)[0]
2126 2128 if opts.get('newest_first'):
2127 2129 o.reverse()
2128 2130 displayer = cmdutil.show_changeset(ui, other, opts)
2129 2131 count = 0
2130 2132 for n in o:
2131 2133 if limit is not None and count >= limit:
2132 2134 break
2133 2135 parents = [p for p in other.changelog.parents(n) if p != nullid]
2134 2136 if opts.get('no_merges') and len(parents) == 2:
2135 2137 continue
2136 2138 count += 1
2137 2139 displayer.show(other[n])
2138 2140 displayer.close()
2139 2141 finally:
2140 2142 if hasattr(other, 'close'):
2141 2143 other.close()
2142 2144 if cleanup:
2143 2145 os.unlink(cleanup)
2144 2146
2145 2147 def init(ui, dest=".", **opts):
2146 2148 """create a new repository in the given directory
2147 2149
2148 2150 Initialize a new repository in the given directory. If the given
2149 2151 directory does not exist, it will be created.
2150 2152
2151 2153 If no directory is given, the current directory is used.
2152 2154
2153 2155 It is possible to specify an ``ssh://`` URL as the destination.
2154 2156 See :hg:`help urls` for more information.
2155 2157
2156 2158 Returns 0 on success.
2157 2159 """
2158 2160 hg.repository(hg.remoteui(ui, opts), dest, create=1)
2159 2161
2160 2162 def locate(ui, repo, *pats, **opts):
2161 2163 """locate files matching specific patterns
2162 2164
2163 2165 Print files under Mercurial control in the working directory whose
2164 2166 names match the given patterns.
2165 2167
2166 2168 By default, this command searches all directories in the working
2167 2169 directory. To search just the current directory and its
2168 2170 subdirectories, use "--include .".
2169 2171
2170 2172 If no patterns are given to match, this command prints the names
2171 2173 of all files under Mercurial control in the working directory.
2172 2174
2173 2175 If you want to feed the output of this command into the "xargs"
2174 2176 command, use the -0 option to both this command and "xargs". This
2175 2177 will avoid the problem of "xargs" treating single filenames that
2176 2178 contain whitespace as multiple filenames.
2177 2179
2178 2180 Returns 0 if a match is found, 1 otherwise.
2179 2181 """
2180 2182 end = opts.get('print0') and '\0' or '\n'
2181 2183 rev = opts.get('rev') or None
2182 2184
2183 2185 ret = 1
2184 2186 m = cmdutil.match(repo, pats, opts, default='relglob')
2185 2187 m.bad = lambda x, y: False
2186 2188 for abs in repo[rev].walk(m):
2187 2189 if not rev and abs not in repo.dirstate:
2188 2190 continue
2189 2191 if opts.get('fullpath'):
2190 2192 ui.write(repo.wjoin(abs), end)
2191 2193 else:
2192 2194 ui.write(((pats and m.rel(abs)) or abs), end)
2193 2195 ret = 0
2194 2196
2195 2197 return ret
2196 2198
2197 2199 def log(ui, repo, *pats, **opts):
2198 2200 """show revision history of entire repository or files
2199 2201
2200 2202 Print the revision history of the specified files or the entire
2201 2203 project.
2202 2204
2203 2205 File history is shown without following rename or copy history of
2204 2206 files. Use -f/--follow with a filename to follow history across
2205 2207 renames and copies. --follow without a filename will only show
2206 2208 ancestors or descendants of the starting revision. --follow-first
2207 2209 only follows the first parent of merge revisions.
2208 2210
2209 2211 If no revision range is specified, the default is tip:0 unless
2210 2212 --follow is set, in which case the working directory parent is
2211 2213 used as the starting revision.
2212 2214
2213 2215 See :hg:`help dates` for a list of formats valid for -d/--date.
2214 2216
2215 2217 By default this command prints revision number and changeset id,
2216 2218 tags, non-trivial parents, user, date and time, and a summary for
2217 2219 each commit. When the -v/--verbose switch is used, the list of
2218 2220 changed files and full commit message are shown.
2219 2221
2220 2222 NOTE: log -p/--patch may generate unexpected diff output for merge
2221 2223 changesets, as it will only compare the merge changeset against
2222 2224 its first parent. Also, only files different from BOTH parents
2223 2225 will appear in files:.
2224 2226
2225 2227 Returns 0 on success.
2226 2228 """
2227 2229
2228 2230 matchfn = cmdutil.match(repo, pats, opts)
2229 2231 limit = cmdutil.loglimit(opts)
2230 2232 count = 0
2231 2233
2232 2234 endrev = None
2233 2235 if opts.get('copies') and opts.get('rev'):
2234 2236 endrev = max(cmdutil.revrange(repo, opts.get('rev'))) + 1
2235 2237
2236 2238 df = False
2237 2239 if opts["date"]:
2238 2240 df = util.matchdate(opts["date"])
2239 2241
2240 2242 branches = opts.get('branch', []) + opts.get('only_branch', [])
2241 2243 opts['branch'] = [repo.lookupbranch(b) for b in branches]
2242 2244
2243 2245 displayer = cmdutil.show_changeset(ui, repo, opts, True, matchfn)
2244 2246 def prep(ctx, fns):
2245 2247 rev = ctx.rev()
2246 2248 parents = [p for p in repo.changelog.parentrevs(rev)
2247 2249 if p != nullrev]
2248 2250 if opts.get('no_merges') and len(parents) == 2:
2249 2251 return
2250 2252 if opts.get('only_merges') and len(parents) != 2:
2251 2253 return
2252 2254 if opts.get('branch') and ctx.branch() not in opts['branch']:
2253 2255 return
2254 2256 if df and not df(ctx.date()[0]):
2255 2257 return
2256 2258 if opts['user'] and not [k for k in opts['user'] if k in ctx.user()]:
2257 2259 return
2258 2260 if opts.get('keyword'):
2259 2261 for k in [kw.lower() for kw in opts['keyword']]:
2260 2262 if (k in ctx.user().lower() or
2261 2263 k in ctx.description().lower() or
2262 2264 k in " ".join(ctx.files()).lower()):
2263 2265 break
2264 2266 else:
2265 2267 return
2266 2268
2267 2269 copies = None
2268 2270 if opts.get('copies') and rev:
2269 2271 copies = []
2270 2272 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2271 2273 for fn in ctx.files():
2272 2274 rename = getrenamed(fn, rev)
2273 2275 if rename:
2274 2276 copies.append((fn, rename[0]))
2275 2277
2276 2278 displayer.show(ctx, copies=copies)
2277 2279
2278 2280 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2279 2281 if count == limit:
2280 2282 break
2281 2283 if displayer.flush(ctx.rev()):
2282 2284 count += 1
2283 2285 displayer.close()
2284 2286
2285 2287 def manifest(ui, repo, node=None, rev=None):
2286 2288 """output the current or given revision of the project manifest
2287 2289
2288 2290 Print a list of version controlled files for the given revision.
2289 2291 If no revision is given, the first parent of the working directory
2290 2292 is used, or the null revision if no revision is checked out.
2291 2293
2292 2294 With -v, print file permissions, symlink and executable bits.
2293 2295 With --debug, print file revision hashes.
2294 2296
2295 2297 Returns 0 on success.
2296 2298 """
2297 2299
2298 2300 if rev and node:
2299 2301 raise util.Abort(_("please specify just one revision"))
2300 2302
2301 2303 if not node:
2302 2304 node = rev
2303 2305
2304 2306 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
2305 2307 ctx = repo[node]
2306 2308 for f in ctx:
2307 2309 if ui.debugflag:
2308 2310 ui.write("%40s " % hex(ctx.manifest()[f]))
2309 2311 if ui.verbose:
2310 2312 ui.write(decor[ctx.flags(f)])
2311 2313 ui.write("%s\n" % f)
2312 2314
2313 2315 def merge(ui, repo, node=None, **opts):
2314 2316 """merge working directory with another revision
2315 2317
2316 2318 The current working directory is updated with all changes made in
2317 2319 the requested revision since the last common predecessor revision.
2318 2320
2319 2321 Files that changed between either parent are marked as changed for
2320 2322 the next commit and a commit must be performed before any further
2321 2323 updates to the repository are allowed. The next commit will have
2322 2324 two parents.
2323 2325
2324 2326 If no revision is specified, the working directory's parent is a
2325 2327 head revision, and the current branch contains exactly one other
2326 2328 head, the other head is merged with by default. Otherwise, an
2327 2329 explicit revision with which to merge with must be provided.
2328 2330
2329 2331 Returns 0 on success, 1 if there are unresolved files.
2330 2332 """
2331 2333
2332 2334 if opts.get('rev') and node:
2333 2335 raise util.Abort(_("please specify just one revision"))
2334 2336 if not node:
2335 2337 node = opts.get('rev')
2336 2338
2337 2339 if not node:
2338 2340 branch = repo.changectx(None).branch()
2339 2341 bheads = repo.branchheads(branch)
2340 2342 if len(bheads) > 2:
2341 2343 ui.warn(_("abort: branch '%s' has %d heads - "
2342 2344 "please merge with an explicit rev\n")
2343 2345 % (branch, len(bheads)))
2344 2346 ui.status(_("(run 'hg heads .' to see heads)\n"))
2345 2347 return False
2346 2348
2347 2349 parent = repo.dirstate.parents()[0]
2348 2350 if len(bheads) == 1:
2349 2351 if len(repo.heads()) > 1:
2350 2352 ui.warn(_("abort: branch '%s' has one head - "
2351 2353 "please merge with an explicit rev\n" % branch))
2352 2354 ui.status(_("(run 'hg heads' to see all heads)\n"))
2353 2355 return False
2354 2356 msg = _('there is nothing to merge')
2355 2357 if parent != repo.lookup(repo[None].branch()):
2356 2358 msg = _('%s - use "hg update" instead') % msg
2357 2359 raise util.Abort(msg)
2358 2360
2359 2361 if parent not in bheads:
2360 2362 raise util.Abort(_('working dir not at a head rev - '
2361 2363 'use "hg update" or merge with an explicit rev'))
2362 2364 node = parent == bheads[0] and bheads[-1] or bheads[0]
2363 2365
2364 2366 if opts.get('preview'):
2365 2367 # find nodes that are ancestors of p2 but not of p1
2366 2368 p1 = repo.lookup('.')
2367 2369 p2 = repo.lookup(node)
2368 2370 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
2369 2371
2370 2372 displayer = cmdutil.show_changeset(ui, repo, opts)
2371 2373 for node in nodes:
2372 2374 displayer.show(repo[node])
2373 2375 displayer.close()
2374 2376 return 0
2375 2377
2376 2378 return hg.merge(repo, node, force=opts.get('force'))
2377 2379
2378 2380 def outgoing(ui, repo, dest=None, **opts):
2379 2381 """show changesets not found in the destination
2380 2382
2381 2383 Show changesets not found in the specified destination repository
2382 2384 or the default push location. These are the changesets that would
2383 2385 be pushed if a push was requested.
2384 2386
2385 2387 See pull for details of valid destination formats.
2386 2388
2387 2389 Returns 0 if there are outgoing changes, 1 otherwise.
2388 2390 """
2389 2391 limit = cmdutil.loglimit(opts)
2390 2392 dest = ui.expandpath(dest or 'default-push', dest or 'default')
2391 2393 dest, branches = hg.parseurl(dest, opts.get('branch'))
2392 2394 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
2393 2395 if revs:
2394 2396 revs = [repo.lookup(rev) for rev in revs]
2395 2397
2396 2398 other = hg.repository(hg.remoteui(repo, opts), dest)
2397 2399 ui.status(_('comparing with %s\n') % url.hidepassword(dest))
2398 o = repo.findoutgoing(other, force=opts.get('force'))
2400 o = discovery.findoutgoing(repo, other, force=opts.get('force'))
2399 2401 if not o:
2400 2402 ui.status(_("no changes found\n"))
2401 2403 return 1
2402 2404 o = repo.changelog.nodesbetween(o, revs)[0]
2403 2405 if opts.get('newest_first'):
2404 2406 o.reverse()
2405 2407 displayer = cmdutil.show_changeset(ui, repo, opts)
2406 2408 count = 0
2407 2409 for n in o:
2408 2410 if limit is not None and count >= limit:
2409 2411 break
2410 2412 parents = [p for p in repo.changelog.parents(n) if p != nullid]
2411 2413 if opts.get('no_merges') and len(parents) == 2:
2412 2414 continue
2413 2415 count += 1
2414 2416 displayer.show(repo[n])
2415 2417 displayer.close()
2416 2418
2417 2419 def parents(ui, repo, file_=None, **opts):
2418 2420 """show the parents of the working directory or revision
2419 2421
2420 2422 Print the working directory's parent revisions. If a revision is
2421 2423 given via -r/--rev, the parent of that revision will be printed.
2422 2424 If a file argument is given, the revision in which the file was
2423 2425 last changed (before the working directory revision or the
2424 2426 argument to --rev if given) is printed.
2425 2427
2426 2428 Returns 0 on success.
2427 2429 """
2428 2430 rev = opts.get('rev')
2429 2431 if rev:
2430 2432 ctx = repo[rev]
2431 2433 else:
2432 2434 ctx = repo[None]
2433 2435
2434 2436 if file_:
2435 2437 m = cmdutil.match(repo, (file_,), opts)
2436 2438 if m.anypats() or len(m.files()) != 1:
2437 2439 raise util.Abort(_('can only specify an explicit filename'))
2438 2440 file_ = m.files()[0]
2439 2441 filenodes = []
2440 2442 for cp in ctx.parents():
2441 2443 if not cp:
2442 2444 continue
2443 2445 try:
2444 2446 filenodes.append(cp.filenode(file_))
2445 2447 except error.LookupError:
2446 2448 pass
2447 2449 if not filenodes:
2448 2450 raise util.Abort(_("'%s' not found in manifest!") % file_)
2449 2451 fl = repo.file(file_)
2450 2452 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
2451 2453 else:
2452 2454 p = [cp.node() for cp in ctx.parents()]
2453 2455
2454 2456 displayer = cmdutil.show_changeset(ui, repo, opts)
2455 2457 for n in p:
2456 2458 if n != nullid:
2457 2459 displayer.show(repo[n])
2458 2460 displayer.close()
2459 2461
2460 2462 def paths(ui, repo, search=None):
2461 2463 """show aliases for remote repositories
2462 2464
2463 2465 Show definition of symbolic path name NAME. If no name is given,
2464 2466 show definition of all available names.
2465 2467
2466 2468 Path names are defined in the [paths] section of
2467 2469 ``/etc/mercurial/hgrc`` and ``$HOME/.hgrc``. If run inside a
2468 2470 repository, ``.hg/hgrc`` is used, too.
2469 2471
2470 2472 The path names ``default`` and ``default-push`` have a special
2471 2473 meaning. When performing a push or pull operation, they are used
2472 2474 as fallbacks if no location is specified on the command-line.
2473 2475 When ``default-push`` is set, it will be used for push and
2474 2476 ``default`` will be used for pull; otherwise ``default`` is used
2475 2477 as the fallback for both. When cloning a repository, the clone
2476 2478 source is written as ``default`` in ``.hg/hgrc``. Note that
2477 2479 ``default`` and ``default-push`` apply to all inbound (e.g.
2478 2480 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
2479 2481 :hg:`bundle`) operations.
2480 2482
2481 2483 See :hg:`help urls` for more information.
2482 2484 """
2483 2485 if search:
2484 2486 for name, path in ui.configitems("paths"):
2485 2487 if name == search:
2486 2488 ui.write("%s\n" % url.hidepassword(path))
2487 2489 return
2488 2490 ui.warn(_("not found!\n"))
2489 2491 return 1
2490 2492 else:
2491 2493 for name, path in ui.configitems("paths"):
2492 2494 ui.write("%s = %s\n" % (name, url.hidepassword(path)))
2493 2495
2494 2496 def postincoming(ui, repo, modheads, optupdate, checkout):
2495 2497 if modheads == 0:
2496 2498 return
2497 2499 if optupdate:
2498 2500 if (modheads <= 1 or len(repo.branchheads()) == 1) or checkout:
2499 2501 return hg.update(repo, checkout)
2500 2502 else:
2501 2503 ui.status(_("not updating, since new heads added\n"))
2502 2504 if modheads > 1:
2503 2505 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
2504 2506 else:
2505 2507 ui.status(_("(run 'hg update' to get a working copy)\n"))
2506 2508
2507 2509 def pull(ui, repo, source="default", **opts):
2508 2510 """pull changes from the specified source
2509 2511
2510 2512 Pull changes from a remote repository to a local one.
2511 2513
2512 2514 This finds all changes from the repository at the specified path
2513 2515 or URL and adds them to a local repository (the current one unless
2514 2516 -R is specified). By default, this does not update the copy of the
2515 2517 project in the working directory.
2516 2518
2517 2519 Use :hg:`incoming` if you want to see what would have been added
2518 2520 by a pull at the time you issued this command. If you then decide
2519 2521 to add those changes to the repository, you should use :hg:`pull
2520 2522 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
2521 2523
2522 2524 If SOURCE is omitted, the 'default' path will be used.
2523 2525 See :hg:`help urls` for more information.
2524 2526
2525 2527 Returns 0 on success, 1 if an update had unresolved files.
2526 2528 """
2527 2529 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
2528 2530 other = hg.repository(hg.remoteui(repo, opts), source)
2529 2531 ui.status(_('pulling from %s\n') % url.hidepassword(source))
2530 2532 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
2531 2533 if revs:
2532 2534 try:
2533 2535 revs = [other.lookup(rev) for rev in revs]
2534 2536 except error.CapabilityError:
2535 2537 err = _("Other repository doesn't support revision lookup, "
2536 2538 "so a rev cannot be specified.")
2537 2539 raise util.Abort(err)
2538 2540
2539 2541 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
2540 2542 if checkout:
2541 2543 checkout = str(repo.changelog.rev(other.lookup(checkout)))
2542 2544 return postincoming(ui, repo, modheads, opts.get('update'), checkout)
2543 2545
2544 2546 def push(ui, repo, dest=None, **opts):
2545 2547 """push changes to the specified destination
2546 2548
2547 2549 Push changesets from the local repository to the specified
2548 2550 destination.
2549 2551
2550 2552 This operation is symmetrical to pull: it is identical to a pull
2551 2553 in the destination repository from the current one.
2552 2554
2553 2555 By default, push will not allow creation of new heads at the
2554 2556 destination, since multiple heads would make it unclear which head
2555 2557 to use. In this situation, it is recommended to pull and merge
2556 2558 before pushing.
2557 2559
2558 2560 Use --new-branch if you want to allow push to create a new named
2559 2561 branch that is not present at the destination. This allows you to
2560 2562 only create a new branch without forcing other changes.
2561 2563
2562 2564 Use -f/--force to override the default behavior and push all
2563 2565 changesets on all branches.
2564 2566
2565 2567 If -r/--rev is used, the specified revision and all its ancestors
2566 2568 will be pushed to the remote repository.
2567 2569
2568 2570 Please see :hg:`help urls` for important details about ``ssh://``
2569 2571 URLs. If DESTINATION is omitted, a default path will be used.
2570 2572
2571 2573 Returns 0 if push was successful, 1 if nothing to push.
2572 2574 """
2573 2575 dest = ui.expandpath(dest or 'default-push', dest or 'default')
2574 2576 dest, branches = hg.parseurl(dest, opts.get('branch'))
2575 2577 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
2576 2578 other = hg.repository(hg.remoteui(repo, opts), dest)
2577 2579 ui.status(_('pushing to %s\n') % url.hidepassword(dest))
2578 2580 if revs:
2579 2581 revs = [repo.lookup(rev) for rev in revs]
2580 2582
2581 2583 # push subrepos depth-first for coherent ordering
2582 2584 c = repo['']
2583 2585 subs = c.substate # only repos that are committed
2584 2586 for s in sorted(subs):
2585 2587 if not c.sub(s).push(opts.get('force')):
2586 2588 return False
2587 2589
2588 2590 r = repo.push(other, opts.get('force'), revs=revs,
2589 2591 newbranch=opts.get('new_branch'))
2590 2592 return r == 0
2591 2593
2592 2594 def recover(ui, repo):
2593 2595 """roll back an interrupted transaction
2594 2596
2595 2597 Recover from an interrupted commit or pull.
2596 2598
2597 2599 This command tries to fix the repository status after an
2598 2600 interrupted operation. It should only be necessary when Mercurial
2599 2601 suggests it.
2600 2602
2601 2603 Returns 0 if successful, 1 if nothing to recover or verify fails.
2602 2604 """
2603 2605 if repo.recover():
2604 2606 return hg.verify(repo)
2605 2607 return 1
2606 2608
2607 2609 def remove(ui, repo, *pats, **opts):
2608 2610 """remove the specified files on the next commit
2609 2611
2610 2612 Schedule the indicated files for removal from the repository.
2611 2613
2612 2614 This only removes files from the current branch, not from the
2613 2615 entire project history. -A/--after can be used to remove only
2614 2616 files that have already been deleted, -f/--force can be used to
2615 2617 force deletion, and -Af can be used to remove files from the next
2616 2618 revision without deleting them from the working directory.
2617 2619
2618 2620 The following table details the behavior of remove for different
2619 2621 file states (columns) and option combinations (rows). The file
2620 2622 states are Added [A], Clean [C], Modified [M] and Missing [!] (as
2621 2623 reported by :hg:`status`). The actions are Warn, Remove (from
2622 2624 branch) and Delete (from disk)::
2623 2625
2624 2626 A C M !
2625 2627 none W RD W R
2626 2628 -f R RD RD R
2627 2629 -A W W W R
2628 2630 -Af R R R R
2629 2631
2630 2632 This command schedules the files to be removed at the next commit.
2631 2633 To undo a remove before that, see :hg:`revert`.
2632 2634
2633 2635 Returns 0 on success, 1 if any warnings encountered.
2634 2636 """
2635 2637
2636 2638 ret = 0
2637 2639 after, force = opts.get('after'), opts.get('force')
2638 2640 if not pats and not after:
2639 2641 raise util.Abort(_('no files specified'))
2640 2642
2641 2643 m = cmdutil.match(repo, pats, opts)
2642 2644 s = repo.status(match=m, clean=True)
2643 2645 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2644 2646
2645 2647 for f in m.files():
2646 2648 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2647 2649 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
2648 2650 ret = 1
2649 2651
2650 2652 def warn(files, reason):
2651 2653 for f in files:
2652 2654 ui.warn(_('not removing %s: file %s (use -f to force removal)\n')
2653 2655 % (m.rel(f), reason))
2654 2656 ret = 1
2655 2657
2656 2658 if force:
2657 2659 remove, forget = modified + deleted + clean, added
2658 2660 elif after:
2659 2661 remove, forget = deleted, []
2660 2662 warn(modified + added + clean, _('still exists'))
2661 2663 else:
2662 2664 remove, forget = deleted + clean, []
2663 2665 warn(modified, _('is modified'))
2664 2666 warn(added, _('has been marked for add'))
2665 2667
2666 2668 for f in sorted(remove + forget):
2667 2669 if ui.verbose or not m.exact(f):
2668 2670 ui.status(_('removing %s\n') % m.rel(f))
2669 2671
2670 2672 repo.forget(forget)
2671 2673 repo.remove(remove, unlink=not after)
2672 2674 return ret
2673 2675
2674 2676 def rename(ui, repo, *pats, **opts):
2675 2677 """rename files; equivalent of copy + remove
2676 2678
2677 2679 Mark dest as copies of sources; mark sources for deletion. If dest
2678 2680 is a directory, copies are put in that directory. If dest is a
2679 2681 file, there can only be one source.
2680 2682
2681 2683 By default, this command copies the contents of files as they
2682 2684 exist in the working directory. If invoked with -A/--after, the
2683 2685 operation is recorded, but no copying is performed.
2684 2686
2685 2687 This command takes effect at the next commit. To undo a rename
2686 2688 before that, see :hg:`revert`.
2687 2689
2688 2690 Returns 0 on success, 1 if errors are encountered.
2689 2691 """
2690 2692 wlock = repo.wlock(False)
2691 2693 try:
2692 2694 return cmdutil.copy(ui, repo, pats, opts, rename=True)
2693 2695 finally:
2694 2696 wlock.release()
2695 2697
2696 2698 def resolve(ui, repo, *pats, **opts):
2697 2699 """various operations to help finish a merge
2698 2700
2699 2701 This command includes several actions that are often useful while
2700 2702 performing a merge, after running ``merge`` but before running
2701 2703 ``commit``. (It is only meaningful if your working directory has
2702 2704 two parents.) It is most relevant for merges with unresolved
2703 2705 conflicts, which are typically a result of non-interactive merging with
2704 2706 ``internal:merge`` or a command-line merge tool like ``diff3``.
2705 2707
2706 2708 The available actions are:
2707 2709
2708 2710 1) list files that were merged with conflicts (U, for unresolved)
2709 2711 and without conflicts (R, for resolved): ``hg resolve -l``
2710 2712 (this is like ``status`` for merges)
2711 2713 2) record that you have resolved conflicts in certain files:
2712 2714 ``hg resolve -m [file ...]`` (default: mark all unresolved files)
2713 2715 3) forget that you have resolved conflicts in certain files:
2714 2716 ``hg resolve -u [file ...]`` (default: unmark all resolved files)
2715 2717 4) discard your current attempt(s) at resolving conflicts and
2716 2718 restart the merge from scratch: ``hg resolve file...``
2717 2719 (or ``-a`` for all unresolved files)
2718 2720
2719 2721 Note that Mercurial will not let you commit files with unresolved merge
2720 2722 conflicts. You must use ``hg resolve -m ...`` before you can commit
2721 2723 after a conflicting merge.
2722 2724
2723 2725 Returns 0 on success, 1 if any files fail a resolve attempt.
2724 2726 """
2725 2727
2726 2728 all, mark, unmark, show, nostatus = \
2727 2729 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
2728 2730
2729 2731 if (show and (mark or unmark)) or (mark and unmark):
2730 2732 raise util.Abort(_("too many options specified"))
2731 2733 if pats and all:
2732 2734 raise util.Abort(_("can't specify --all and patterns"))
2733 2735 if not (all or pats or show or mark or unmark):
2734 2736 raise util.Abort(_('no files or directories specified; '
2735 2737 'use --all to remerge all files'))
2736 2738
2737 2739 ms = mergemod.mergestate(repo)
2738 2740 m = cmdutil.match(repo, pats, opts)
2739 2741 ret = 0
2740 2742
2741 2743 for f in ms:
2742 2744 if m(f):
2743 2745 if show:
2744 2746 if nostatus:
2745 2747 ui.write("%s\n" % f)
2746 2748 else:
2747 2749 ui.write("%s %s\n" % (ms[f].upper(), f),
2748 2750 label='resolve.' +
2749 2751 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
2750 2752 elif mark:
2751 2753 ms.mark(f, "r")
2752 2754 elif unmark:
2753 2755 ms.mark(f, "u")
2754 2756 else:
2755 2757 wctx = repo[None]
2756 2758 mctx = wctx.parents()[-1]
2757 2759
2758 2760 # backup pre-resolve (merge uses .orig for its own purposes)
2759 2761 a = repo.wjoin(f)
2760 2762 util.copyfile(a, a + ".resolve")
2761 2763
2762 2764 # resolve file
2763 2765 if ms.resolve(f, wctx, mctx):
2764 2766 ret = 1
2765 2767
2766 2768 # replace filemerge's .orig file with our resolve file
2767 2769 util.rename(a + ".resolve", a + ".orig")
2768 2770 return ret
2769 2771
2770 2772 def revert(ui, repo, *pats, **opts):
2771 2773 """restore individual files or directories to an earlier state
2772 2774
2773 2775 (Use update -r to check out earlier revisions, revert does not
2774 2776 change the working directory parents.)
2775 2777
2776 2778 With no revision specified, revert the named files or directories
2777 2779 to the contents they had in the parent of the working directory.
2778 2780 This restores the contents of the affected files to an unmodified
2779 2781 state and unschedules adds, removes, copies, and renames. If the
2780 2782 working directory has two parents, you must explicitly specify a
2781 2783 revision.
2782 2784
2783 2785 Using the -r/--rev option, revert the given files or directories
2784 2786 to their contents as of a specific revision. This can be helpful
2785 2787 to "roll back" some or all of an earlier change. See :hg:`help
2786 2788 dates` for a list of formats valid for -d/--date.
2787 2789
2788 2790 Revert modifies the working directory. It does not commit any
2789 2791 changes, or change the parent of the working directory. If you
2790 2792 revert to a revision other than the parent of the working
2791 2793 directory, the reverted files will thus appear modified
2792 2794 afterwards.
2793 2795
2794 2796 If a file has been deleted, it is restored. If the executable mode
2795 2797 of a file was changed, it is reset.
2796 2798
2797 2799 If names are given, all files matching the names are reverted.
2798 2800 If no arguments are given, no files are reverted.
2799 2801
2800 2802 Modified files are saved with a .orig suffix before reverting.
2801 2803 To disable these backups, use --no-backup.
2802 2804
2803 2805 Returns 0 on success.
2804 2806 """
2805 2807
2806 2808 if opts["date"]:
2807 2809 if opts["rev"]:
2808 2810 raise util.Abort(_("you can't specify a revision and a date"))
2809 2811 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
2810 2812
2811 2813 if not pats and not opts.get('all'):
2812 2814 raise util.Abort(_('no files or directories specified; '
2813 2815 'use --all to revert the whole repo'))
2814 2816
2815 2817 parent, p2 = repo.dirstate.parents()
2816 2818 if not opts.get('rev') and p2 != nullid:
2817 2819 raise util.Abort(_('uncommitted merge - please provide a '
2818 2820 'specific revision'))
2819 2821 ctx = repo[opts.get('rev')]
2820 2822 node = ctx.node()
2821 2823 mf = ctx.manifest()
2822 2824 if node == parent:
2823 2825 pmf = mf
2824 2826 else:
2825 2827 pmf = None
2826 2828
2827 2829 # need all matching names in dirstate and manifest of target rev,
2828 2830 # so have to walk both. do not print errors if files exist in one
2829 2831 # but not other.
2830 2832
2831 2833 names = {}
2832 2834
2833 2835 wlock = repo.wlock()
2834 2836 try:
2835 2837 # walk dirstate.
2836 2838
2837 2839 m = cmdutil.match(repo, pats, opts)
2838 2840 m.bad = lambda x, y: False
2839 2841 for abs in repo.walk(m):
2840 2842 names[abs] = m.rel(abs), m.exact(abs)
2841 2843
2842 2844 # walk target manifest.
2843 2845
2844 2846 def badfn(path, msg):
2845 2847 if path in names:
2846 2848 return
2847 2849 path_ = path + '/'
2848 2850 for f in names:
2849 2851 if f.startswith(path_):
2850 2852 return
2851 2853 ui.warn("%s: %s\n" % (m.rel(path), msg))
2852 2854
2853 2855 m = cmdutil.match(repo, pats, opts)
2854 2856 m.bad = badfn
2855 2857 for abs in repo[node].walk(m):
2856 2858 if abs not in names:
2857 2859 names[abs] = m.rel(abs), m.exact(abs)
2858 2860
2859 2861 m = cmdutil.matchfiles(repo, names)
2860 2862 changes = repo.status(match=m)[:4]
2861 2863 modified, added, removed, deleted = map(set, changes)
2862 2864
2863 2865 # if f is a rename, also revert the source
2864 2866 cwd = repo.getcwd()
2865 2867 for f in added:
2866 2868 src = repo.dirstate.copied(f)
2867 2869 if src and src not in names and repo.dirstate[src] == 'r':
2868 2870 removed.add(src)
2869 2871 names[src] = (repo.pathto(src, cwd), True)
2870 2872
2871 2873 def removeforget(abs):
2872 2874 if repo.dirstate[abs] == 'a':
2873 2875 return _('forgetting %s\n')
2874 2876 return _('removing %s\n')
2875 2877
2876 2878 revert = ([], _('reverting %s\n'))
2877 2879 add = ([], _('adding %s\n'))
2878 2880 remove = ([], removeforget)
2879 2881 undelete = ([], _('undeleting %s\n'))
2880 2882
2881 2883 disptable = (
2882 2884 # dispatch table:
2883 2885 # file state
2884 2886 # action if in target manifest
2885 2887 # action if not in target manifest
2886 2888 # make backup if in target manifest
2887 2889 # make backup if not in target manifest
2888 2890 (modified, revert, remove, True, True),
2889 2891 (added, revert, remove, True, False),
2890 2892 (removed, undelete, None, False, False),
2891 2893 (deleted, revert, remove, False, False),
2892 2894 )
2893 2895
2894 2896 for abs, (rel, exact) in sorted(names.items()):
2895 2897 mfentry = mf.get(abs)
2896 2898 target = repo.wjoin(abs)
2897 2899 def handle(xlist, dobackup):
2898 2900 xlist[0].append(abs)
2899 2901 if dobackup and not opts.get('no_backup') and util.lexists(target):
2900 2902 bakname = "%s.orig" % rel
2901 2903 ui.note(_('saving current version of %s as %s\n') %
2902 2904 (rel, bakname))
2903 2905 if not opts.get('dry_run'):
2904 2906 util.copyfile(target, bakname)
2905 2907 if ui.verbose or not exact:
2906 2908 msg = xlist[1]
2907 2909 if not isinstance(msg, basestring):
2908 2910 msg = msg(abs)
2909 2911 ui.status(msg % rel)
2910 2912 for table, hitlist, misslist, backuphit, backupmiss in disptable:
2911 2913 if abs not in table:
2912 2914 continue
2913 2915 # file has changed in dirstate
2914 2916 if mfentry:
2915 2917 handle(hitlist, backuphit)
2916 2918 elif misslist is not None:
2917 2919 handle(misslist, backupmiss)
2918 2920 break
2919 2921 else:
2920 2922 if abs not in repo.dirstate:
2921 2923 if mfentry:
2922 2924 handle(add, True)
2923 2925 elif exact:
2924 2926 ui.warn(_('file not managed: %s\n') % rel)
2925 2927 continue
2926 2928 # file has not changed in dirstate
2927 2929 if node == parent:
2928 2930 if exact:
2929 2931 ui.warn(_('no changes needed to %s\n') % rel)
2930 2932 continue
2931 2933 if pmf is None:
2932 2934 # only need parent manifest in this unlikely case,
2933 2935 # so do not read by default
2934 2936 pmf = repo[parent].manifest()
2935 2937 if abs in pmf:
2936 2938 if mfentry:
2937 2939 # if version of file is same in parent and target
2938 2940 # manifests, do nothing
2939 2941 if (pmf[abs] != mfentry or
2940 2942 pmf.flags(abs) != mf.flags(abs)):
2941 2943 handle(revert, False)
2942 2944 else:
2943 2945 handle(remove, False)
2944 2946
2945 2947 if not opts.get('dry_run'):
2946 2948 def checkout(f):
2947 2949 fc = ctx[f]
2948 2950 repo.wwrite(f, fc.data(), fc.flags())
2949 2951
2950 2952 audit_path = util.path_auditor(repo.root)
2951 2953 for f in remove[0]:
2952 2954 if repo.dirstate[f] == 'a':
2953 2955 repo.dirstate.forget(f)
2954 2956 continue
2955 2957 audit_path(f)
2956 2958 try:
2957 2959 util.unlink(repo.wjoin(f))
2958 2960 except OSError:
2959 2961 pass
2960 2962 repo.dirstate.remove(f)
2961 2963
2962 2964 normal = None
2963 2965 if node == parent:
2964 2966 # We're reverting to our parent. If possible, we'd like status
2965 2967 # to report the file as clean. We have to use normallookup for
2966 2968 # merges to avoid losing information about merged/dirty files.
2967 2969 if p2 != nullid:
2968 2970 normal = repo.dirstate.normallookup
2969 2971 else:
2970 2972 normal = repo.dirstate.normal
2971 2973 for f in revert[0]:
2972 2974 checkout(f)
2973 2975 if normal:
2974 2976 normal(f)
2975 2977
2976 2978 for f in add[0]:
2977 2979 checkout(f)
2978 2980 repo.dirstate.add(f)
2979 2981
2980 2982 normal = repo.dirstate.normallookup
2981 2983 if node == parent and p2 == nullid:
2982 2984 normal = repo.dirstate.normal
2983 2985 for f in undelete[0]:
2984 2986 checkout(f)
2985 2987 normal(f)
2986 2988
2987 2989 finally:
2988 2990 wlock.release()
2989 2991
2990 2992 def rollback(ui, repo, **opts):
2991 2993 """roll back the last transaction (dangerous)
2992 2994
2993 2995 This command should be used with care. There is only one level of
2994 2996 rollback, and there is no way to undo a rollback. It will also
2995 2997 restore the dirstate at the time of the last transaction, losing
2996 2998 any dirstate changes since that time. This command does not alter
2997 2999 the working directory.
2998 3000
2999 3001 Transactions are used to encapsulate the effects of all commands
3000 3002 that create new changesets or propagate existing changesets into a
3001 3003 repository. For example, the following commands are transactional,
3002 3004 and their effects can be rolled back:
3003 3005
3004 3006 - commit
3005 3007 - import
3006 3008 - pull
3007 3009 - push (with this repository as the destination)
3008 3010 - unbundle
3009 3011
3010 3012 This command is not intended for use on public repositories. Once
3011 3013 changes are visible for pull by other users, rolling a transaction
3012 3014 back locally is ineffective (someone else may already have pulled
3013 3015 the changes). Furthermore, a race is possible with readers of the
3014 3016 repository; for example an in-progress pull from the repository
3015 3017 may fail if a rollback is performed.
3016 3018
3017 3019 Returns 0 on success, 1 if no rollback data is available.
3018 3020 """
3019 3021 return repo.rollback(opts.get('dry_run'))
3020 3022
3021 3023 def root(ui, repo):
3022 3024 """print the root (top) of the current working directory
3023 3025
3024 3026 Print the root directory of the current repository.
3025 3027
3026 3028 Returns 0 on success.
3027 3029 """
3028 3030 ui.write(repo.root + "\n")
3029 3031
3030 3032 def serve(ui, repo, **opts):
3031 3033 """start stand-alone webserver
3032 3034
3033 3035 Start a local HTTP repository browser and pull server. You can use
3034 3036 this for ad-hoc sharing and browing of repositories. It is
3035 3037 recommended to use a real web server to serve a repository for
3036 3038 longer periods of time.
3037 3039
3038 3040 Please note that the server does not implement access control.
3039 3041 This means that, by default, anybody can read from the server and
3040 3042 nobody can write to it by default. Set the ``web.allow_push``
3041 3043 option to ``*`` to allow everybody to push to the server. You
3042 3044 should use a real web server if you need to authenticate users.
3043 3045
3044 3046 By default, the server logs accesses to stdout and errors to
3045 3047 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
3046 3048 files.
3047 3049
3048 3050 To have the server choose a free port number to listen on, specify
3049 3051 a port number of 0; in this case, the server will print the port
3050 3052 number it uses.
3051 3053
3052 3054 Returns 0 on success.
3053 3055 """
3054 3056
3055 3057 if opts["stdio"]:
3056 3058 if repo is None:
3057 3059 raise error.RepoError(_("There is no Mercurial repository here"
3058 3060 " (.hg not found)"))
3059 3061 s = sshserver.sshserver(ui, repo)
3060 3062 s.serve_forever()
3061 3063
3062 3064 # this way we can check if something was given in the command-line
3063 3065 if opts.get('port'):
3064 3066 opts['port'] = int(opts.get('port'))
3065 3067
3066 3068 baseui = repo and repo.baseui or ui
3067 3069 optlist = ("name templates style address port prefix ipv6"
3068 3070 " accesslog errorlog certificate encoding")
3069 3071 for o in optlist.split():
3070 3072 val = opts.get(o, '')
3071 3073 if val in (None, ''): # should check against default options instead
3072 3074 continue
3073 3075 baseui.setconfig("web", o, val)
3074 3076 if repo and repo.ui != baseui:
3075 3077 repo.ui.setconfig("web", o, val)
3076 3078
3077 3079 o = opts.get('web_conf') or opts.get('webdir_conf')
3078 3080 if not o:
3079 3081 if not repo:
3080 3082 raise error.RepoError(_("There is no Mercurial repository"
3081 3083 " here (.hg not found)"))
3082 3084 o = repo.root
3083 3085
3084 3086 app = hgweb.hgweb(o, baseui=ui)
3085 3087
3086 3088 class service(object):
3087 3089 def init(self):
3088 3090 util.set_signal_handler()
3089 3091 self.httpd = hgweb.server.create_server(ui, app)
3090 3092
3091 3093 if opts['port'] and not ui.verbose:
3092 3094 return
3093 3095
3094 3096 if self.httpd.prefix:
3095 3097 prefix = self.httpd.prefix.strip('/') + '/'
3096 3098 else:
3097 3099 prefix = ''
3098 3100
3099 3101 port = ':%d' % self.httpd.port
3100 3102 if port == ':80':
3101 3103 port = ''
3102 3104
3103 3105 bindaddr = self.httpd.addr
3104 3106 if bindaddr == '0.0.0.0':
3105 3107 bindaddr = '*'
3106 3108 elif ':' in bindaddr: # IPv6
3107 3109 bindaddr = '[%s]' % bindaddr
3108 3110
3109 3111 fqaddr = self.httpd.fqaddr
3110 3112 if ':' in fqaddr:
3111 3113 fqaddr = '[%s]' % fqaddr
3112 3114 if opts['port']:
3113 3115 write = ui.status
3114 3116 else:
3115 3117 write = ui.write
3116 3118 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
3117 3119 (fqaddr, port, prefix, bindaddr, self.httpd.port))
3118 3120
3119 3121 def run(self):
3120 3122 self.httpd.serve_forever()
3121 3123
3122 3124 service = service()
3123 3125
3124 3126 cmdutil.service(opts, initfn=service.init, runfn=service.run)
3125 3127
3126 3128 def status(ui, repo, *pats, **opts):
3127 3129 """show changed files in the working directory
3128 3130
3129 3131 Show status of files in the repository. If names are given, only
3130 3132 files that match are shown. Files that are clean or ignored or
3131 3133 the source of a copy/move operation, are not listed unless
3132 3134 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
3133 3135 Unless options described with "show only ..." are given, the
3134 3136 options -mardu are used.
3135 3137
3136 3138 Option -q/--quiet hides untracked (unknown and ignored) files
3137 3139 unless explicitly requested with -u/--unknown or -i/--ignored.
3138 3140
3139 3141 NOTE: status may appear to disagree with diff if permissions have
3140 3142 changed or a merge has occurred. The standard diff format does not
3141 3143 report permission changes and diff only reports changes relative
3142 3144 to one merge parent.
3143 3145
3144 3146 If one revision is given, it is used as the base revision.
3145 3147 If two revisions are given, the differences between them are
3146 3148 shown. The --change option can also be used as a shortcut to list
3147 3149 the changed files of a revision from its first parent.
3148 3150
3149 3151 The codes used to show the status of files are::
3150 3152
3151 3153 M = modified
3152 3154 A = added
3153 3155 R = removed
3154 3156 C = clean
3155 3157 ! = missing (deleted by non-hg command, but still tracked)
3156 3158 ? = not tracked
3157 3159 I = ignored
3158 3160 = origin of the previous file listed as A (added)
3159 3161
3160 3162 Returns 0 on success.
3161 3163 """
3162 3164
3163 3165 revs = opts.get('rev')
3164 3166 change = opts.get('change')
3165 3167
3166 3168 if revs and change:
3167 3169 msg = _('cannot specify --rev and --change at the same time')
3168 3170 raise util.Abort(msg)
3169 3171 elif change:
3170 3172 node2 = repo.lookup(change)
3171 3173 node1 = repo[node2].parents()[0].node()
3172 3174 else:
3173 3175 node1, node2 = cmdutil.revpair(repo, revs)
3174 3176
3175 3177 cwd = (pats and repo.getcwd()) or ''
3176 3178 end = opts.get('print0') and '\0' or '\n'
3177 3179 copy = {}
3178 3180 states = 'modified added removed deleted unknown ignored clean'.split()
3179 3181 show = [k for k in states if opts.get(k)]
3180 3182 if opts.get('all'):
3181 3183 show += ui.quiet and (states[:4] + ['clean']) or states
3182 3184 if not show:
3183 3185 show = ui.quiet and states[:4] or states[:5]
3184 3186
3185 3187 stat = repo.status(node1, node2, cmdutil.match(repo, pats, opts),
3186 3188 'ignored' in show, 'clean' in show, 'unknown' in show)
3187 3189 changestates = zip(states, 'MAR!?IC', stat)
3188 3190
3189 3191 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
3190 3192 ctxn = repo[nullid]
3191 3193 ctx1 = repo[node1]
3192 3194 ctx2 = repo[node2]
3193 3195 added = stat[1]
3194 3196 if node2 is None:
3195 3197 added = stat[0] + stat[1] # merged?
3196 3198
3197 3199 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
3198 3200 if k in added:
3199 3201 copy[k] = v
3200 3202 elif v in added:
3201 3203 copy[v] = k
3202 3204
3203 3205 for state, char, files in changestates:
3204 3206 if state in show:
3205 3207 format = "%s %%s%s" % (char, end)
3206 3208 if opts.get('no_status'):
3207 3209 format = "%%s%s" % end
3208 3210
3209 3211 for f in files:
3210 3212 ui.write(format % repo.pathto(f, cwd),
3211 3213 label='status.' + state)
3212 3214 if f in copy:
3213 3215 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
3214 3216 label='status.copied')
3215 3217
3216 3218 def summary(ui, repo, **opts):
3217 3219 """summarize working directory state
3218 3220
3219 3221 This generates a brief summary of the working directory state,
3220 3222 including parents, branch, commit status, and available updates.
3221 3223
3222 3224 With the --remote option, this will check the default paths for
3223 3225 incoming and outgoing changes. This can be time-consuming.
3224 3226
3225 3227 Returns 0 on success.
3226 3228 """
3227 3229
3228 3230 ctx = repo[None]
3229 3231 parents = ctx.parents()
3230 3232 pnode = parents[0].node()
3231 3233
3232 3234 for p in parents:
3233 3235 # label with log.changeset (instead of log.parent) since this
3234 3236 # shows a working directory parent *changeset*:
3235 3237 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
3236 3238 label='log.changeset')
3237 3239 ui.write(' '.join(p.tags()), label='log.tag')
3238 3240 if p.rev() == -1:
3239 3241 if not len(repo):
3240 3242 ui.write(_(' (empty repository)'))
3241 3243 else:
3242 3244 ui.write(_(' (no revision checked out)'))
3243 3245 ui.write('\n')
3244 3246 if p.description():
3245 3247 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
3246 3248 label='log.summary')
3247 3249
3248 3250 branch = ctx.branch()
3249 3251 bheads = repo.branchheads(branch)
3250 3252 m = _('branch: %s\n') % branch
3251 3253 if branch != 'default':
3252 3254 ui.write(m, label='log.branch')
3253 3255 else:
3254 3256 ui.status(m, label='log.branch')
3255 3257
3256 3258 st = list(repo.status(unknown=True))[:6]
3257 3259
3258 3260 ms = mergemod.mergestate(repo)
3259 3261 st.append([f for f in ms if ms[f] == 'u'])
3260 3262
3261 3263 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
3262 3264 st.append(subs)
3263 3265
3264 3266 labels = [ui.label(_('%d modified'), 'status.modified'),
3265 3267 ui.label(_('%d added'), 'status.added'),
3266 3268 ui.label(_('%d removed'), 'status.removed'),
3267 3269 ui.label(_('%d deleted'), 'status.deleted'),
3268 3270 ui.label(_('%d unknown'), 'status.unknown'),
3269 3271 ui.label(_('%d ignored'), 'status.ignored'),
3270 3272 ui.label(_('%d unresolved'), 'resolve.unresolved'),
3271 3273 ui.label(_('%d subrepos'), 'status.modified')]
3272 3274 t = []
3273 3275 for s, l in zip(st, labels):
3274 3276 if s:
3275 3277 t.append(l % len(s))
3276 3278
3277 3279 t = ', '.join(t)
3278 3280 cleanworkdir = False
3279 3281
3280 3282 if len(parents) > 1:
3281 3283 t += _(' (merge)')
3282 3284 elif branch != parents[0].branch():
3283 3285 t += _(' (new branch)')
3284 3286 elif (parents[0].extra().get('close') and
3285 3287 pnode in repo.branchheads(branch, closed=True)):
3286 3288 t += _(' (head closed)')
3287 3289 elif (not st[0] and not st[1] and not st[2] and not st[7]):
3288 3290 t += _(' (clean)')
3289 3291 cleanworkdir = True
3290 3292 elif pnode not in bheads:
3291 3293 t += _(' (new branch head)')
3292 3294
3293 3295 if cleanworkdir:
3294 3296 ui.status(_('commit: %s\n') % t.strip())
3295 3297 else:
3296 3298 ui.write(_('commit: %s\n') % t.strip())
3297 3299
3298 3300 # all ancestors of branch heads - all ancestors of parent = new csets
3299 3301 new = [0] * len(repo)
3300 3302 cl = repo.changelog
3301 3303 for a in [cl.rev(n) for n in bheads]:
3302 3304 new[a] = 1
3303 3305 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
3304 3306 new[a] = 1
3305 3307 for a in [p.rev() for p in parents]:
3306 3308 if a >= 0:
3307 3309 new[a] = 0
3308 3310 for a in cl.ancestors(*[p.rev() for p in parents]):
3309 3311 new[a] = 0
3310 3312 new = sum(new)
3311 3313
3312 3314 if new == 0:
3313 3315 ui.status(_('update: (current)\n'))
3314 3316 elif pnode not in bheads:
3315 3317 ui.write(_('update: %d new changesets (update)\n') % new)
3316 3318 else:
3317 3319 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
3318 3320 (new, len(bheads)))
3319 3321
3320 3322 if opts.get('remote'):
3321 3323 t = []
3322 3324 source, branches = hg.parseurl(ui.expandpath('default'))
3323 3325 other = hg.repository(hg.remoteui(repo, {}), source)
3324 3326 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
3325 3327 ui.debug('comparing with %s\n' % url.hidepassword(source))
3326 3328 repo.ui.pushbuffer()
3327 common, incoming, rheads = repo.findcommonincoming(other)
3329 common, incoming, rheads = discovery.findcommonincoming(repo, other)
3328 3330 repo.ui.popbuffer()
3329 3331 if incoming:
3330 3332 t.append(_('1 or more incoming'))
3331 3333
3332 3334 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
3333 3335 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
3334 3336 other = hg.repository(hg.remoteui(repo, {}), dest)
3335 3337 ui.debug('comparing with %s\n' % url.hidepassword(dest))
3336 3338 repo.ui.pushbuffer()
3337 o = repo.findoutgoing(other)
3339 o = discovery.findoutgoing(repo, other)
3338 3340 repo.ui.popbuffer()
3339 3341 o = repo.changelog.nodesbetween(o, None)[0]
3340 3342 if o:
3341 3343 t.append(_('%d outgoing') % len(o))
3342 3344
3343 3345 if t:
3344 3346 ui.write(_('remote: %s\n') % (', '.join(t)))
3345 3347 else:
3346 3348 ui.status(_('remote: (synced)\n'))
3347 3349
3348 3350 def tag(ui, repo, name1, *names, **opts):
3349 3351 """add one or more tags for the current or given revision
3350 3352
3351 3353 Name a particular revision using <name>.
3352 3354
3353 3355 Tags are used to name particular revisions of the repository and are
3354 3356 very useful to compare different revisions, to go back to significant
3355 3357 earlier versions or to mark branch points as releases, etc.
3356 3358
3357 3359 If no revision is given, the parent of the working directory is
3358 3360 used, or tip if no revision is checked out.
3359 3361
3360 3362 To facilitate version control, distribution, and merging of tags,
3361 3363 they are stored as a file named ".hgtags" which is managed
3362 3364 similarly to other project files and can be hand-edited if
3363 3365 necessary. The file '.hg/localtags' is used for local tags (not
3364 3366 shared among repositories).
3365 3367
3366 3368 See :hg:`help dates` for a list of formats valid for -d/--date.
3367 3369
3368 3370 Since tag names have priority over branch names during revision
3369 3371 lookup, using an existing branch name as a tag name is discouraged.
3370 3372
3371 3373 Returns 0 on success.
3372 3374 """
3373 3375
3374 3376 rev_ = "."
3375 3377 names = [t.strip() for t in (name1,) + names]
3376 3378 if len(names) != len(set(names)):
3377 3379 raise util.Abort(_('tag names must be unique'))
3378 3380 for n in names:
3379 3381 if n in ['tip', '.', 'null']:
3380 3382 raise util.Abort(_('the name \'%s\' is reserved') % n)
3381 3383 if opts.get('rev') and opts.get('remove'):
3382 3384 raise util.Abort(_("--rev and --remove are incompatible"))
3383 3385 if opts.get('rev'):
3384 3386 rev_ = opts['rev']
3385 3387 message = opts.get('message')
3386 3388 if opts.get('remove'):
3387 3389 expectedtype = opts.get('local') and 'local' or 'global'
3388 3390 for n in names:
3389 3391 if not repo.tagtype(n):
3390 3392 raise util.Abort(_('tag \'%s\' does not exist') % n)
3391 3393 if repo.tagtype(n) != expectedtype:
3392 3394 if expectedtype == 'global':
3393 3395 raise util.Abort(_('tag \'%s\' is not a global tag') % n)
3394 3396 else:
3395 3397 raise util.Abort(_('tag \'%s\' is not a local tag') % n)
3396 3398 rev_ = nullid
3397 3399 if not message:
3398 3400 # we don't translate commit messages
3399 3401 message = 'Removed tag %s' % ', '.join(names)
3400 3402 elif not opts.get('force'):
3401 3403 for n in names:
3402 3404 if n in repo.tags():
3403 3405 raise util.Abort(_('tag \'%s\' already exists '
3404 3406 '(use -f to force)') % n)
3405 3407 if not rev_ and repo.dirstate.parents()[1] != nullid:
3406 3408 raise util.Abort(_('uncommitted merge - please provide a '
3407 3409 'specific revision'))
3408 3410 r = repo[rev_].node()
3409 3411
3410 3412 if not message:
3411 3413 # we don't translate commit messages
3412 3414 message = ('Added tag %s for changeset %s' %
3413 3415 (', '.join(names), short(r)))
3414 3416
3415 3417 date = opts.get('date')
3416 3418 if date:
3417 3419 date = util.parsedate(date)
3418 3420
3419 3421 if opts.get('edit'):
3420 3422 message = ui.edit(message, ui.username())
3421 3423
3422 3424 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
3423 3425
3424 3426 def tags(ui, repo):
3425 3427 """list repository tags
3426 3428
3427 3429 This lists both regular and local tags. When the -v/--verbose
3428 3430 switch is used, a third column "local" is printed for local tags.
3429 3431
3430 3432 Returns 0 on success.
3431 3433 """
3432 3434
3433 3435 hexfunc = ui.debugflag and hex or short
3434 3436 tagtype = ""
3435 3437
3436 3438 for t, n in reversed(repo.tagslist()):
3437 3439 if ui.quiet:
3438 3440 ui.write("%s\n" % t)
3439 3441 continue
3440 3442
3441 3443 try:
3442 3444 hn = hexfunc(n)
3443 3445 r = "%5d:%s" % (repo.changelog.rev(n), hn)
3444 3446 except error.LookupError:
3445 3447 r = " ?:%s" % hn
3446 3448 else:
3447 3449 spaces = " " * (30 - encoding.colwidth(t))
3448 3450 if ui.verbose:
3449 3451 if repo.tagtype(t) == 'local':
3450 3452 tagtype = " local"
3451 3453 else:
3452 3454 tagtype = ""
3453 3455 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
3454 3456
3455 3457 def tip(ui, repo, **opts):
3456 3458 """show the tip revision
3457 3459
3458 3460 The tip revision (usually just called the tip) is the changeset
3459 3461 most recently added to the repository (and therefore the most
3460 3462 recently changed head).
3461 3463
3462 3464 If you have just made a commit, that commit will be the tip. If
3463 3465 you have just pulled changes from another repository, the tip of
3464 3466 that repository becomes the current tip. The "tip" tag is special
3465 3467 and cannot be renamed or assigned to a different changeset.
3466 3468
3467 3469 Returns 0 on success.
3468 3470 """
3469 3471 displayer = cmdutil.show_changeset(ui, repo, opts)
3470 3472 displayer.show(repo[len(repo) - 1])
3471 3473 displayer.close()
3472 3474
3473 3475 def unbundle(ui, repo, fname1, *fnames, **opts):
3474 3476 """apply one or more changegroup files
3475 3477
3476 3478 Apply one or more compressed changegroup files generated by the
3477 3479 bundle command.
3478 3480
3479 3481 Returns 0 on success, 1 if an update has unresolved files.
3480 3482 """
3481 3483 fnames = (fname1,) + fnames
3482 3484
3483 3485 lock = repo.lock()
3484 3486 try:
3485 3487 for fname in fnames:
3486 3488 f = url.open(ui, fname)
3487 3489 gen = changegroup.readbundle(f, fname)
3488 3490 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
3489 3491 finally:
3490 3492 lock.release()
3491 3493
3492 3494 return postincoming(ui, repo, modheads, opts.get('update'), None)
3493 3495
3494 3496 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
3495 3497 """update working directory (or switch revisions)
3496 3498
3497 3499 Update the repository's working directory to the specified
3498 3500 changeset.
3499 3501
3500 3502 If no changeset is specified, attempt to update to the head of the
3501 3503 current branch. If this head is a descendant of the working
3502 3504 directory's parent, update to it, otherwise abort.
3503 3505
3504 3506 The following rules apply when the working directory contains
3505 3507 uncommitted changes:
3506 3508
3507 3509 1. If neither -c/--check nor -C/--clean is specified, and if
3508 3510 the requested changeset is an ancestor or descendant of
3509 3511 the working directory's parent, the uncommitted changes
3510 3512 are merged into the requested changeset and the merged
3511 3513 result is left uncommitted. If the requested changeset is
3512 3514 not an ancestor or descendant (that is, it is on another
3513 3515 branch), the update is aborted and the uncommitted changes
3514 3516 are preserved.
3515 3517
3516 3518 2. With the -c/--check option, the update is aborted and the
3517 3519 uncommitted changes are preserved.
3518 3520
3519 3521 3. With the -C/--clean option, uncommitted changes are discarded and
3520 3522 the working directory is updated to the requested changeset.
3521 3523
3522 3524 Use null as the changeset to remove the working directory (like
3523 3525 :hg:`clone -U`).
3524 3526
3525 3527 If you want to update just one file to an older changeset, use :hg:`revert`.
3526 3528
3527 3529 See :hg:`help dates` for a list of formats valid for -d/--date.
3528 3530
3529 3531 Returns 0 on success, 1 if there are unresolved files.
3530 3532 """
3531 3533 if rev and node:
3532 3534 raise util.Abort(_("please specify just one revision"))
3533 3535
3534 3536 if not rev:
3535 3537 rev = node
3536 3538
3537 3539 if check and clean:
3538 3540 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
3539 3541
3540 3542 if check:
3541 3543 # we could use dirty() but we can ignore merge and branch trivia
3542 3544 c = repo[None]
3543 3545 if c.modified() or c.added() or c.removed():
3544 3546 raise util.Abort(_("uncommitted local changes"))
3545 3547
3546 3548 if date:
3547 3549 if rev:
3548 3550 raise util.Abort(_("you can't specify a revision and a date"))
3549 3551 rev = cmdutil.finddate(ui, repo, date)
3550 3552
3551 3553 if clean or check:
3552 3554 return hg.clean(repo, rev)
3553 3555 else:
3554 3556 return hg.update(repo, rev)
3555 3557
3556 3558 def verify(ui, repo):
3557 3559 """verify the integrity of the repository
3558 3560
3559 3561 Verify the integrity of the current repository.
3560 3562
3561 3563 This will perform an extensive check of the repository's
3562 3564 integrity, validating the hashes and checksums of each entry in
3563 3565 the changelog, manifest, and tracked files, as well as the
3564 3566 integrity of their crosslinks and indices.
3565 3567
3566 3568 Returns 0 on success, 1 if errors are encountered.
3567 3569 """
3568 3570 return hg.verify(repo)
3569 3571
3570 3572 def version_(ui):
3571 3573 """output version and copyright information"""
3572 3574 ui.write(_("Mercurial Distributed SCM (version %s)\n")
3573 3575 % util.version())
3574 3576 ui.status(_(
3575 3577 "\nCopyright (C) 2005-2010 Matt Mackall <mpm@selenic.com> and others\n"
3576 3578 "This is free software; see the source for copying conditions. "
3577 3579 "There is NO\nwarranty; "
3578 3580 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
3579 3581 ))
3580 3582
3581 3583 # Command options and aliases are listed here, alphabetically
3582 3584
3583 3585 globalopts = [
3584 3586 ('R', 'repository', '',
3585 3587 _('repository root directory or name of overlay bundle file')),
3586 3588 ('', 'cwd', '', _('change working directory')),
3587 3589 ('y', 'noninteractive', None,
3588 3590 _('do not prompt, assume \'yes\' for any required answers')),
3589 3591 ('q', 'quiet', None, _('suppress output')),
3590 3592 ('v', 'verbose', None, _('enable additional output')),
3591 3593 ('', 'config', [],
3592 3594 _('set/override config option (use \'section.name=value\')')),
3593 3595 ('', 'debug', None, _('enable debugging output')),
3594 3596 ('', 'debugger', None, _('start debugger')),
3595 3597 ('', 'encoding', encoding.encoding, _('set the charset encoding')),
3596 3598 ('', 'encodingmode', encoding.encodingmode,
3597 3599 _('set the charset encoding mode')),
3598 3600 ('', 'traceback', None, _('always print a traceback on exception')),
3599 3601 ('', 'time', None, _('time how long the command takes')),
3600 3602 ('', 'profile', None, _('print command execution profile')),
3601 3603 ('', 'version', None, _('output version information and exit')),
3602 3604 ('h', 'help', None, _('display help and exit')),
3603 3605 ]
3604 3606
3605 3607 dryrunopts = [('n', 'dry-run', None,
3606 3608 _('do not perform actions, just print output'))]
3607 3609
3608 3610 remoteopts = [
3609 3611 ('e', 'ssh', '', _('specify ssh command to use')),
3610 3612 ('', 'remotecmd', '', _('specify hg command to run on the remote side')),
3611 3613 ]
3612 3614
3613 3615 walkopts = [
3614 3616 ('I', 'include', [], _('include names matching the given patterns')),
3615 3617 ('X', 'exclude', [], _('exclude names matching the given patterns')),
3616 3618 ]
3617 3619
3618 3620 commitopts = [
3619 3621 ('m', 'message', '', _('use <text> as commit message')),
3620 3622 ('l', 'logfile', '', _('read commit message from <file>')),
3621 3623 ]
3622 3624
3623 3625 commitopts2 = [
3624 3626 ('d', 'date', '', _('record datecode as commit date')),
3625 3627 ('u', 'user', '', _('record the specified user as committer')),
3626 3628 ]
3627 3629
3628 3630 templateopts = [
3629 3631 ('', 'style', '', _('display using template map file')),
3630 3632 ('', 'template', '', _('display with template')),
3631 3633 ]
3632 3634
3633 3635 logopts = [
3634 3636 ('p', 'patch', None, _('show patch')),
3635 3637 ('g', 'git', None, _('use git extended diff format')),
3636 3638 ('l', 'limit', '', _('limit number of changes displayed')),
3637 3639 ('M', 'no-merges', None, _('do not show merges')),
3638 3640 ('', 'stat', None, _('output diffstat-style summary of changes')),
3639 3641 ] + templateopts
3640 3642
3641 3643 diffopts = [
3642 3644 ('a', 'text', None, _('treat all files as text')),
3643 3645 ('g', 'git', None, _('use git extended diff format')),
3644 3646 ('', 'nodates', None, _('omit dates from diff headers'))
3645 3647 ]
3646 3648
3647 3649 diffopts2 = [
3648 3650 ('p', 'show-function', None, _('show which function each change is in')),
3649 3651 ('', 'reverse', None, _('produce a diff that undoes the changes')),
3650 3652 ('w', 'ignore-all-space', None,
3651 3653 _('ignore white space when comparing lines')),
3652 3654 ('b', 'ignore-space-change', None,
3653 3655 _('ignore changes in the amount of white space')),
3654 3656 ('B', 'ignore-blank-lines', None,
3655 3657 _('ignore changes whose lines are all blank')),
3656 3658 ('U', 'unified', '', _('number of lines of context to show')),
3657 3659 ('', 'stat', None, _('output diffstat-style summary of changes')),
3658 3660 ]
3659 3661
3660 3662 similarityopts = [
3661 3663 ('s', 'similarity', '',
3662 3664 _('guess renamed files by similarity (0<=s<=100)'))
3663 3665 ]
3664 3666
3665 3667 table = {
3666 3668 "^add": (add, walkopts + dryrunopts, _('[OPTION]... [FILE]...')),
3667 3669 "addremove":
3668 3670 (addremove, similarityopts + walkopts + dryrunopts,
3669 3671 _('[OPTION]... [FILE]...')),
3670 3672 "^annotate|blame":
3671 3673 (annotate,
3672 3674 [('r', 'rev', '', _('annotate the specified revision')),
3673 3675 ('', 'follow', None,
3674 3676 _('follow copies/renames and list the filename (DEPRECATED)')),
3675 3677 ('', 'no-follow', None, _("don't follow copies and renames")),
3676 3678 ('a', 'text', None, _('treat all files as text')),
3677 3679 ('u', 'user', None, _('list the author (long with -v)')),
3678 3680 ('f', 'file', None, _('list the filename')),
3679 3681 ('d', 'date', None, _('list the date (short with -q)')),
3680 3682 ('n', 'number', None, _('list the revision number (default)')),
3681 3683 ('c', 'changeset', None, _('list the changeset')),
3682 3684 ('l', 'line-number', None,
3683 3685 _('show line number at the first appearance'))
3684 3686 ] + walkopts,
3685 3687 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...')),
3686 3688 "archive":
3687 3689 (archive,
3688 3690 [('', 'no-decode', None, _('do not pass files through decoders')),
3689 3691 ('p', 'prefix', '', _('directory prefix for files in archive')),
3690 3692 ('r', 'rev', '', _('revision to distribute')),
3691 3693 ('t', 'type', '', _('type of distribution to create')),
3692 3694 ] + walkopts,
3693 3695 _('[OPTION]... DEST')),
3694 3696 "backout":
3695 3697 (backout,
3696 3698 [('', 'merge', None,
3697 3699 _('merge with old dirstate parent after backout')),
3698 3700 ('', 'parent', '', _('parent to choose when backing out merge')),
3699 3701 ('r', 'rev', '', _('revision to backout')),
3700 3702 ] + walkopts + commitopts + commitopts2,
3701 3703 _('[OPTION]... [-r] REV')),
3702 3704 "bisect":
3703 3705 (bisect,
3704 3706 [('r', 'reset', False, _('reset bisect state')),
3705 3707 ('g', 'good', False, _('mark changeset good')),
3706 3708 ('b', 'bad', False, _('mark changeset bad')),
3707 3709 ('s', 'skip', False, _('skip testing changeset')),
3708 3710 ('c', 'command', '', _('use command to check changeset state')),
3709 3711 ('U', 'noupdate', False, _('do not update to target'))],
3710 3712 _("[-gbsr] [-U] [-c CMD] [REV]")),
3711 3713 "branch":
3712 3714 (branch,
3713 3715 [('f', 'force', None,
3714 3716 _('set branch name even if it shadows an existing branch')),
3715 3717 ('C', 'clean', None, _('reset branch name to parent branch name'))],
3716 3718 _('[-fC] [NAME]')),
3717 3719 "branches":
3718 3720 (branches,
3719 3721 [('a', 'active', False,
3720 3722 _('show only branches that have unmerged heads')),
3721 3723 ('c', 'closed', False,
3722 3724 _('show normal and closed branches'))],
3723 3725 _('[-ac]')),
3724 3726 "bundle":
3725 3727 (bundle,
3726 3728 [('f', 'force', None,
3727 3729 _('run even when the destination is unrelated')),
3728 3730 ('r', 'rev', [],
3729 3731 _('a changeset intended to be added to the destination')),
3730 3732 ('b', 'branch', [],
3731 3733 _('a specific branch you would like to bundle')),
3732 3734 ('', 'base', [],
3733 3735 _('a base changeset assumed to be available at the destination')),
3734 3736 ('a', 'all', None, _('bundle all changesets in the repository')),
3735 3737 ('t', 'type', 'bzip2', _('bundle compression type to use')),
3736 3738 ] + remoteopts,
3737 3739 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]')),
3738 3740 "cat":
3739 3741 (cat,
3740 3742 [('o', 'output', '', _('print output to file with formatted name')),
3741 3743 ('r', 'rev', '', _('print the given revision')),
3742 3744 ('', 'decode', None, _('apply any matching decode filter')),
3743 3745 ] + walkopts,
3744 3746 _('[OPTION]... FILE...')),
3745 3747 "^clone":
3746 3748 (clone,
3747 3749 [('U', 'noupdate', None,
3748 3750 _('the clone will include an empty working copy (only a repository)')),
3749 3751 ('u', 'updaterev', '',
3750 3752 _('revision, tag or branch to check out')),
3751 3753 ('r', 'rev', [],
3752 3754 _('include the specified changeset')),
3753 3755 ('b', 'branch', [],
3754 3756 _('clone only the specified branch')),
3755 3757 ('', 'pull', None, _('use pull protocol to copy metadata')),
3756 3758 ('', 'uncompressed', None,
3757 3759 _('use uncompressed transfer (fast over LAN)')),
3758 3760 ] + remoteopts,
3759 3761 _('[OPTION]... SOURCE [DEST]')),
3760 3762 "^commit|ci":
3761 3763 (commit,
3762 3764 [('A', 'addremove', None,
3763 3765 _('mark new/missing files as added/removed before committing')),
3764 3766 ('', 'close-branch', None,
3765 3767 _('mark a branch as closed, hiding it from the branch list')),
3766 3768 ] + walkopts + commitopts + commitopts2,
3767 3769 _('[OPTION]... [FILE]...')),
3768 3770 "copy|cp":
3769 3771 (copy,
3770 3772 [('A', 'after', None, _('record a copy that has already occurred')),
3771 3773 ('f', 'force', None,
3772 3774 _('forcibly copy over an existing managed file')),
3773 3775 ] + walkopts + dryrunopts,
3774 3776 _('[OPTION]... [SOURCE]... DEST')),
3775 3777 "debugancestor": (debugancestor, [], _('[INDEX] REV1 REV2')),
3776 3778 "debugcheckstate": (debugcheckstate, [], ''),
3777 3779 "debugcommands": (debugcommands, [], _('[COMMAND]')),
3778 3780 "debugcomplete":
3779 3781 (debugcomplete,
3780 3782 [('o', 'options', None, _('show the command options'))],
3781 3783 _('[-o] CMD')),
3782 3784 "debugdate":
3783 3785 (debugdate,
3784 3786 [('e', 'extended', None, _('try extended date formats'))],
3785 3787 _('[-e] DATE [RANGE]')),
3786 3788 "debugdata": (debugdata, [], _('FILE REV')),
3787 3789 "debugfsinfo": (debugfsinfo, [], _('[PATH]')),
3788 3790 "debugindex": (debugindex, [], _('FILE')),
3789 3791 "debugindexdot": (debugindexdot, [], _('FILE')),
3790 3792 "debuginstall": (debuginstall, [], ''),
3791 3793 "debugrebuildstate":
3792 3794 (debugrebuildstate,
3793 3795 [('r', 'rev', '', _('revision to rebuild to'))],
3794 3796 _('[-r REV] [REV]')),
3795 3797 "debugrename":
3796 3798 (debugrename,
3797 3799 [('r', 'rev', '', _('revision to debug'))],
3798 3800 _('[-r REV] FILE')),
3799 3801 "debugrevspec":
3800 3802 (debugrevspec, [], ('REVSPEC')),
3801 3803 "debugsetparents":
3802 3804 (debugsetparents, [], _('REV1 [REV2]')),
3803 3805 "debugstate":
3804 3806 (debugstate,
3805 3807 [('', 'nodates', None, _('do not display the saved mtime'))],
3806 3808 _('[OPTION]...')),
3807 3809 "debugsub":
3808 3810 (debugsub,
3809 3811 [('r', 'rev', '', _('revision to check'))],
3810 3812 _('[-r REV] [REV]')),
3811 3813 "debugwalk": (debugwalk, walkopts, _('[OPTION]... [FILE]...')),
3812 3814 "^diff":
3813 3815 (diff,
3814 3816 [('r', 'rev', [], _('revision')),
3815 3817 ('c', 'change', '', _('change made by revision'))
3816 3818 ] + diffopts + diffopts2 + walkopts,
3817 3819 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...')),
3818 3820 "^export":
3819 3821 (export,
3820 3822 [('o', 'output', '', _('print output to file with formatted name')),
3821 3823 ('', 'switch-parent', None, _('diff against the second parent')),
3822 3824 ('r', 'rev', [], _('revisions to export')),
3823 3825 ] + diffopts,
3824 3826 _('[OPTION]... [-o OUTFILESPEC] REV...')),
3825 3827 "^forget":
3826 3828 (forget,
3827 3829 [] + walkopts,
3828 3830 _('[OPTION]... FILE...')),
3829 3831 "grep":
3830 3832 (grep,
3831 3833 [('0', 'print0', None, _('end fields with NUL')),
3832 3834 ('', 'all', None, _('print all revisions that match')),
3833 3835 ('f', 'follow', None,
3834 3836 _('follow changeset history,'
3835 3837 ' or file history across copies and renames')),
3836 3838 ('i', 'ignore-case', None, _('ignore case when matching')),
3837 3839 ('l', 'files-with-matches', None,
3838 3840 _('print only filenames and revisions that match')),
3839 3841 ('n', 'line-number', None, _('print matching line numbers')),
3840 3842 ('r', 'rev', [], _('only search files changed within revision range')),
3841 3843 ('u', 'user', None, _('list the author (long with -v)')),
3842 3844 ('d', 'date', None, _('list the date (short with -q)')),
3843 3845 ] + walkopts,
3844 3846 _('[OPTION]... PATTERN [FILE]...')),
3845 3847 "heads":
3846 3848 (heads,
3847 3849 [('r', 'rev', '', _('show only heads which are descendants of REV')),
3848 3850 ('t', 'topo', False, _('show topological heads only')),
3849 3851 ('a', 'active', False,
3850 3852 _('show active branchheads only [DEPRECATED]')),
3851 3853 ('c', 'closed', False,
3852 3854 _('show normal and closed branch heads')),
3853 3855 ] + templateopts,
3854 3856 _('[-ac] [-r REV] [REV]...')),
3855 3857 "help": (help_, [], _('[TOPIC]')),
3856 3858 "identify|id":
3857 3859 (identify,
3858 3860 [('r', 'rev', '', _('identify the specified revision')),
3859 3861 ('n', 'num', None, _('show local revision number')),
3860 3862 ('i', 'id', None, _('show global revision id')),
3861 3863 ('b', 'branch', None, _('show branch')),
3862 3864 ('t', 'tags', None, _('show tags'))],
3863 3865 _('[-nibt] [-r REV] [SOURCE]')),
3864 3866 "import|patch":
3865 3867 (import_,
3866 3868 [('p', 'strip', 1,
3867 3869 _('directory strip option for patch. This has the same '
3868 3870 'meaning as the corresponding patch option')),
3869 3871 ('b', 'base', '', _('base path')),
3870 3872 ('f', 'force', None,
3871 3873 _('skip check for outstanding uncommitted changes')),
3872 3874 ('', 'no-commit', None,
3873 3875 _("don't commit, just update the working directory")),
3874 3876 ('', 'exact', None,
3875 3877 _('apply patch to the nodes from which it was generated')),
3876 3878 ('', 'import-branch', None,
3877 3879 _('use any branch information in patch (implied by --exact)'))] +
3878 3880 commitopts + commitopts2 + similarityopts,
3879 3881 _('[OPTION]... PATCH...')),
3880 3882 "incoming|in":
3881 3883 (incoming,
3882 3884 [('f', 'force', None,
3883 3885 _('run even if remote repository is unrelated')),
3884 3886 ('n', 'newest-first', None, _('show newest record first')),
3885 3887 ('', 'bundle', '', _('file to store the bundles into')),
3886 3888 ('r', 'rev', [],
3887 3889 _('a remote changeset intended to be added')),
3888 3890 ('b', 'branch', [],
3889 3891 _('a specific branch you would like to pull')),
3890 3892 ] + logopts + remoteopts,
3891 3893 _('[-p] [-n] [-M] [-f] [-r REV]...'
3892 3894 ' [--bundle FILENAME] [SOURCE]')),
3893 3895 "^init":
3894 3896 (init,
3895 3897 remoteopts,
3896 3898 _('[-e CMD] [--remotecmd CMD] [DEST]')),
3897 3899 "locate":
3898 3900 (locate,
3899 3901 [('r', 'rev', '', _('search the repository as it is in REV')),
3900 3902 ('0', 'print0', None,
3901 3903 _('end filenames with NUL, for use with xargs')),
3902 3904 ('f', 'fullpath', None,
3903 3905 _('print complete paths from the filesystem root')),
3904 3906 ] + walkopts,
3905 3907 _('[OPTION]... [PATTERN]...')),
3906 3908 "^log|history":
3907 3909 (log,
3908 3910 [('f', 'follow', None,
3909 3911 _('follow changeset history,'
3910 3912 ' or file history across copies and renames')),
3911 3913 ('', 'follow-first', None,
3912 3914 _('only follow the first parent of merge changesets')),
3913 3915 ('d', 'date', '', _('show revisions matching date spec')),
3914 3916 ('C', 'copies', None, _('show copied files')),
3915 3917 ('k', 'keyword', [], _('do case-insensitive search for a keyword')),
3916 3918 ('r', 'rev', [], _('show the specified revision or range')),
3917 3919 ('', 'removed', None, _('include revisions where files were removed')),
3918 3920 ('m', 'only-merges', None, _('show only merges')),
3919 3921 ('u', 'user', [], _('revisions committed by user')),
3920 3922 ('', 'only-branch', [],
3921 3923 _('show only changesets within the given named branch (DEPRECATED)')),
3922 3924 ('b', 'branch', [],
3923 3925 _('show changesets within the given named branch')),
3924 3926 ('P', 'prune', [],
3925 3927 _('do not display revision or any of its ancestors')),
3926 3928 ] + logopts + walkopts,
3927 3929 _('[OPTION]... [FILE]')),
3928 3930 "manifest":
3929 3931 (manifest,
3930 3932 [('r', 'rev', '', _('revision to display'))],
3931 3933 _('[-r REV]')),
3932 3934 "^merge":
3933 3935 (merge,
3934 3936 [('f', 'force', None, _('force a merge with outstanding changes')),
3935 3937 ('r', 'rev', '', _('revision to merge')),
3936 3938 ('P', 'preview', None,
3937 3939 _('review revisions to merge (no merge is performed)'))],
3938 3940 _('[-P] [-f] [[-r] REV]')),
3939 3941 "outgoing|out":
3940 3942 (outgoing,
3941 3943 [('f', 'force', None,
3942 3944 _('run even when the destination is unrelated')),
3943 3945 ('r', 'rev', [],
3944 3946 _('a changeset intended to be included in the destination')),
3945 3947 ('n', 'newest-first', None, _('show newest record first')),
3946 3948 ('b', 'branch', [],
3947 3949 _('a specific branch you would like to push')),
3948 3950 ] + logopts + remoteopts,
3949 3951 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]')),
3950 3952 "parents":
3951 3953 (parents,
3952 3954 [('r', 'rev', '', _('show parents of the specified revision')),
3953 3955 ] + templateopts,
3954 3956 _('[-r REV] [FILE]')),
3955 3957 "paths": (paths, [], _('[NAME]')),
3956 3958 "^pull":
3957 3959 (pull,
3958 3960 [('u', 'update', None,
3959 3961 _('update to new branch head if changesets were pulled')),
3960 3962 ('f', 'force', None,
3961 3963 _('run even when remote repository is unrelated')),
3962 3964 ('r', 'rev', [],
3963 3965 _('a remote changeset intended to be added')),
3964 3966 ('b', 'branch', [],
3965 3967 _('a specific branch you would like to pull')),
3966 3968 ] + remoteopts,
3967 3969 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]')),
3968 3970 "^push":
3969 3971 (push,
3970 3972 [('f', 'force', None, _('force push')),
3971 3973 ('r', 'rev', [],
3972 3974 _('a changeset intended to be included in the destination')),
3973 3975 ('b', 'branch', [],
3974 3976 _('a specific branch you would like to push')),
3975 3977 ('', 'new-branch', False, _('allow pushing a new branch')),
3976 3978 ] + remoteopts,
3977 3979 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]')),
3978 3980 "recover": (recover, []),
3979 3981 "^remove|rm":
3980 3982 (remove,
3981 3983 [('A', 'after', None, _('record delete for missing files')),
3982 3984 ('f', 'force', None,
3983 3985 _('remove (and delete) file even if added or modified')),
3984 3986 ] + walkopts,
3985 3987 _('[OPTION]... FILE...')),
3986 3988 "rename|mv":
3987 3989 (rename,
3988 3990 [('A', 'after', None, _('record a rename that has already occurred')),
3989 3991 ('f', 'force', None,
3990 3992 _('forcibly copy over an existing managed file')),
3991 3993 ] + walkopts + dryrunopts,
3992 3994 _('[OPTION]... SOURCE... DEST')),
3993 3995 "resolve":
3994 3996 (resolve,
3995 3997 [('a', 'all', None, _('select all unresolved files')),
3996 3998 ('l', 'list', None, _('list state of files needing merge')),
3997 3999 ('m', 'mark', None, _('mark files as resolved')),
3998 4000 ('u', 'unmark', None, _('unmark files as resolved')),
3999 4001 ('n', 'no-status', None, _('hide status prefix'))]
4000 4002 + walkopts,
4001 4003 _('[OPTION]... [FILE]...')),
4002 4004 "revert":
4003 4005 (revert,
4004 4006 [('a', 'all', None, _('revert all changes when no arguments given')),
4005 4007 ('d', 'date', '', _('tipmost revision matching date')),
4006 4008 ('r', 'rev', '', _('revert to the specified revision')),
4007 4009 ('', 'no-backup', None, _('do not save backup copies of files')),
4008 4010 ] + walkopts + dryrunopts,
4009 4011 _('[OPTION]... [-r REV] [NAME]...')),
4010 4012 "rollback": (rollback, dryrunopts),
4011 4013 "root": (root, []),
4012 4014 "^serve":
4013 4015 (serve,
4014 4016 [('A', 'accesslog', '', _('name of access log file to write to')),
4015 4017 ('d', 'daemon', None, _('run server in background')),
4016 4018 ('', 'daemon-pipefds', '', _('used internally by daemon mode')),
4017 4019 ('E', 'errorlog', '', _('name of error log file to write to')),
4018 4020 # use string type, then we can check if something was passed
4019 4021 ('p', 'port', '', _('port to listen on (default: 8000)')),
4020 4022 ('a', 'address', '',
4021 4023 _('address to listen on (default: all interfaces)')),
4022 4024 ('', 'prefix', '',
4023 4025 _('prefix path to serve from (default: server root)')),
4024 4026 ('n', 'name', '',
4025 4027 _('name to show in web pages (default: working directory)')),
4026 4028 ('', 'web-conf', '', _('name of the hgweb config file'
4027 4029 ' (serve more than one repository)')),
4028 4030 ('', 'webdir-conf', '', _('name of the hgweb config file'
4029 4031 ' (DEPRECATED)')),
4030 4032 ('', 'pid-file', '', _('name of file to write process ID to')),
4031 4033 ('', 'stdio', None, _('for remote clients')),
4032 4034 ('t', 'templates', '', _('web templates to use')),
4033 4035 ('', 'style', '', _('template style to use')),
4034 4036 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4035 4037 ('', 'certificate', '', _('SSL certificate file'))],
4036 4038 _('[OPTION]...')),
4037 4039 "showconfig|debugconfig":
4038 4040 (showconfig,
4039 4041 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4040 4042 _('[-u] [NAME]...')),
4041 4043 "^summary|sum":
4042 4044 (summary,
4043 4045 [('', 'remote', None, _('check for push and pull'))], '[--remote]'),
4044 4046 "^status|st":
4045 4047 (status,
4046 4048 [('A', 'all', None, _('show status of all files')),
4047 4049 ('m', 'modified', None, _('show only modified files')),
4048 4050 ('a', 'added', None, _('show only added files')),
4049 4051 ('r', 'removed', None, _('show only removed files')),
4050 4052 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4051 4053 ('c', 'clean', None, _('show only files without changes')),
4052 4054 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4053 4055 ('i', 'ignored', None, _('show only ignored files')),
4054 4056 ('n', 'no-status', None, _('hide status prefix')),
4055 4057 ('C', 'copies', None, _('show source of copied files')),
4056 4058 ('0', 'print0', None,
4057 4059 _('end filenames with NUL, for use with xargs')),
4058 4060 ('', 'rev', [], _('show difference from revision')),
4059 4061 ('', 'change', '', _('list the changed files of a revision')),
4060 4062 ] + walkopts,
4061 4063 _('[OPTION]... [FILE]...')),
4062 4064 "tag":
4063 4065 (tag,
4064 4066 [('f', 'force', None, _('replace existing tag')),
4065 4067 ('l', 'local', None, _('make the tag local')),
4066 4068 ('r', 'rev', '', _('revision to tag')),
4067 4069 ('', 'remove', None, _('remove a tag')),
4068 4070 # -l/--local is already there, commitopts cannot be used
4069 4071 ('e', 'edit', None, _('edit commit message')),
4070 4072 ('m', 'message', '', _('use <text> as commit message')),
4071 4073 ] + commitopts2,
4072 4074 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...')),
4073 4075 "tags": (tags, [], ''),
4074 4076 "tip":
4075 4077 (tip,
4076 4078 [('p', 'patch', None, _('show patch')),
4077 4079 ('g', 'git', None, _('use git extended diff format')),
4078 4080 ] + templateopts,
4079 4081 _('[-p] [-g]')),
4080 4082 "unbundle":
4081 4083 (unbundle,
4082 4084 [('u', 'update', None,
4083 4085 _('update to new branch head if changesets were unbundled'))],
4084 4086 _('[-u] FILE...')),
4085 4087 "^update|up|checkout|co":
4086 4088 (update,
4087 4089 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
4088 4090 ('c', 'check', None, _('check for uncommitted changes')),
4089 4091 ('d', 'date', '', _('tipmost revision matching date')),
4090 4092 ('r', 'rev', '', _('revision'))],
4091 4093 _('[-c] [-C] [-d DATE] [[-r] REV]')),
4092 4094 "verify": (verify, []),
4093 4095 "version": (version_, []),
4094 4096 }
4095 4097
4096 4098 norepo = ("clone init version help debugcommands debugcomplete debugdata"
4097 4099 " debugindex debugindexdot debugdate debuginstall debugfsinfo")
4098 4100 optionalrepo = ("identify paths serve showconfig debugancestor")
This diff has been collapsed as it changes many lines, (2537 lines changed) Show them Hide them
@@ -1,2297 +1,350
1 1 # localrepo.py - read/write repository class for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 from node import bin, hex, nullid, nullrev, short
8 from node import nullid, short
9 9 from i18n import _
10 import repo, changegroup, subrepo
11 import changelog, dirstate, filelog, manifest, context
12 import lock, transaction, store, encoding
13 import util, extensions, hook, error
14 import match as matchmod
15 import merge as mergemod
16 import tags as tagsmod
17 import url as urlmod
18 from lock import release
19 import weakref, stat, errno, os, time, inspect
20 propertycache = util.propertycache
10 import util, error
21 11
22 class localrepository(repo.repository):
23 capabilities = set(('lookup', 'changegroupsubset', 'branchmap'))
24 supported = set('revlogv1 store fncache shared'.split())
25
26 def __init__(self, baseui, path=None, create=0):
27 repo.repository.__init__(self)
28 self.root = os.path.realpath(util.expandpath(path))
29 self.path = os.path.join(self.root, ".hg")
30 self.origroot = path
31 self.opener = util.opener(self.path)
32 self.wopener = util.opener(self.root)
33 self.baseui = baseui
34 self.ui = baseui.copy()
35
36 try:
37 self.ui.readconfig(self.join("hgrc"), self.root)
38 extensions.loadall(self.ui)
39 except IOError:
40 pass
12 def findincoming(repo, remote, base=None, heads=None, force=False):
13 """Return list of roots of the subsets of missing nodes from remote
41 14
42 if not os.path.isdir(self.path):
43 if create:
44 if not os.path.exists(path):
45 os.mkdir(path)
46 os.mkdir(self.path)
47 requirements = ["revlogv1"]
48 if self.ui.configbool('format', 'usestore', True):
49 os.mkdir(os.path.join(self.path, "store"))
50 requirements.append("store")
51 if self.ui.configbool('format', 'usefncache', True):
52 requirements.append("fncache")
53 # create an invalid changelog
54 self.opener("00changelog.i", "a").write(
55 '\0\0\0\2' # represents revlogv2
56 ' dummy changelog to prevent using the old repo layout'
57 )
58 reqfile = self.opener("requires", "w")
59 for r in requirements:
60 reqfile.write("%s\n" % r)
61 reqfile.close()
62 else:
63 raise error.RepoError(_("repository %s not found") % path)
64 elif create:
65 raise error.RepoError(_("repository %s already exists") % path)
66 else:
67 # find requirements
68 requirements = set()
69 try:
70 requirements = set(self.opener("requires").read().splitlines())
71 except IOError, inst:
72 if inst.errno != errno.ENOENT:
73 raise
74 for r in requirements - self.supported:
75 raise error.RepoError(_("requirement '%s' not supported") % r)
76
77 self.sharedpath = self.path
78 try:
79 s = os.path.realpath(self.opener("sharedpath").read())
80 if not os.path.exists(s):
81 raise error.RepoError(
82 _('.hg/sharedpath points to nonexistent directory %s') % s)
83 self.sharedpath = s
84 except IOError, inst:
85 if inst.errno != errno.ENOENT:
86 raise
87
88 self.store = store.store(requirements, self.sharedpath, util.opener)
89 self.spath = self.store.path
90 self.sopener = self.store.opener
91 self.sjoin = self.store.join
92 self.opener.createmode = self.store.createmode
93 self.sopener.options = {}
94
95 # These two define the set of tags for this repository. _tags
96 # maps tag name to node; _tagtypes maps tag name to 'global' or
97 # 'local'. (Global tags are defined by .hgtags across all
98 # heads, and local tags are defined in .hg/localtags.) They
99 # constitute the in-memory cache of tags.
100 self._tags = None
101 self._tagtypes = None
102
103 self._branchcache = None # in UTF-8
104 self._branchcachetip = None
105 self.nodetagscache = None
106 self.filterpats = {}
107 self._datafilters = {}
108 self._transref = self._lockref = self._wlockref = None
109
110 @propertycache
111 def changelog(self):
112 c = changelog.changelog(self.sopener)
113 if 'HG_PENDING' in os.environ:
114 p = os.environ['HG_PENDING']
115 if p.startswith(self.root):
116 c.readpending('00changelog.i.a')
117 self.sopener.options['defversion'] = c.version
118 return c
119
120 @propertycache
121 def manifest(self):
122 return manifest.manifest(self.sopener)
123
124 @propertycache
125 def dirstate(self):
126 return dirstate.dirstate(self.opener, self.ui, self.root)
127
128 def __getitem__(self, changeid):
129 if changeid is None:
130 return context.workingctx(self)
131 return context.changectx(self, changeid)
132
133 def __contains__(self, changeid):
134 try:
135 return bool(self.lookup(changeid))
136 except error.RepoLookupError:
137 return False
138
139 def __nonzero__(self):
140 return True
15 If base dict is specified, assume that these nodes and their parents
16 exist on the remote side and that no child of a node of base exists
17 in both remote and repo.
18 Furthermore base will be updated to include the nodes that exists
19 in repo and remote but no children exists in repo and remote.
20 If a list of heads is specified, return only nodes which are heads
21 or ancestors of these heads.
141 22
142 def __len__(self):
143 return len(self.changelog)
144
145 def __iter__(self):
146 for i in xrange(len(self)):
147 yield i
148
149 def url(self):
150 return 'file:' + self.root
151
152 def hook(self, name, throw=False, **args):
153 return hook.hook(self.ui, self, name, throw, **args)
154
155 tag_disallowed = ':\r\n'
156
157 def _tag(self, names, node, message, local, user, date, extra={}):
158 if isinstance(names, str):
159 allchars = names
160 names = (names,)
161 else:
162 allchars = ''.join(names)
163 for c in self.tag_disallowed:
164 if c in allchars:
165 raise util.Abort(_('%r cannot be used in a tag name') % c)
166
167 branches = self.branchmap()
168 for name in names:
169 self.hook('pretag', throw=True, node=hex(node), tag=name,
170 local=local)
171 if name in branches:
172 self.ui.warn(_("warning: tag %s conflicts with existing"
173 " branch name\n") % name)
174
175 def writetags(fp, names, munge, prevtags):
176 fp.seek(0, 2)
177 if prevtags and prevtags[-1] != '\n':
178 fp.write('\n')
179 for name in names:
180 m = munge and munge(name) or name
181 if self._tagtypes and name in self._tagtypes:
182 old = self._tags.get(name, nullid)
183 fp.write('%s %s\n' % (hex(old), m))
184 fp.write('%s %s\n' % (hex(node), m))
185 fp.close()
186
187 prevtags = ''
188 if local:
189 try:
190 fp = self.opener('localtags', 'r+')
191 except IOError:
192 fp = self.opener('localtags', 'a')
193 else:
194 prevtags = fp.read()
195
196 # local tags are stored in the current charset
197 writetags(fp, names, None, prevtags)
198 for name in names:
199 self.hook('tag', node=hex(node), tag=name, local=local)
200 return
201
202 try:
203 fp = self.wfile('.hgtags', 'rb+')
204 except IOError:
205 fp = self.wfile('.hgtags', 'ab')
206 else:
207 prevtags = fp.read()
23 All the ancestors of base are in repo and in remote.
24 All the descendants of the list returned are missing in repo.
25 (and so we know that the rest of the nodes are missing in remote, see
26 outgoing)
27 """
28 return findcommonincoming(repo, remote, base, heads, force)[1]
208 29
209 # committed tags are stored in UTF-8
210 writetags(fp, names, encoding.fromlocal, prevtags)
211
212 if '.hgtags' not in self.dirstate:
213 self.add(['.hgtags'])
214
215 m = matchmod.exact(self.root, '', ['.hgtags'])
216 tagnode = self.commit(message, user, date, extra=extra, match=m)
217
218 for name in names:
219 self.hook('tag', node=hex(node), tag=name, local=local)
220
221 return tagnode
222
223 def tag(self, names, node, message, local, user, date):
224 '''tag a revision with one or more symbolic names.
225
226 names is a list of strings or, when adding a single tag, names may be a
227 string.
228
229 if local is True, the tags are stored in a per-repository file.
230 otherwise, they are stored in the .hgtags file, and a new
231 changeset is committed with the change.
232
233 keyword arguments:
234
235 local: whether to store tags in non-version-controlled file
236 (default False)
237
238 message: commit message to use if committing
239
240 user: name of user to use if committing
241
242 date: date tuple to use if committing'''
30 def findcommonincoming(repo, remote, base=None, heads=None, force=False):
31 """Return a tuple (common, missing roots, heads) used to identify
32 missing nodes from remote.
243 33
244 for x in self.status()[:5]:
245 if '.hgtags' in x:
246 raise util.Abort(_('working copy of .hgtags is changed '
247 '(please commit .hgtags manually)'))
248
249 self.tags() # instantiate the cache
250 self._tag(names, node, message, local, user, date)
251
252 def tags(self):
253 '''return a mapping of tag to node'''
254 if self._tags is None:
255 (self._tags, self._tagtypes) = self._findtags()
256
257 return self._tags
258
259 def _findtags(self):
260 '''Do the hard work of finding tags. Return a pair of dicts
261 (tags, tagtypes) where tags maps tag name to node, and tagtypes
262 maps tag name to a string like \'global\' or \'local\'.
263 Subclasses or extensions are free to add their own tags, but
264 should be aware that the returned dicts will be retained for the
265 duration of the localrepo object.'''
266
267 # XXX what tagtype should subclasses/extensions use? Currently
268 # mq and bookmarks add tags, but do not set the tagtype at all.
269 # Should each extension invent its own tag type? Should there
270 # be one tagtype for all such "virtual" tags? Or is the status
271 # quo fine?
272
273 alltags = {} # map tag name to (node, hist)
274 tagtypes = {}
275
276 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
277 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
34 If base dict is specified, assume that these nodes and their parents
35 exist on the remote side and that no child of a node of base exists
36 in both remote and repo.
37 Furthermore base will be updated to include the nodes that exists
38 in repo and remote but no children exists in repo and remote.
39 If a list of heads is specified, return only nodes which are heads
40 or ancestors of these heads.
278 41
279 # Build the return dicts. Have to re-encode tag names because
280 # the tags module always uses UTF-8 (in order not to lose info
281 # writing to the cache), but the rest of Mercurial wants them in
282 # local encoding.
283 tags = {}
284 for (name, (node, hist)) in alltags.iteritems():
285 if node != nullid:
286 tags[encoding.tolocal(name)] = node
287 tags['tip'] = self.changelog.tip()
288 tagtypes = dict([(encoding.tolocal(name), value)
289 for (name, value) in tagtypes.iteritems()])
290 return (tags, tagtypes)
291
292 def tagtype(self, tagname):
293 '''
294 return the type of the given tag. result can be:
295
296 'local' : a local tag
297 'global' : a global tag
298 None : tag does not exist
299 '''
300
301 self.tags()
302
303 return self._tagtypes.get(tagname)
42 All the ancestors of base are in repo and in remote.
43 """
44 m = repo.changelog.nodemap
45 search = []
46 fetch = set()
47 seen = set()
48 seenbranch = set()
49 if base is None:
50 base = {}
304 51
305 def tagslist(self):
306 '''return a list of tags ordered by revision'''
307 l = []
308 for t, n in self.tags().iteritems():
309 try:
310 r = self.changelog.rev(n)
311 except:
312 r = -2 # sort to the beginning of the list if unknown
313 l.append((r, t, n))
314 return [(t, n) for r, t, n in sorted(l)]
315
316 def nodetags(self, node):
317 '''return the tags associated with a node'''
318 if not self.nodetagscache:
319 self.nodetagscache = {}
320 for t, n in self.tags().iteritems():
321 self.nodetagscache.setdefault(n, []).append(t)
322 for tags in self.nodetagscache.itervalues():
323 tags.sort()
324 return self.nodetagscache.get(node, [])
52 if not heads:
53 heads = remote.heads()
325 54
326 def _branchtags(self, partial, lrev):
327 # TODO: rename this function?
328 tiprev = len(self) - 1
329 if lrev != tiprev:
330 ctxgen = (self[r] for r in xrange(lrev + 1, tiprev + 1))
331 self._updatebranchcache(partial, ctxgen)
332 self._writebranchcache(partial, self.changelog.tip(), tiprev)
333
334 return partial
55 if repo.changelog.tip() == nullid:
56 base[nullid] = 1
57 if heads != [nullid]:
58 return [nullid], [nullid], list(heads)
59 return [nullid], [], []
335 60
336 def branchmap(self):
337 '''returns a dictionary {branch: [branchheads]}'''
338 tip = self.changelog.tip()
339 if self._branchcache is not None and self._branchcachetip == tip:
340 return self._branchcache
341
342 oldtip = self._branchcachetip
343 self._branchcachetip = tip
344 if oldtip is None or oldtip not in self.changelog.nodemap:
345 partial, last, lrev = self._readbranchcache()
346 else:
347 lrev = self.changelog.rev(oldtip)
348 partial = self._branchcache
61 # assume we're closer to the tip than the root
62 # and start by examining the heads
63 repo.ui.status(_("searching for changes\n"))
349 64
350 self._branchtags(partial, lrev)
351 # this private cache holds all heads (not just tips)
352 self._branchcache = partial
353
354 return self._branchcache
65 unknown = []
66 for h in heads:
67 if h not in m:
68 unknown.append(h)
69 else:
70 base[h] = 1
355 71
356 def branchtags(self):
357 '''return a dict where branch names map to the tipmost head of
358 the branch, open heads come before closed'''
359 bt = {}
360 for bn, heads in self.branchmap().iteritems():
361 tip = heads[-1]
362 for h in reversed(heads):
363 if 'close' not in self.changelog.read(h)[5]:
364 tip = h
365 break
366 bt[bn] = tip
367 return bt
368
369
370 def _readbranchcache(self):
371 partial = {}
372 try:
373 f = self.opener("branchheads.cache")
374 lines = f.read().split('\n')
375 f.close()
376 except (IOError, OSError):
377 return {}, nullid, nullrev
72 heads = unknown
73 if not unknown:
74 return base.keys(), [], []
378 75
379 try:
380 last, lrev = lines.pop(0).split(" ", 1)
381 last, lrev = bin(last), int(lrev)
382 if lrev >= len(self) or self[lrev].node() != last:
383 # invalidate the cache
384 raise ValueError('invalidating branch cache (tip differs)')
385 for l in lines:
386 if not l:
387 continue
388 node, label = l.split(" ", 1)
389 partial.setdefault(label.strip(), []).append(bin(node))
390 except KeyboardInterrupt:
391 raise
392 except Exception, inst:
393 if self.ui.debugflag:
394 self.ui.warn(str(inst), '\n')
395 partial, last, lrev = {}, nullid, nullrev
396 return partial, last, lrev
76 req = set(unknown)
77 reqcnt = 0
397 78
398 def _writebranchcache(self, branches, tip, tiprev):
399 try:
400 f = self.opener("branchheads.cache", "w", atomictemp=True)
401 f.write("%s %s\n" % (hex(tip), tiprev))
402 for label, nodes in branches.iteritems():
403 for node in nodes:
404 f.write("%s %s\n" % (hex(node), label))
405 f.rename()
406 except (IOError, OSError):
407 pass
408
409 def _updatebranchcache(self, partial, ctxgen):
410 # collect new branch entries
411 newbranches = {}
412 for c in ctxgen:
413 newbranches.setdefault(c.branch(), []).append(c.node())
414 # if older branchheads are reachable from new ones, they aren't
415 # really branchheads. Note checking parents is insufficient:
416 # 1 (branch a) -> 2 (branch b) -> 3 (branch a)
417 for branch, newnodes in newbranches.iteritems():
418 bheads = partial.setdefault(branch, [])
419 bheads.extend(newnodes)
420 if len(bheads) <= 1:
79 # search through remote branches
80 # a 'branch' here is a linear segment of history, with four parts:
81 # head, root, first parent, second parent
82 # (a branch always has two parents (or none) by definition)
83 unknown = remote.branches(unknown)
84 while unknown:
85 r = []
86 while unknown:
87 n = unknown.pop(0)
88 if n[0] in seen:
421 89 continue
422 # starting from tip means fewer passes over reachable
423 while newnodes:
424 latest = newnodes.pop()
425 if latest not in bheads:
426 continue
427 minbhrev = self[min([self[bh].rev() for bh in bheads])].node()
428 reachable = self.changelog.reachable(latest, minbhrev)
429 reachable.remove(latest)
430 bheads = [b for b in bheads if b not in reachable]
431 partial[branch] = bheads
432
433 def lookup(self, key):
434 if isinstance(key, int):
435 return self.changelog.node(key)
436 elif key == '.':
437 return self.dirstate.parents()[0]
438 elif key == 'null':
439 return nullid
440 elif key == 'tip':
441 return self.changelog.tip()
442 n = self.changelog._match(key)
443 if n:
444 return n
445 if key in self.tags():
446 return self.tags()[key]
447 if key in self.branchtags():
448 return self.branchtags()[key]
449 n = self.changelog._partialmatch(key)
450 if n:
451 return n
452
453 # can't find key, check if it might have come from damaged dirstate
454 if key in self.dirstate.parents():
455 raise error.Abort(_("working directory has unknown parent '%s'!")
456 % short(key))
457 try:
458 if len(key) == 20:
459 key = hex(key)
460 except:
461 pass
462 raise error.RepoLookupError(_("unknown revision '%s'") % key)
463
464 def lookupbranch(self, key, remote=None):
465 repo = remote or self
466 if key in repo.branchmap():
467 return key
468
469 repo = (remote and remote.local()) and remote or self
470 return repo[key].branch()
471
472 def local(self):
473 return True
474
475 def join(self, f):
476 return os.path.join(self.path, f)
477
478 def wjoin(self, f):
479 return os.path.join(self.root, f)
480
481 def rjoin(self, f):
482 return os.path.join(self.root, util.pconvert(f))
483
484 def file(self, f):
485 if f[0] == '/':
486 f = f[1:]
487 return filelog.filelog(self.sopener, f)
488
489 def changectx(self, changeid):
490 return self[changeid]
491
492 def parents(self, changeid=None):
493 '''get list of changectxs for parents of changeid'''
494 return self[changeid].parents()
495
496 def filectx(self, path, changeid=None, fileid=None):
497 """changeid can be a changeset revision, node, or tag.
498 fileid can be a file revision or node."""
499 return context.filectx(self, path, changeid, fileid)
500
501 def getcwd(self):
502 return self.dirstate.getcwd()
503
504 def pathto(self, f, cwd=None):
505 return self.dirstate.pathto(f, cwd)
506
507 def wfile(self, f, mode='r'):
508 return self.wopener(f, mode)
509
510 def _link(self, f):
511 return os.path.islink(self.wjoin(f))
512
513 def _filter(self, filter, filename, data):
514 if filter not in self.filterpats:
515 l = []
516 for pat, cmd in self.ui.configitems(filter):
517 if cmd == '!':
518 continue
519 mf = matchmod.match(self.root, '', [pat])
520 fn = None
521 params = cmd
522 for name, filterfn in self._datafilters.iteritems():
523 if cmd.startswith(name):
524 fn = filterfn
525 params = cmd[len(name):].lstrip()
526 break
527 if not fn:
528 fn = lambda s, c, **kwargs: util.filter(s, c)
529 # Wrap old filters not supporting keyword arguments
530 if not inspect.getargspec(fn)[2]:
531 oldfn = fn
532 fn = lambda s, c, **kwargs: oldfn(s, c)
533 l.append((mf, fn, params))
534 self.filterpats[filter] = l
535
536 for mf, fn, cmd in self.filterpats[filter]:
537 if mf(filename):
538 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
539 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
540 break
541
542 return data
543
544 def adddatafilter(self, name, filter):
545 self._datafilters[name] = filter
546
547 def wread(self, filename):
548 if self._link(filename):
549 data = os.readlink(self.wjoin(filename))
550 else:
551 data = self.wopener(filename, 'r').read()
552 return self._filter("encode", filename, data)
553
554 def wwrite(self, filename, data, flags):
555 data = self._filter("decode", filename, data)
556 try:
557 os.unlink(self.wjoin(filename))
558 except OSError:
559 pass
560 if 'l' in flags:
561 self.wopener.symlink(data, filename)
562 else:
563 self.wopener(filename, 'w').write(data)
564 if 'x' in flags:
565 util.set_flags(self.wjoin(filename), False, True)
566
567 def wwritedata(self, filename, data):
568 return self._filter("decode", filename, data)
569
570 def transaction(self, desc):
571 tr = self._transref and self._transref() or None
572 if tr and tr.running():
573 return tr.nest()
574 90
575 # abort here if the journal already exists
576 if os.path.exists(self.sjoin("journal")):
577 raise error.RepoError(
578 _("abandoned transaction found - run hg recover"))
579
580 # save dirstate for rollback
581 try:
582 ds = self.opener("dirstate").read()
583 except IOError:
584 ds = ""
585 self.opener("journal.dirstate", "w").write(ds)
586 self.opener("journal.branch", "w").write(self.dirstate.branch())
587 self.opener("journal.desc", "w").write("%d\n%s\n" % (len(self), desc))
588
589 renames = [(self.sjoin("journal"), self.sjoin("undo")),
590 (self.join("journal.dirstate"), self.join("undo.dirstate")),
591 (self.join("journal.branch"), self.join("undo.branch")),
592 (self.join("journal.desc"), self.join("undo.desc"))]
593 tr = transaction.transaction(self.ui.warn, self.sopener,
594 self.sjoin("journal"),
595 aftertrans(renames),
596 self.store.createmode)
597 self._transref = weakref.ref(tr)
598 return tr
599
600 def recover(self):
601 lock = self.lock()
602 try:
603 if os.path.exists(self.sjoin("journal")):
604 self.ui.status(_("rolling back interrupted transaction\n"))
605 transaction.rollback(self.sopener, self.sjoin("journal"),
606 self.ui.warn)
607 self.invalidate()
608 return True
91 repo.ui.debug("examining %s:%s\n"
92 % (short(n[0]), short(n[1])))
93 if n[0] == nullid: # found the end of the branch
94 pass
95 elif n in seenbranch:
96 repo.ui.debug("branch already found\n")
97 continue
98 elif n[1] and n[1] in m: # do we know the base?
99 repo.ui.debug("found incomplete branch %s:%s\n"
100 % (short(n[0]), short(n[1])))
101 search.append(n[0:2]) # schedule branch range for scanning
102 seenbranch.add(n)
609 103 else:
610 self.ui.warn(_("no interrupted transaction available\n"))
611 return False
612 finally:
613 lock.release()
614
615 def rollback(self, dryrun=False):
616 wlock = lock = None
617 try:
618 wlock = self.wlock()
619 lock = self.lock()
620 if os.path.exists(self.sjoin("undo")):
621 try:
622 args = self.opener("undo.desc", "r").read().splitlines()
623 if len(args) >= 3 and self.ui.verbose:
624 desc = _("rolling back to revision %s"
625 " (undo %s: %s)\n") % (
626 int(args[0]) - 1, args[1], args[2])
627 elif len(args) >= 2:
628 desc = _("rolling back to revision %s (undo %s)\n") % (
629 int(args[0]) - 1, args[1])
630 except IOError:
631 desc = _("rolling back unknown transaction\n")
632 self.ui.status(desc)
633 if dryrun:
634 return
635 transaction.rollback(self.sopener, self.sjoin("undo"),
636 self.ui.warn)
637 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
638 try:
639 branch = self.opener("undo.branch").read()
640 self.dirstate.setbranch(branch)
641 except IOError:
642 self.ui.warn(_("Named branch could not be reset, "
643 "current branch still is: %s\n")
644 % encoding.tolocal(self.dirstate.branch()))
645 self.invalidate()
646 self.dirstate.invalidate()
647 self.destroyed()
648 else:
649 self.ui.warn(_("no rollback information available\n"))
650 return 1
651 finally:
652 release(lock, wlock)
653
654 def invalidatecaches(self):
655 self._tags = None
656 self._tagtypes = None
657 self.nodetagscache = None
658 self._branchcache = None # in UTF-8
659 self._branchcachetip = None
660
661 def invalidate(self):
662 for a in "changelog manifest".split():
663 if a in self.__dict__:
664 delattr(self, a)
665 self.invalidatecaches()
666
667 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
668 try:
669 l = lock.lock(lockname, 0, releasefn, desc=desc)
670 except error.LockHeld, inst:
671 if not wait:
672 raise
673 self.ui.warn(_("waiting for lock on %s held by %r\n") %
674 (desc, inst.locker))
675 # default to 600 seconds timeout
676 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
677 releasefn, desc=desc)
678 if acquirefn:
679 acquirefn()
680 return l
681
682 def lock(self, wait=True):
683 '''Lock the repository store (.hg/store) and return a weak reference
684 to the lock. Use this before modifying the store (e.g. committing or
685 stripping). If you are opening a transaction, get a lock as well.)'''
686 l = self._lockref and self._lockref()
687 if l is not None and l.held:
688 l.lock()
689 return l
690
691 l = self._lock(self.sjoin("lock"), wait, None, self.invalidate,
692 _('repository %s') % self.origroot)
693 self._lockref = weakref.ref(l)
694 return l
695
696 def wlock(self, wait=True):
697 '''Lock the non-store parts of the repository (everything under
698 .hg except .hg/store) and return a weak reference to the lock.
699 Use this before modifying files in .hg.'''
700 l = self._wlockref and self._wlockref()
701 if l is not None and l.held:
702 l.lock()
703 return l
704
705 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
706 self.dirstate.invalidate, _('working directory of %s') %
707 self.origroot)
708 self._wlockref = weakref.ref(l)
709 return l
104 if n[1] not in seen and n[1] not in fetch:
105 if n[2] in m and n[3] in m:
106 repo.ui.debug("found new changeset %s\n" %
107 short(n[1]))
108 fetch.add(n[1]) # earliest unknown
109 for p in n[2:4]:
110 if p in m:
111 base[p] = 1 # latest known
710 112
711 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
712 """
713 commit an individual file as part of a larger transaction
714 """
715
716 fname = fctx.path()
717 text = fctx.data()
718 flog = self.file(fname)
719 fparent1 = manifest1.get(fname, nullid)
720 fparent2 = fparent2o = manifest2.get(fname, nullid)
721
722 meta = {}
723 copy = fctx.renamed()
724 if copy and copy[0] != fname:
725 # Mark the new revision of this file as a copy of another
726 # file. This copy data will effectively act as a parent
727 # of this new revision. If this is a merge, the first
728 # parent will be the nullid (meaning "look up the copy data")
729 # and the second one will be the other parent. For example:
730 #
731 # 0 --- 1 --- 3 rev1 changes file foo
732 # \ / rev2 renames foo to bar and changes it
733 # \- 2 -/ rev3 should have bar with all changes and
734 # should record that bar descends from
735 # bar in rev2 and foo in rev1
736 #
737 # this allows this merge to succeed:
738 #
739 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
740 # \ / merging rev3 and rev4 should use bar@rev2
741 # \- 2 --- 4 as the merge base
742 #
743
744 cfname = copy[0]
745 crev = manifest1.get(cfname)
746 newfparent = fparent2
747
748 if manifest2: # branch merge
749 if fparent2 == nullid or crev is None: # copied on remote side
750 if cfname in manifest2:
751 crev = manifest2[cfname]
752 newfparent = fparent1
753
754 # find source in nearest ancestor if we've lost track
755 if not crev:
756 self.ui.debug(" %s: searching for copy revision for %s\n" %
757 (fname, cfname))
758 for ancestor in self['.'].ancestors():
759 if cfname in ancestor:
760 crev = ancestor[cfname].filenode()
761 break
762
763 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
764 meta["copy"] = cfname
765 meta["copyrev"] = hex(crev)
766 fparent1, fparent2 = nullid, newfparent
767 elif fparent2 != nullid:
768 # is one parent an ancestor of the other?
769 fparentancestor = flog.ancestor(fparent1, fparent2)
770 if fparentancestor == fparent1:
771 fparent1, fparent2 = fparent2, nullid
772 elif fparentancestor == fparent2:
773 fparent2 = nullid
774
775 # is the file changed?
776 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
777 changelist.append(fname)
778 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
113 for p in n[2:4]:
114 if p not in req and p not in m:
115 r.append(p)
116 req.add(p)
117 seen.add(n[0])
779 118
780 # are just the flags changed during merge?
781 if fparent1 != fparent2o and manifest1.flags(fname) != fctx.flags():
782 changelist.append(fname)
783
784 return fparent1
785
786 def commit(self, text="", user=None, date=None, match=None, force=False,
787 editor=False, extra={}):
788 """Add a new revision to current repository.
789
790 Revision information is gathered from the working directory,
791 match can be used to filter the committed files. If editor is
792 supplied, it is called to get a commit message.
793 """
794
795 def fail(f, msg):
796 raise util.Abort('%s: %s' % (f, msg))
797
798 if not match:
799 match = matchmod.always(self.root, '')
800
801 if not force:
802 vdirs = []
803 match.dir = vdirs.append
804 match.bad = fail
805
806 wlock = self.wlock()
807 try:
808 wctx = self[None]
809 merge = len(wctx.parents()) > 1
810
811 if (not force and merge and match and
812 (match.files() or match.anypats())):
813 raise util.Abort(_('cannot partially commit a merge '
814 '(do not specify files or patterns)'))
815
816 changes = self.status(match=match, clean=force)
817 if force:
818 changes[0].extend(changes[6]) # mq may commit unchanged files
819
820 # check subrepos
821 subs = []
822 removedsubs = set()
823 for p in wctx.parents():
824 removedsubs.update(s for s in p.substate if match(s))
825 for s in wctx.substate:
826 removedsubs.discard(s)
827 if match(s) and wctx.sub(s).dirty():
828 subs.append(s)
829 if (subs or removedsubs) and '.hgsubstate' not in changes[0]:
830 changes[0].insert(0, '.hgsubstate')
831
832 # make sure all explicit patterns are matched
833 if not force and match.files():
834 matched = set(changes[0] + changes[1] + changes[2])
835
836 for f in match.files():
837 if f == '.' or f in matched or f in wctx.substate:
838 continue
839 if f in changes[3]: # missing
840 fail(f, _('file not found!'))
841 if f in vdirs: # visited directory
842 d = f + '/'
843 for mf in matched:
844 if mf.startswith(d):
845 break
846 else:
847 fail(f, _("no match under directory!"))
848 elif f not in self.dirstate:
849 fail(f, _("file not tracked!"))
850
851 if (not force and not extra.get("close") and not merge
852 and not (changes[0] or changes[1] or changes[2])
853 and wctx.branch() == wctx.p1().branch()):
854 return None
119 if r:
120 reqcnt += 1
121 repo.ui.progress(_('searching'), reqcnt, unit=_('queries'))
122 repo.ui.debug("request %d: %s\n" %
123 (reqcnt, " ".join(map(short, r))))
124 for p in xrange(0, len(r), 10):
125 for b in remote.branches(r[p:p + 10]):
126 repo.ui.debug("received %s:%s\n" %
127 (short(b[0]), short(b[1])))
128 unknown.append(b)
855 129
856 ms = mergemod.mergestate(self)
857 for f in changes[0]:
858 if f in ms and ms[f] == 'u':
859 raise util.Abort(_("unresolved merge conflicts "
860 "(see hg resolve)"))
861
862 cctx = context.workingctx(self, text, user, date, extra, changes)
863 if editor:
864 cctx._text = editor(self, cctx, subs)
865 edited = (text != cctx._text)
866
867 # commit subs
868 if subs or removedsubs:
869 state = wctx.substate.copy()
870 for s in subs:
871 sub = wctx.sub(s)
872 self.ui.status(_('committing subrepository %s\n') %
873 subrepo.relpath(sub))
874 sr = sub.commit(cctx._text, user, date)
875 state[s] = (state[s][0], sr)
876 subrepo.writestate(self, state)
877
878 # Save commit message in case this transaction gets rolled back
879 # (e.g. by a pretxncommit hook). Leave the content alone on
880 # the assumption that the user will use the same editor again.
881 msgfile = self.opener('last-message.txt', 'wb')
882 msgfile.write(cctx._text)
883 msgfile.close()
884
885 p1, p2 = self.dirstate.parents()
886 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
887 try:
888 self.hook("precommit", throw=True, parent1=hookp1, parent2=hookp2)
889 ret = self.commitctx(cctx, True)
890 except:
891 if edited:
892 msgfn = self.pathto(msgfile.name[len(self.root)+1:])
893 self.ui.write(
894 _('note: commit message saved in %s\n') % msgfn)
895 raise
896
897 # update dirstate and mergestate
898 for f in changes[0] + changes[1]:
899 self.dirstate.normal(f)
900 for f in changes[2]:
901 self.dirstate.forget(f)
902 self.dirstate.setparents(ret)
903 ms.reset()
904 finally:
905 wlock.release()
906
907 self.hook("commit", node=hex(ret), parent1=hookp1, parent2=hookp2)
908 return ret
909
910 def commitctx(self, ctx, error=False):
911 """Add a new revision to current repository.
912 Revision information is passed via the context argument.
913 """
914
915 tr = lock = None
916 removed = ctx.removed()
917 p1, p2 = ctx.p1(), ctx.p2()
918 m1 = p1.manifest().copy()
919 m2 = p2.manifest()
920 user = ctx.user()
921
922 lock = self.lock()
923 try:
924 tr = self.transaction("commit")
925 trp = weakref.proxy(tr)
926
927 # check in files
928 new = {}
929 changed = []
930 linkrev = len(self)
931 for f in sorted(ctx.modified() + ctx.added()):
932 self.ui.note(f + "\n")
933 try:
934 fctx = ctx[f]
935 new[f] = self._filecommit(fctx, m1, m2, linkrev, trp,
936 changed)
937 m1.set(f, fctx.flags())
938 except OSError, inst:
939 self.ui.warn(_("trouble committing %s!\n") % f)
940 raise
941 except IOError, inst:
942 errcode = getattr(inst, 'errno', errno.ENOENT)
943 if error or errcode and errcode != errno.ENOENT:
944 self.ui.warn(_("trouble committing %s!\n") % f)
945 raise
130 # do binary search on the branches we found
131 while search:
132 newsearch = []
133 reqcnt += 1
134 repo.ui.progress(_('searching'), reqcnt, unit=_('queries'))
135 for n, l in zip(search, remote.between(search)):
136 l.append(n[1])
137 p = n[0]
138 f = 1
139 for i in l:
140 repo.ui.debug("narrowing %d:%d %s\n" % (f, len(l), short(i)))
141 if i in m:
142 if f <= 2:
143 repo.ui.debug("found new branch changeset %s\n" %
144 short(p))
145 fetch.add(p)
146 base[i] = 1
946 147 else:
947 removed.append(f)
948
949 # update manifest
950 m1.update(new)
951 removed = [f for f in sorted(removed) if f in m1 or f in m2]
952 drop = [f for f in removed if f in m1]
953 for f in drop:
954 del m1[f]
955 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
956 p2.manifestnode(), (new, drop))
957
958 # update changelog
959 self.changelog.delayupdate()
960 n = self.changelog.add(mn, changed + removed, ctx.description(),
961 trp, p1.node(), p2.node(),
962 user, ctx.date(), ctx.extra().copy())
963 p = lambda: self.changelog.writepending() and self.root or ""
964 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
965 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
966 parent2=xp2, pending=p)
967 self.changelog.finalize(trp)
968 tr.close()
969
970 if self._branchcache:
971 self.branchtags()
972 return n
973 finally:
974 if tr:
975 tr.release()
976 lock.release()
977
978 def destroyed(self):
979 '''Inform the repository that nodes have been destroyed.
980 Intended for use by strip and rollback, so there's a common
981 place for anything that has to be done after destroying history.'''
982 # XXX it might be nice if we could take the list of destroyed
983 # nodes, but I don't see an easy way for rollback() to do that
984
985 # Ensure the persistent tag cache is updated. Doing it now
986 # means that the tag cache only has to worry about destroyed
987 # heads immediately after a strip/rollback. That in turn
988 # guarantees that "cachetip == currenttip" (comparing both rev
989 # and node) always means no nodes have been added or destroyed.
990
991 # XXX this is suboptimal when qrefresh'ing: we strip the current
992 # head, refresh the tag cache, then immediately add a new head.
993 # But I think doing it this way is necessary for the "instant
994 # tag cache retrieval" case to work.
995 self.invalidatecaches()
148 repo.ui.debug("narrowed branch search to %s:%s\n"
149 % (short(p), short(i)))
150 newsearch.append((p, i))
151 break
152 p, f = i, f * 2
153 search = newsearch
996 154
997 def walk(self, match, node=None):
998 '''
999 walk recursively through the directory tree or a given
1000 changeset, finding all files matched by the match
1001 function
1002 '''
1003 return self[node].walk(match)
1004
1005 def status(self, node1='.', node2=None, match=None,
1006 ignored=False, clean=False, unknown=False):
1007 """return status of files between two nodes or node and working directory
1008
1009 If node1 is None, use the first dirstate parent instead.
1010 If node2 is None, compare node1 with working directory.
1011 """
1012
1013 def mfmatches(ctx):
1014 mf = ctx.manifest().copy()
1015 for fn in mf.keys():
1016 if not match(fn):
1017 del mf[fn]
1018 return mf
1019
1020 if isinstance(node1, context.changectx):
1021 ctx1 = node1
1022 else:
1023 ctx1 = self[node1]
1024 if isinstance(node2, context.changectx):
1025 ctx2 = node2
1026 else:
1027 ctx2 = self[node2]
1028
1029 working = ctx2.rev() is None
1030 parentworking = working and ctx1 == self['.']
1031 match = match or matchmod.always(self.root, self.getcwd())
1032 listignored, listclean, listunknown = ignored, clean, unknown
1033
1034 # load earliest manifest first for caching reasons
1035 if not working and ctx2.rev() < ctx1.rev():
1036 ctx2.manifest()
1037
1038 if not parentworking:
1039 def bad(f, msg):
1040 if f not in ctx1:
1041 self.ui.warn('%s: %s\n' % (self.dirstate.pathto(f), msg))
1042 match.bad = bad
1043
1044 if working: # we need to scan the working dir
1045 subrepos = []
1046 if '.hgsub' in self.dirstate:
1047 subrepos = ctx1.substate.keys()
1048 s = self.dirstate.status(match, subrepos, listignored,
1049 listclean, listunknown)
1050 cmp, modified, added, removed, deleted, unknown, ignored, clean = s
1051
1052 # check for any possibly clean files
1053 if parentworking and cmp:
1054 fixup = []
1055 # do a full compare of any files that might have changed
1056 for f in sorted(cmp):
1057 if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
1058 or ctx1[f].cmp(ctx2[f].data())):
1059 modified.append(f)
1060 else:
1061 fixup.append(f)
1062
1063 if listclean:
1064 clean += fixup
155 # sanity check our fetch list
156 for f in fetch:
157 if f in m:
158 raise error.RepoError(_("already have changeset ")
159 + short(f[:4]))
1065 160
1066 # update dirstate for files that are actually clean
1067 if fixup:
1068 try:
1069 # updating the dirstate is optional
1070 # so we don't wait on the lock
1071 wlock = self.wlock(False)
1072 try:
1073 for f in fixup:
1074 self.dirstate.normal(f)
1075 finally:
1076 wlock.release()
1077 except error.LockError:
1078 pass
1079
1080 if not parentworking:
1081 mf1 = mfmatches(ctx1)
1082 if working:
1083 # we are comparing working dir against non-parent
1084 # generate a pseudo-manifest for the working dir
1085 mf2 = mfmatches(self['.'])
1086 for f in cmp + modified + added:
1087 mf2[f] = None
1088 mf2.set(f, ctx2.flags(f))
1089 for f in removed:
1090 if f in mf2:
1091 del mf2[f]
1092 else:
1093 # we are comparing two revisions
1094 deleted, unknown, ignored = [], [], []
1095 mf2 = mfmatches(ctx2)
161 if base.keys() == [nullid]:
162 if force:
163 repo.ui.warn(_("warning: repository is unrelated\n"))
164 else:
165 raise util.Abort(_("repository is unrelated"))
1096 166
1097 modified, added, clean = [], [], []
1098 for fn in mf2:
1099 if fn in mf1:
1100 if (mf1.flags(fn) != mf2.flags(fn) or
1101 (mf1[fn] != mf2[fn] and
1102 (mf2[fn] or ctx1[fn].cmp(ctx2[fn].data())))):
1103 modified.append(fn)
1104 elif listclean:
1105 clean.append(fn)
1106 del mf1[fn]
1107 else:
1108 added.append(fn)
1109 removed = mf1.keys()
1110
1111 r = modified, added, removed, deleted, unknown, ignored, clean
1112 [l.sort() for l in r]
1113 return r
167 repo.ui.debug("found new changesets starting at " +
168 " ".join([short(f) for f in fetch]) + "\n")
1114 169
1115 def add(self, list):
1116 wlock = self.wlock()
1117 try:
1118 rejected = []
1119 for f in list:
1120 p = self.wjoin(f)
1121 try:
1122 st = os.lstat(p)
1123 except:
1124 self.ui.warn(_("%s does not exist!\n") % f)
1125 rejected.append(f)
1126 continue
1127 if st.st_size > 10000000:
1128 self.ui.warn(_("%s: up to %d MB of RAM may be required "
1129 "to manage this file\n"
1130 "(use 'hg revert %s' to cancel the "
1131 "pending addition)\n")
1132 % (f, 3 * st.st_size // 1000000, f))
1133 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1134 self.ui.warn(_("%s not added: only files and symlinks "
1135 "supported currently\n") % f)
1136 rejected.append(p)
1137 elif self.dirstate[f] in 'amn':
1138 self.ui.warn(_("%s already tracked!\n") % f)
1139 elif self.dirstate[f] == 'r':
1140 self.dirstate.normallookup(f)
1141 else:
1142 self.dirstate.add(f)
1143 return rejected
1144 finally:
1145 wlock.release()
170 repo.ui.progress(_('searching'), None)
171 repo.ui.debug("%d total queries\n" % reqcnt)
172
173 return base.keys(), list(fetch), heads
174
175 def findoutgoing(repo, remote, base=None, heads=None, force=False):
176 """Return list of nodes that are roots of subsets not in remote
1146 177
1147 def forget(self, list):
1148 wlock = self.wlock()
1149 try:
1150 for f in list:
1151 if self.dirstate[f] != 'a':
1152 self.ui.warn(_("%s not added!\n") % f)
1153 else:
1154 self.dirstate.forget(f)
1155 finally:
1156 wlock.release()
1157
1158 def remove(self, list, unlink=False):
1159 if unlink:
1160 for f in list:
1161 try:
1162 util.unlink(self.wjoin(f))
1163 except OSError, inst:
1164 if inst.errno != errno.ENOENT:
1165 raise
1166 wlock = self.wlock()
1167 try:
1168 for f in list:
1169 if unlink and os.path.exists(self.wjoin(f)):
1170 self.ui.warn(_("%s still exists!\n") % f)
1171 elif self.dirstate[f] == 'a':
1172 self.dirstate.forget(f)
1173 elif f not in self.dirstate:
1174 self.ui.warn(_("%s not tracked!\n") % f)
1175 else:
1176 self.dirstate.remove(f)
1177 finally:
1178 wlock.release()
1179
1180 def undelete(self, list):
1181 manifests = [self.manifest.read(self.changelog.read(p)[0])
1182 for p in self.dirstate.parents() if p != nullid]
1183 wlock = self.wlock()
1184 try:
1185 for f in list:
1186 if self.dirstate[f] != 'r':
1187 self.ui.warn(_("%s not removed!\n") % f)
1188 else:
1189 m = f in manifests[0] and manifests[0] or manifests[1]
1190 t = self.file(f).read(m[f])
1191 self.wwrite(f, t, m.flags(f))
1192 self.dirstate.normal(f)
1193 finally:
1194 wlock.release()
1195
1196 def copy(self, source, dest):
1197 p = self.wjoin(dest)
1198 if not (os.path.exists(p) or os.path.islink(p)):
1199 self.ui.warn(_("%s does not exist!\n") % dest)
1200 elif not (os.path.isfile(p) or os.path.islink(p)):
1201 self.ui.warn(_("copy failed: %s is not a file or a "
1202 "symbolic link\n") % dest)
1203 else:
1204 wlock = self.wlock()
1205 try:
1206 if self.dirstate[dest] in '?r':
1207 self.dirstate.add(dest)
1208 self.dirstate.copy(source, dest)
1209 finally:
1210 wlock.release()
1211
1212 def heads(self, start=None):
1213 heads = self.changelog.heads(start)
1214 # sort the output in rev descending order
1215 heads = [(-self.changelog.rev(h), h) for h in heads]
1216 return [n for (r, n) in sorted(heads)]
1217
1218 def branchheads(self, branch=None, start=None, closed=False):
1219 '''return a (possibly filtered) list of heads for the given branch
1220
1221 Heads are returned in topological order, from newest to oldest.
1222 If branch is None, use the dirstate branch.
1223 If start is not None, return only heads reachable from start.
1224 If closed is True, return heads that are marked as closed as well.
1225 '''
1226 if branch is None:
1227 branch = self[None].branch()
1228 branches = self.branchmap()
1229 if branch not in branches:
1230 return []
1231 # the cache returns heads ordered lowest to highest
1232 bheads = list(reversed(branches[branch]))
1233 if start is not None:
1234 # filter out the heads that cannot be reached from startrev
1235 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1236 bheads = [h for h in bheads if h in fbheads]
1237 if not closed:
1238 bheads = [h for h in bheads if
1239 ('close' not in self.changelog.read(h)[5])]
1240 return bheads
1241
1242 def branches(self, nodes):
1243 if not nodes:
1244 nodes = [self.changelog.tip()]
1245 b = []
1246 for n in nodes:
1247 t = n
1248 while 1:
1249 p = self.changelog.parents(n)
1250 if p[1] != nullid or p[0] == nullid:
1251 b.append((t, n, p[0], p[1]))
1252 break
1253 n = p[0]
1254 return b
1255
1256 def between(self, pairs):
1257 r = []
1258
1259 for top, bottom in pairs:
1260 n, l, i = top, [], 0
1261 f = 1
1262
1263 while n != bottom and n != nullid:
1264 p = self.changelog.parents(n)[0]
1265 if i == f:
1266 l.append(n)
1267 f = f * 2
1268 n = p
1269 i += 1
1270
1271 r.append(l)
1272
1273 return r
1274
1275 def findincoming(self, remote, base=None, heads=None, force=False):
1276 """Return list of roots of the subsets of missing nodes from remote
1277
1278 If base dict is specified, assume that these nodes and their parents
1279 exist on the remote side and that no child of a node of base exists
1280 in both remote and self.
1281 Furthermore base will be updated to include the nodes that exists
1282 in self and remote but no children exists in self and remote.
1283 If a list of heads is specified, return only nodes which are heads
1284 or ancestors of these heads.
178 If base dict is specified, assume that these nodes and their parents
179 exist on the remote side.
180 If a list of heads is specified, return only nodes which are heads
181 or ancestors of these heads, and return a second element which
182 contains all remote heads which get new children.
183 """
184 if base is None:
185 base = {}
186 findincoming(repo, remote, base, heads, force=force)
1285 187
1286 All the ancestors of base are in self and in remote.
1287 All the descendants of the list returned are missing in self.
1288 (and so we know that the rest of the nodes are missing in remote, see
1289 outgoing)
1290 """
1291 return self.findcommonincoming(remote, base, heads, force)[1]
1292
1293 def findcommonincoming(self, remote, base=None, heads=None, force=False):
1294 """Return a tuple (common, missing roots, heads) used to identify
1295 missing nodes from remote.
1296
1297 If base dict is specified, assume that these nodes and their parents
1298 exist on the remote side and that no child of a node of base exists
1299 in both remote and self.
1300 Furthermore base will be updated to include the nodes that exists
1301 in self and remote but no children exists in self and remote.
1302 If a list of heads is specified, return only nodes which are heads
1303 or ancestors of these heads.
1304
1305 All the ancestors of base are in self and in remote.
1306 """
1307 m = self.changelog.nodemap
1308 search = []
1309 fetch = set()
1310 seen = set()
1311 seenbranch = set()
1312 if base is None:
1313 base = {}
1314
1315 if not heads:
1316 heads = remote.heads()
188 repo.ui.debug("common changesets up to "
189 + " ".join(map(short, base.keys())) + "\n")
1317 190
1318 if self.changelog.tip() == nullid:
1319 base[nullid] = 1
1320 if heads != [nullid]:
1321 return [nullid], [nullid], list(heads)
1322 return [nullid], [], []
1323
1324 # assume we're closer to the tip than the root
1325 # and start by examining the heads
1326 self.ui.status(_("searching for changes\n"))
1327
1328 unknown = []
1329 for h in heads:
1330 if h not in m:
1331 unknown.append(h)
1332 else:
1333 base[h] = 1
1334
1335 heads = unknown
1336 if not unknown:
1337 return base.keys(), [], []
1338
1339 req = set(unknown)
1340 reqcnt = 0
1341
1342 # search through remote branches
1343 # a 'branch' here is a linear segment of history, with four parts:
1344 # head, root, first parent, second parent
1345 # (a branch always has two parents (or none) by definition)
1346 unknown = remote.branches(unknown)
1347 while unknown:
1348 r = []
1349 while unknown:
1350 n = unknown.pop(0)
1351 if n[0] in seen:
1352 continue
191 remain = set(repo.changelog.nodemap)
1353 192
1354 self.ui.debug("examining %s:%s\n"
1355 % (short(n[0]), short(n[1])))
1356 if n[0] == nullid: # found the end of the branch
1357 pass
1358 elif n in seenbranch:
1359 self.ui.debug("branch already found\n")
1360 continue
1361 elif n[1] and n[1] in m: # do we know the base?
1362 self.ui.debug("found incomplete branch %s:%s\n"
1363 % (short(n[0]), short(n[1])))
1364 search.append(n[0:2]) # schedule branch range for scanning
1365 seenbranch.add(n)
1366 else:
1367 if n[1] not in seen and n[1] not in fetch:
1368 if n[2] in m and n[3] in m:
1369 self.ui.debug("found new changeset %s\n" %
1370 short(n[1]))
1371 fetch.add(n[1]) # earliest unknown
1372 for p in n[2:4]:
1373 if p in m:
1374 base[p] = 1 # latest known
1375
1376 for p in n[2:4]:
1377 if p not in req and p not in m:
1378 r.append(p)
1379 req.add(p)
1380 seen.add(n[0])
1381
1382 if r:
1383 reqcnt += 1
1384 self.ui.progress(_('searching'), reqcnt, unit=_('queries'))
1385 self.ui.debug("request %d: %s\n" %
1386 (reqcnt, " ".join(map(short, r))))
1387 for p in xrange(0, len(r), 10):
1388 for b in remote.branches(r[p:p + 10]):
1389 self.ui.debug("received %s:%s\n" %
1390 (short(b[0]), short(b[1])))
1391 unknown.append(b)
1392
1393 # do binary search on the branches we found
1394 while search:
1395 newsearch = []
1396 reqcnt += 1
1397 self.ui.progress(_('searching'), reqcnt, unit=_('queries'))
1398 for n, l in zip(search, remote.between(search)):
1399 l.append(n[1])
1400 p = n[0]
1401 f = 1
1402 for i in l:
1403 self.ui.debug("narrowing %d:%d %s\n" % (f, len(l), short(i)))
1404 if i in m:
1405 if f <= 2:
1406 self.ui.debug("found new branch changeset %s\n" %
1407 short(p))
1408 fetch.add(p)
1409 base[i] = 1
1410 else:
1411 self.ui.debug("narrowed branch search to %s:%s\n"
1412 % (short(p), short(i)))
1413 newsearch.append((p, i))
1414 break
1415 p, f = i, f * 2
1416 search = newsearch
1417
1418 # sanity check our fetch list
1419 for f in fetch:
1420 if f in m:
1421 raise error.RepoError(_("already have changeset ")
1422 + short(f[:4]))
1423
1424 if base.keys() == [nullid]:
1425 if force:
1426 self.ui.warn(_("warning: repository is unrelated\n"))
1427 else:
1428 raise util.Abort(_("repository is unrelated"))
1429
1430 self.ui.debug("found new changesets starting at " +
1431 " ".join([short(f) for f in fetch]) + "\n")
193 # prune everything remote has from the tree
194 remain.remove(nullid)
195 remove = base.keys()
196 while remove:
197 n = remove.pop(0)
198 if n in remain:
199 remain.remove(n)
200 for p in repo.changelog.parents(n):
201 remove.append(p)
1432 202
1433 self.ui.progress(_('searching'), None)
1434 self.ui.debug("%d total queries\n" % reqcnt)
1435
1436 return base.keys(), list(fetch), heads
1437
1438 def findoutgoing(self, remote, base=None, heads=None, force=False):
1439 """Return list of nodes that are roots of subsets not in remote
1440
1441 If base dict is specified, assume that these nodes and their parents
1442 exist on the remote side.
1443 If a list of heads is specified, return only nodes which are heads
1444 or ancestors of these heads, and return a second element which
1445 contains all remote heads which get new children.
1446 """
1447 if base is None:
1448 base = {}
1449 self.findincoming(remote, base, heads, force=force)
1450
1451 self.ui.debug("common changesets up to "
1452 + " ".join(map(short, base.keys())) + "\n")
1453
1454 remain = set(self.changelog.nodemap)
1455
1456 # prune everything remote has from the tree
1457 remain.remove(nullid)
1458 remove = base.keys()
1459 while remove:
1460 n = remove.pop(0)
1461 if n in remain:
1462 remain.remove(n)
1463 for p in self.changelog.parents(n):
1464 remove.append(p)
1465
1466 # find every node whose parents have been pruned
1467 subset = []
1468 # find every remote head that will get new children
1469 updated_heads = set()
1470 for n in remain:
1471 p1, p2 = self.changelog.parents(n)
1472 if p1 not in remain and p2 not in remain:
1473 subset.append(n)
1474 if heads:
1475 if p1 in heads:
1476 updated_heads.add(p1)
1477 if p2 in heads:
1478 updated_heads.add(p2)
1479
1480 # this is the set of all roots we have to push
203 # find every node whose parents have been pruned
204 subset = []
205 # find every remote head that will get new children
206 updated_heads = set()
207 for n in remain:
208 p1, p2 = repo.changelog.parents(n)
209 if p1 not in remain and p2 not in remain:
210 subset.append(n)
1481 211 if heads:
1482 return subset, list(updated_heads)
1483 else:
1484 return subset
1485
1486 def pull(self, remote, heads=None, force=False):
1487 lock = self.lock()
1488 try:
1489 common, fetch, rheads = self.findcommonincoming(remote, heads=heads,
1490 force=force)
1491 if not fetch:
1492 self.ui.status(_("no changes found\n"))
1493 return 0
1494
1495 if fetch == [nullid]:
1496 self.ui.status(_("requesting all changes\n"))
1497 elif heads is None and remote.capable('changegroupsubset'):
1498 # issue1320, avoid a race if remote changed after discovery
1499 heads = rheads
212 if p1 in heads:
213 updated_heads.add(p1)
214 if p2 in heads:
215 updated_heads.add(p2)
1500 216
1501 if heads is None:
1502 cg = remote.changegroup(fetch, 'pull')
1503 else:
1504 if not remote.capable('changegroupsubset'):
1505 raise util.Abort(_("Partial pull cannot be done because "
1506 "other repository doesn't support "
1507 "changegroupsubset."))
1508 cg = remote.changegroupsubset(fetch, heads, 'pull')
1509 return self.addchangegroup(cg, 'pull', remote.url())
1510 finally:
1511 lock.release()
1512
1513 def push(self, remote, force=False, revs=None, newbranch=False):
1514 '''Push outgoing changesets (limited by revs) from the current
1515 repository to remote. Return an integer:
1516 - 0 means HTTP error *or* nothing to push
1517 - 1 means we pushed and remote head count is unchanged *or*
1518 we have outgoing changesets but refused to push
1519 - other values as described by addchangegroup()
1520 '''
1521 # there are two ways to push to remote repo:
1522 #
1523 # addchangegroup assumes local user can lock remote
1524 # repo (local filesystem, old ssh servers).
1525 #
1526 # unbundle assumes local user cannot lock remote repo (new ssh
1527 # servers, http servers).
1528
1529 if remote.capable('unbundle'):
1530 return self.push_unbundle(remote, force, revs, newbranch)
1531 return self.push_addchangegroup(remote, force, revs, newbranch)
1532
1533 def prepush(self, remote, force, revs, newbranch):
1534 '''Analyze the local and remote repositories and determine which
1535 changesets need to be pushed to the remote. Return value depends
1536 on circumstances:
1537
1538 If we are not going to push anything, return a tuple (None,
1539 outgoing) where outgoing is 0 if there are no outgoing
1540 changesets and 1 if there are, but we refuse to push them
1541 (e.g. would create new remote heads).
1542
1543 Otherwise, return a tuple (changegroup, remoteheads), where
1544 changegroup is a readable file-like object whose read() returns
1545 successive changegroup chunks ready to be sent over the wire and
1546 remoteheads is the list of remote heads.'''
1547 common = {}
1548 remote_heads = remote.heads()
1549 inc = self.findincoming(remote, common, remote_heads, force=force)
1550
1551 cl = self.changelog
1552 update, updated_heads = self.findoutgoing(remote, common, remote_heads)
1553 outg, bases, heads = cl.nodesbetween(update, revs)
1554
1555 if not bases:
1556 self.ui.status(_("no changes found\n"))
1557 return None, 1
1558
1559 if not force and remote_heads != [nullid]:
1560
1561 def fail_multiple_heads(unsynced, branch=None):
1562 if branch:
1563 msg = _("abort: push creates new remote heads"
1564 " on branch '%s'!\n") % branch
1565 else:
1566 msg = _("abort: push creates new remote heads!\n")
1567 self.ui.warn(msg)
1568 if unsynced:
1569 self.ui.status(_("(you should pull and merge or"
1570 " use push -f to force)\n"))
1571 else:
1572 self.ui.status(_("(did you forget to merge?"
1573 " use push -f to force)\n"))
1574 return None, 0
217 # this is the set of all roots we have to push
218 if heads:
219 return subset, list(updated_heads)
220 else:
221 return subset
1575 222
1576 if remote.capable('branchmap'):
1577 # Check for each named branch if we're creating new remote heads.
1578 # To be a remote head after push, node must be either:
1579 # - unknown locally
1580 # - a local outgoing head descended from update
1581 # - a remote head that's known locally and not
1582 # ancestral to an outgoing head
1583 #
1584 # New named branches cannot be created without --force.
1585
1586 # 1. Create set of branches involved in the push.
1587 branches = set(self[n].branch() for n in outg)
1588
1589 # 2. Check for new branches on the remote.
1590 remotemap = remote.branchmap()
1591 newbranches = branches - set(remotemap)
1592 if newbranches and not newbranch: # new branch requires --new-branch
1593 branchnames = ', '.join("%s" % b for b in newbranches)
1594 self.ui.warn(_("abort: push creates "
1595 "new remote branches: %s!\n")
1596 % branchnames)
1597 self.ui.status(_("(use 'hg push --new-branch' to create new "
1598 "remote branches)\n"))
1599 return None, 0
1600 branches.difference_update(newbranches)
223 def prepush(repo, remote, force, revs, newbranch):
224 '''Analyze the local and remote repositories and determine which
225 changesets need to be pushed to the remote. Return value depends
226 on circumstances:
1601 227
1602 # 3. Construct the initial oldmap and newmap dicts.
1603 # They contain information about the remote heads before and
1604 # after the push, respectively.
1605 # Heads not found locally are not included in either dict,
1606 # since they won't be affected by the push.
1607 # unsynced contains all branches with incoming changesets.
1608 oldmap = {}
1609 newmap = {}
1610 unsynced = set()
1611 for branch in branches:
1612 remoteheads = remotemap[branch]
1613 prunedheads = [h for h in remoteheads if h in cl.nodemap]
1614 oldmap[branch] = prunedheads
1615 newmap[branch] = list(prunedheads)
1616 if len(remoteheads) > len(prunedheads):
1617 unsynced.add(branch)
1618
1619 # 4. Update newmap with outgoing changes.
1620 # This will possibly add new heads and remove existing ones.
1621 ctxgen = (self[n] for n in outg)
1622 self._updatebranchcache(newmap, ctxgen)
1623
1624 # 5. Check for new heads.
1625 # If there are more heads after the push than before, a suitable
1626 # warning, depending on unsynced status, is displayed.
1627 for branch in branches:
1628 if len(newmap[branch]) > len(oldmap[branch]):
1629 return fail_multiple_heads(branch in unsynced, branch)
1630
1631 # 6. Check for unsynced changes on involved branches.
1632 if unsynced:
1633 self.ui.warn(_("note: unsynced remote changes!\n"))
228 If we are not going to push anything, return a tuple (None,
229 outgoing) where outgoing is 0 if there are no outgoing
230 changesets and 1 if there are, but we refuse to push them
231 (e.g. would create new remote heads).
1634 232
1635 else:
1636 # Old servers: Check for new topological heads.
1637 # Code based on _updatebranchcache.
1638 newheads = set(h for h in remote_heads if h in cl.nodemap)
1639 oldheadcnt = len(newheads)
1640 newheads.update(outg)
1641 if len(newheads) > 1:
1642 for latest in reversed(outg):
1643 if latest not in newheads:
1644 continue
1645 minhrev = min(cl.rev(h) for h in newheads)
1646 reachable = cl.reachable(latest, cl.node(minhrev))
1647 reachable.remove(latest)
1648 newheads.difference_update(reachable)
1649 if len(newheads) > oldheadcnt:
1650 return fail_multiple_heads(inc)
1651 if inc:
1652 self.ui.warn(_("note: unsynced remote changes!\n"))
1653
1654 if revs is None:
1655 # use the fast path, no race possible on push
1656 nodes = self.changelog.findmissing(common.keys())
1657 cg = self._changegroup(nodes, 'push')
1658 else:
1659 cg = self.changegroupsubset(update, revs, 'push')
1660 return cg, remote_heads
233 Otherwise, return a tuple (changegroup, remoteheads), where
234 changegroup is a readable file-like object whose read() returns
235 successive changegroup chunks ready to be sent over the wire and
236 remoteheads is the list of remote heads.'''
237 common = {}
238 remote_heads = remote.heads()
239 inc = findincoming(repo, remote, common, remote_heads, force=force)
1661 240
1662 def push_addchangegroup(self, remote, force, revs, newbranch):
1663 '''Push a changegroup by locking the remote and sending the
1664 addchangegroup command to it. Used for local and old SSH repos.
1665 Return an integer: see push().
1666 '''
1667 lock = remote.lock()
1668 try:
1669 ret = self.prepush(remote, force, revs, newbranch)
1670 if ret[0] is not None:
1671 cg, remote_heads = ret
1672 # here, we return an integer indicating remote head count change
1673 return remote.addchangegroup(cg, 'push', self.url())
1674 # and here we return 0 for "nothing to push" or 1 for
1675 # "something to push but I refuse"
1676 return ret[1]
1677 finally:
1678 lock.release()
1679
1680 def push_unbundle(self, remote, force, revs, newbranch):
1681 '''Push a changegroup by unbundling it on the remote. Used for new
1682 SSH and HTTP repos. Return an integer: see push().'''
1683 # local repo finds heads on server, finds out what revs it
1684 # must push. once revs transferred, if server finds it has
1685 # different heads (someone else won commit/push race), server
1686 # aborts.
241 cl = repo.changelog
242 update, updated_heads = findoutgoing(repo, remote, common, remote_heads)
243 outg, bases, heads = cl.nodesbetween(update, revs)
1687 244
1688 ret = self.prepush(remote, force, revs, newbranch)
1689 if ret[0] is not None:
1690 cg, remote_heads = ret
1691 if force:
1692 remote_heads = ['force']
1693 # ssh: return remote's addchangegroup()
1694 # http: return remote's addchangegroup() or 0 for error
1695 return remote.unbundle(cg, remote_heads, 'push')
1696 # as in push_addchangegroup()
1697 return ret[1]
245 if not bases:
246 repo.ui.status(_("no changes found\n"))
247 return None, 1
1698 248
1699 def changegroupinfo(self, nodes, source):
1700 if self.ui.verbose or source == 'bundle':
1701 self.ui.status(_("%d changesets found\n") % len(nodes))
1702 if self.ui.debugflag:
1703 self.ui.debug("list of changesets:\n")
1704 for node in nodes:
1705 self.ui.debug("%s\n" % hex(node))
1706
1707 def changegroupsubset(self, bases, heads, source, extranodes=None):
1708 """Compute a changegroup consisting of all the nodes that are
1709 descendents of any of the bases and ancestors of any of the heads.
1710 Return a chunkbuffer object whose read() method will return
1711 successive changegroup chunks.
1712
1713 It is fairly complex as determining which filenodes and which
1714 manifest nodes need to be included for the changeset to be complete
1715 is non-trivial.
1716
1717 Another wrinkle is doing the reverse, figuring out which changeset in
1718 the changegroup a particular filenode or manifestnode belongs to.
249 if not force and remote_heads != [nullid]:
1719 250
1720 The caller can specify some nodes that must be included in the
1721 changegroup using the extranodes argument. It should be a dict
1722 where the keys are the filenames (or 1 for the manifest), and the
1723 values are lists of (node, linknode) tuples, where node is a wanted
1724 node and linknode is the changelog node that should be transmitted as
1725 the linkrev.
1726 """
1727
1728 # Set up some initial variables
1729 # Make it easy to refer to self.changelog
1730 cl = self.changelog
1731 # msng is short for missing - compute the list of changesets in this
1732 # changegroup.
1733 if not bases:
1734 bases = [nullid]
1735 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1736
1737 if extranodes is None:
1738 # can we go through the fast path ?
1739 heads.sort()
1740 allheads = self.heads()
1741 allheads.sort()
1742 if heads == allheads:
1743 return self._changegroup(msng_cl_lst, source)
1744
1745 # slow path
1746 self.hook('preoutgoing', throw=True, source=source)
1747
1748 self.changegroupinfo(msng_cl_lst, source)
1749 # Some bases may turn out to be superfluous, and some heads may be
1750 # too. nodesbetween will return the minimal set of bases and heads
1751 # necessary to re-create the changegroup.
1752
1753 # Known heads are the list of heads that it is assumed the recipient
1754 # of this changegroup will know about.
1755 knownheads = set()
1756 # We assume that all parents of bases are known heads.
1757 for n in bases:
1758 knownheads.update(cl.parents(n))
1759 knownheads.discard(nullid)
1760 knownheads = list(knownheads)
1761 if knownheads:
1762 # Now that we know what heads are known, we can compute which
1763 # changesets are known. The recipient must know about all
1764 # changesets required to reach the known heads from the null
1765 # changeset.
1766 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1767 junk = None
1768 # Transform the list into a set.
1769 has_cl_set = set(has_cl_set)
1770 else:
1771 # If there were no known heads, the recipient cannot be assumed to
1772 # know about any changesets.
1773 has_cl_set = set()
1774
1775 # Make it easy to refer to self.manifest
1776 mnfst = self.manifest
1777 # We don't know which manifests are missing yet
1778 msng_mnfst_set = {}
1779 # Nor do we know which filenodes are missing.
1780 msng_filenode_set = {}
1781
1782 junk = mnfst.index[len(mnfst) - 1] # Get around a bug in lazyindex
1783 junk = None
1784
1785 # A changeset always belongs to itself, so the changenode lookup
1786 # function for a changenode is identity.
1787 def identity(x):
1788 return x
1789
1790 # If we determine that a particular file or manifest node must be a
1791 # node that the recipient of the changegroup will already have, we can
1792 # also assume the recipient will have all the parents. This function
1793 # prunes them from the set of missing nodes.
1794 def prune_parents(revlog, hasset, msngset):
1795 for r in revlog.ancestors(*[revlog.rev(n) for n in hasset]):
1796 msngset.pop(revlog.node(r), None)
1797
1798 # Use the information collected in collect_manifests_and_files to say
1799 # which changenode any manifestnode belongs to.
1800 def lookup_manifest_link(mnfstnode):
1801 return msng_mnfst_set[mnfstnode]
1802
1803 # A function generating function that sets up the initial environment
1804 # the inner function.
1805 def filenode_collector(changedfiles):
1806 # This gathers information from each manifestnode included in the
1807 # changegroup about which filenodes the manifest node references
1808 # so we can include those in the changegroup too.
1809 #
1810 # It also remembers which changenode each filenode belongs to. It
1811 # does this by assuming the a filenode belongs to the changenode
1812 # the first manifest that references it belongs to.
1813 def collect_msng_filenodes(mnfstnode):
1814 r = mnfst.rev(mnfstnode)
1815 if r - 1 in mnfst.parentrevs(r):
1816 # If the previous rev is one of the parents,
1817 # we only need to see a diff.
1818 deltamf = mnfst.readdelta(mnfstnode)
1819 # For each line in the delta
1820 for f, fnode in deltamf.iteritems():
1821 f = changedfiles.get(f, None)
1822 # And if the file is in the list of files we care
1823 # about.
1824 if f is not None:
1825 # Get the changenode this manifest belongs to
1826 clnode = msng_mnfst_set[mnfstnode]
1827 # Create the set of filenodes for the file if
1828 # there isn't one already.
1829 ndset = msng_filenode_set.setdefault(f, {})
1830 # And set the filenode's changelog node to the
1831 # manifest's if it hasn't been set already.
1832 ndset.setdefault(fnode, clnode)
1833 else:
1834 # Otherwise we need a full manifest.
1835 m = mnfst.read(mnfstnode)
1836 # For every file in we care about.
1837 for f in changedfiles:
1838 fnode = m.get(f, None)
1839 # If it's in the manifest
1840 if fnode is not None:
1841 # See comments above.
1842 clnode = msng_mnfst_set[mnfstnode]
1843 ndset = msng_filenode_set.setdefault(f, {})
1844 ndset.setdefault(fnode, clnode)
1845 return collect_msng_filenodes
1846
1847 # We have a list of filenodes we think we need for a file, lets remove
1848 # all those we know the recipient must have.
1849 def prune_filenodes(f, filerevlog):
1850 msngset = msng_filenode_set[f]
1851 hasset = set()
1852 # If a 'missing' filenode thinks it belongs to a changenode we
1853 # assume the recipient must have, then the recipient must have
1854 # that filenode.
1855 for n in msngset:
1856 clnode = cl.node(filerevlog.linkrev(filerevlog.rev(n)))
1857 if clnode in has_cl_set:
1858 hasset.add(n)
1859 prune_parents(filerevlog, hasset, msngset)
251 def fail_multiple_heads(unsynced, branch=None):
252 if branch:
253 msg = _("abort: push creates new remote heads"
254 " on branch '%s'!\n") % branch
255 else:
256 msg = _("abort: push creates new remote heads!\n")
257 repo.ui.warn(msg)
258 if unsynced:
259 repo.ui.status(_("(you should pull and merge or"
260 " use push -f to force)\n"))
261 else:
262 repo.ui.status(_("(did you forget to merge?"
263 " use push -f to force)\n"))
264 return None, 0
1860 265
1861 # A function generator function that sets up the a context for the
1862 # inner function.
1863 def lookup_filenode_link_func(fname):
1864 msngset = msng_filenode_set[fname]
1865 # Lookup the changenode the filenode belongs to.
1866 def lookup_filenode_link(fnode):
1867 return msngset[fnode]
1868 return lookup_filenode_link
1869
1870 # Add the nodes that were explicitly requested.
1871 def add_extra_nodes(name, nodes):
1872 if not extranodes or name not in extranodes:
1873 return
1874
1875 for node, linknode in extranodes[name]:
1876 if node not in nodes:
1877 nodes[node] = linknode
1878
1879 # Now that we have all theses utility functions to help out and
1880 # logically divide up the task, generate the group.
1881 def gengroup():
1882 # The set of changed files starts empty.
1883 changedfiles = {}
1884 collect = changegroup.collector(cl, msng_mnfst_set, changedfiles)
266 if remote.capable('branchmap'):
267 # Check for each named branch if we're creating new remote heads.
268 # To be a remote head after push, node must be either:
269 # - unknown locally
270 # - a local outgoing head descended from update
271 # - a remote head that's known locally and not
272 # ancestral to an outgoing head
273 #
274 # New named branches cannot be created without --force.
1885 275
1886 # Create a changenode group generator that will call our functions
1887 # back to lookup the owning changenode and collect information.
1888 group = cl.group(msng_cl_lst, identity, collect)
1889 cnt = 0
1890 for chnk in group:
1891 yield chnk
1892 self.ui.progress(_('bundling changes'), cnt, unit=_('chunks'))
1893 cnt += 1
1894 self.ui.progress(_('bundling changes'), None)
1895
1896
1897 # Figure out which manifest nodes (of the ones we think might be
1898 # part of the changegroup) the recipient must know about and
1899 # remove them from the changegroup.
1900 has_mnfst_set = set()
1901 for n in msng_mnfst_set:
1902 # If a 'missing' manifest thinks it belongs to a changenode
1903 # the recipient is assumed to have, obviously the recipient
1904 # must have that manifest.
1905 linknode = cl.node(mnfst.linkrev(mnfst.rev(n)))
1906 if linknode in has_cl_set:
1907 has_mnfst_set.add(n)
1908 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1909 add_extra_nodes(1, msng_mnfst_set)
1910 msng_mnfst_lst = msng_mnfst_set.keys()
1911 # Sort the manifestnodes by revision number.
1912 msng_mnfst_lst.sort(key=mnfst.rev)
1913 # Create a generator for the manifestnodes that calls our lookup
1914 # and data collection functions back.
1915 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1916 filenode_collector(changedfiles))
1917 cnt = 0
1918 for chnk in group:
1919 yield chnk
1920 self.ui.progress(_('bundling manifests'), cnt, unit=_('chunks'))
1921 cnt += 1
1922 self.ui.progress(_('bundling manifests'), None)
1923
1924 # These are no longer needed, dereference and toss the memory for
1925 # them.
1926 msng_mnfst_lst = None
1927 msng_mnfst_set.clear()
276 # 1. Create set of branches involved in the push.
277 branches = set(repo[n].branch() for n in outg)
1928 278
1929 if extranodes:
1930 for fname in extranodes:
1931 if isinstance(fname, int):
1932 continue
1933 msng_filenode_set.setdefault(fname, {})
1934 changedfiles[fname] = 1
1935 # Go through all our files in order sorted by name.
1936 cnt = 0
1937 for fname in sorted(changedfiles):
1938 filerevlog = self.file(fname)
1939 if not len(filerevlog):
1940 raise util.Abort(_("empty or missing revlog for %s") % fname)
1941 # Toss out the filenodes that the recipient isn't really
1942 # missing.
1943 if fname in msng_filenode_set:
1944 prune_filenodes(fname, filerevlog)
1945 add_extra_nodes(fname, msng_filenode_set[fname])
1946 msng_filenode_lst = msng_filenode_set[fname].keys()
1947 else:
1948 msng_filenode_lst = []
1949 # If any filenodes are left, generate the group for them,
1950 # otherwise don't bother.
1951 if len(msng_filenode_lst) > 0:
1952 yield changegroup.chunkheader(len(fname))
1953 yield fname
1954 # Sort the filenodes by their revision #
1955 msng_filenode_lst.sort(key=filerevlog.rev)
1956 # Create a group generator and only pass in a changenode
1957 # lookup function as we need to collect no information
1958 # from filenodes.
1959 group = filerevlog.group(msng_filenode_lst,
1960 lookup_filenode_link_func(fname))
1961 for chnk in group:
1962 self.ui.progress(
1963 _('bundling files'), cnt, item=fname, unit=_('chunks'))
1964 cnt += 1
1965 yield chnk
1966 if fname in msng_filenode_set:
1967 # Don't need this anymore, toss it to free memory.
1968 del msng_filenode_set[fname]
1969 # Signal that no more groups are left.
1970 yield changegroup.closechunk()
1971 self.ui.progress(_('bundling files'), None)
1972
1973 if msng_cl_lst:
1974 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1975
1976 return util.chunkbuffer(gengroup())
1977
1978 def changegroup(self, basenodes, source):
1979 # to avoid a race we use changegroupsubset() (issue1320)
1980 return self.changegroupsubset(basenodes, self.heads(), source)
1981
1982 def _changegroup(self, nodes, source):
1983 """Compute the changegroup of all nodes that we have that a recipient
1984 doesn't. Return a chunkbuffer object whose read() method will return
1985 successive changegroup chunks.
1986
1987 This is much easier than the previous function as we can assume that
1988 the recipient has any changenode we aren't sending them.
1989
1990 nodes is the set of nodes to send"""
1991
1992 self.hook('preoutgoing', throw=True, source=source)
1993
1994 cl = self.changelog
1995 revset = set([cl.rev(n) for n in nodes])
1996 self.changegroupinfo(nodes, source)
1997
1998 def identity(x):
1999 return x
2000
2001 def gennodelst(log):
2002 for r in log:
2003 if log.linkrev(r) in revset:
2004 yield log.node(r)
279 # 2. Check for new branches on the remote.
280 remotemap = remote.branchmap()
281 newbranches = branches - set(remotemap)
282 if newbranches and not newbranch: # new branch requires --new-branch
283 branchnames = ', '.join("%s" % b for b in newbranches)
284 repo.ui.warn(_("abort: push creates "
285 "new remote branches: %s!\n")
286 % branchnames)
287 repo.ui.status(_("(use 'hg push --new-branch' to create new "
288 "remote branches)\n"))
289 return None, 0
290 branches.difference_update(newbranches)
2005 291
2006 def lookuprevlink_func(revlog):
2007 def lookuprevlink(n):
2008 return cl.node(revlog.linkrev(revlog.rev(n)))
2009 return lookuprevlink
2010
2011 def gengroup():
2012 '''yield a sequence of changegroup chunks (strings)'''
2013 # construct a list of all changed files
2014 changedfiles = {}
2015 mmfs = {}
2016 collect = changegroup.collector(cl, mmfs, changedfiles)
2017
2018 cnt = 0
2019 for chnk in cl.group(nodes, identity, collect):
2020 self.ui.progress(_('bundling changes'), cnt, unit=_('chunks'))
2021 cnt += 1
2022 yield chnk
2023 self.ui.progress(_('bundling changes'), None)
2024
2025 mnfst = self.manifest
2026 nodeiter = gennodelst(mnfst)
2027 cnt = 0
2028 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
2029 self.ui.progress(_('bundling manifests'), cnt, unit=_('chunks'))
2030 cnt += 1
2031 yield chnk
2032 self.ui.progress(_('bundling manifests'), None)
2033
2034 cnt = 0
2035 for fname in sorted(changedfiles):
2036 filerevlog = self.file(fname)
2037 if not len(filerevlog):
2038 raise util.Abort(_("empty or missing revlog for %s") % fname)
2039 nodeiter = gennodelst(filerevlog)
2040 nodeiter = list(nodeiter)
2041 if nodeiter:
2042 yield changegroup.chunkheader(len(fname))
2043 yield fname
2044 lookup = lookuprevlink_func(filerevlog)
2045 for chnk in filerevlog.group(nodeiter, lookup):
2046 self.ui.progress(
2047 _('bundling files'), cnt, item=fname, unit=_('chunks'))
2048 cnt += 1
2049 yield chnk
2050 self.ui.progress(_('bundling files'), None)
2051
2052 yield changegroup.closechunk()
2053
2054 if nodes:
2055 self.hook('outgoing', node=hex(nodes[0]), source=source)
2056
2057 return util.chunkbuffer(gengroup())
2058
2059 def addchangegroup(self, source, srctype, url, emptyok=False):
2060 """Add the changegroup returned by source.read() to this repo.
2061 srctype is a string like 'push', 'pull', or 'unbundle'. url is
2062 the URL of the repo where this changegroup is coming from.
292 # 3. Construct the initial oldmap and newmap dicts.
293 # They contain information about the remote heads before and
294 # after the push, respectively.
295 # Heads not found locally are not included in either dict,
296 # since they won't be affected by the push.
297 # unsynced contains all branches with incoming changesets.
298 oldmap = {}
299 newmap = {}
300 unsynced = set()
301 for branch in branches:
302 remoteheads = remotemap[branch]
303 prunedheads = [h for h in remoteheads if h in cl.nodemap]
304 oldmap[branch] = prunedheads
305 newmap[branch] = list(prunedheads)
306 if len(remoteheads) > len(prunedheads):
307 unsynced.add(branch)
2063 308
2064 Return an integer summarizing the change to this repo:
2065 - nothing changed or no source: 0
2066 - more heads than before: 1+added heads (2..n)
2067 - fewer heads than before: -1-removed heads (-2..-n)
2068 - number of heads stays the same: 1
2069 """
2070 def csmap(x):
2071 self.ui.debug("add changeset %s\n" % short(x))
2072 return len(cl)
2073
2074 def revmap(x):
2075 return cl.rev(x)
2076
2077 if not source:
2078 return 0
2079
2080 self.hook('prechangegroup', throw=True, source=srctype, url=url)
2081
2082 changesets = files = revisions = 0
2083 efiles = set()
2084
2085 # write changelog data to temp files so concurrent readers will not see
2086 # inconsistent view
2087 cl = self.changelog
2088 cl.delayupdate()
2089 oldheads = len(cl.heads())
309 # 4. Update newmap with outgoing changes.
310 # This will possibly add new heads and remove existing ones.
311 ctxgen = (repo[n] for n in outg)
312 repo._updatebranchcache(newmap, ctxgen)
2090 313
2091 tr = self.transaction("\n".join([srctype, urlmod.hidepassword(url)]))
2092 try:
2093 trp = weakref.proxy(tr)
2094 # pull off the changeset group
2095 self.ui.status(_("adding changesets\n"))
2096 clstart = len(cl)
2097 class prog(object):
2098 step = _('changesets')
2099 count = 1
2100 ui = self.ui
2101 total = None
2102 def __call__(self):
2103 self.ui.progress(self.step, self.count, unit=_('chunks'),
2104 total=self.total)
2105 self.count += 1
2106 pr = prog()
2107 chunkiter = changegroup.chunkiter(source, progress=pr)
2108 if cl.addgroup(chunkiter, csmap, trp) is None and not emptyok:
2109 raise util.Abort(_("received changelog group is empty"))
2110 clend = len(cl)
2111 changesets = clend - clstart
2112 for c in xrange(clstart, clend):
2113 efiles.update(self[c].files())
2114 efiles = len(efiles)
2115 self.ui.progress(_('changesets'), None)
2116
2117 # pull off the manifest group
2118 self.ui.status(_("adding manifests\n"))
2119 pr.step = _('manifests')
2120 pr.count = 1
2121 pr.total = changesets # manifests <= changesets
2122 chunkiter = changegroup.chunkiter(source, progress=pr)
2123 # no need to check for empty manifest group here:
2124 # if the result of the merge of 1 and 2 is the same in 3 and 4,
2125 # no new manifest will be created and the manifest group will
2126 # be empty during the pull
2127 self.manifest.addgroup(chunkiter, revmap, trp)
2128 self.ui.progress(_('manifests'), None)
2129
2130 needfiles = {}
2131 if self.ui.configbool('server', 'validate', default=False):
2132 # validate incoming csets have their manifests
2133 for cset in xrange(clstart, clend):
2134 mfest = self.changelog.read(self.changelog.node(cset))[0]
2135 mfest = self.manifest.readdelta(mfest)
2136 # store file nodes we must see
2137 for f, n in mfest.iteritems():
2138 needfiles.setdefault(f, set()).add(n)
314 # 5. Check for new heads.
315 # If there are more heads after the push than before, a suitable
316 # warning, depending on unsynced status, is displayed.
317 for branch in branches:
318 if len(newmap[branch]) > len(oldmap[branch]):
319 return fail_multiple_heads(branch in unsynced, branch)
2139 320
2140 # process the files
2141 self.ui.status(_("adding file changes\n"))
2142 pr.step = 'files'
2143 pr.count = 1
2144 pr.total = efiles
2145 while 1:
2146 f = changegroup.getchunk(source)
2147 if not f:
2148 break
2149 self.ui.debug("adding %s revisions\n" % f)
2150 pr()
2151 fl = self.file(f)
2152 o = len(fl)
2153 chunkiter = changegroup.chunkiter(source)
2154 if fl.addgroup(chunkiter, revmap, trp) is None:
2155 raise util.Abort(_("received file revlog group is empty"))
2156 revisions += len(fl) - o
2157 files += 1
2158 if f in needfiles:
2159 needs = needfiles[f]
2160 for new in xrange(o, len(fl)):
2161 n = fl.node(new)
2162 if n in needs:
2163 needs.remove(n)
2164 if not needs:
2165 del needfiles[f]
2166 self.ui.progress(_('files'), None)
2167
2168 for f, needs in needfiles.iteritems():
2169 fl = self.file(f)
2170 for n in needs:
2171 try:
2172 fl.rev(n)
2173 except error.LookupError:
2174 raise util.Abort(
2175 _('missing file data for %s:%s - run hg verify') %
2176 (f, hex(n)))
2177
2178 newheads = len(cl.heads())
2179 heads = ""
2180 if oldheads and newheads != oldheads:
2181 heads = _(" (%+d heads)") % (newheads - oldheads)
2182
2183 self.ui.status(_("added %d changesets"
2184 " with %d changes to %d files%s\n")
2185 % (changesets, revisions, files, heads))
2186
2187 if changesets > 0:
2188 p = lambda: cl.writepending() and self.root or ""
2189 self.hook('pretxnchangegroup', throw=True,
2190 node=hex(cl.node(clstart)), source=srctype,
2191 url=url, pending=p)
2192
2193 # make changelog see real files again
2194 cl.finalize(trp)
2195
2196 tr.close()
2197 finally:
2198 tr.release()
2199
2200 if changesets > 0:
2201 # forcefully update the on-disk branch cache
2202 self.ui.debug("updating the branch cache\n")
2203 self.branchtags()
2204 self.hook("changegroup", node=hex(cl.node(clstart)),
2205 source=srctype, url=url)
2206
2207 for i in xrange(clstart, clend):
2208 self.hook("incoming", node=hex(cl.node(i)),
2209 source=srctype, url=url)
2210
2211 # never return 0 here:
2212 if newheads < oldheads:
2213 return newheads - oldheads - 1
2214 else:
2215 return newheads - oldheads + 1
2216
321 # 6. Check for unsynced changes on involved branches.
322 if unsynced:
323 repo.ui.warn(_("note: unsynced remote changes!\n"))
2217 324
2218 def stream_in(self, remote):
2219 fp = remote.stream_out()
2220 l = fp.readline()
2221 try:
2222 resp = int(l)
2223 except ValueError:
2224 raise error.ResponseError(
2225 _('Unexpected response from remote server:'), l)
2226 if resp == 1:
2227 raise util.Abort(_('operation forbidden by server'))
2228 elif resp == 2:
2229 raise util.Abort(_('locking the remote repository failed'))
2230 elif resp != 0:
2231 raise util.Abort(_('the server sent an unknown error code'))
2232 self.ui.status(_('streaming all changes\n'))
2233 l = fp.readline()
2234 try:
2235 total_files, total_bytes = map(int, l.split(' ', 1))
2236 except (ValueError, TypeError):
2237 raise error.ResponseError(
2238 _('Unexpected response from remote server:'), l)
2239 self.ui.status(_('%d files to transfer, %s of data\n') %
2240 (total_files, util.bytecount(total_bytes)))
2241 start = time.time()
2242 for i in xrange(total_files):
2243 # XXX doesn't support '\n' or '\r' in filenames
2244 l = fp.readline()
2245 try:
2246 name, size = l.split('\0', 1)
2247 size = int(size)
2248 except (ValueError, TypeError):
2249 raise error.ResponseError(
2250 _('Unexpected response from remote server:'), l)
2251 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
2252 # for backwards compat, name was partially encoded
2253 ofp = self.sopener(store.decodedir(name), 'w')
2254 for chunk in util.filechunkiter(fp, limit=size):
2255 ofp.write(chunk)
2256 ofp.close()
2257 elapsed = time.time() - start
2258 if elapsed <= 0:
2259 elapsed = 0.001
2260 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
2261 (util.bytecount(total_bytes), elapsed,
2262 util.bytecount(total_bytes / elapsed)))
2263 self.invalidate()
2264 return len(self.heads()) + 1
325 else:
326 # Old servers: Check for new topological heads.
327 # Code based on _updatebranchcache.
328 newheads = set(h for h in remote_heads if h in cl.nodemap)
329 oldheadcnt = len(newheads)
330 newheads.update(outg)
331 if len(newheads) > 1:
332 for latest in reversed(outg):
333 if latest not in newheads:
334 continue
335 minhrev = min(cl.rev(h) for h in newheads)
336 reachable = cl.reachable(latest, cl.node(minhrev))
337 reachable.remove(latest)
338 newheads.difference_update(reachable)
339 if len(newheads) > oldheadcnt:
340 return fail_multiple_heads(inc)
341 if inc:
342 repo.ui.warn(_("note: unsynced remote changes!\n"))
2265 343
2266 def clone(self, remote, heads=[], stream=False):
2267 '''clone remote repository.
2268
2269 keyword arguments:
2270 heads: list of revs to clone (forces use of pull)
2271 stream: use streaming clone if possible'''
2272
2273 # now, all clients that can request uncompressed clones can
2274 # read repo formats supported by all servers that can serve
2275 # them.
2276
2277 # if revlog format changes, client will have to check version
2278 # and format flags on "stream" capability, and use
2279 # uncompressed only if compatible.
2280
2281 if stream and not heads and remote.capable('stream'):
2282 return self.stream_in(remote)
2283 return self.pull(remote, heads)
2284
2285 # used to avoid circular references so destructors work
2286 def aftertrans(files):
2287 renamefiles = [tuple(t) for t in files]
2288 def a():
2289 for src, dest in renamefiles:
2290 util.rename(src, dest)
2291 return a
2292
2293 def instance(ui, path, create):
2294 return localrepository(ui, util.drop_scheme('file', path), create)
2295
2296 def islocal(path):
2297 return True
344 if revs is None:
345 # use the fast path, no race possible on push
346 nodes = repo.changelog.findmissing(common.keys())
347 cg = repo._changegroup(nodes, 'push')
348 else:
349 cg = repo.changegroupsubset(update, revs, 'push')
350 return cg, remote_heads
@@ -1,2297 +1,1958
1 1 # localrepo.py - read/write repository class for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from node import bin, hex, nullid, nullrev, short
9 9 from i18n import _
10 import repo, changegroup, subrepo
10 import repo, changegroup, subrepo, discovery
11 11 import changelog, dirstate, filelog, manifest, context
12 12 import lock, transaction, store, encoding
13 13 import util, extensions, hook, error
14 14 import match as matchmod
15 15 import merge as mergemod
16 16 import tags as tagsmod
17 17 import url as urlmod
18 18 from lock import release
19 19 import weakref, stat, errno, os, time, inspect
20 20 propertycache = util.propertycache
21 21
22 22 class localrepository(repo.repository):
23 23 capabilities = set(('lookup', 'changegroupsubset', 'branchmap'))
24 24 supported = set('revlogv1 store fncache shared'.split())
25 25
26 26 def __init__(self, baseui, path=None, create=0):
27 27 repo.repository.__init__(self)
28 28 self.root = os.path.realpath(util.expandpath(path))
29 29 self.path = os.path.join(self.root, ".hg")
30 30 self.origroot = path
31 31 self.opener = util.opener(self.path)
32 32 self.wopener = util.opener(self.root)
33 33 self.baseui = baseui
34 34 self.ui = baseui.copy()
35 35
36 36 try:
37 37 self.ui.readconfig(self.join("hgrc"), self.root)
38 38 extensions.loadall(self.ui)
39 39 except IOError:
40 40 pass
41 41
42 42 if not os.path.isdir(self.path):
43 43 if create:
44 44 if not os.path.exists(path):
45 45 os.mkdir(path)
46 46 os.mkdir(self.path)
47 47 requirements = ["revlogv1"]
48 48 if self.ui.configbool('format', 'usestore', True):
49 49 os.mkdir(os.path.join(self.path, "store"))
50 50 requirements.append("store")
51 51 if self.ui.configbool('format', 'usefncache', True):
52 52 requirements.append("fncache")
53 53 # create an invalid changelog
54 54 self.opener("00changelog.i", "a").write(
55 55 '\0\0\0\2' # represents revlogv2
56 56 ' dummy changelog to prevent using the old repo layout'
57 57 )
58 58 reqfile = self.opener("requires", "w")
59 59 for r in requirements:
60 60 reqfile.write("%s\n" % r)
61 61 reqfile.close()
62 62 else:
63 63 raise error.RepoError(_("repository %s not found") % path)
64 64 elif create:
65 65 raise error.RepoError(_("repository %s already exists") % path)
66 66 else:
67 67 # find requirements
68 68 requirements = set()
69 69 try:
70 70 requirements = set(self.opener("requires").read().splitlines())
71 71 except IOError, inst:
72 72 if inst.errno != errno.ENOENT:
73 73 raise
74 74 for r in requirements - self.supported:
75 75 raise error.RepoError(_("requirement '%s' not supported") % r)
76 76
77 77 self.sharedpath = self.path
78 78 try:
79 79 s = os.path.realpath(self.opener("sharedpath").read())
80 80 if not os.path.exists(s):
81 81 raise error.RepoError(
82 82 _('.hg/sharedpath points to nonexistent directory %s') % s)
83 83 self.sharedpath = s
84 84 except IOError, inst:
85 85 if inst.errno != errno.ENOENT:
86 86 raise
87 87
88 88 self.store = store.store(requirements, self.sharedpath, util.opener)
89 89 self.spath = self.store.path
90 90 self.sopener = self.store.opener
91 91 self.sjoin = self.store.join
92 92 self.opener.createmode = self.store.createmode
93 93 self.sopener.options = {}
94 94
95 95 # These two define the set of tags for this repository. _tags
96 96 # maps tag name to node; _tagtypes maps tag name to 'global' or
97 97 # 'local'. (Global tags are defined by .hgtags across all
98 98 # heads, and local tags are defined in .hg/localtags.) They
99 99 # constitute the in-memory cache of tags.
100 100 self._tags = None
101 101 self._tagtypes = None
102 102
103 103 self._branchcache = None # in UTF-8
104 104 self._branchcachetip = None
105 105 self.nodetagscache = None
106 106 self.filterpats = {}
107 107 self._datafilters = {}
108 108 self._transref = self._lockref = self._wlockref = None
109 109
110 110 @propertycache
111 111 def changelog(self):
112 112 c = changelog.changelog(self.sopener)
113 113 if 'HG_PENDING' in os.environ:
114 114 p = os.environ['HG_PENDING']
115 115 if p.startswith(self.root):
116 116 c.readpending('00changelog.i.a')
117 117 self.sopener.options['defversion'] = c.version
118 118 return c
119 119
120 120 @propertycache
121 121 def manifest(self):
122 122 return manifest.manifest(self.sopener)
123 123
124 124 @propertycache
125 125 def dirstate(self):
126 126 return dirstate.dirstate(self.opener, self.ui, self.root)
127 127
128 128 def __getitem__(self, changeid):
129 129 if changeid is None:
130 130 return context.workingctx(self)
131 131 return context.changectx(self, changeid)
132 132
133 133 def __contains__(self, changeid):
134 134 try:
135 135 return bool(self.lookup(changeid))
136 136 except error.RepoLookupError:
137 137 return False
138 138
139 139 def __nonzero__(self):
140 140 return True
141 141
142 142 def __len__(self):
143 143 return len(self.changelog)
144 144
145 145 def __iter__(self):
146 146 for i in xrange(len(self)):
147 147 yield i
148 148
149 149 def url(self):
150 150 return 'file:' + self.root
151 151
152 152 def hook(self, name, throw=False, **args):
153 153 return hook.hook(self.ui, self, name, throw, **args)
154 154
155 155 tag_disallowed = ':\r\n'
156 156
157 157 def _tag(self, names, node, message, local, user, date, extra={}):
158 158 if isinstance(names, str):
159 159 allchars = names
160 160 names = (names,)
161 161 else:
162 162 allchars = ''.join(names)
163 163 for c in self.tag_disallowed:
164 164 if c in allchars:
165 165 raise util.Abort(_('%r cannot be used in a tag name') % c)
166 166
167 167 branches = self.branchmap()
168 168 for name in names:
169 169 self.hook('pretag', throw=True, node=hex(node), tag=name,
170 170 local=local)
171 171 if name in branches:
172 172 self.ui.warn(_("warning: tag %s conflicts with existing"
173 173 " branch name\n") % name)
174 174
175 175 def writetags(fp, names, munge, prevtags):
176 176 fp.seek(0, 2)
177 177 if prevtags and prevtags[-1] != '\n':
178 178 fp.write('\n')
179 179 for name in names:
180 180 m = munge and munge(name) or name
181 181 if self._tagtypes and name in self._tagtypes:
182 182 old = self._tags.get(name, nullid)
183 183 fp.write('%s %s\n' % (hex(old), m))
184 184 fp.write('%s %s\n' % (hex(node), m))
185 185 fp.close()
186 186
187 187 prevtags = ''
188 188 if local:
189 189 try:
190 190 fp = self.opener('localtags', 'r+')
191 191 except IOError:
192 192 fp = self.opener('localtags', 'a')
193 193 else:
194 194 prevtags = fp.read()
195 195
196 196 # local tags are stored in the current charset
197 197 writetags(fp, names, None, prevtags)
198 198 for name in names:
199 199 self.hook('tag', node=hex(node), tag=name, local=local)
200 200 return
201 201
202 202 try:
203 203 fp = self.wfile('.hgtags', 'rb+')
204 204 except IOError:
205 205 fp = self.wfile('.hgtags', 'ab')
206 206 else:
207 207 prevtags = fp.read()
208 208
209 209 # committed tags are stored in UTF-8
210 210 writetags(fp, names, encoding.fromlocal, prevtags)
211 211
212 212 if '.hgtags' not in self.dirstate:
213 213 self.add(['.hgtags'])
214 214
215 215 m = matchmod.exact(self.root, '', ['.hgtags'])
216 216 tagnode = self.commit(message, user, date, extra=extra, match=m)
217 217
218 218 for name in names:
219 219 self.hook('tag', node=hex(node), tag=name, local=local)
220 220
221 221 return tagnode
222 222
223 223 def tag(self, names, node, message, local, user, date):
224 224 '''tag a revision with one or more symbolic names.
225 225
226 226 names is a list of strings or, when adding a single tag, names may be a
227 227 string.
228 228
229 229 if local is True, the tags are stored in a per-repository file.
230 230 otherwise, they are stored in the .hgtags file, and a new
231 231 changeset is committed with the change.
232 232
233 233 keyword arguments:
234 234
235 235 local: whether to store tags in non-version-controlled file
236 236 (default False)
237 237
238 238 message: commit message to use if committing
239 239
240 240 user: name of user to use if committing
241 241
242 242 date: date tuple to use if committing'''
243 243
244 244 for x in self.status()[:5]:
245 245 if '.hgtags' in x:
246 246 raise util.Abort(_('working copy of .hgtags is changed '
247 247 '(please commit .hgtags manually)'))
248 248
249 249 self.tags() # instantiate the cache
250 250 self._tag(names, node, message, local, user, date)
251 251
252 252 def tags(self):
253 253 '''return a mapping of tag to node'''
254 254 if self._tags is None:
255 255 (self._tags, self._tagtypes) = self._findtags()
256 256
257 257 return self._tags
258 258
259 259 def _findtags(self):
260 260 '''Do the hard work of finding tags. Return a pair of dicts
261 261 (tags, tagtypes) where tags maps tag name to node, and tagtypes
262 262 maps tag name to a string like \'global\' or \'local\'.
263 263 Subclasses or extensions are free to add their own tags, but
264 264 should be aware that the returned dicts will be retained for the
265 265 duration of the localrepo object.'''
266 266
267 267 # XXX what tagtype should subclasses/extensions use? Currently
268 268 # mq and bookmarks add tags, but do not set the tagtype at all.
269 269 # Should each extension invent its own tag type? Should there
270 270 # be one tagtype for all such "virtual" tags? Or is the status
271 271 # quo fine?
272 272
273 273 alltags = {} # map tag name to (node, hist)
274 274 tagtypes = {}
275 275
276 276 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
277 277 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
278 278
279 279 # Build the return dicts. Have to re-encode tag names because
280 280 # the tags module always uses UTF-8 (in order not to lose info
281 281 # writing to the cache), but the rest of Mercurial wants them in
282 282 # local encoding.
283 283 tags = {}
284 284 for (name, (node, hist)) in alltags.iteritems():
285 285 if node != nullid:
286 286 tags[encoding.tolocal(name)] = node
287 287 tags['tip'] = self.changelog.tip()
288 288 tagtypes = dict([(encoding.tolocal(name), value)
289 289 for (name, value) in tagtypes.iteritems()])
290 290 return (tags, tagtypes)
291 291
292 292 def tagtype(self, tagname):
293 293 '''
294 294 return the type of the given tag. result can be:
295 295
296 296 'local' : a local tag
297 297 'global' : a global tag
298 298 None : tag does not exist
299 299 '''
300 300
301 301 self.tags()
302 302
303 303 return self._tagtypes.get(tagname)
304 304
305 305 def tagslist(self):
306 306 '''return a list of tags ordered by revision'''
307 307 l = []
308 308 for t, n in self.tags().iteritems():
309 309 try:
310 310 r = self.changelog.rev(n)
311 311 except:
312 312 r = -2 # sort to the beginning of the list if unknown
313 313 l.append((r, t, n))
314 314 return [(t, n) for r, t, n in sorted(l)]
315 315
316 316 def nodetags(self, node):
317 317 '''return the tags associated with a node'''
318 318 if not self.nodetagscache:
319 319 self.nodetagscache = {}
320 320 for t, n in self.tags().iteritems():
321 321 self.nodetagscache.setdefault(n, []).append(t)
322 322 for tags in self.nodetagscache.itervalues():
323 323 tags.sort()
324 324 return self.nodetagscache.get(node, [])
325 325
326 326 def _branchtags(self, partial, lrev):
327 327 # TODO: rename this function?
328 328 tiprev = len(self) - 1
329 329 if lrev != tiprev:
330 330 ctxgen = (self[r] for r in xrange(lrev + 1, tiprev + 1))
331 331 self._updatebranchcache(partial, ctxgen)
332 332 self._writebranchcache(partial, self.changelog.tip(), tiprev)
333 333
334 334 return partial
335 335
336 336 def branchmap(self):
337 337 '''returns a dictionary {branch: [branchheads]}'''
338 338 tip = self.changelog.tip()
339 339 if self._branchcache is not None and self._branchcachetip == tip:
340 340 return self._branchcache
341 341
342 342 oldtip = self._branchcachetip
343 343 self._branchcachetip = tip
344 344 if oldtip is None or oldtip not in self.changelog.nodemap:
345 345 partial, last, lrev = self._readbranchcache()
346 346 else:
347 347 lrev = self.changelog.rev(oldtip)
348 348 partial = self._branchcache
349 349
350 350 self._branchtags(partial, lrev)
351 351 # this private cache holds all heads (not just tips)
352 352 self._branchcache = partial
353 353
354 354 return self._branchcache
355 355
356 356 def branchtags(self):
357 357 '''return a dict where branch names map to the tipmost head of
358 358 the branch, open heads come before closed'''
359 359 bt = {}
360 360 for bn, heads in self.branchmap().iteritems():
361 361 tip = heads[-1]
362 362 for h in reversed(heads):
363 363 if 'close' not in self.changelog.read(h)[5]:
364 364 tip = h
365 365 break
366 366 bt[bn] = tip
367 367 return bt
368 368
369 369
370 370 def _readbranchcache(self):
371 371 partial = {}
372 372 try:
373 373 f = self.opener("branchheads.cache")
374 374 lines = f.read().split('\n')
375 375 f.close()
376 376 except (IOError, OSError):
377 377 return {}, nullid, nullrev
378 378
379 379 try:
380 380 last, lrev = lines.pop(0).split(" ", 1)
381 381 last, lrev = bin(last), int(lrev)
382 382 if lrev >= len(self) or self[lrev].node() != last:
383 383 # invalidate the cache
384 384 raise ValueError('invalidating branch cache (tip differs)')
385 385 for l in lines:
386 386 if not l:
387 387 continue
388 388 node, label = l.split(" ", 1)
389 389 partial.setdefault(label.strip(), []).append(bin(node))
390 390 except KeyboardInterrupt:
391 391 raise
392 392 except Exception, inst:
393 393 if self.ui.debugflag:
394 394 self.ui.warn(str(inst), '\n')
395 395 partial, last, lrev = {}, nullid, nullrev
396 396 return partial, last, lrev
397 397
398 398 def _writebranchcache(self, branches, tip, tiprev):
399 399 try:
400 400 f = self.opener("branchheads.cache", "w", atomictemp=True)
401 401 f.write("%s %s\n" % (hex(tip), tiprev))
402 402 for label, nodes in branches.iteritems():
403 403 for node in nodes:
404 404 f.write("%s %s\n" % (hex(node), label))
405 405 f.rename()
406 406 except (IOError, OSError):
407 407 pass
408 408
409 409 def _updatebranchcache(self, partial, ctxgen):
410 410 # collect new branch entries
411 411 newbranches = {}
412 412 for c in ctxgen:
413 413 newbranches.setdefault(c.branch(), []).append(c.node())
414 414 # if older branchheads are reachable from new ones, they aren't
415 415 # really branchheads. Note checking parents is insufficient:
416 416 # 1 (branch a) -> 2 (branch b) -> 3 (branch a)
417 417 for branch, newnodes in newbranches.iteritems():
418 418 bheads = partial.setdefault(branch, [])
419 419 bheads.extend(newnodes)
420 420 if len(bheads) <= 1:
421 421 continue
422 422 # starting from tip means fewer passes over reachable
423 423 while newnodes:
424 424 latest = newnodes.pop()
425 425 if latest not in bheads:
426 426 continue
427 427 minbhrev = self[min([self[bh].rev() for bh in bheads])].node()
428 428 reachable = self.changelog.reachable(latest, minbhrev)
429 429 reachable.remove(latest)
430 430 bheads = [b for b in bheads if b not in reachable]
431 431 partial[branch] = bheads
432 432
433 433 def lookup(self, key):
434 434 if isinstance(key, int):
435 435 return self.changelog.node(key)
436 436 elif key == '.':
437 437 return self.dirstate.parents()[0]
438 438 elif key == 'null':
439 439 return nullid
440 440 elif key == 'tip':
441 441 return self.changelog.tip()
442 442 n = self.changelog._match(key)
443 443 if n:
444 444 return n
445 445 if key in self.tags():
446 446 return self.tags()[key]
447 447 if key in self.branchtags():
448 448 return self.branchtags()[key]
449 449 n = self.changelog._partialmatch(key)
450 450 if n:
451 451 return n
452 452
453 453 # can't find key, check if it might have come from damaged dirstate
454 454 if key in self.dirstate.parents():
455 455 raise error.Abort(_("working directory has unknown parent '%s'!")
456 456 % short(key))
457 457 try:
458 458 if len(key) == 20:
459 459 key = hex(key)
460 460 except:
461 461 pass
462 462 raise error.RepoLookupError(_("unknown revision '%s'") % key)
463 463
464 464 def lookupbranch(self, key, remote=None):
465 465 repo = remote or self
466 466 if key in repo.branchmap():
467 467 return key
468 468
469 469 repo = (remote and remote.local()) and remote or self
470 470 return repo[key].branch()
471 471
472 472 def local(self):
473 473 return True
474 474
475 475 def join(self, f):
476 476 return os.path.join(self.path, f)
477 477
478 478 def wjoin(self, f):
479 479 return os.path.join(self.root, f)
480 480
481 481 def rjoin(self, f):
482 482 return os.path.join(self.root, util.pconvert(f))
483 483
484 484 def file(self, f):
485 485 if f[0] == '/':
486 486 f = f[1:]
487 487 return filelog.filelog(self.sopener, f)
488 488
489 489 def changectx(self, changeid):
490 490 return self[changeid]
491 491
492 492 def parents(self, changeid=None):
493 493 '''get list of changectxs for parents of changeid'''
494 494 return self[changeid].parents()
495 495
496 496 def filectx(self, path, changeid=None, fileid=None):
497 497 """changeid can be a changeset revision, node, or tag.
498 498 fileid can be a file revision or node."""
499 499 return context.filectx(self, path, changeid, fileid)
500 500
501 501 def getcwd(self):
502 502 return self.dirstate.getcwd()
503 503
504 504 def pathto(self, f, cwd=None):
505 505 return self.dirstate.pathto(f, cwd)
506 506
507 507 def wfile(self, f, mode='r'):
508 508 return self.wopener(f, mode)
509 509
510 510 def _link(self, f):
511 511 return os.path.islink(self.wjoin(f))
512 512
513 513 def _filter(self, filter, filename, data):
514 514 if filter not in self.filterpats:
515 515 l = []
516 516 for pat, cmd in self.ui.configitems(filter):
517 517 if cmd == '!':
518 518 continue
519 519 mf = matchmod.match(self.root, '', [pat])
520 520 fn = None
521 521 params = cmd
522 522 for name, filterfn in self._datafilters.iteritems():
523 523 if cmd.startswith(name):
524 524 fn = filterfn
525 525 params = cmd[len(name):].lstrip()
526 526 break
527 527 if not fn:
528 528 fn = lambda s, c, **kwargs: util.filter(s, c)
529 529 # Wrap old filters not supporting keyword arguments
530 530 if not inspect.getargspec(fn)[2]:
531 531 oldfn = fn
532 532 fn = lambda s, c, **kwargs: oldfn(s, c)
533 533 l.append((mf, fn, params))
534 534 self.filterpats[filter] = l
535 535
536 536 for mf, fn, cmd in self.filterpats[filter]:
537 537 if mf(filename):
538 538 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
539 539 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
540 540 break
541 541
542 542 return data
543 543
544 544 def adddatafilter(self, name, filter):
545 545 self._datafilters[name] = filter
546 546
547 547 def wread(self, filename):
548 548 if self._link(filename):
549 549 data = os.readlink(self.wjoin(filename))
550 550 else:
551 551 data = self.wopener(filename, 'r').read()
552 552 return self._filter("encode", filename, data)
553 553
554 554 def wwrite(self, filename, data, flags):
555 555 data = self._filter("decode", filename, data)
556 556 try:
557 557 os.unlink(self.wjoin(filename))
558 558 except OSError:
559 559 pass
560 560 if 'l' in flags:
561 561 self.wopener.symlink(data, filename)
562 562 else:
563 563 self.wopener(filename, 'w').write(data)
564 564 if 'x' in flags:
565 565 util.set_flags(self.wjoin(filename), False, True)
566 566
567 567 def wwritedata(self, filename, data):
568 568 return self._filter("decode", filename, data)
569 569
570 570 def transaction(self, desc):
571 571 tr = self._transref and self._transref() or None
572 572 if tr and tr.running():
573 573 return tr.nest()
574 574
575 575 # abort here if the journal already exists
576 576 if os.path.exists(self.sjoin("journal")):
577 577 raise error.RepoError(
578 578 _("abandoned transaction found - run hg recover"))
579 579
580 580 # save dirstate for rollback
581 581 try:
582 582 ds = self.opener("dirstate").read()
583 583 except IOError:
584 584 ds = ""
585 585 self.opener("journal.dirstate", "w").write(ds)
586 586 self.opener("journal.branch", "w").write(self.dirstate.branch())
587 587 self.opener("journal.desc", "w").write("%d\n%s\n" % (len(self), desc))
588 588
589 589 renames = [(self.sjoin("journal"), self.sjoin("undo")),
590 590 (self.join("journal.dirstate"), self.join("undo.dirstate")),
591 591 (self.join("journal.branch"), self.join("undo.branch")),
592 592 (self.join("journal.desc"), self.join("undo.desc"))]
593 593 tr = transaction.transaction(self.ui.warn, self.sopener,
594 594 self.sjoin("journal"),
595 595 aftertrans(renames),
596 596 self.store.createmode)
597 597 self._transref = weakref.ref(tr)
598 598 return tr
599 599
600 600 def recover(self):
601 601 lock = self.lock()
602 602 try:
603 603 if os.path.exists(self.sjoin("journal")):
604 604 self.ui.status(_("rolling back interrupted transaction\n"))
605 605 transaction.rollback(self.sopener, self.sjoin("journal"),
606 606 self.ui.warn)
607 607 self.invalidate()
608 608 return True
609 609 else:
610 610 self.ui.warn(_("no interrupted transaction available\n"))
611 611 return False
612 612 finally:
613 613 lock.release()
614 614
615 615 def rollback(self, dryrun=False):
616 616 wlock = lock = None
617 617 try:
618 618 wlock = self.wlock()
619 619 lock = self.lock()
620 620 if os.path.exists(self.sjoin("undo")):
621 621 try:
622 622 args = self.opener("undo.desc", "r").read().splitlines()
623 623 if len(args) >= 3 and self.ui.verbose:
624 624 desc = _("rolling back to revision %s"
625 625 " (undo %s: %s)\n") % (
626 626 int(args[0]) - 1, args[1], args[2])
627 627 elif len(args) >= 2:
628 628 desc = _("rolling back to revision %s (undo %s)\n") % (
629 629 int(args[0]) - 1, args[1])
630 630 except IOError:
631 631 desc = _("rolling back unknown transaction\n")
632 632 self.ui.status(desc)
633 633 if dryrun:
634 634 return
635 635 transaction.rollback(self.sopener, self.sjoin("undo"),
636 636 self.ui.warn)
637 637 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
638 638 try:
639 639 branch = self.opener("undo.branch").read()
640 640 self.dirstate.setbranch(branch)
641 641 except IOError:
642 642 self.ui.warn(_("Named branch could not be reset, "
643 643 "current branch still is: %s\n")
644 644 % encoding.tolocal(self.dirstate.branch()))
645 645 self.invalidate()
646 646 self.dirstate.invalidate()
647 647 self.destroyed()
648 648 else:
649 649 self.ui.warn(_("no rollback information available\n"))
650 650 return 1
651 651 finally:
652 652 release(lock, wlock)
653 653
654 654 def invalidatecaches(self):
655 655 self._tags = None
656 656 self._tagtypes = None
657 657 self.nodetagscache = None
658 658 self._branchcache = None # in UTF-8
659 659 self._branchcachetip = None
660 660
661 661 def invalidate(self):
662 662 for a in "changelog manifest".split():
663 663 if a in self.__dict__:
664 664 delattr(self, a)
665 665 self.invalidatecaches()
666 666
667 667 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
668 668 try:
669 669 l = lock.lock(lockname, 0, releasefn, desc=desc)
670 670 except error.LockHeld, inst:
671 671 if not wait:
672 672 raise
673 673 self.ui.warn(_("waiting for lock on %s held by %r\n") %
674 674 (desc, inst.locker))
675 675 # default to 600 seconds timeout
676 676 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
677 677 releasefn, desc=desc)
678 678 if acquirefn:
679 679 acquirefn()
680 680 return l
681 681
682 682 def lock(self, wait=True):
683 683 '''Lock the repository store (.hg/store) and return a weak reference
684 684 to the lock. Use this before modifying the store (e.g. committing or
685 685 stripping). If you are opening a transaction, get a lock as well.)'''
686 686 l = self._lockref and self._lockref()
687 687 if l is not None and l.held:
688 688 l.lock()
689 689 return l
690 690
691 691 l = self._lock(self.sjoin("lock"), wait, None, self.invalidate,
692 692 _('repository %s') % self.origroot)
693 693 self._lockref = weakref.ref(l)
694 694 return l
695 695
696 696 def wlock(self, wait=True):
697 697 '''Lock the non-store parts of the repository (everything under
698 698 .hg except .hg/store) and return a weak reference to the lock.
699 699 Use this before modifying files in .hg.'''
700 700 l = self._wlockref and self._wlockref()
701 701 if l is not None and l.held:
702 702 l.lock()
703 703 return l
704 704
705 705 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
706 706 self.dirstate.invalidate, _('working directory of %s') %
707 707 self.origroot)
708 708 self._wlockref = weakref.ref(l)
709 709 return l
710 710
711 711 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
712 712 """
713 713 commit an individual file as part of a larger transaction
714 714 """
715 715
716 716 fname = fctx.path()
717 717 text = fctx.data()
718 718 flog = self.file(fname)
719 719 fparent1 = manifest1.get(fname, nullid)
720 720 fparent2 = fparent2o = manifest2.get(fname, nullid)
721 721
722 722 meta = {}
723 723 copy = fctx.renamed()
724 724 if copy and copy[0] != fname:
725 725 # Mark the new revision of this file as a copy of another
726 726 # file. This copy data will effectively act as a parent
727 727 # of this new revision. If this is a merge, the first
728 728 # parent will be the nullid (meaning "look up the copy data")
729 729 # and the second one will be the other parent. For example:
730 730 #
731 731 # 0 --- 1 --- 3 rev1 changes file foo
732 732 # \ / rev2 renames foo to bar and changes it
733 733 # \- 2 -/ rev3 should have bar with all changes and
734 734 # should record that bar descends from
735 735 # bar in rev2 and foo in rev1
736 736 #
737 737 # this allows this merge to succeed:
738 738 #
739 739 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
740 740 # \ / merging rev3 and rev4 should use bar@rev2
741 741 # \- 2 --- 4 as the merge base
742 742 #
743 743
744 744 cfname = copy[0]
745 745 crev = manifest1.get(cfname)
746 746 newfparent = fparent2
747 747
748 748 if manifest2: # branch merge
749 749 if fparent2 == nullid or crev is None: # copied on remote side
750 750 if cfname in manifest2:
751 751 crev = manifest2[cfname]
752 752 newfparent = fparent1
753 753
754 754 # find source in nearest ancestor if we've lost track
755 755 if not crev:
756 756 self.ui.debug(" %s: searching for copy revision for %s\n" %
757 757 (fname, cfname))
758 758 for ancestor in self['.'].ancestors():
759 759 if cfname in ancestor:
760 760 crev = ancestor[cfname].filenode()
761 761 break
762 762
763 763 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
764 764 meta["copy"] = cfname
765 765 meta["copyrev"] = hex(crev)
766 766 fparent1, fparent2 = nullid, newfparent
767 767 elif fparent2 != nullid:
768 768 # is one parent an ancestor of the other?
769 769 fparentancestor = flog.ancestor(fparent1, fparent2)
770 770 if fparentancestor == fparent1:
771 771 fparent1, fparent2 = fparent2, nullid
772 772 elif fparentancestor == fparent2:
773 773 fparent2 = nullid
774 774
775 775 # is the file changed?
776 776 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
777 777 changelist.append(fname)
778 778 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
779 779
780 780 # are just the flags changed during merge?
781 781 if fparent1 != fparent2o and manifest1.flags(fname) != fctx.flags():
782 782 changelist.append(fname)
783 783
784 784 return fparent1
785 785
786 786 def commit(self, text="", user=None, date=None, match=None, force=False,
787 787 editor=False, extra={}):
788 788 """Add a new revision to current repository.
789 789
790 790 Revision information is gathered from the working directory,
791 791 match can be used to filter the committed files. If editor is
792 792 supplied, it is called to get a commit message.
793 793 """
794 794
795 795 def fail(f, msg):
796 796 raise util.Abort('%s: %s' % (f, msg))
797 797
798 798 if not match:
799 799 match = matchmod.always(self.root, '')
800 800
801 801 if not force:
802 802 vdirs = []
803 803 match.dir = vdirs.append
804 804 match.bad = fail
805 805
806 806 wlock = self.wlock()
807 807 try:
808 808 wctx = self[None]
809 809 merge = len(wctx.parents()) > 1
810 810
811 811 if (not force and merge and match and
812 812 (match.files() or match.anypats())):
813 813 raise util.Abort(_('cannot partially commit a merge '
814 814 '(do not specify files or patterns)'))
815 815
816 816 changes = self.status(match=match, clean=force)
817 817 if force:
818 818 changes[0].extend(changes[6]) # mq may commit unchanged files
819 819
820 820 # check subrepos
821 821 subs = []
822 822 removedsubs = set()
823 823 for p in wctx.parents():
824 824 removedsubs.update(s for s in p.substate if match(s))
825 825 for s in wctx.substate:
826 826 removedsubs.discard(s)
827 827 if match(s) and wctx.sub(s).dirty():
828 828 subs.append(s)
829 829 if (subs or removedsubs) and '.hgsubstate' not in changes[0]:
830 830 changes[0].insert(0, '.hgsubstate')
831 831
832 832 # make sure all explicit patterns are matched
833 833 if not force and match.files():
834 834 matched = set(changes[0] + changes[1] + changes[2])
835 835
836 836 for f in match.files():
837 837 if f == '.' or f in matched or f in wctx.substate:
838 838 continue
839 839 if f in changes[3]: # missing
840 840 fail(f, _('file not found!'))
841 841 if f in vdirs: # visited directory
842 842 d = f + '/'
843 843 for mf in matched:
844 844 if mf.startswith(d):
845 845 break
846 846 else:
847 847 fail(f, _("no match under directory!"))
848 848 elif f not in self.dirstate:
849 849 fail(f, _("file not tracked!"))
850 850
851 851 if (not force and not extra.get("close") and not merge
852 852 and not (changes[0] or changes[1] or changes[2])
853 853 and wctx.branch() == wctx.p1().branch()):
854 854 return None
855 855
856 856 ms = mergemod.mergestate(self)
857 857 for f in changes[0]:
858 858 if f in ms and ms[f] == 'u':
859 859 raise util.Abort(_("unresolved merge conflicts "
860 860 "(see hg resolve)"))
861 861
862 862 cctx = context.workingctx(self, text, user, date, extra, changes)
863 863 if editor:
864 864 cctx._text = editor(self, cctx, subs)
865 865 edited = (text != cctx._text)
866 866
867 867 # commit subs
868 868 if subs or removedsubs:
869 869 state = wctx.substate.copy()
870 870 for s in subs:
871 871 sub = wctx.sub(s)
872 872 self.ui.status(_('committing subrepository %s\n') %
873 873 subrepo.relpath(sub))
874 874 sr = sub.commit(cctx._text, user, date)
875 875 state[s] = (state[s][0], sr)
876 876 subrepo.writestate(self, state)
877 877
878 878 # Save commit message in case this transaction gets rolled back
879 879 # (e.g. by a pretxncommit hook). Leave the content alone on
880 880 # the assumption that the user will use the same editor again.
881 881 msgfile = self.opener('last-message.txt', 'wb')
882 882 msgfile.write(cctx._text)
883 883 msgfile.close()
884 884
885 885 p1, p2 = self.dirstate.parents()
886 886 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
887 887 try:
888 888 self.hook("precommit", throw=True, parent1=hookp1, parent2=hookp2)
889 889 ret = self.commitctx(cctx, True)
890 890 except:
891 891 if edited:
892 892 msgfn = self.pathto(msgfile.name[len(self.root)+1:])
893 893 self.ui.write(
894 894 _('note: commit message saved in %s\n') % msgfn)
895 895 raise
896 896
897 897 # update dirstate and mergestate
898 898 for f in changes[0] + changes[1]:
899 899 self.dirstate.normal(f)
900 900 for f in changes[2]:
901 901 self.dirstate.forget(f)
902 902 self.dirstate.setparents(ret)
903 903 ms.reset()
904 904 finally:
905 905 wlock.release()
906 906
907 907 self.hook("commit", node=hex(ret), parent1=hookp1, parent2=hookp2)
908 908 return ret
909 909
910 910 def commitctx(self, ctx, error=False):
911 911 """Add a new revision to current repository.
912 912 Revision information is passed via the context argument.
913 913 """
914 914
915 915 tr = lock = None
916 916 removed = ctx.removed()
917 917 p1, p2 = ctx.p1(), ctx.p2()
918 918 m1 = p1.manifest().copy()
919 919 m2 = p2.manifest()
920 920 user = ctx.user()
921 921
922 922 lock = self.lock()
923 923 try:
924 924 tr = self.transaction("commit")
925 925 trp = weakref.proxy(tr)
926 926
927 927 # check in files
928 928 new = {}
929 929 changed = []
930 930 linkrev = len(self)
931 931 for f in sorted(ctx.modified() + ctx.added()):
932 932 self.ui.note(f + "\n")
933 933 try:
934 934 fctx = ctx[f]
935 935 new[f] = self._filecommit(fctx, m1, m2, linkrev, trp,
936 936 changed)
937 937 m1.set(f, fctx.flags())
938 938 except OSError, inst:
939 939 self.ui.warn(_("trouble committing %s!\n") % f)
940 940 raise
941 941 except IOError, inst:
942 942 errcode = getattr(inst, 'errno', errno.ENOENT)
943 943 if error or errcode and errcode != errno.ENOENT:
944 944 self.ui.warn(_("trouble committing %s!\n") % f)
945 945 raise
946 946 else:
947 947 removed.append(f)
948 948
949 949 # update manifest
950 950 m1.update(new)
951 951 removed = [f for f in sorted(removed) if f in m1 or f in m2]
952 952 drop = [f for f in removed if f in m1]
953 953 for f in drop:
954 954 del m1[f]
955 955 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
956 956 p2.manifestnode(), (new, drop))
957 957
958 958 # update changelog
959 959 self.changelog.delayupdate()
960 960 n = self.changelog.add(mn, changed + removed, ctx.description(),
961 961 trp, p1.node(), p2.node(),
962 962 user, ctx.date(), ctx.extra().copy())
963 963 p = lambda: self.changelog.writepending() and self.root or ""
964 964 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
965 965 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
966 966 parent2=xp2, pending=p)
967 967 self.changelog.finalize(trp)
968 968 tr.close()
969 969
970 970 if self._branchcache:
971 971 self.branchtags()
972 972 return n
973 973 finally:
974 974 if tr:
975 975 tr.release()
976 976 lock.release()
977 977
978 978 def destroyed(self):
979 979 '''Inform the repository that nodes have been destroyed.
980 980 Intended for use by strip and rollback, so there's a common
981 981 place for anything that has to be done after destroying history.'''
982 982 # XXX it might be nice if we could take the list of destroyed
983 983 # nodes, but I don't see an easy way for rollback() to do that
984 984
985 985 # Ensure the persistent tag cache is updated. Doing it now
986 986 # means that the tag cache only has to worry about destroyed
987 987 # heads immediately after a strip/rollback. That in turn
988 988 # guarantees that "cachetip == currenttip" (comparing both rev
989 989 # and node) always means no nodes have been added or destroyed.
990 990
991 991 # XXX this is suboptimal when qrefresh'ing: we strip the current
992 992 # head, refresh the tag cache, then immediately add a new head.
993 993 # But I think doing it this way is necessary for the "instant
994 994 # tag cache retrieval" case to work.
995 995 self.invalidatecaches()
996 996
997 997 def walk(self, match, node=None):
998 998 '''
999 999 walk recursively through the directory tree or a given
1000 1000 changeset, finding all files matched by the match
1001 1001 function
1002 1002 '''
1003 1003 return self[node].walk(match)
1004 1004
1005 1005 def status(self, node1='.', node2=None, match=None,
1006 1006 ignored=False, clean=False, unknown=False):
1007 1007 """return status of files between two nodes or node and working directory
1008 1008
1009 1009 If node1 is None, use the first dirstate parent instead.
1010 1010 If node2 is None, compare node1 with working directory.
1011 1011 """
1012 1012
1013 1013 def mfmatches(ctx):
1014 1014 mf = ctx.manifest().copy()
1015 1015 for fn in mf.keys():
1016 1016 if not match(fn):
1017 1017 del mf[fn]
1018 1018 return mf
1019 1019
1020 1020 if isinstance(node1, context.changectx):
1021 1021 ctx1 = node1
1022 1022 else:
1023 1023 ctx1 = self[node1]
1024 1024 if isinstance(node2, context.changectx):
1025 1025 ctx2 = node2
1026 1026 else:
1027 1027 ctx2 = self[node2]
1028 1028
1029 1029 working = ctx2.rev() is None
1030 1030 parentworking = working and ctx1 == self['.']
1031 1031 match = match or matchmod.always(self.root, self.getcwd())
1032 1032 listignored, listclean, listunknown = ignored, clean, unknown
1033 1033
1034 1034 # load earliest manifest first for caching reasons
1035 1035 if not working and ctx2.rev() < ctx1.rev():
1036 1036 ctx2.manifest()
1037 1037
1038 1038 if not parentworking:
1039 1039 def bad(f, msg):
1040 1040 if f not in ctx1:
1041 1041 self.ui.warn('%s: %s\n' % (self.dirstate.pathto(f), msg))
1042 1042 match.bad = bad
1043 1043
1044 1044 if working: # we need to scan the working dir
1045 1045 subrepos = []
1046 1046 if '.hgsub' in self.dirstate:
1047 1047 subrepos = ctx1.substate.keys()
1048 1048 s = self.dirstate.status(match, subrepos, listignored,
1049 1049 listclean, listunknown)
1050 1050 cmp, modified, added, removed, deleted, unknown, ignored, clean = s
1051 1051
1052 1052 # check for any possibly clean files
1053 1053 if parentworking and cmp:
1054 1054 fixup = []
1055 1055 # do a full compare of any files that might have changed
1056 1056 for f in sorted(cmp):
1057 1057 if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
1058 1058 or ctx1[f].cmp(ctx2[f].data())):
1059 1059 modified.append(f)
1060 1060 else:
1061 1061 fixup.append(f)
1062 1062
1063 1063 if listclean:
1064 1064 clean += fixup
1065 1065
1066 1066 # update dirstate for files that are actually clean
1067 1067 if fixup:
1068 1068 try:
1069 1069 # updating the dirstate is optional
1070 1070 # so we don't wait on the lock
1071 1071 wlock = self.wlock(False)
1072 1072 try:
1073 1073 for f in fixup:
1074 1074 self.dirstate.normal(f)
1075 1075 finally:
1076 1076 wlock.release()
1077 1077 except error.LockError:
1078 1078 pass
1079 1079
1080 1080 if not parentworking:
1081 1081 mf1 = mfmatches(ctx1)
1082 1082 if working:
1083 1083 # we are comparing working dir against non-parent
1084 1084 # generate a pseudo-manifest for the working dir
1085 1085 mf2 = mfmatches(self['.'])
1086 1086 for f in cmp + modified + added:
1087 1087 mf2[f] = None
1088 1088 mf2.set(f, ctx2.flags(f))
1089 1089 for f in removed:
1090 1090 if f in mf2:
1091 1091 del mf2[f]
1092 1092 else:
1093 1093 # we are comparing two revisions
1094 1094 deleted, unknown, ignored = [], [], []
1095 1095 mf2 = mfmatches(ctx2)
1096 1096
1097 1097 modified, added, clean = [], [], []
1098 1098 for fn in mf2:
1099 1099 if fn in mf1:
1100 1100 if (mf1.flags(fn) != mf2.flags(fn) or
1101 1101 (mf1[fn] != mf2[fn] and
1102 1102 (mf2[fn] or ctx1[fn].cmp(ctx2[fn].data())))):
1103 1103 modified.append(fn)
1104 1104 elif listclean:
1105 1105 clean.append(fn)
1106 1106 del mf1[fn]
1107 1107 else:
1108 1108 added.append(fn)
1109 1109 removed = mf1.keys()
1110 1110
1111 1111 r = modified, added, removed, deleted, unknown, ignored, clean
1112 1112 [l.sort() for l in r]
1113 1113 return r
1114 1114
1115 1115 def add(self, list):
1116 1116 wlock = self.wlock()
1117 1117 try:
1118 1118 rejected = []
1119 1119 for f in list:
1120 1120 p = self.wjoin(f)
1121 1121 try:
1122 1122 st = os.lstat(p)
1123 1123 except:
1124 1124 self.ui.warn(_("%s does not exist!\n") % f)
1125 1125 rejected.append(f)
1126 1126 continue
1127 1127 if st.st_size > 10000000:
1128 1128 self.ui.warn(_("%s: up to %d MB of RAM may be required "
1129 1129 "to manage this file\n"
1130 1130 "(use 'hg revert %s' to cancel the "
1131 1131 "pending addition)\n")
1132 1132 % (f, 3 * st.st_size // 1000000, f))
1133 1133 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1134 1134 self.ui.warn(_("%s not added: only files and symlinks "
1135 1135 "supported currently\n") % f)
1136 1136 rejected.append(p)
1137 1137 elif self.dirstate[f] in 'amn':
1138 1138 self.ui.warn(_("%s already tracked!\n") % f)
1139 1139 elif self.dirstate[f] == 'r':
1140 1140 self.dirstate.normallookup(f)
1141 1141 else:
1142 1142 self.dirstate.add(f)
1143 1143 return rejected
1144 1144 finally:
1145 1145 wlock.release()
1146 1146
1147 1147 def forget(self, list):
1148 1148 wlock = self.wlock()
1149 1149 try:
1150 1150 for f in list:
1151 1151 if self.dirstate[f] != 'a':
1152 1152 self.ui.warn(_("%s not added!\n") % f)
1153 1153 else:
1154 1154 self.dirstate.forget(f)
1155 1155 finally:
1156 1156 wlock.release()
1157 1157
1158 1158 def remove(self, list, unlink=False):
1159 1159 if unlink:
1160 1160 for f in list:
1161 1161 try:
1162 1162 util.unlink(self.wjoin(f))
1163 1163 except OSError, inst:
1164 1164 if inst.errno != errno.ENOENT:
1165 1165 raise
1166 1166 wlock = self.wlock()
1167 1167 try:
1168 1168 for f in list:
1169 1169 if unlink and os.path.exists(self.wjoin(f)):
1170 1170 self.ui.warn(_("%s still exists!\n") % f)
1171 1171 elif self.dirstate[f] == 'a':
1172 1172 self.dirstate.forget(f)
1173 1173 elif f not in self.dirstate:
1174 1174 self.ui.warn(_("%s not tracked!\n") % f)
1175 1175 else:
1176 1176 self.dirstate.remove(f)
1177 1177 finally:
1178 1178 wlock.release()
1179 1179
1180 1180 def undelete(self, list):
1181 1181 manifests = [self.manifest.read(self.changelog.read(p)[0])
1182 1182 for p in self.dirstate.parents() if p != nullid]
1183 1183 wlock = self.wlock()
1184 1184 try:
1185 1185 for f in list:
1186 1186 if self.dirstate[f] != 'r':
1187 1187 self.ui.warn(_("%s not removed!\n") % f)
1188 1188 else:
1189 1189 m = f in manifests[0] and manifests[0] or manifests[1]
1190 1190 t = self.file(f).read(m[f])
1191 1191 self.wwrite(f, t, m.flags(f))
1192 1192 self.dirstate.normal(f)
1193 1193 finally:
1194 1194 wlock.release()
1195 1195
1196 1196 def copy(self, source, dest):
1197 1197 p = self.wjoin(dest)
1198 1198 if not (os.path.exists(p) or os.path.islink(p)):
1199 1199 self.ui.warn(_("%s does not exist!\n") % dest)
1200 1200 elif not (os.path.isfile(p) or os.path.islink(p)):
1201 1201 self.ui.warn(_("copy failed: %s is not a file or a "
1202 1202 "symbolic link\n") % dest)
1203 1203 else:
1204 1204 wlock = self.wlock()
1205 1205 try:
1206 1206 if self.dirstate[dest] in '?r':
1207 1207 self.dirstate.add(dest)
1208 1208 self.dirstate.copy(source, dest)
1209 1209 finally:
1210 1210 wlock.release()
1211 1211
1212 1212 def heads(self, start=None):
1213 1213 heads = self.changelog.heads(start)
1214 1214 # sort the output in rev descending order
1215 1215 heads = [(-self.changelog.rev(h), h) for h in heads]
1216 1216 return [n for (r, n) in sorted(heads)]
1217 1217
1218 1218 def branchheads(self, branch=None, start=None, closed=False):
1219 1219 '''return a (possibly filtered) list of heads for the given branch
1220 1220
1221 1221 Heads are returned in topological order, from newest to oldest.
1222 1222 If branch is None, use the dirstate branch.
1223 1223 If start is not None, return only heads reachable from start.
1224 1224 If closed is True, return heads that are marked as closed as well.
1225 1225 '''
1226 1226 if branch is None:
1227 1227 branch = self[None].branch()
1228 1228 branches = self.branchmap()
1229 1229 if branch not in branches:
1230 1230 return []
1231 1231 # the cache returns heads ordered lowest to highest
1232 1232 bheads = list(reversed(branches[branch]))
1233 1233 if start is not None:
1234 1234 # filter out the heads that cannot be reached from startrev
1235 1235 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1236 1236 bheads = [h for h in bheads if h in fbheads]
1237 1237 if not closed:
1238 1238 bheads = [h for h in bheads if
1239 1239 ('close' not in self.changelog.read(h)[5])]
1240 1240 return bheads
1241 1241
1242 1242 def branches(self, nodes):
1243 1243 if not nodes:
1244 1244 nodes = [self.changelog.tip()]
1245 1245 b = []
1246 1246 for n in nodes:
1247 1247 t = n
1248 1248 while 1:
1249 1249 p = self.changelog.parents(n)
1250 1250 if p[1] != nullid or p[0] == nullid:
1251 1251 b.append((t, n, p[0], p[1]))
1252 1252 break
1253 1253 n = p[0]
1254 1254 return b
1255 1255
1256 1256 def between(self, pairs):
1257 1257 r = []
1258 1258
1259 1259 for top, bottom in pairs:
1260 1260 n, l, i = top, [], 0
1261 1261 f = 1
1262 1262
1263 1263 while n != bottom and n != nullid:
1264 1264 p = self.changelog.parents(n)[0]
1265 1265 if i == f:
1266 1266 l.append(n)
1267 1267 f = f * 2
1268 1268 n = p
1269 1269 i += 1
1270 1270
1271 1271 r.append(l)
1272 1272
1273 1273 return r
1274 1274
1275 def findincoming(self, remote, base=None, heads=None, force=False):
1276 """Return list of roots of the subsets of missing nodes from remote
1277
1278 If base dict is specified, assume that these nodes and their parents
1279 exist on the remote side and that no child of a node of base exists
1280 in both remote and self.
1281 Furthermore base will be updated to include the nodes that exists
1282 in self and remote but no children exists in self and remote.
1283 If a list of heads is specified, return only nodes which are heads
1284 or ancestors of these heads.
1285
1286 All the ancestors of base are in self and in remote.
1287 All the descendants of the list returned are missing in self.
1288 (and so we know that the rest of the nodes are missing in remote, see
1289 outgoing)
1290 """
1291 return self.findcommonincoming(remote, base, heads, force)[1]
1292
1293 def findcommonincoming(self, remote, base=None, heads=None, force=False):
1294 """Return a tuple (common, missing roots, heads) used to identify
1295 missing nodes from remote.
1296
1297 If base dict is specified, assume that these nodes and their parents
1298 exist on the remote side and that no child of a node of base exists
1299 in both remote and self.
1300 Furthermore base will be updated to include the nodes that exists
1301 in self and remote but no children exists in self and remote.
1302 If a list of heads is specified, return only nodes which are heads
1303 or ancestors of these heads.
1304
1305 All the ancestors of base are in self and in remote.
1306 """
1307 m = self.changelog.nodemap
1308 search = []
1309 fetch = set()
1310 seen = set()
1311 seenbranch = set()
1312 if base is None:
1313 base = {}
1314
1315 if not heads:
1316 heads = remote.heads()
1317
1318 if self.changelog.tip() == nullid:
1319 base[nullid] = 1
1320 if heads != [nullid]:
1321 return [nullid], [nullid], list(heads)
1322 return [nullid], [], []
1323
1324 # assume we're closer to the tip than the root
1325 # and start by examining the heads
1326 self.ui.status(_("searching for changes\n"))
1327
1328 unknown = []
1329 for h in heads:
1330 if h not in m:
1331 unknown.append(h)
1332 else:
1333 base[h] = 1
1334
1335 heads = unknown
1336 if not unknown:
1337 return base.keys(), [], []
1338
1339 req = set(unknown)
1340 reqcnt = 0
1341
1342 # search through remote branches
1343 # a 'branch' here is a linear segment of history, with four parts:
1344 # head, root, first parent, second parent
1345 # (a branch always has two parents (or none) by definition)
1346 unknown = remote.branches(unknown)
1347 while unknown:
1348 r = []
1349 while unknown:
1350 n = unknown.pop(0)
1351 if n[0] in seen:
1352 continue
1353
1354 self.ui.debug("examining %s:%s\n"
1355 % (short(n[0]), short(n[1])))
1356 if n[0] == nullid: # found the end of the branch
1357 pass
1358 elif n in seenbranch:
1359 self.ui.debug("branch already found\n")
1360 continue
1361 elif n[1] and n[1] in m: # do we know the base?
1362 self.ui.debug("found incomplete branch %s:%s\n"
1363 % (short(n[0]), short(n[1])))
1364 search.append(n[0:2]) # schedule branch range for scanning
1365 seenbranch.add(n)
1366 else:
1367 if n[1] not in seen and n[1] not in fetch:
1368 if n[2] in m and n[3] in m:
1369 self.ui.debug("found new changeset %s\n" %
1370 short(n[1]))
1371 fetch.add(n[1]) # earliest unknown
1372 for p in n[2:4]:
1373 if p in m:
1374 base[p] = 1 # latest known
1375
1376 for p in n[2:4]:
1377 if p not in req and p not in m:
1378 r.append(p)
1379 req.add(p)
1380 seen.add(n[0])
1381
1382 if r:
1383 reqcnt += 1
1384 self.ui.progress(_('searching'), reqcnt, unit=_('queries'))
1385 self.ui.debug("request %d: %s\n" %
1386 (reqcnt, " ".join(map(short, r))))
1387 for p in xrange(0, len(r), 10):
1388 for b in remote.branches(r[p:p + 10]):
1389 self.ui.debug("received %s:%s\n" %
1390 (short(b[0]), short(b[1])))
1391 unknown.append(b)
1392
1393 # do binary search on the branches we found
1394 while search:
1395 newsearch = []
1396 reqcnt += 1
1397 self.ui.progress(_('searching'), reqcnt, unit=_('queries'))
1398 for n, l in zip(search, remote.between(search)):
1399 l.append(n[1])
1400 p = n[0]
1401 f = 1
1402 for i in l:
1403 self.ui.debug("narrowing %d:%d %s\n" % (f, len(l), short(i)))
1404 if i in m:
1405 if f <= 2:
1406 self.ui.debug("found new branch changeset %s\n" %
1407 short(p))
1408 fetch.add(p)
1409 base[i] = 1
1410 else:
1411 self.ui.debug("narrowed branch search to %s:%s\n"
1412 % (short(p), short(i)))
1413 newsearch.append((p, i))
1414 break
1415 p, f = i, f * 2
1416 search = newsearch
1417
1418 # sanity check our fetch list
1419 for f in fetch:
1420 if f in m:
1421 raise error.RepoError(_("already have changeset ")
1422 + short(f[:4]))
1423
1424 if base.keys() == [nullid]:
1425 if force:
1426 self.ui.warn(_("warning: repository is unrelated\n"))
1427 else:
1428 raise util.Abort(_("repository is unrelated"))
1429
1430 self.ui.debug("found new changesets starting at " +
1431 " ".join([short(f) for f in fetch]) + "\n")
1432
1433 self.ui.progress(_('searching'), None)
1434 self.ui.debug("%d total queries\n" % reqcnt)
1435
1436 return base.keys(), list(fetch), heads
1437
1438 def findoutgoing(self, remote, base=None, heads=None, force=False):
1439 """Return list of nodes that are roots of subsets not in remote
1440
1441 If base dict is specified, assume that these nodes and their parents
1442 exist on the remote side.
1443 If a list of heads is specified, return only nodes which are heads
1444 or ancestors of these heads, and return a second element which
1445 contains all remote heads which get new children.
1446 """
1447 if base is None:
1448 base = {}
1449 self.findincoming(remote, base, heads, force=force)
1450
1451 self.ui.debug("common changesets up to "
1452 + " ".join(map(short, base.keys())) + "\n")
1453
1454 remain = set(self.changelog.nodemap)
1455
1456 # prune everything remote has from the tree
1457 remain.remove(nullid)
1458 remove = base.keys()
1459 while remove:
1460 n = remove.pop(0)
1461 if n in remain:
1462 remain.remove(n)
1463 for p in self.changelog.parents(n):
1464 remove.append(p)
1465
1466 # find every node whose parents have been pruned
1467 subset = []
1468 # find every remote head that will get new children
1469 updated_heads = set()
1470 for n in remain:
1471 p1, p2 = self.changelog.parents(n)
1472 if p1 not in remain and p2 not in remain:
1473 subset.append(n)
1474 if heads:
1475 if p1 in heads:
1476 updated_heads.add(p1)
1477 if p2 in heads:
1478 updated_heads.add(p2)
1479
1480 # this is the set of all roots we have to push
1481 if heads:
1482 return subset, list(updated_heads)
1483 else:
1484 return subset
1485
1486 1275 def pull(self, remote, heads=None, force=False):
1487 1276 lock = self.lock()
1488 1277 try:
1489 common, fetch, rheads = self.findcommonincoming(remote, heads=heads,
1490 force=force)
1278 tmp = discovery.findcommonincoming(self, remote, heads=heads,
1279 force=force)
1280 common, fetch, rheads = tmp
1491 1281 if not fetch:
1492 1282 self.ui.status(_("no changes found\n"))
1493 1283 return 0
1494 1284
1495 1285 if fetch == [nullid]:
1496 1286 self.ui.status(_("requesting all changes\n"))
1497 1287 elif heads is None and remote.capable('changegroupsubset'):
1498 1288 # issue1320, avoid a race if remote changed after discovery
1499 1289 heads = rheads
1500 1290
1501 1291 if heads is None:
1502 1292 cg = remote.changegroup(fetch, 'pull')
1503 1293 else:
1504 1294 if not remote.capable('changegroupsubset'):
1505 1295 raise util.Abort(_("Partial pull cannot be done because "
1506 1296 "other repository doesn't support "
1507 1297 "changegroupsubset."))
1508 1298 cg = remote.changegroupsubset(fetch, heads, 'pull')
1509 1299 return self.addchangegroup(cg, 'pull', remote.url())
1510 1300 finally:
1511 1301 lock.release()
1512 1302
1513 1303 def push(self, remote, force=False, revs=None, newbranch=False):
1514 1304 '''Push outgoing changesets (limited by revs) from the current
1515 1305 repository to remote. Return an integer:
1516 1306 - 0 means HTTP error *or* nothing to push
1517 1307 - 1 means we pushed and remote head count is unchanged *or*
1518 1308 we have outgoing changesets but refused to push
1519 1309 - other values as described by addchangegroup()
1520 1310 '''
1521 1311 # there are two ways to push to remote repo:
1522 1312 #
1523 1313 # addchangegroup assumes local user can lock remote
1524 1314 # repo (local filesystem, old ssh servers).
1525 1315 #
1526 1316 # unbundle assumes local user cannot lock remote repo (new ssh
1527 1317 # servers, http servers).
1528 1318
1529 1319 if remote.capable('unbundle'):
1530 1320 return self.push_unbundle(remote, force, revs, newbranch)
1531 1321 return self.push_addchangegroup(remote, force, revs, newbranch)
1532 1322
1533 def prepush(self, remote, force, revs, newbranch):
1534 '''Analyze the local and remote repositories and determine which
1535 changesets need to be pushed to the remote. Return value depends
1536 on circumstances:
1537
1538 If we are not going to push anything, return a tuple (None,
1539 outgoing) where outgoing is 0 if there are no outgoing
1540 changesets and 1 if there are, but we refuse to push them
1541 (e.g. would create new remote heads).
1542
1543 Otherwise, return a tuple (changegroup, remoteheads), where
1544 changegroup is a readable file-like object whose read() returns
1545 successive changegroup chunks ready to be sent over the wire and
1546 remoteheads is the list of remote heads.'''
1547 common = {}
1548 remote_heads = remote.heads()
1549 inc = self.findincoming(remote, common, remote_heads, force=force)
1550
1551 cl = self.changelog
1552 update, updated_heads = self.findoutgoing(remote, common, remote_heads)
1553 outg, bases, heads = cl.nodesbetween(update, revs)
1554
1555 if not bases:
1556 self.ui.status(_("no changes found\n"))
1557 return None, 1
1558
1559 if not force and remote_heads != [nullid]:
1560
1561 def fail_multiple_heads(unsynced, branch=None):
1562 if branch:
1563 msg = _("abort: push creates new remote heads"
1564 " on branch '%s'!\n") % branch
1565 else:
1566 msg = _("abort: push creates new remote heads!\n")
1567 self.ui.warn(msg)
1568 if unsynced:
1569 self.ui.status(_("(you should pull and merge or"
1570 " use push -f to force)\n"))
1571 else:
1572 self.ui.status(_("(did you forget to merge?"
1573 " use push -f to force)\n"))
1574 return None, 0
1575
1576 if remote.capable('branchmap'):
1577 # Check for each named branch if we're creating new remote heads.
1578 # To be a remote head after push, node must be either:
1579 # - unknown locally
1580 # - a local outgoing head descended from update
1581 # - a remote head that's known locally and not
1582 # ancestral to an outgoing head
1583 #
1584 # New named branches cannot be created without --force.
1585
1586 # 1. Create set of branches involved in the push.
1587 branches = set(self[n].branch() for n in outg)
1588
1589 # 2. Check for new branches on the remote.
1590 remotemap = remote.branchmap()
1591 newbranches = branches - set(remotemap)
1592 if newbranches and not newbranch: # new branch requires --new-branch
1593 branchnames = ', '.join("%s" % b for b in newbranches)
1594 self.ui.warn(_("abort: push creates "
1595 "new remote branches: %s!\n")
1596 % branchnames)
1597 self.ui.status(_("(use 'hg push --new-branch' to create new "
1598 "remote branches)\n"))
1599 return None, 0
1600 branches.difference_update(newbranches)
1601
1602 # 3. Construct the initial oldmap and newmap dicts.
1603 # They contain information about the remote heads before and
1604 # after the push, respectively.
1605 # Heads not found locally are not included in either dict,
1606 # since they won't be affected by the push.
1607 # unsynced contains all branches with incoming changesets.
1608 oldmap = {}
1609 newmap = {}
1610 unsynced = set()
1611 for branch in branches:
1612 remoteheads = remotemap[branch]
1613 prunedheads = [h for h in remoteheads if h in cl.nodemap]
1614 oldmap[branch] = prunedheads
1615 newmap[branch] = list(prunedheads)
1616 if len(remoteheads) > len(prunedheads):
1617 unsynced.add(branch)
1618
1619 # 4. Update newmap with outgoing changes.
1620 # This will possibly add new heads and remove existing ones.
1621 ctxgen = (self[n] for n in outg)
1622 self._updatebranchcache(newmap, ctxgen)
1623
1624 # 5. Check for new heads.
1625 # If there are more heads after the push than before, a suitable
1626 # warning, depending on unsynced status, is displayed.
1627 for branch in branches:
1628 if len(newmap[branch]) > len(oldmap[branch]):
1629 return fail_multiple_heads(branch in unsynced, branch)
1630
1631 # 6. Check for unsynced changes on involved branches.
1632 if unsynced:
1633 self.ui.warn(_("note: unsynced remote changes!\n"))
1634
1635 else:
1636 # Old servers: Check for new topological heads.
1637 # Code based on _updatebranchcache.
1638 newheads = set(h for h in remote_heads if h in cl.nodemap)
1639 oldheadcnt = len(newheads)
1640 newheads.update(outg)
1641 if len(newheads) > 1:
1642 for latest in reversed(outg):
1643 if latest not in newheads:
1644 continue
1645 minhrev = min(cl.rev(h) for h in newheads)
1646 reachable = cl.reachable(latest, cl.node(minhrev))
1647 reachable.remove(latest)
1648 newheads.difference_update(reachable)
1649 if len(newheads) > oldheadcnt:
1650 return fail_multiple_heads(inc)
1651 if inc:
1652 self.ui.warn(_("note: unsynced remote changes!\n"))
1653
1654 if revs is None:
1655 # use the fast path, no race possible on push
1656 nodes = self.changelog.findmissing(common.keys())
1657 cg = self._changegroup(nodes, 'push')
1658 else:
1659 cg = self.changegroupsubset(update, revs, 'push')
1660 return cg, remote_heads
1661
1662 1323 def push_addchangegroup(self, remote, force, revs, newbranch):
1663 1324 '''Push a changegroup by locking the remote and sending the
1664 1325 addchangegroup command to it. Used for local and old SSH repos.
1665 1326 Return an integer: see push().
1666 1327 '''
1667 1328 lock = remote.lock()
1668 1329 try:
1669 ret = self.prepush(remote, force, revs, newbranch)
1330 ret = discovery.prepush(self, remote, force, revs, newbranch)
1670 1331 if ret[0] is not None:
1671 1332 cg, remote_heads = ret
1672 1333 # here, we return an integer indicating remote head count change
1673 1334 return remote.addchangegroup(cg, 'push', self.url())
1674 1335 # and here we return 0 for "nothing to push" or 1 for
1675 1336 # "something to push but I refuse"
1676 1337 return ret[1]
1677 1338 finally:
1678 1339 lock.release()
1679 1340
1680 1341 def push_unbundle(self, remote, force, revs, newbranch):
1681 1342 '''Push a changegroup by unbundling it on the remote. Used for new
1682 1343 SSH and HTTP repos. Return an integer: see push().'''
1683 1344 # local repo finds heads on server, finds out what revs it
1684 1345 # must push. once revs transferred, if server finds it has
1685 1346 # different heads (someone else won commit/push race), server
1686 1347 # aborts.
1687 1348
1688 ret = self.prepush(remote, force, revs, newbranch)
1349 ret = discovery.prepush(self, remote, force, revs, newbranch)
1689 1350 if ret[0] is not None:
1690 1351 cg, remote_heads = ret
1691 1352 if force:
1692 1353 remote_heads = ['force']
1693 1354 # ssh: return remote's addchangegroup()
1694 1355 # http: return remote's addchangegroup() or 0 for error
1695 1356 return remote.unbundle(cg, remote_heads, 'push')
1696 1357 # as in push_addchangegroup()
1697 1358 return ret[1]
1698 1359
1699 1360 def changegroupinfo(self, nodes, source):
1700 1361 if self.ui.verbose or source == 'bundle':
1701 1362 self.ui.status(_("%d changesets found\n") % len(nodes))
1702 1363 if self.ui.debugflag:
1703 1364 self.ui.debug("list of changesets:\n")
1704 1365 for node in nodes:
1705 1366 self.ui.debug("%s\n" % hex(node))
1706 1367
1707 1368 def changegroupsubset(self, bases, heads, source, extranodes=None):
1708 1369 """Compute a changegroup consisting of all the nodes that are
1709 1370 descendents of any of the bases and ancestors of any of the heads.
1710 1371 Return a chunkbuffer object whose read() method will return
1711 1372 successive changegroup chunks.
1712 1373
1713 1374 It is fairly complex as determining which filenodes and which
1714 1375 manifest nodes need to be included for the changeset to be complete
1715 1376 is non-trivial.
1716 1377
1717 1378 Another wrinkle is doing the reverse, figuring out which changeset in
1718 1379 the changegroup a particular filenode or manifestnode belongs to.
1719 1380
1720 1381 The caller can specify some nodes that must be included in the
1721 1382 changegroup using the extranodes argument. It should be a dict
1722 1383 where the keys are the filenames (or 1 for the manifest), and the
1723 1384 values are lists of (node, linknode) tuples, where node is a wanted
1724 1385 node and linknode is the changelog node that should be transmitted as
1725 1386 the linkrev.
1726 1387 """
1727 1388
1728 1389 # Set up some initial variables
1729 1390 # Make it easy to refer to self.changelog
1730 1391 cl = self.changelog
1731 1392 # msng is short for missing - compute the list of changesets in this
1732 1393 # changegroup.
1733 1394 if not bases:
1734 1395 bases = [nullid]
1735 1396 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1736 1397
1737 1398 if extranodes is None:
1738 1399 # can we go through the fast path ?
1739 1400 heads.sort()
1740 1401 allheads = self.heads()
1741 1402 allheads.sort()
1742 1403 if heads == allheads:
1743 1404 return self._changegroup(msng_cl_lst, source)
1744 1405
1745 1406 # slow path
1746 1407 self.hook('preoutgoing', throw=True, source=source)
1747 1408
1748 1409 self.changegroupinfo(msng_cl_lst, source)
1749 1410 # Some bases may turn out to be superfluous, and some heads may be
1750 1411 # too. nodesbetween will return the minimal set of bases and heads
1751 1412 # necessary to re-create the changegroup.
1752 1413
1753 1414 # Known heads are the list of heads that it is assumed the recipient
1754 1415 # of this changegroup will know about.
1755 1416 knownheads = set()
1756 1417 # We assume that all parents of bases are known heads.
1757 1418 for n in bases:
1758 1419 knownheads.update(cl.parents(n))
1759 1420 knownheads.discard(nullid)
1760 1421 knownheads = list(knownheads)
1761 1422 if knownheads:
1762 1423 # Now that we know what heads are known, we can compute which
1763 1424 # changesets are known. The recipient must know about all
1764 1425 # changesets required to reach the known heads from the null
1765 1426 # changeset.
1766 1427 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1767 1428 junk = None
1768 1429 # Transform the list into a set.
1769 1430 has_cl_set = set(has_cl_set)
1770 1431 else:
1771 1432 # If there were no known heads, the recipient cannot be assumed to
1772 1433 # know about any changesets.
1773 1434 has_cl_set = set()
1774 1435
1775 1436 # Make it easy to refer to self.manifest
1776 1437 mnfst = self.manifest
1777 1438 # We don't know which manifests are missing yet
1778 1439 msng_mnfst_set = {}
1779 1440 # Nor do we know which filenodes are missing.
1780 1441 msng_filenode_set = {}
1781 1442
1782 1443 junk = mnfst.index[len(mnfst) - 1] # Get around a bug in lazyindex
1783 1444 junk = None
1784 1445
1785 1446 # A changeset always belongs to itself, so the changenode lookup
1786 1447 # function for a changenode is identity.
1787 1448 def identity(x):
1788 1449 return x
1789 1450
1790 1451 # If we determine that a particular file or manifest node must be a
1791 1452 # node that the recipient of the changegroup will already have, we can
1792 1453 # also assume the recipient will have all the parents. This function
1793 1454 # prunes them from the set of missing nodes.
1794 1455 def prune_parents(revlog, hasset, msngset):
1795 1456 for r in revlog.ancestors(*[revlog.rev(n) for n in hasset]):
1796 1457 msngset.pop(revlog.node(r), None)
1797 1458
1798 1459 # Use the information collected in collect_manifests_and_files to say
1799 1460 # which changenode any manifestnode belongs to.
1800 1461 def lookup_manifest_link(mnfstnode):
1801 1462 return msng_mnfst_set[mnfstnode]
1802 1463
1803 1464 # A function generating function that sets up the initial environment
1804 1465 # the inner function.
1805 1466 def filenode_collector(changedfiles):
1806 1467 # This gathers information from each manifestnode included in the
1807 1468 # changegroup about which filenodes the manifest node references
1808 1469 # so we can include those in the changegroup too.
1809 1470 #
1810 1471 # It also remembers which changenode each filenode belongs to. It
1811 1472 # does this by assuming the a filenode belongs to the changenode
1812 1473 # the first manifest that references it belongs to.
1813 1474 def collect_msng_filenodes(mnfstnode):
1814 1475 r = mnfst.rev(mnfstnode)
1815 1476 if r - 1 in mnfst.parentrevs(r):
1816 1477 # If the previous rev is one of the parents,
1817 1478 # we only need to see a diff.
1818 1479 deltamf = mnfst.readdelta(mnfstnode)
1819 1480 # For each line in the delta
1820 1481 for f, fnode in deltamf.iteritems():
1821 1482 f = changedfiles.get(f, None)
1822 1483 # And if the file is in the list of files we care
1823 1484 # about.
1824 1485 if f is not None:
1825 1486 # Get the changenode this manifest belongs to
1826 1487 clnode = msng_mnfst_set[mnfstnode]
1827 1488 # Create the set of filenodes for the file if
1828 1489 # there isn't one already.
1829 1490 ndset = msng_filenode_set.setdefault(f, {})
1830 1491 # And set the filenode's changelog node to the
1831 1492 # manifest's if it hasn't been set already.
1832 1493 ndset.setdefault(fnode, clnode)
1833 1494 else:
1834 1495 # Otherwise we need a full manifest.
1835 1496 m = mnfst.read(mnfstnode)
1836 1497 # For every file in we care about.
1837 1498 for f in changedfiles:
1838 1499 fnode = m.get(f, None)
1839 1500 # If it's in the manifest
1840 1501 if fnode is not None:
1841 1502 # See comments above.
1842 1503 clnode = msng_mnfst_set[mnfstnode]
1843 1504 ndset = msng_filenode_set.setdefault(f, {})
1844 1505 ndset.setdefault(fnode, clnode)
1845 1506 return collect_msng_filenodes
1846 1507
1847 1508 # We have a list of filenodes we think we need for a file, lets remove
1848 1509 # all those we know the recipient must have.
1849 1510 def prune_filenodes(f, filerevlog):
1850 1511 msngset = msng_filenode_set[f]
1851 1512 hasset = set()
1852 1513 # If a 'missing' filenode thinks it belongs to a changenode we
1853 1514 # assume the recipient must have, then the recipient must have
1854 1515 # that filenode.
1855 1516 for n in msngset:
1856 1517 clnode = cl.node(filerevlog.linkrev(filerevlog.rev(n)))
1857 1518 if clnode in has_cl_set:
1858 1519 hasset.add(n)
1859 1520 prune_parents(filerevlog, hasset, msngset)
1860 1521
1861 1522 # A function generator function that sets up the a context for the
1862 1523 # inner function.
1863 1524 def lookup_filenode_link_func(fname):
1864 1525 msngset = msng_filenode_set[fname]
1865 1526 # Lookup the changenode the filenode belongs to.
1866 1527 def lookup_filenode_link(fnode):
1867 1528 return msngset[fnode]
1868 1529 return lookup_filenode_link
1869 1530
1870 1531 # Add the nodes that were explicitly requested.
1871 1532 def add_extra_nodes(name, nodes):
1872 1533 if not extranodes or name not in extranodes:
1873 1534 return
1874 1535
1875 1536 for node, linknode in extranodes[name]:
1876 1537 if node not in nodes:
1877 1538 nodes[node] = linknode
1878 1539
1879 1540 # Now that we have all theses utility functions to help out and
1880 1541 # logically divide up the task, generate the group.
1881 1542 def gengroup():
1882 1543 # The set of changed files starts empty.
1883 1544 changedfiles = {}
1884 1545 collect = changegroup.collector(cl, msng_mnfst_set, changedfiles)
1885 1546
1886 1547 # Create a changenode group generator that will call our functions
1887 1548 # back to lookup the owning changenode and collect information.
1888 1549 group = cl.group(msng_cl_lst, identity, collect)
1889 1550 cnt = 0
1890 1551 for chnk in group:
1891 1552 yield chnk
1892 1553 self.ui.progress(_('bundling changes'), cnt, unit=_('chunks'))
1893 1554 cnt += 1
1894 1555 self.ui.progress(_('bundling changes'), None)
1895 1556
1896 1557
1897 1558 # Figure out which manifest nodes (of the ones we think might be
1898 1559 # part of the changegroup) the recipient must know about and
1899 1560 # remove them from the changegroup.
1900 1561 has_mnfst_set = set()
1901 1562 for n in msng_mnfst_set:
1902 1563 # If a 'missing' manifest thinks it belongs to a changenode
1903 1564 # the recipient is assumed to have, obviously the recipient
1904 1565 # must have that manifest.
1905 1566 linknode = cl.node(mnfst.linkrev(mnfst.rev(n)))
1906 1567 if linknode in has_cl_set:
1907 1568 has_mnfst_set.add(n)
1908 1569 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1909 1570 add_extra_nodes(1, msng_mnfst_set)
1910 1571 msng_mnfst_lst = msng_mnfst_set.keys()
1911 1572 # Sort the manifestnodes by revision number.
1912 1573 msng_mnfst_lst.sort(key=mnfst.rev)
1913 1574 # Create a generator for the manifestnodes that calls our lookup
1914 1575 # and data collection functions back.
1915 1576 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1916 1577 filenode_collector(changedfiles))
1917 1578 cnt = 0
1918 1579 for chnk in group:
1919 1580 yield chnk
1920 1581 self.ui.progress(_('bundling manifests'), cnt, unit=_('chunks'))
1921 1582 cnt += 1
1922 1583 self.ui.progress(_('bundling manifests'), None)
1923 1584
1924 1585 # These are no longer needed, dereference and toss the memory for
1925 1586 # them.
1926 1587 msng_mnfst_lst = None
1927 1588 msng_mnfst_set.clear()
1928 1589
1929 1590 if extranodes:
1930 1591 for fname in extranodes:
1931 1592 if isinstance(fname, int):
1932 1593 continue
1933 1594 msng_filenode_set.setdefault(fname, {})
1934 1595 changedfiles[fname] = 1
1935 1596 # Go through all our files in order sorted by name.
1936 1597 cnt = 0
1937 1598 for fname in sorted(changedfiles):
1938 1599 filerevlog = self.file(fname)
1939 1600 if not len(filerevlog):
1940 1601 raise util.Abort(_("empty or missing revlog for %s") % fname)
1941 1602 # Toss out the filenodes that the recipient isn't really
1942 1603 # missing.
1943 1604 if fname in msng_filenode_set:
1944 1605 prune_filenodes(fname, filerevlog)
1945 1606 add_extra_nodes(fname, msng_filenode_set[fname])
1946 1607 msng_filenode_lst = msng_filenode_set[fname].keys()
1947 1608 else:
1948 1609 msng_filenode_lst = []
1949 1610 # If any filenodes are left, generate the group for them,
1950 1611 # otherwise don't bother.
1951 1612 if len(msng_filenode_lst) > 0:
1952 1613 yield changegroup.chunkheader(len(fname))
1953 1614 yield fname
1954 1615 # Sort the filenodes by their revision #
1955 1616 msng_filenode_lst.sort(key=filerevlog.rev)
1956 1617 # Create a group generator and only pass in a changenode
1957 1618 # lookup function as we need to collect no information
1958 1619 # from filenodes.
1959 1620 group = filerevlog.group(msng_filenode_lst,
1960 1621 lookup_filenode_link_func(fname))
1961 1622 for chnk in group:
1962 1623 self.ui.progress(
1963 1624 _('bundling files'), cnt, item=fname, unit=_('chunks'))
1964 1625 cnt += 1
1965 1626 yield chnk
1966 1627 if fname in msng_filenode_set:
1967 1628 # Don't need this anymore, toss it to free memory.
1968 1629 del msng_filenode_set[fname]
1969 1630 # Signal that no more groups are left.
1970 1631 yield changegroup.closechunk()
1971 1632 self.ui.progress(_('bundling files'), None)
1972 1633
1973 1634 if msng_cl_lst:
1974 1635 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1975 1636
1976 1637 return util.chunkbuffer(gengroup())
1977 1638
1978 1639 def changegroup(self, basenodes, source):
1979 1640 # to avoid a race we use changegroupsubset() (issue1320)
1980 1641 return self.changegroupsubset(basenodes, self.heads(), source)
1981 1642
1982 1643 def _changegroup(self, nodes, source):
1983 1644 """Compute the changegroup of all nodes that we have that a recipient
1984 1645 doesn't. Return a chunkbuffer object whose read() method will return
1985 1646 successive changegroup chunks.
1986 1647
1987 1648 This is much easier than the previous function as we can assume that
1988 1649 the recipient has any changenode we aren't sending them.
1989 1650
1990 1651 nodes is the set of nodes to send"""
1991 1652
1992 1653 self.hook('preoutgoing', throw=True, source=source)
1993 1654
1994 1655 cl = self.changelog
1995 1656 revset = set([cl.rev(n) for n in nodes])
1996 1657 self.changegroupinfo(nodes, source)
1997 1658
1998 1659 def identity(x):
1999 1660 return x
2000 1661
2001 1662 def gennodelst(log):
2002 1663 for r in log:
2003 1664 if log.linkrev(r) in revset:
2004 1665 yield log.node(r)
2005 1666
2006 1667 def lookuprevlink_func(revlog):
2007 1668 def lookuprevlink(n):
2008 1669 return cl.node(revlog.linkrev(revlog.rev(n)))
2009 1670 return lookuprevlink
2010 1671
2011 1672 def gengroup():
2012 1673 '''yield a sequence of changegroup chunks (strings)'''
2013 1674 # construct a list of all changed files
2014 1675 changedfiles = {}
2015 1676 mmfs = {}
2016 1677 collect = changegroup.collector(cl, mmfs, changedfiles)
2017 1678
2018 1679 cnt = 0
2019 1680 for chnk in cl.group(nodes, identity, collect):
2020 1681 self.ui.progress(_('bundling changes'), cnt, unit=_('chunks'))
2021 1682 cnt += 1
2022 1683 yield chnk
2023 1684 self.ui.progress(_('bundling changes'), None)
2024 1685
2025 1686 mnfst = self.manifest
2026 1687 nodeiter = gennodelst(mnfst)
2027 1688 cnt = 0
2028 1689 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
2029 1690 self.ui.progress(_('bundling manifests'), cnt, unit=_('chunks'))
2030 1691 cnt += 1
2031 1692 yield chnk
2032 1693 self.ui.progress(_('bundling manifests'), None)
2033 1694
2034 1695 cnt = 0
2035 1696 for fname in sorted(changedfiles):
2036 1697 filerevlog = self.file(fname)
2037 1698 if not len(filerevlog):
2038 1699 raise util.Abort(_("empty or missing revlog for %s") % fname)
2039 1700 nodeiter = gennodelst(filerevlog)
2040 1701 nodeiter = list(nodeiter)
2041 1702 if nodeiter:
2042 1703 yield changegroup.chunkheader(len(fname))
2043 1704 yield fname
2044 1705 lookup = lookuprevlink_func(filerevlog)
2045 1706 for chnk in filerevlog.group(nodeiter, lookup):
2046 1707 self.ui.progress(
2047 1708 _('bundling files'), cnt, item=fname, unit=_('chunks'))
2048 1709 cnt += 1
2049 1710 yield chnk
2050 1711 self.ui.progress(_('bundling files'), None)
2051 1712
2052 1713 yield changegroup.closechunk()
2053 1714
2054 1715 if nodes:
2055 1716 self.hook('outgoing', node=hex(nodes[0]), source=source)
2056 1717
2057 1718 return util.chunkbuffer(gengroup())
2058 1719
2059 1720 def addchangegroup(self, source, srctype, url, emptyok=False):
2060 1721 """Add the changegroup returned by source.read() to this repo.
2061 1722 srctype is a string like 'push', 'pull', or 'unbundle'. url is
2062 1723 the URL of the repo where this changegroup is coming from.
2063 1724
2064 1725 Return an integer summarizing the change to this repo:
2065 1726 - nothing changed or no source: 0
2066 1727 - more heads than before: 1+added heads (2..n)
2067 1728 - fewer heads than before: -1-removed heads (-2..-n)
2068 1729 - number of heads stays the same: 1
2069 1730 """
2070 1731 def csmap(x):
2071 1732 self.ui.debug("add changeset %s\n" % short(x))
2072 1733 return len(cl)
2073 1734
2074 1735 def revmap(x):
2075 1736 return cl.rev(x)
2076 1737
2077 1738 if not source:
2078 1739 return 0
2079 1740
2080 1741 self.hook('prechangegroup', throw=True, source=srctype, url=url)
2081 1742
2082 1743 changesets = files = revisions = 0
2083 1744 efiles = set()
2084 1745
2085 1746 # write changelog data to temp files so concurrent readers will not see
2086 1747 # inconsistent view
2087 1748 cl = self.changelog
2088 1749 cl.delayupdate()
2089 1750 oldheads = len(cl.heads())
2090 1751
2091 1752 tr = self.transaction("\n".join([srctype, urlmod.hidepassword(url)]))
2092 1753 try:
2093 1754 trp = weakref.proxy(tr)
2094 1755 # pull off the changeset group
2095 1756 self.ui.status(_("adding changesets\n"))
2096 1757 clstart = len(cl)
2097 1758 class prog(object):
2098 1759 step = _('changesets')
2099 1760 count = 1
2100 1761 ui = self.ui
2101 1762 total = None
2102 1763 def __call__(self):
2103 1764 self.ui.progress(self.step, self.count, unit=_('chunks'),
2104 1765 total=self.total)
2105 1766 self.count += 1
2106 1767 pr = prog()
2107 1768 chunkiter = changegroup.chunkiter(source, progress=pr)
2108 1769 if cl.addgroup(chunkiter, csmap, trp) is None and not emptyok:
2109 1770 raise util.Abort(_("received changelog group is empty"))
2110 1771 clend = len(cl)
2111 1772 changesets = clend - clstart
2112 1773 for c in xrange(clstart, clend):
2113 1774 efiles.update(self[c].files())
2114 1775 efiles = len(efiles)
2115 1776 self.ui.progress(_('changesets'), None)
2116 1777
2117 1778 # pull off the manifest group
2118 1779 self.ui.status(_("adding manifests\n"))
2119 1780 pr.step = _('manifests')
2120 1781 pr.count = 1
2121 1782 pr.total = changesets # manifests <= changesets
2122 1783 chunkiter = changegroup.chunkiter(source, progress=pr)
2123 1784 # no need to check for empty manifest group here:
2124 1785 # if the result of the merge of 1 and 2 is the same in 3 and 4,
2125 1786 # no new manifest will be created and the manifest group will
2126 1787 # be empty during the pull
2127 1788 self.manifest.addgroup(chunkiter, revmap, trp)
2128 1789 self.ui.progress(_('manifests'), None)
2129 1790
2130 1791 needfiles = {}
2131 1792 if self.ui.configbool('server', 'validate', default=False):
2132 1793 # validate incoming csets have their manifests
2133 1794 for cset in xrange(clstart, clend):
2134 1795 mfest = self.changelog.read(self.changelog.node(cset))[0]
2135 1796 mfest = self.manifest.readdelta(mfest)
2136 1797 # store file nodes we must see
2137 1798 for f, n in mfest.iteritems():
2138 1799 needfiles.setdefault(f, set()).add(n)
2139 1800
2140 1801 # process the files
2141 1802 self.ui.status(_("adding file changes\n"))
2142 1803 pr.step = 'files'
2143 1804 pr.count = 1
2144 1805 pr.total = efiles
2145 1806 while 1:
2146 1807 f = changegroup.getchunk(source)
2147 1808 if not f:
2148 1809 break
2149 1810 self.ui.debug("adding %s revisions\n" % f)
2150 1811 pr()
2151 1812 fl = self.file(f)
2152 1813 o = len(fl)
2153 1814 chunkiter = changegroup.chunkiter(source)
2154 1815 if fl.addgroup(chunkiter, revmap, trp) is None:
2155 1816 raise util.Abort(_("received file revlog group is empty"))
2156 1817 revisions += len(fl) - o
2157 1818 files += 1
2158 1819 if f in needfiles:
2159 1820 needs = needfiles[f]
2160 1821 for new in xrange(o, len(fl)):
2161 1822 n = fl.node(new)
2162 1823 if n in needs:
2163 1824 needs.remove(n)
2164 1825 if not needs:
2165 1826 del needfiles[f]
2166 1827 self.ui.progress(_('files'), None)
2167 1828
2168 1829 for f, needs in needfiles.iteritems():
2169 1830 fl = self.file(f)
2170 1831 for n in needs:
2171 1832 try:
2172 1833 fl.rev(n)
2173 1834 except error.LookupError:
2174 1835 raise util.Abort(
2175 1836 _('missing file data for %s:%s - run hg verify') %
2176 1837 (f, hex(n)))
2177 1838
2178 1839 newheads = len(cl.heads())
2179 1840 heads = ""
2180 1841 if oldheads and newheads != oldheads:
2181 1842 heads = _(" (%+d heads)") % (newheads - oldheads)
2182 1843
2183 1844 self.ui.status(_("added %d changesets"
2184 1845 " with %d changes to %d files%s\n")
2185 1846 % (changesets, revisions, files, heads))
2186 1847
2187 1848 if changesets > 0:
2188 1849 p = lambda: cl.writepending() and self.root or ""
2189 1850 self.hook('pretxnchangegroup', throw=True,
2190 1851 node=hex(cl.node(clstart)), source=srctype,
2191 1852 url=url, pending=p)
2192 1853
2193 1854 # make changelog see real files again
2194 1855 cl.finalize(trp)
2195 1856
2196 1857 tr.close()
2197 1858 finally:
2198 1859 tr.release()
2199 1860
2200 1861 if changesets > 0:
2201 1862 # forcefully update the on-disk branch cache
2202 1863 self.ui.debug("updating the branch cache\n")
2203 1864 self.branchtags()
2204 1865 self.hook("changegroup", node=hex(cl.node(clstart)),
2205 1866 source=srctype, url=url)
2206 1867
2207 1868 for i in xrange(clstart, clend):
2208 1869 self.hook("incoming", node=hex(cl.node(i)),
2209 1870 source=srctype, url=url)
2210 1871
2211 1872 # never return 0 here:
2212 1873 if newheads < oldheads:
2213 1874 return newheads - oldheads - 1
2214 1875 else:
2215 1876 return newheads - oldheads + 1
2216 1877
2217 1878
2218 1879 def stream_in(self, remote):
2219 1880 fp = remote.stream_out()
2220 1881 l = fp.readline()
2221 1882 try:
2222 1883 resp = int(l)
2223 1884 except ValueError:
2224 1885 raise error.ResponseError(
2225 1886 _('Unexpected response from remote server:'), l)
2226 1887 if resp == 1:
2227 1888 raise util.Abort(_('operation forbidden by server'))
2228 1889 elif resp == 2:
2229 1890 raise util.Abort(_('locking the remote repository failed'))
2230 1891 elif resp != 0:
2231 1892 raise util.Abort(_('the server sent an unknown error code'))
2232 1893 self.ui.status(_('streaming all changes\n'))
2233 1894 l = fp.readline()
2234 1895 try:
2235 1896 total_files, total_bytes = map(int, l.split(' ', 1))
2236 1897 except (ValueError, TypeError):
2237 1898 raise error.ResponseError(
2238 1899 _('Unexpected response from remote server:'), l)
2239 1900 self.ui.status(_('%d files to transfer, %s of data\n') %
2240 1901 (total_files, util.bytecount(total_bytes)))
2241 1902 start = time.time()
2242 1903 for i in xrange(total_files):
2243 1904 # XXX doesn't support '\n' or '\r' in filenames
2244 1905 l = fp.readline()
2245 1906 try:
2246 1907 name, size = l.split('\0', 1)
2247 1908 size = int(size)
2248 1909 except (ValueError, TypeError):
2249 1910 raise error.ResponseError(
2250 1911 _('Unexpected response from remote server:'), l)
2251 1912 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
2252 1913 # for backwards compat, name was partially encoded
2253 1914 ofp = self.sopener(store.decodedir(name), 'w')
2254 1915 for chunk in util.filechunkiter(fp, limit=size):
2255 1916 ofp.write(chunk)
2256 1917 ofp.close()
2257 1918 elapsed = time.time() - start
2258 1919 if elapsed <= 0:
2259 1920 elapsed = 0.001
2260 1921 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
2261 1922 (util.bytecount(total_bytes), elapsed,
2262 1923 util.bytecount(total_bytes / elapsed)))
2263 1924 self.invalidate()
2264 1925 return len(self.heads()) + 1
2265 1926
2266 1927 def clone(self, remote, heads=[], stream=False):
2267 1928 '''clone remote repository.
2268 1929
2269 1930 keyword arguments:
2270 1931 heads: list of revs to clone (forces use of pull)
2271 1932 stream: use streaming clone if possible'''
2272 1933
2273 1934 # now, all clients that can request uncompressed clones can
2274 1935 # read repo formats supported by all servers that can serve
2275 1936 # them.
2276 1937
2277 1938 # if revlog format changes, client will have to check version
2278 1939 # and format flags on "stream" capability, and use
2279 1940 # uncompressed only if compatible.
2280 1941
2281 1942 if stream and not heads and remote.capable('stream'):
2282 1943 return self.stream_in(remote)
2283 1944 return self.pull(remote, heads)
2284 1945
2285 1946 # used to avoid circular references so destructors work
2286 1947 def aftertrans(files):
2287 1948 renamefiles = [tuple(t) for t in files]
2288 1949 def a():
2289 1950 for src, dest in renamefiles:
2290 1951 util.rename(src, dest)
2291 1952 return a
2292 1953
2293 1954 def instance(ui, path, create):
2294 1955 return localrepository(ui, util.drop_scheme('file', path), create)
2295 1956
2296 1957 def islocal(path):
2297 1958 return True
@@ -1,554 +1,554
1 1 # revset.py - revision set queries for mercurial
2 2 #
3 3 # Copyright 2010 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 import re
9 import parser, util, error
9 import parser, util, error, discovery
10 10 import match as _match
11 11
12 12 elements = {
13 13 "(": (20, ("group", 1, ")"), ("func", 1, ")")),
14 14 "-": (19, ("negate", 19), ("minus", 19)),
15 15 "::": (17, ("dagrangepre", 17), ("dagrange", 17),
16 16 ("dagrangepost", 17)),
17 17 "..": (17, ("dagrangepre", 17), ("dagrange", 17),
18 18 ("dagrangepost", 17)),
19 19 ":": (15, ("rangepre", 15), ("range", 15), ("rangepost", 15)),
20 20 "not": (10, ("not", 10)),
21 21 "!": (10, ("not", 10)),
22 22 "and": (5, None, ("and", 5)),
23 23 "&": (5, None, ("and", 5)),
24 24 "or": (4, None, ("or", 4)),
25 25 "|": (4, None, ("or", 4)),
26 26 "+": (4, None, ("or", 4)),
27 27 ",": (2, None, ("list", 2)),
28 28 ")": (0, None, None),
29 29 "symbol": (0, ("symbol",), None),
30 30 "string": (0, ("string",), None),
31 31 "end": (0, None, None),
32 32 }
33 33
34 34 keywords = set(['and', 'or', 'not'])
35 35
36 36 def tokenize(program):
37 37 pos, l = 0, len(program)
38 38 while pos < l:
39 39 c = program[pos]
40 40 if c.isspace(): # skip inter-token whitespace
41 41 pass
42 42 elif c == ':' and program[pos:pos + 2] == '::': # look ahead carefully
43 43 yield ('::', None, pos)
44 44 pos += 1 # skip ahead
45 45 elif c == '.' and program[pos:pos + 2] == '..': # look ahead carefully
46 46 yield ('..', None, pos)
47 47 pos += 1 # skip ahead
48 48 elif c in "():,-|&+!": # handle simple operators
49 49 yield (c, None, pos)
50 50 elif c in '"\'': # handle quoted strings
51 51 pos += 1
52 52 s = pos
53 53 while pos < l: # find closing quote
54 54 d = program[pos]
55 55 if d == '\\': # skip over escaped characters
56 56 pos += 2
57 57 continue
58 58 if d == c:
59 59 yield ('string', program[s:pos].decode('string-escape'), s)
60 60 break
61 61 pos += 1
62 62 else:
63 63 raise error.ParseError("unterminated string", s)
64 64 elif c.isalnum() or c in '.': # gather up a symbol/keyword
65 65 s = pos
66 66 pos += 1
67 67 while pos < l: # find end of symbol
68 68 d = program[pos]
69 69 if not (d.isalnum() or d in "._"):
70 70 break
71 71 if d == '.' and program[pos - 1] == '.': # special case for ..
72 72 pos -= 1
73 73 break
74 74 pos += 1
75 75 sym = program[s:pos]
76 76 if sym in keywords: # operator keywords
77 77 yield (sym, None, s)
78 78 else:
79 79 yield ('symbol', sym, s)
80 80 pos -= 1
81 81 else:
82 82 raise error.ParseError("syntax error", pos)
83 83 pos += 1
84 84 yield ('end', None, pos)
85 85
86 86 # helpers
87 87
88 88 def getstring(x, err):
89 89 if x[0] == 'string' or x[0] == 'symbol':
90 90 return x[1]
91 91 raise error.ParseError(err)
92 92
93 93 def getlist(x):
94 94 if not x:
95 95 return []
96 96 if x[0] == 'list':
97 97 return getlist(x[1]) + [x[2]]
98 98 return [x]
99 99
100 100 def getpair(x, err):
101 101 l = getlist(x)
102 102 if len(l) != 2:
103 103 raise error.ParseError(err)
104 104 return l
105 105
106 106 def getset(repo, subset, x):
107 107 if not x:
108 108 raise error.ParseError("missing argument")
109 109 return methods[x[0]](repo, subset, *x[1:])
110 110
111 111 # operator methods
112 112
113 113 def negate(repo, subset, x):
114 114 return getset(repo, subset,
115 115 ('string', '-' + getstring(x, "can't negate that")))
116 116
117 117 def stringset(repo, subset, x):
118 118 x = repo[x].rev()
119 119 if x == -1 and len(subset) == len(repo):
120 120 return [-1]
121 121 if x in subset:
122 122 return [x]
123 123 return []
124 124
125 125 def symbolset(repo, subset, x):
126 126 if x in symbols:
127 127 raise error.ParseError("can't use %s here" % x)
128 128 return stringset(repo, subset, x)
129 129
130 130 def rangeset(repo, subset, x, y):
131 131 m = getset(repo, subset, x)[0]
132 132 n = getset(repo, subset, y)[-1]
133 133 if m < n:
134 134 return range(m, n + 1)
135 135 return range(m, n - 1, -1)
136 136
137 137 def andset(repo, subset, x, y):
138 138 return getset(repo, getset(repo, subset, x), y)
139 139
140 140 def orset(repo, subset, x, y):
141 141 s = set(getset(repo, subset, x))
142 142 s |= set(getset(repo, [r for r in subset if r not in s], y))
143 143 return [r for r in subset if r in s]
144 144
145 145 def notset(repo, subset, x):
146 146 s = set(getset(repo, subset, x))
147 147 return [r for r in subset if r not in s]
148 148
149 149 def listset(repo, subset, a, b):
150 150 raise error.ParseError("can't use a list in this context")
151 151
152 152 def func(repo, subset, a, b):
153 153 if a[0] == 'symbol' and a[1] in symbols:
154 154 return symbols[a[1]](repo, subset, b)
155 155 raise error.ParseError("not a function: %s" % a[1])
156 156
157 157 # functions
158 158
159 159 def p1(repo, subset, x):
160 160 ps = set()
161 161 cl = repo.changelog
162 162 for r in getset(repo, subset, x):
163 163 ps.add(cl.parentrevs(r)[0])
164 164 return [r for r in subset if r in ps]
165 165
166 166 def p2(repo, subset, x):
167 167 ps = set()
168 168 cl = repo.changelog
169 169 for r in getset(repo, subset, x):
170 170 ps.add(cl.parentrevs(r)[1])
171 171 return [r for r in subset if r in ps]
172 172
173 173 def parents(repo, subset, x):
174 174 ps = set()
175 175 cl = repo.changelog
176 176 for r in getset(repo, subset, x):
177 177 ps.update(cl.parentrevs(r))
178 178 return [r for r in subset if r in ps]
179 179
180 180 def maxrev(repo, subset, x):
181 181 s = getset(repo, subset, x)
182 182 if s:
183 183 m = max(s)
184 184 if m in subset:
185 185 return [m]
186 186 return []
187 187
188 188 def limit(repo, subset, x):
189 189 l = getpair(x, "limit wants two args")
190 190 try:
191 191 lim = int(getstring(l[1], "limit wants a number"))
192 192 except ValueError:
193 193 raise error.ParseError("limit expects a number")
194 194 return getset(repo, subset, l[0])[:lim]
195 195
196 196 def children(repo, subset, x):
197 197 cs = set()
198 198 cl = repo.changelog
199 199 s = set(getset(repo, subset, x))
200 200 for r in xrange(0, len(repo)):
201 201 for p in cl.parentrevs(r):
202 202 if p in s:
203 203 cs.add(r)
204 204 return [r for r in subset if r in cs]
205 205
206 206 def branch(repo, subset, x):
207 207 s = getset(repo, range(len(repo)), x)
208 208 b = set()
209 209 for r in s:
210 210 b.add(repo[r].branch())
211 211 s = set(s)
212 212 return [r for r in subset if r in s or repo[r].branch() in b]
213 213
214 214 def ancestor(repo, subset, x):
215 215 l = getpair(x, "ancestor wants two args")
216 216 a = getset(repo, subset, l[0])
217 217 b = getset(repo, subset, l[1])
218 218 if len(a) > 1 or len(b) > 1:
219 219 raise error.ParseError("ancestor args must be single revisions")
220 220 return [repo[a[0]].ancestor(repo[b[0]]).rev()]
221 221
222 222 def ancestors(repo, subset, x):
223 223 args = getset(repo, range(len(repo)), x)
224 224 s = set(repo.changelog.ancestors(*args)) | set(args)
225 225 return [r for r in subset if r in s]
226 226
227 227 def descendants(repo, subset, x):
228 228 args = getset(repo, range(len(repo)), x)
229 229 s = set(repo.changelog.descendants(*args)) | set(args)
230 230 return [r for r in subset if r in s]
231 231
232 232 def follow(repo, subset, x):
233 233 if x:
234 234 raise error.ParseError("follow takes no args")
235 235 p = repo['.'].rev()
236 236 s = set(repo.changelog.ancestors(p)) | set([p])
237 237 return [r for r in subset if r in s]
238 238
239 239 def date(repo, subset, x):
240 240 ds = getstring(x, 'date wants a string')
241 241 dm = util.matchdate(ds)
242 242 return [r for r in subset if dm(repo[r].date()[0])]
243 243
244 244 def keyword(repo, subset, x):
245 245 kw = getstring(x, "keyword wants a string").lower()
246 246 l = []
247 247 for r in subset:
248 248 c = repo[r]
249 249 t = " ".join(c.files() + [c.user(), c.description()])
250 250 if kw in t.lower():
251 251 l.append(r)
252 252 return l
253 253
254 254 def grep(repo, subset, x):
255 255 gr = re.compile(getstring(x, "grep wants a string"))
256 256 l = []
257 257 for r in subset:
258 258 c = repo[r]
259 259 for e in c.files() + [c.user(), c.description()]:
260 260 if gr.search(e):
261 261 l.append(r)
262 262 continue
263 263 return l
264 264
265 265 def author(repo, subset, x):
266 266 n = getstring(x, "author wants a string").lower()
267 267 return [r for r in subset if n in repo[r].user().lower()]
268 268
269 269 def hasfile(repo, subset, x):
270 270 pat = getstring(x, "file wants a pattern")
271 271 m = _match.match(repo.root, repo.getcwd(), [pat])
272 272 s = []
273 273 for r in subset:
274 274 for f in repo[r].files():
275 275 if m(f):
276 276 s.append(r)
277 277 continue
278 278 return s
279 279
280 280 def contains(repo, subset, x):
281 281 pat = getstring(x, "file wants a pattern")
282 282 m = _match.match(repo.root, repo.getcwd(), [pat])
283 283 s = []
284 284 if m.files() == [pat]:
285 285 for r in subset:
286 286 if pat in repo[r]:
287 287 s.append(r)
288 288 continue
289 289 else:
290 290 for r in subset:
291 291 c = repo[r]
292 292 for f in repo[r].manifest():
293 293 if m(f):
294 294 s.append(r)
295 295 continue
296 296 return s
297 297
298 298 def checkstatus(repo, subset, pat, field):
299 299 m = _match.match(repo.root, repo.getcwd(), [pat])
300 300 s = []
301 301 fast = (m.files() == [pat])
302 302 for r in subset:
303 303 c = repo[r]
304 304 if fast:
305 305 if pat not in c.files():
306 306 continue
307 307 else:
308 308 for f in c.files():
309 309 if m(f):
310 310 break
311 311 else:
312 312 continue
313 313 files = repo.status(c.p1().node(), c.node())[field]
314 314 if fast:
315 315 if pat in files:
316 316 s.append(r)
317 317 continue
318 318 else:
319 319 for f in files:
320 320 if m(f):
321 321 s.append(r)
322 322 continue
323 323 return s
324 324
325 325 def modifies(repo, subset, x):
326 326 pat = getstring(x, "modifies wants a pattern")
327 327 return checkstatus(repo, subset, pat, 0)
328 328
329 329 def adds(repo, subset, x):
330 330 pat = getstring(x, "adds wants a pattern")
331 331 return checkstatus(repo, subset, pat, 1)
332 332
333 333 def removes(repo, subset, x):
334 334 pat = getstring(x, "removes wants a pattern")
335 335 return checkstatus(repo, subset, pat, 2)
336 336
337 337 def merge(repo, subset, x):
338 338 if x:
339 339 raise error.ParseError("merge takes no args")
340 340 cl = repo.changelog
341 341 return [r for r in subset if cl.parentrevs(r)[1] != -1]
342 342
343 343 def closed(repo, subset, x):
344 344 return [r for r in subset if repo[r].extra('close')]
345 345
346 346 def head(repo, subset, x):
347 347 hs = set()
348 348 for b, ls in repo.branchmap().iteritems():
349 349 hs.update(repo[h].rev() for h in ls)
350 350 return [r for r in subset if r in hs]
351 351
352 352 def reverse(repo, subset, x):
353 353 l = getset(repo, subset, x)
354 354 l.reverse()
355 355 return l
356 356
357 357 def sort(repo, subset, x):
358 358 l = getlist(x)
359 359 keys = "rev"
360 360 if len(l) == 2:
361 361 keys = getstring(l[1], "sort spec must be a string")
362 362
363 363 s = l[0]
364 364 keys = keys.split()
365 365 l = []
366 366 def invert(s):
367 367 return "".join(chr(255 - ord(c)) for c in s)
368 368 for r in getset(repo, subset, s):
369 369 c = repo[r]
370 370 e = []
371 371 for k in keys:
372 372 if k == 'rev':
373 373 e.append(r)
374 374 elif k == '-rev':
375 375 e.append(-r)
376 376 elif k == 'branch':
377 377 e.append(c.branch())
378 378 elif k == '-branch':
379 379 e.append(invert(c.branch()))
380 380 elif k == 'desc':
381 381 e.append(c.description())
382 382 elif k == '-desc':
383 383 e.append(invert(c.description()))
384 384 elif k in 'user author':
385 385 e.append(c.user())
386 386 elif k in '-user -author':
387 387 e.append(invert(c.user()))
388 388 elif k == 'date':
389 389 e.append(c.date()[0])
390 390 elif k == '-date':
391 391 e.append(-c.date()[0])
392 392 else:
393 393 raise error.ParseError("unknown sort key %r" % k)
394 394 e.append(r)
395 395 l.append(e)
396 396 l.sort()
397 397 return [e[-1] for e in l]
398 398
399 399 def getall(repo, subset, x):
400 400 return subset
401 401
402 402 def heads(repo, subset, x):
403 403 s = getset(repo, subset, x)
404 404 ps = set(parents(repo, subset, x))
405 405 return [r for r in s if r not in ps]
406 406
407 407 def roots(repo, subset, x):
408 408 s = getset(repo, subset, x)
409 409 cs = set(children(repo, subset, x))
410 410 return [r for r in s if r not in cs]
411 411
412 412 def outgoing(repo, subset, x):
413 413 import hg # avoid start-up nasties
414 414 l = getlist(x)
415 415 if len(l) == 1:
416 416 dest = getstring(l[0], "outgoing wants a repo path")
417 417 else:
418 418 dest = ''
419 419 dest = repo.ui.expandpath(dest or 'default-push', dest or 'default')
420 420 dest, branches = hg.parseurl(dest)
421 421 other = hg.repository(hg.remoteui(repo, {}), dest)
422 422 repo.ui.pushbuffer()
423 o = repo.findoutgoing(other)
423 o = discovery.findoutgoing(repo, other)
424 424 repo.ui.popbuffer()
425 425 cl = repo.changelog
426 426 o = set([cl.rev(r) for r in repo.changelog.nodesbetween(o, None)[0]])
427 427 print 'out', dest, o
428 428 return [r for r in subset if r in o]
429 429
430 430 def tagged(repo, subset, x):
431 431 cl = repo.changelog
432 432 s = set([cl.rev(n) for t, n in repo.tagslist() if t != 'tip'])
433 433 return [r for r in subset if r in s]
434 434
435 435 symbols = {
436 436 "adds": adds,
437 437 "all": getall,
438 438 "ancestor": ancestor,
439 439 "ancestors": ancestors,
440 440 "author": author,
441 441 "branch": branch,
442 442 "children": children,
443 443 "closed": closed,
444 444 "contains": contains,
445 445 "date": date,
446 446 "descendants": descendants,
447 447 "file": hasfile,
448 448 "follow": follow,
449 449 "grep": grep,
450 450 "head": head,
451 451 "heads": heads,
452 452 "keyword": keyword,
453 453 "limit": limit,
454 454 "max": maxrev,
455 455 "merge": merge,
456 456 "modifies": modifies,
457 457 "outgoing": outgoing,
458 458 "p1": p1,
459 459 "p2": p2,
460 460 "parents": parents,
461 461 "removes": removes,
462 462 "reverse": reverse,
463 463 "roots": roots,
464 464 "sort": sort,
465 465 "tagged": tagged,
466 466 "user": author,
467 467 }
468 468
469 469 methods = {
470 470 "negate": negate,
471 471 "range": rangeset,
472 472 "string": stringset,
473 473 "symbol": symbolset,
474 474 "and": andset,
475 475 "or": orset,
476 476 "not": notset,
477 477 "list": listset,
478 478 "func": func,
479 479 }
480 480
481 481 def optimize(x, small):
482 482 if x == None:
483 483 return 0, x
484 484
485 485 smallbonus = 1
486 486 if small:
487 487 smallbonus = .5
488 488
489 489 op = x[0]
490 490 if op == 'minus':
491 491 return optimize(('and', x[1], ('not', x[2])), small)
492 492 elif op == 'dagrange':
493 493 return optimize(('and', ('func', ('symbol', 'descendants'), x[1]),
494 494 ('func', ('symbol', 'ancestors'), x[2])), small)
495 495 elif op == 'dagrangepre':
496 496 return optimize(('func', ('symbol', 'ancestors'), x[1]), small)
497 497 elif op == 'dagrangepost':
498 498 return optimize(('func', ('symbol', 'descendants'), x[1]), small)
499 499 elif op == 'rangepre':
500 500 return optimize(('range', ('string', '0'), x[1]), small)
501 501 elif op == 'rangepost':
502 502 return optimize(('range', x[1], ('string', 'tip')), small)
503 503 elif op in 'string symbol negate':
504 504 return smallbonus, x # single revisions are small
505 505 elif op == 'and' or op == 'dagrange':
506 506 wa, ta = optimize(x[1], True)
507 507 wb, tb = optimize(x[2], True)
508 508 w = min(wa, wb)
509 509 if wa > wb:
510 510 return w, (op, tb, ta)
511 511 return w, (op, ta, tb)
512 512 elif op == 'or':
513 513 wa, ta = optimize(x[1], False)
514 514 wb, tb = optimize(x[2], False)
515 515 if wb < wa:
516 516 wb, wa = wa, wb
517 517 return max(wa, wb), (op, ta, tb)
518 518 elif op == 'not':
519 519 o = optimize(x[1], not small)
520 520 return o[0], (op, o[1])
521 521 elif op == 'group':
522 522 return optimize(x[1], small)
523 523 elif op in 'range list':
524 524 wa, ta = optimize(x[1], small)
525 525 wb, tb = optimize(x[2], small)
526 526 return wa + wb, (op, ta, tb)
527 527 elif op == 'func':
528 528 f = getstring(x[1], "not a symbol")
529 529 wa, ta = optimize(x[2], small)
530 530 if f in "grep date user author keyword branch file":
531 531 w = 10 # slow
532 532 elif f in "modifies adds removes outgoing":
533 533 w = 30 # slower
534 534 elif f == "contains":
535 535 w = 100 # very slow
536 536 elif f == "ancestor":
537 537 w = 1 * smallbonus
538 538 elif f == "reverse limit":
539 539 w = 0
540 540 elif f in "sort":
541 541 w = 10 # assume most sorts look at changelog
542 542 else:
543 543 w = 1
544 544 return w + wa, (op, x[1], ta)
545 545 return 1, x
546 546
547 547 parse = parser.parser(tokenize, elements).parse
548 548
549 549 def match(spec):
550 550 tree = parse(spec)
551 551 weight, tree = optimize(tree, True)
552 552 def mfunc(repo, subset):
553 553 return getset(repo, subset, tree)
554 554 return mfunc
General Comments 0
You need to be logged in to leave comments. Login now