Show More
@@ -1,2978 +1,2977 | |||||
1 | # cmdutil.py - help for command processing in mercurial |
|
1 | # cmdutil.py - help for command processing in mercurial | |
2 | # |
|
2 | # | |
3 | # Copyright 2005-2007 Matt Mackall <mpm@selenic.com> |
|
3 | # Copyright 2005-2007 Matt Mackall <mpm@selenic.com> | |
4 | # |
|
4 | # | |
5 | # This software may be used and distributed according to the terms of the |
|
5 | # This software may be used and distributed according to the terms of the | |
6 | # GNU General Public License version 2 or any later version. |
|
6 | # GNU General Public License version 2 or any later version. | |
7 |
|
7 | |||
8 | from node import hex, nullid, nullrev, short |
|
8 | from node import hex, nullid, nullrev, short | |
9 | from i18n import _ |
|
9 | from i18n import _ | |
10 | import os, sys, errno, re, tempfile |
|
10 | import os, sys, errno, re, tempfile | |
11 | import util, scmutil, templater, patch, error, templatekw, revlog, copies |
|
11 | import util, scmutil, templater, patch, error, templatekw, revlog, copies | |
12 | import match as matchmod |
|
12 | import match as matchmod | |
13 | import context, repair, graphmod, revset, phases, obsolete, pathutil |
|
13 | import context, repair, graphmod, revset, phases, obsolete, pathutil | |
14 | import changelog |
|
14 | import changelog | |
15 | import bookmarks |
|
15 | import bookmarks | |
16 | import encoding |
|
16 | import encoding | |
17 | import lock as lockmod |
|
17 | import lock as lockmod | |
18 |
|
18 | |||
19 | def parsealiases(cmd): |
|
19 | def parsealiases(cmd): | |
20 | return cmd.lstrip("^").split("|") |
|
20 | return cmd.lstrip("^").split("|") | |
21 |
|
21 | |||
22 | def findpossible(cmd, table, strict=False): |
|
22 | def findpossible(cmd, table, strict=False): | |
23 | """ |
|
23 | """ | |
24 | Return cmd -> (aliases, command table entry) |
|
24 | Return cmd -> (aliases, command table entry) | |
25 | for each matching command. |
|
25 | for each matching command. | |
26 | Return debug commands (or their aliases) only if no normal command matches. |
|
26 | Return debug commands (or their aliases) only if no normal command matches. | |
27 | """ |
|
27 | """ | |
28 | choice = {} |
|
28 | choice = {} | |
29 | debugchoice = {} |
|
29 | debugchoice = {} | |
30 |
|
30 | |||
31 | if cmd in table: |
|
31 | if cmd in table: | |
32 | # short-circuit exact matches, "log" alias beats "^log|history" |
|
32 | # short-circuit exact matches, "log" alias beats "^log|history" | |
33 | keys = [cmd] |
|
33 | keys = [cmd] | |
34 | else: |
|
34 | else: | |
35 | keys = table.keys() |
|
35 | keys = table.keys() | |
36 |
|
36 | |||
37 | for e in keys: |
|
37 | for e in keys: | |
38 | aliases = parsealiases(e) |
|
38 | aliases = parsealiases(e) | |
39 | found = None |
|
39 | found = None | |
40 | if cmd in aliases: |
|
40 | if cmd in aliases: | |
41 | found = cmd |
|
41 | found = cmd | |
42 | elif not strict: |
|
42 | elif not strict: | |
43 | for a in aliases: |
|
43 | for a in aliases: | |
44 | if a.startswith(cmd): |
|
44 | if a.startswith(cmd): | |
45 | found = a |
|
45 | found = a | |
46 | break |
|
46 | break | |
47 | if found is not None: |
|
47 | if found is not None: | |
48 | if aliases[0].startswith("debug") or found.startswith("debug"): |
|
48 | if aliases[0].startswith("debug") or found.startswith("debug"): | |
49 | debugchoice[found] = (aliases, table[e]) |
|
49 | debugchoice[found] = (aliases, table[e]) | |
50 | else: |
|
50 | else: | |
51 | choice[found] = (aliases, table[e]) |
|
51 | choice[found] = (aliases, table[e]) | |
52 |
|
52 | |||
53 | if not choice and debugchoice: |
|
53 | if not choice and debugchoice: | |
54 | choice = debugchoice |
|
54 | choice = debugchoice | |
55 |
|
55 | |||
56 | return choice |
|
56 | return choice | |
57 |
|
57 | |||
58 | def findcmd(cmd, table, strict=True): |
|
58 | def findcmd(cmd, table, strict=True): | |
59 | """Return (aliases, command table entry) for command string.""" |
|
59 | """Return (aliases, command table entry) for command string.""" | |
60 | choice = findpossible(cmd, table, strict) |
|
60 | choice = findpossible(cmd, table, strict) | |
61 |
|
61 | |||
62 | if cmd in choice: |
|
62 | if cmd in choice: | |
63 | return choice[cmd] |
|
63 | return choice[cmd] | |
64 |
|
64 | |||
65 | if len(choice) > 1: |
|
65 | if len(choice) > 1: | |
66 | clist = choice.keys() |
|
66 | clist = choice.keys() | |
67 | clist.sort() |
|
67 | clist.sort() | |
68 | raise error.AmbiguousCommand(cmd, clist) |
|
68 | raise error.AmbiguousCommand(cmd, clist) | |
69 |
|
69 | |||
70 | if choice: |
|
70 | if choice: | |
71 | return choice.values()[0] |
|
71 | return choice.values()[0] | |
72 |
|
72 | |||
73 | raise error.UnknownCommand(cmd) |
|
73 | raise error.UnknownCommand(cmd) | |
74 |
|
74 | |||
75 | def findrepo(p): |
|
75 | def findrepo(p): | |
76 | while not os.path.isdir(os.path.join(p, ".hg")): |
|
76 | while not os.path.isdir(os.path.join(p, ".hg")): | |
77 | oldp, p = p, os.path.dirname(p) |
|
77 | oldp, p = p, os.path.dirname(p) | |
78 | if p == oldp: |
|
78 | if p == oldp: | |
79 | return None |
|
79 | return None | |
80 |
|
80 | |||
81 | return p |
|
81 | return p | |
82 |
|
82 | |||
83 | def bailifchanged(repo): |
|
83 | def bailifchanged(repo): | |
84 | if repo.dirstate.p2() != nullid: |
|
84 | if repo.dirstate.p2() != nullid: | |
85 | raise util.Abort(_('outstanding uncommitted merge')) |
|
85 | raise util.Abort(_('outstanding uncommitted merge')) | |
86 | modified, added, removed, deleted = repo.status()[:4] |
|
86 | modified, added, removed, deleted = repo.status()[:4] | |
87 | if modified or added or removed or deleted: |
|
87 | if modified or added or removed or deleted: | |
88 | raise util.Abort(_('uncommitted changes')) |
|
88 | raise util.Abort(_('uncommitted changes')) | |
89 | ctx = repo[None] |
|
89 | ctx = repo[None] | |
90 | for s in sorted(ctx.substate): |
|
90 | for s in sorted(ctx.substate): | |
91 | if ctx.sub(s).dirty(): |
|
91 | if ctx.sub(s).dirty(): | |
92 | raise util.Abort(_("uncommitted changes in subrepo %s") % s) |
|
92 | raise util.Abort(_("uncommitted changes in subrepo %s") % s) | |
93 |
|
93 | |||
94 | def logmessage(ui, opts): |
|
94 | def logmessage(ui, opts): | |
95 | """ get the log message according to -m and -l option """ |
|
95 | """ get the log message according to -m and -l option """ | |
96 | message = opts.get('message') |
|
96 | message = opts.get('message') | |
97 | logfile = opts.get('logfile') |
|
97 | logfile = opts.get('logfile') | |
98 |
|
98 | |||
99 | if message and logfile: |
|
99 | if message and logfile: | |
100 | raise util.Abort(_('options --message and --logfile are mutually ' |
|
100 | raise util.Abort(_('options --message and --logfile are mutually ' | |
101 | 'exclusive')) |
|
101 | 'exclusive')) | |
102 | if not message and logfile: |
|
102 | if not message and logfile: | |
103 | try: |
|
103 | try: | |
104 | if logfile == '-': |
|
104 | if logfile == '-': | |
105 | message = ui.fin.read() |
|
105 | message = ui.fin.read() | |
106 | else: |
|
106 | else: | |
107 | message = '\n'.join(util.readfile(logfile).splitlines()) |
|
107 | message = '\n'.join(util.readfile(logfile).splitlines()) | |
108 | except IOError, inst: |
|
108 | except IOError, inst: | |
109 | raise util.Abort(_("can't read commit message '%s': %s") % |
|
109 | raise util.Abort(_("can't read commit message '%s': %s") % | |
110 | (logfile, inst.strerror)) |
|
110 | (logfile, inst.strerror)) | |
111 | return message |
|
111 | return message | |
112 |
|
112 | |||
113 | def mergeeditform(ctxorbool, baseform): |
|
113 | def mergeeditform(ctxorbool, baseform): | |
114 | """build appropriate editform from ctxorbool and baseform |
|
114 | """build appropriate editform from ctxorbool and baseform | |
115 |
|
115 | |||
116 | 'ctxorbool' is one of a ctx to be committed, or a bool whether |
|
116 | 'ctxorbool' is one of a ctx to be committed, or a bool whether | |
117 | merging is committed. |
|
117 | merging is committed. | |
118 |
|
118 | |||
119 | This returns editform 'baseform' with '.merge' if merging is |
|
119 | This returns editform 'baseform' with '.merge' if merging is | |
120 | committed, or one with '.normal' suffix otherwise. |
|
120 | committed, or one with '.normal' suffix otherwise. | |
121 | """ |
|
121 | """ | |
122 | if isinstance(ctxorbool, bool): |
|
122 | if isinstance(ctxorbool, bool): | |
123 | if ctxorbool: |
|
123 | if ctxorbool: | |
124 | return baseform + ".merge" |
|
124 | return baseform + ".merge" | |
125 | elif 1 < len(ctxorbool.parents()): |
|
125 | elif 1 < len(ctxorbool.parents()): | |
126 | return baseform + ".merge" |
|
126 | return baseform + ".merge" | |
127 |
|
127 | |||
128 | return baseform + ".normal" |
|
128 | return baseform + ".normal" | |
129 |
|
129 | |||
130 | def getcommiteditor(edit=False, finishdesc=None, extramsg=None, |
|
130 | def getcommiteditor(edit=False, finishdesc=None, extramsg=None, | |
131 | editform='', **opts): |
|
131 | editform='', **opts): | |
132 | """get appropriate commit message editor according to '--edit' option |
|
132 | """get appropriate commit message editor according to '--edit' option | |
133 |
|
133 | |||
134 | 'finishdesc' is a function to be called with edited commit message |
|
134 | 'finishdesc' is a function to be called with edited commit message | |
135 | (= 'description' of the new changeset) just after editing, but |
|
135 | (= 'description' of the new changeset) just after editing, but | |
136 | before checking empty-ness. It should return actual text to be |
|
136 | before checking empty-ness. It should return actual text to be | |
137 | stored into history. This allows to change description before |
|
137 | stored into history. This allows to change description before | |
138 | storing. |
|
138 | storing. | |
139 |
|
139 | |||
140 | 'extramsg' is a extra message to be shown in the editor instead of |
|
140 | 'extramsg' is a extra message to be shown in the editor instead of | |
141 | 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL |
|
141 | 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL | |
142 | is automatically added. |
|
142 | is automatically added. | |
143 |
|
143 | |||
144 | 'editform' is a dot-separated list of names, to distinguish |
|
144 | 'editform' is a dot-separated list of names, to distinguish | |
145 | the purpose of commit text editing. |
|
145 | the purpose of commit text editing. | |
146 |
|
146 | |||
147 | 'getcommiteditor' returns 'commitforceeditor' regardless of |
|
147 | 'getcommiteditor' returns 'commitforceeditor' regardless of | |
148 | 'edit', if one of 'finishdesc' or 'extramsg' is specified, because |
|
148 | 'edit', if one of 'finishdesc' or 'extramsg' is specified, because | |
149 | they are specific for usage in MQ. |
|
149 | they are specific for usage in MQ. | |
150 | """ |
|
150 | """ | |
151 | if edit or finishdesc or extramsg: |
|
151 | if edit or finishdesc or extramsg: | |
152 | return lambda r, c, s: commitforceeditor(r, c, s, |
|
152 | return lambda r, c, s: commitforceeditor(r, c, s, | |
153 | finishdesc=finishdesc, |
|
153 | finishdesc=finishdesc, | |
154 | extramsg=extramsg, |
|
154 | extramsg=extramsg, | |
155 | editform=editform) |
|
155 | editform=editform) | |
156 | elif editform: |
|
156 | elif editform: | |
157 | return lambda r, c, s: commiteditor(r, c, s, editform=editform) |
|
157 | return lambda r, c, s: commiteditor(r, c, s, editform=editform) | |
158 | else: |
|
158 | else: | |
159 | return commiteditor |
|
159 | return commiteditor | |
160 |
|
160 | |||
161 | def loglimit(opts): |
|
161 | def loglimit(opts): | |
162 | """get the log limit according to option -l/--limit""" |
|
162 | """get the log limit according to option -l/--limit""" | |
163 | limit = opts.get('limit') |
|
163 | limit = opts.get('limit') | |
164 | if limit: |
|
164 | if limit: | |
165 | try: |
|
165 | try: | |
166 | limit = int(limit) |
|
166 | limit = int(limit) | |
167 | except ValueError: |
|
167 | except ValueError: | |
168 | raise util.Abort(_('limit must be a positive integer')) |
|
168 | raise util.Abort(_('limit must be a positive integer')) | |
169 | if limit <= 0: |
|
169 | if limit <= 0: | |
170 | raise util.Abort(_('limit must be positive')) |
|
170 | raise util.Abort(_('limit must be positive')) | |
171 | else: |
|
171 | else: | |
172 | limit = None |
|
172 | limit = None | |
173 | return limit |
|
173 | return limit | |
174 |
|
174 | |||
175 | def makefilename(repo, pat, node, desc=None, |
|
175 | def makefilename(repo, pat, node, desc=None, | |
176 | total=None, seqno=None, revwidth=None, pathname=None): |
|
176 | total=None, seqno=None, revwidth=None, pathname=None): | |
177 | node_expander = { |
|
177 | node_expander = { | |
178 | 'H': lambda: hex(node), |
|
178 | 'H': lambda: hex(node), | |
179 | 'R': lambda: str(repo.changelog.rev(node)), |
|
179 | 'R': lambda: str(repo.changelog.rev(node)), | |
180 | 'h': lambda: short(node), |
|
180 | 'h': lambda: short(node), | |
181 | 'm': lambda: re.sub('[^\w]', '_', str(desc)) |
|
181 | 'm': lambda: re.sub('[^\w]', '_', str(desc)) | |
182 | } |
|
182 | } | |
183 | expander = { |
|
183 | expander = { | |
184 | '%': lambda: '%', |
|
184 | '%': lambda: '%', | |
185 | 'b': lambda: os.path.basename(repo.root), |
|
185 | 'b': lambda: os.path.basename(repo.root), | |
186 | } |
|
186 | } | |
187 |
|
187 | |||
188 | try: |
|
188 | try: | |
189 | if node: |
|
189 | if node: | |
190 | expander.update(node_expander) |
|
190 | expander.update(node_expander) | |
191 | if node: |
|
191 | if node: | |
192 | expander['r'] = (lambda: |
|
192 | expander['r'] = (lambda: | |
193 | str(repo.changelog.rev(node)).zfill(revwidth or 0)) |
|
193 | str(repo.changelog.rev(node)).zfill(revwidth or 0)) | |
194 | if total is not None: |
|
194 | if total is not None: | |
195 | expander['N'] = lambda: str(total) |
|
195 | expander['N'] = lambda: str(total) | |
196 | if seqno is not None: |
|
196 | if seqno is not None: | |
197 | expander['n'] = lambda: str(seqno) |
|
197 | expander['n'] = lambda: str(seqno) | |
198 | if total is not None and seqno is not None: |
|
198 | if total is not None and seqno is not None: | |
199 | expander['n'] = lambda: str(seqno).zfill(len(str(total))) |
|
199 | expander['n'] = lambda: str(seqno).zfill(len(str(total))) | |
200 | if pathname is not None: |
|
200 | if pathname is not None: | |
201 | expander['s'] = lambda: os.path.basename(pathname) |
|
201 | expander['s'] = lambda: os.path.basename(pathname) | |
202 | expander['d'] = lambda: os.path.dirname(pathname) or '.' |
|
202 | expander['d'] = lambda: os.path.dirname(pathname) or '.' | |
203 | expander['p'] = lambda: pathname |
|
203 | expander['p'] = lambda: pathname | |
204 |
|
204 | |||
205 | newname = [] |
|
205 | newname = [] | |
206 | patlen = len(pat) |
|
206 | patlen = len(pat) | |
207 | i = 0 |
|
207 | i = 0 | |
208 | while i < patlen: |
|
208 | while i < patlen: | |
209 | c = pat[i] |
|
209 | c = pat[i] | |
210 | if c == '%': |
|
210 | if c == '%': | |
211 | i += 1 |
|
211 | i += 1 | |
212 | c = pat[i] |
|
212 | c = pat[i] | |
213 | c = expander[c]() |
|
213 | c = expander[c]() | |
214 | newname.append(c) |
|
214 | newname.append(c) | |
215 | i += 1 |
|
215 | i += 1 | |
216 | return ''.join(newname) |
|
216 | return ''.join(newname) | |
217 | except KeyError, inst: |
|
217 | except KeyError, inst: | |
218 | raise util.Abort(_("invalid format spec '%%%s' in output filename") % |
|
218 | raise util.Abort(_("invalid format spec '%%%s' in output filename") % | |
219 | inst.args[0]) |
|
219 | inst.args[0]) | |
220 |
|
220 | |||
221 | def makefileobj(repo, pat, node=None, desc=None, total=None, |
|
221 | def makefileobj(repo, pat, node=None, desc=None, total=None, | |
222 | seqno=None, revwidth=None, mode='wb', modemap=None, |
|
222 | seqno=None, revwidth=None, mode='wb', modemap=None, | |
223 | pathname=None): |
|
223 | pathname=None): | |
224 |
|
224 | |||
225 | writable = mode not in ('r', 'rb') |
|
225 | writable = mode not in ('r', 'rb') | |
226 |
|
226 | |||
227 | if not pat or pat == '-': |
|
227 | if not pat or pat == '-': | |
228 | fp = writable and repo.ui.fout or repo.ui.fin |
|
228 | fp = writable and repo.ui.fout or repo.ui.fin | |
229 | if util.safehasattr(fp, 'fileno'): |
|
229 | if util.safehasattr(fp, 'fileno'): | |
230 | return os.fdopen(os.dup(fp.fileno()), mode) |
|
230 | return os.fdopen(os.dup(fp.fileno()), mode) | |
231 | else: |
|
231 | else: | |
232 | # if this fp can't be duped properly, return |
|
232 | # if this fp can't be duped properly, return | |
233 | # a dummy object that can be closed |
|
233 | # a dummy object that can be closed | |
234 | class wrappedfileobj(object): |
|
234 | class wrappedfileobj(object): | |
235 | noop = lambda x: None |
|
235 | noop = lambda x: None | |
236 | def __init__(self, f): |
|
236 | def __init__(self, f): | |
237 | self.f = f |
|
237 | self.f = f | |
238 | def __getattr__(self, attr): |
|
238 | def __getattr__(self, attr): | |
239 | if attr == 'close': |
|
239 | if attr == 'close': | |
240 | return self.noop |
|
240 | return self.noop | |
241 | else: |
|
241 | else: | |
242 | return getattr(self.f, attr) |
|
242 | return getattr(self.f, attr) | |
243 |
|
243 | |||
244 | return wrappedfileobj(fp) |
|
244 | return wrappedfileobj(fp) | |
245 | if util.safehasattr(pat, 'write') and writable: |
|
245 | if util.safehasattr(pat, 'write') and writable: | |
246 | return pat |
|
246 | return pat | |
247 | if util.safehasattr(pat, 'read') and 'r' in mode: |
|
247 | if util.safehasattr(pat, 'read') and 'r' in mode: | |
248 | return pat |
|
248 | return pat | |
249 | fn = makefilename(repo, pat, node, desc, total, seqno, revwidth, pathname) |
|
249 | fn = makefilename(repo, pat, node, desc, total, seqno, revwidth, pathname) | |
250 | if modemap is not None: |
|
250 | if modemap is not None: | |
251 | mode = modemap.get(fn, mode) |
|
251 | mode = modemap.get(fn, mode) | |
252 | if mode == 'wb': |
|
252 | if mode == 'wb': | |
253 | modemap[fn] = 'ab' |
|
253 | modemap[fn] = 'ab' | |
254 | return open(fn, mode) |
|
254 | return open(fn, mode) | |
255 |
|
255 | |||
256 | def openrevlog(repo, cmd, file_, opts): |
|
256 | def openrevlog(repo, cmd, file_, opts): | |
257 | """opens the changelog, manifest, a filelog or a given revlog""" |
|
257 | """opens the changelog, manifest, a filelog or a given revlog""" | |
258 | cl = opts['changelog'] |
|
258 | cl = opts['changelog'] | |
259 | mf = opts['manifest'] |
|
259 | mf = opts['manifest'] | |
260 | msg = None |
|
260 | msg = None | |
261 | if cl and mf: |
|
261 | if cl and mf: | |
262 | msg = _('cannot specify --changelog and --manifest at the same time') |
|
262 | msg = _('cannot specify --changelog and --manifest at the same time') | |
263 | elif cl or mf: |
|
263 | elif cl or mf: | |
264 | if file_: |
|
264 | if file_: | |
265 | msg = _('cannot specify filename with --changelog or --manifest') |
|
265 | msg = _('cannot specify filename with --changelog or --manifest') | |
266 | elif not repo: |
|
266 | elif not repo: | |
267 | msg = _('cannot specify --changelog or --manifest ' |
|
267 | msg = _('cannot specify --changelog or --manifest ' | |
268 | 'without a repository') |
|
268 | 'without a repository') | |
269 | if msg: |
|
269 | if msg: | |
270 | raise util.Abort(msg) |
|
270 | raise util.Abort(msg) | |
271 |
|
271 | |||
272 | r = None |
|
272 | r = None | |
273 | if repo: |
|
273 | if repo: | |
274 | if cl: |
|
274 | if cl: | |
275 | r = repo.unfiltered().changelog |
|
275 | r = repo.unfiltered().changelog | |
276 | elif mf: |
|
276 | elif mf: | |
277 | r = repo.manifest |
|
277 | r = repo.manifest | |
278 | elif file_: |
|
278 | elif file_: | |
279 | filelog = repo.file(file_) |
|
279 | filelog = repo.file(file_) | |
280 | if len(filelog): |
|
280 | if len(filelog): | |
281 | r = filelog |
|
281 | r = filelog | |
282 | if not r: |
|
282 | if not r: | |
283 | if not file_: |
|
283 | if not file_: | |
284 | raise error.CommandError(cmd, _('invalid arguments')) |
|
284 | raise error.CommandError(cmd, _('invalid arguments')) | |
285 | if not os.path.isfile(file_): |
|
285 | if not os.path.isfile(file_): | |
286 | raise util.Abort(_("revlog '%s' not found") % file_) |
|
286 | raise util.Abort(_("revlog '%s' not found") % file_) | |
287 | r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), |
|
287 | r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), | |
288 | file_[:-2] + ".i") |
|
288 | file_[:-2] + ".i") | |
289 | return r |
|
289 | return r | |
290 |
|
290 | |||
291 | def copy(ui, repo, pats, opts, rename=False): |
|
291 | def copy(ui, repo, pats, opts, rename=False): | |
292 | # called with the repo lock held |
|
292 | # called with the repo lock held | |
293 | # |
|
293 | # | |
294 | # hgsep => pathname that uses "/" to separate directories |
|
294 | # hgsep => pathname that uses "/" to separate directories | |
295 | # ossep => pathname that uses os.sep to separate directories |
|
295 | # ossep => pathname that uses os.sep to separate directories | |
296 | cwd = repo.getcwd() |
|
296 | cwd = repo.getcwd() | |
297 | targets = {} |
|
297 | targets = {} | |
298 | after = opts.get("after") |
|
298 | after = opts.get("after") | |
299 | dryrun = opts.get("dry_run") |
|
299 | dryrun = opts.get("dry_run") | |
300 | wctx = repo[None] |
|
300 | wctx = repo[None] | |
301 |
|
301 | |||
302 | def walkpat(pat): |
|
302 | def walkpat(pat): | |
303 | srcs = [] |
|
303 | srcs = [] | |
304 | badstates = after and '?' or '?r' |
|
304 | badstates = after and '?' or '?r' | |
305 | m = scmutil.match(repo[None], [pat], opts, globbed=True) |
|
305 | m = scmutil.match(repo[None], [pat], opts, globbed=True) | |
306 | for abs in repo.walk(m): |
|
306 | for abs in repo.walk(m): | |
307 | state = repo.dirstate[abs] |
|
307 | state = repo.dirstate[abs] | |
308 | rel = m.rel(abs) |
|
308 | rel = m.rel(abs) | |
309 | exact = m.exact(abs) |
|
309 | exact = m.exact(abs) | |
310 | if state in badstates: |
|
310 | if state in badstates: | |
311 | if exact and state == '?': |
|
311 | if exact and state == '?': | |
312 | ui.warn(_('%s: not copying - file is not managed\n') % rel) |
|
312 | ui.warn(_('%s: not copying - file is not managed\n') % rel) | |
313 | if exact and state == 'r': |
|
313 | if exact and state == 'r': | |
314 | ui.warn(_('%s: not copying - file has been marked for' |
|
314 | ui.warn(_('%s: not copying - file has been marked for' | |
315 | ' remove\n') % rel) |
|
315 | ' remove\n') % rel) | |
316 | continue |
|
316 | continue | |
317 | # abs: hgsep |
|
317 | # abs: hgsep | |
318 | # rel: ossep |
|
318 | # rel: ossep | |
319 | srcs.append((abs, rel, exact)) |
|
319 | srcs.append((abs, rel, exact)) | |
320 | return srcs |
|
320 | return srcs | |
321 |
|
321 | |||
322 | # abssrc: hgsep |
|
322 | # abssrc: hgsep | |
323 | # relsrc: ossep |
|
323 | # relsrc: ossep | |
324 | # otarget: ossep |
|
324 | # otarget: ossep | |
325 | def copyfile(abssrc, relsrc, otarget, exact): |
|
325 | def copyfile(abssrc, relsrc, otarget, exact): | |
326 | abstarget = pathutil.canonpath(repo.root, cwd, otarget) |
|
326 | abstarget = pathutil.canonpath(repo.root, cwd, otarget) | |
327 | if '/' in abstarget: |
|
327 | if '/' in abstarget: | |
328 | # We cannot normalize abstarget itself, this would prevent |
|
328 | # We cannot normalize abstarget itself, this would prevent | |
329 | # case only renames, like a => A. |
|
329 | # case only renames, like a => A. | |
330 | abspath, absname = abstarget.rsplit('/', 1) |
|
330 | abspath, absname = abstarget.rsplit('/', 1) | |
331 | abstarget = repo.dirstate.normalize(abspath) + '/' + absname |
|
331 | abstarget = repo.dirstate.normalize(abspath) + '/' + absname | |
332 | reltarget = repo.pathto(abstarget, cwd) |
|
332 | reltarget = repo.pathto(abstarget, cwd) | |
333 | target = repo.wjoin(abstarget) |
|
333 | target = repo.wjoin(abstarget) | |
334 | src = repo.wjoin(abssrc) |
|
334 | src = repo.wjoin(abssrc) | |
335 | state = repo.dirstate[abstarget] |
|
335 | state = repo.dirstate[abstarget] | |
336 |
|
336 | |||
337 | scmutil.checkportable(ui, abstarget) |
|
337 | scmutil.checkportable(ui, abstarget) | |
338 |
|
338 | |||
339 | # check for collisions |
|
339 | # check for collisions | |
340 | prevsrc = targets.get(abstarget) |
|
340 | prevsrc = targets.get(abstarget) | |
341 | if prevsrc is not None: |
|
341 | if prevsrc is not None: | |
342 | ui.warn(_('%s: not overwriting - %s collides with %s\n') % |
|
342 | ui.warn(_('%s: not overwriting - %s collides with %s\n') % | |
343 | (reltarget, repo.pathto(abssrc, cwd), |
|
343 | (reltarget, repo.pathto(abssrc, cwd), | |
344 | repo.pathto(prevsrc, cwd))) |
|
344 | repo.pathto(prevsrc, cwd))) | |
345 | return |
|
345 | return | |
346 |
|
346 | |||
347 | # check for overwrites |
|
347 | # check for overwrites | |
348 | exists = os.path.lexists(target) |
|
348 | exists = os.path.lexists(target) | |
349 | samefile = False |
|
349 | samefile = False | |
350 | if exists and abssrc != abstarget: |
|
350 | if exists and abssrc != abstarget: | |
351 | if (repo.dirstate.normalize(abssrc) == |
|
351 | if (repo.dirstate.normalize(abssrc) == | |
352 | repo.dirstate.normalize(abstarget)): |
|
352 | repo.dirstate.normalize(abstarget)): | |
353 | if not rename: |
|
353 | if not rename: | |
354 | ui.warn(_("%s: can't copy - same file\n") % reltarget) |
|
354 | ui.warn(_("%s: can't copy - same file\n") % reltarget) | |
355 | return |
|
355 | return | |
356 | exists = False |
|
356 | exists = False | |
357 | samefile = True |
|
357 | samefile = True | |
358 |
|
358 | |||
359 | if not after and exists or after and state in 'mn': |
|
359 | if not after and exists or after and state in 'mn': | |
360 | if not opts['force']: |
|
360 | if not opts['force']: | |
361 | ui.warn(_('%s: not overwriting - file exists\n') % |
|
361 | ui.warn(_('%s: not overwriting - file exists\n') % | |
362 | reltarget) |
|
362 | reltarget) | |
363 | return |
|
363 | return | |
364 |
|
364 | |||
365 | if after: |
|
365 | if after: | |
366 | if not exists: |
|
366 | if not exists: | |
367 | if rename: |
|
367 | if rename: | |
368 | ui.warn(_('%s: not recording move - %s does not exist\n') % |
|
368 | ui.warn(_('%s: not recording move - %s does not exist\n') % | |
369 | (relsrc, reltarget)) |
|
369 | (relsrc, reltarget)) | |
370 | else: |
|
370 | else: | |
371 | ui.warn(_('%s: not recording copy - %s does not exist\n') % |
|
371 | ui.warn(_('%s: not recording copy - %s does not exist\n') % | |
372 | (relsrc, reltarget)) |
|
372 | (relsrc, reltarget)) | |
373 | return |
|
373 | return | |
374 | elif not dryrun: |
|
374 | elif not dryrun: | |
375 | try: |
|
375 | try: | |
376 | if exists: |
|
376 | if exists: | |
377 | os.unlink(target) |
|
377 | os.unlink(target) | |
378 | targetdir = os.path.dirname(target) or '.' |
|
378 | targetdir = os.path.dirname(target) or '.' | |
379 | if not os.path.isdir(targetdir): |
|
379 | if not os.path.isdir(targetdir): | |
380 | os.makedirs(targetdir) |
|
380 | os.makedirs(targetdir) | |
381 | if samefile: |
|
381 | if samefile: | |
382 | tmp = target + "~hgrename" |
|
382 | tmp = target + "~hgrename" | |
383 | os.rename(src, tmp) |
|
383 | os.rename(src, tmp) | |
384 | os.rename(tmp, target) |
|
384 | os.rename(tmp, target) | |
385 | else: |
|
385 | else: | |
386 | util.copyfile(src, target) |
|
386 | util.copyfile(src, target) | |
387 | srcexists = True |
|
387 | srcexists = True | |
388 | except IOError, inst: |
|
388 | except IOError, inst: | |
389 | if inst.errno == errno.ENOENT: |
|
389 | if inst.errno == errno.ENOENT: | |
390 | ui.warn(_('%s: deleted in working copy\n') % relsrc) |
|
390 | ui.warn(_('%s: deleted in working copy\n') % relsrc) | |
391 | srcexists = False |
|
391 | srcexists = False | |
392 | else: |
|
392 | else: | |
393 | ui.warn(_('%s: cannot copy - %s\n') % |
|
393 | ui.warn(_('%s: cannot copy - %s\n') % | |
394 | (relsrc, inst.strerror)) |
|
394 | (relsrc, inst.strerror)) | |
395 | return True # report a failure |
|
395 | return True # report a failure | |
396 |
|
396 | |||
397 | if ui.verbose or not exact: |
|
397 | if ui.verbose or not exact: | |
398 | if rename: |
|
398 | if rename: | |
399 | ui.status(_('moving %s to %s\n') % (relsrc, reltarget)) |
|
399 | ui.status(_('moving %s to %s\n') % (relsrc, reltarget)) | |
400 | else: |
|
400 | else: | |
401 | ui.status(_('copying %s to %s\n') % (relsrc, reltarget)) |
|
401 | ui.status(_('copying %s to %s\n') % (relsrc, reltarget)) | |
402 |
|
402 | |||
403 | targets[abstarget] = abssrc |
|
403 | targets[abstarget] = abssrc | |
404 |
|
404 | |||
405 | # fix up dirstate |
|
405 | # fix up dirstate | |
406 | scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget, |
|
406 | scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget, | |
407 | dryrun=dryrun, cwd=cwd) |
|
407 | dryrun=dryrun, cwd=cwd) | |
408 | if rename and not dryrun: |
|
408 | if rename and not dryrun: | |
409 | if not after and srcexists and not samefile: |
|
409 | if not after and srcexists and not samefile: | |
410 | util.unlinkpath(repo.wjoin(abssrc)) |
|
410 | util.unlinkpath(repo.wjoin(abssrc)) | |
411 | wctx.forget([abssrc]) |
|
411 | wctx.forget([abssrc]) | |
412 |
|
412 | |||
413 | # pat: ossep |
|
413 | # pat: ossep | |
414 | # dest ossep |
|
414 | # dest ossep | |
415 | # srcs: list of (hgsep, hgsep, ossep, bool) |
|
415 | # srcs: list of (hgsep, hgsep, ossep, bool) | |
416 | # return: function that takes hgsep and returns ossep |
|
416 | # return: function that takes hgsep and returns ossep | |
417 | def targetpathfn(pat, dest, srcs): |
|
417 | def targetpathfn(pat, dest, srcs): | |
418 | if os.path.isdir(pat): |
|
418 | if os.path.isdir(pat): | |
419 | abspfx = pathutil.canonpath(repo.root, cwd, pat) |
|
419 | abspfx = pathutil.canonpath(repo.root, cwd, pat) | |
420 | abspfx = util.localpath(abspfx) |
|
420 | abspfx = util.localpath(abspfx) | |
421 | if destdirexists: |
|
421 | if destdirexists: | |
422 | striplen = len(os.path.split(abspfx)[0]) |
|
422 | striplen = len(os.path.split(abspfx)[0]) | |
423 | else: |
|
423 | else: | |
424 | striplen = len(abspfx) |
|
424 | striplen = len(abspfx) | |
425 | if striplen: |
|
425 | if striplen: | |
426 | striplen += len(os.sep) |
|
426 | striplen += len(os.sep) | |
427 | res = lambda p: os.path.join(dest, util.localpath(p)[striplen:]) |
|
427 | res = lambda p: os.path.join(dest, util.localpath(p)[striplen:]) | |
428 | elif destdirexists: |
|
428 | elif destdirexists: | |
429 | res = lambda p: os.path.join(dest, |
|
429 | res = lambda p: os.path.join(dest, | |
430 | os.path.basename(util.localpath(p))) |
|
430 | os.path.basename(util.localpath(p))) | |
431 | else: |
|
431 | else: | |
432 | res = lambda p: dest |
|
432 | res = lambda p: dest | |
433 | return res |
|
433 | return res | |
434 |
|
434 | |||
435 | # pat: ossep |
|
435 | # pat: ossep | |
436 | # dest ossep |
|
436 | # dest ossep | |
437 | # srcs: list of (hgsep, hgsep, ossep, bool) |
|
437 | # srcs: list of (hgsep, hgsep, ossep, bool) | |
438 | # return: function that takes hgsep and returns ossep |
|
438 | # return: function that takes hgsep and returns ossep | |
439 | def targetpathafterfn(pat, dest, srcs): |
|
439 | def targetpathafterfn(pat, dest, srcs): | |
440 | if matchmod.patkind(pat): |
|
440 | if matchmod.patkind(pat): | |
441 | # a mercurial pattern |
|
441 | # a mercurial pattern | |
442 | res = lambda p: os.path.join(dest, |
|
442 | res = lambda p: os.path.join(dest, | |
443 | os.path.basename(util.localpath(p))) |
|
443 | os.path.basename(util.localpath(p))) | |
444 | else: |
|
444 | else: | |
445 | abspfx = pathutil.canonpath(repo.root, cwd, pat) |
|
445 | abspfx = pathutil.canonpath(repo.root, cwd, pat) | |
446 | if len(abspfx) < len(srcs[0][0]): |
|
446 | if len(abspfx) < len(srcs[0][0]): | |
447 | # A directory. Either the target path contains the last |
|
447 | # A directory. Either the target path contains the last | |
448 | # component of the source path or it does not. |
|
448 | # component of the source path or it does not. | |
449 | def evalpath(striplen): |
|
449 | def evalpath(striplen): | |
450 | score = 0 |
|
450 | score = 0 | |
451 | for s in srcs: |
|
451 | for s in srcs: | |
452 | t = os.path.join(dest, util.localpath(s[0])[striplen:]) |
|
452 | t = os.path.join(dest, util.localpath(s[0])[striplen:]) | |
453 | if os.path.lexists(t): |
|
453 | if os.path.lexists(t): | |
454 | score += 1 |
|
454 | score += 1 | |
455 | return score |
|
455 | return score | |
456 |
|
456 | |||
457 | abspfx = util.localpath(abspfx) |
|
457 | abspfx = util.localpath(abspfx) | |
458 | striplen = len(abspfx) |
|
458 | striplen = len(abspfx) | |
459 | if striplen: |
|
459 | if striplen: | |
460 | striplen += len(os.sep) |
|
460 | striplen += len(os.sep) | |
461 | if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])): |
|
461 | if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])): | |
462 | score = evalpath(striplen) |
|
462 | score = evalpath(striplen) | |
463 | striplen1 = len(os.path.split(abspfx)[0]) |
|
463 | striplen1 = len(os.path.split(abspfx)[0]) | |
464 | if striplen1: |
|
464 | if striplen1: | |
465 | striplen1 += len(os.sep) |
|
465 | striplen1 += len(os.sep) | |
466 | if evalpath(striplen1) > score: |
|
466 | if evalpath(striplen1) > score: | |
467 | striplen = striplen1 |
|
467 | striplen = striplen1 | |
468 | res = lambda p: os.path.join(dest, |
|
468 | res = lambda p: os.path.join(dest, | |
469 | util.localpath(p)[striplen:]) |
|
469 | util.localpath(p)[striplen:]) | |
470 | else: |
|
470 | else: | |
471 | # a file |
|
471 | # a file | |
472 | if destdirexists: |
|
472 | if destdirexists: | |
473 | res = lambda p: os.path.join(dest, |
|
473 | res = lambda p: os.path.join(dest, | |
474 | os.path.basename(util.localpath(p))) |
|
474 | os.path.basename(util.localpath(p))) | |
475 | else: |
|
475 | else: | |
476 | res = lambda p: dest |
|
476 | res = lambda p: dest | |
477 | return res |
|
477 | return res | |
478 |
|
478 | |||
479 |
|
479 | |||
480 | pats = scmutil.expandpats(pats) |
|
480 | pats = scmutil.expandpats(pats) | |
481 | if not pats: |
|
481 | if not pats: | |
482 | raise util.Abort(_('no source or destination specified')) |
|
482 | raise util.Abort(_('no source or destination specified')) | |
483 | if len(pats) == 1: |
|
483 | if len(pats) == 1: | |
484 | raise util.Abort(_('no destination specified')) |
|
484 | raise util.Abort(_('no destination specified')) | |
485 | dest = pats.pop() |
|
485 | dest = pats.pop() | |
486 | destdirexists = os.path.isdir(dest) and not os.path.islink(dest) |
|
486 | destdirexists = os.path.isdir(dest) and not os.path.islink(dest) | |
487 | if not destdirexists: |
|
487 | if not destdirexists: | |
488 | if len(pats) > 1 or matchmod.patkind(pats[0]): |
|
488 | if len(pats) > 1 or matchmod.patkind(pats[0]): | |
489 | raise util.Abort(_('with multiple sources, destination must be an ' |
|
489 | raise util.Abort(_('with multiple sources, destination must be an ' | |
490 | 'existing directory')) |
|
490 | 'existing directory')) | |
491 | if util.endswithsep(dest): |
|
491 | if util.endswithsep(dest): | |
492 | raise util.Abort(_('destination %s is not a directory') % dest) |
|
492 | raise util.Abort(_('destination %s is not a directory') % dest) | |
493 |
|
493 | |||
494 | tfn = targetpathfn |
|
494 | tfn = targetpathfn | |
495 | if after: |
|
495 | if after: | |
496 | tfn = targetpathafterfn |
|
496 | tfn = targetpathafterfn | |
497 | copylist = [] |
|
497 | copylist = [] | |
498 | for pat in pats: |
|
498 | for pat in pats: | |
499 | srcs = walkpat(pat) |
|
499 | srcs = walkpat(pat) | |
500 | if not srcs: |
|
500 | if not srcs: | |
501 | continue |
|
501 | continue | |
502 | copylist.append((tfn(pat, dest, srcs), srcs)) |
|
502 | copylist.append((tfn(pat, dest, srcs), srcs)) | |
503 | if not copylist: |
|
503 | if not copylist: | |
504 | raise util.Abort(_('no files to copy')) |
|
504 | raise util.Abort(_('no files to copy')) | |
505 |
|
505 | |||
506 | errors = 0 |
|
506 | errors = 0 | |
507 | for targetpath, srcs in copylist: |
|
507 | for targetpath, srcs in copylist: | |
508 | for abssrc, relsrc, exact in srcs: |
|
508 | for abssrc, relsrc, exact in srcs: | |
509 | if copyfile(abssrc, relsrc, targetpath(abssrc), exact): |
|
509 | if copyfile(abssrc, relsrc, targetpath(abssrc), exact): | |
510 | errors += 1 |
|
510 | errors += 1 | |
511 |
|
511 | |||
512 | if errors: |
|
512 | if errors: | |
513 | ui.warn(_('(consider using --after)\n')) |
|
513 | ui.warn(_('(consider using --after)\n')) | |
514 |
|
514 | |||
515 | return errors != 0 |
|
515 | return errors != 0 | |
516 |
|
516 | |||
517 | def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None, |
|
517 | def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None, | |
518 | runargs=None, appendpid=False): |
|
518 | runargs=None, appendpid=False): | |
519 | '''Run a command as a service.''' |
|
519 | '''Run a command as a service.''' | |
520 |
|
520 | |||
521 | def writepid(pid): |
|
521 | def writepid(pid): | |
522 | if opts['pid_file']: |
|
522 | if opts['pid_file']: | |
523 | mode = appendpid and 'a' or 'w' |
|
523 | mode = appendpid and 'a' or 'w' | |
524 | fp = open(opts['pid_file'], mode) |
|
524 | fp = open(opts['pid_file'], mode) | |
525 | fp.write(str(pid) + '\n') |
|
525 | fp.write(str(pid) + '\n') | |
526 | fp.close() |
|
526 | fp.close() | |
527 |
|
527 | |||
528 | if opts['daemon'] and not opts['daemon_pipefds']: |
|
528 | if opts['daemon'] and not opts['daemon_pipefds']: | |
529 | # Signal child process startup with file removal |
|
529 | # Signal child process startup with file removal | |
530 | lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-') |
|
530 | lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-') | |
531 | os.close(lockfd) |
|
531 | os.close(lockfd) | |
532 | try: |
|
532 | try: | |
533 | if not runargs: |
|
533 | if not runargs: | |
534 | runargs = util.hgcmd() + sys.argv[1:] |
|
534 | runargs = util.hgcmd() + sys.argv[1:] | |
535 | runargs.append('--daemon-pipefds=%s' % lockpath) |
|
535 | runargs.append('--daemon-pipefds=%s' % lockpath) | |
536 | # Don't pass --cwd to the child process, because we've already |
|
536 | # Don't pass --cwd to the child process, because we've already | |
537 | # changed directory. |
|
537 | # changed directory. | |
538 | for i in xrange(1, len(runargs)): |
|
538 | for i in xrange(1, len(runargs)): | |
539 | if runargs[i].startswith('--cwd='): |
|
539 | if runargs[i].startswith('--cwd='): | |
540 | del runargs[i] |
|
540 | del runargs[i] | |
541 | break |
|
541 | break | |
542 | elif runargs[i].startswith('--cwd'): |
|
542 | elif runargs[i].startswith('--cwd'): | |
543 | del runargs[i:i + 2] |
|
543 | del runargs[i:i + 2] | |
544 | break |
|
544 | break | |
545 | def condfn(): |
|
545 | def condfn(): | |
546 | return not os.path.exists(lockpath) |
|
546 | return not os.path.exists(lockpath) | |
547 | pid = util.rundetached(runargs, condfn) |
|
547 | pid = util.rundetached(runargs, condfn) | |
548 | if pid < 0: |
|
548 | if pid < 0: | |
549 | raise util.Abort(_('child process failed to start')) |
|
549 | raise util.Abort(_('child process failed to start')) | |
550 | writepid(pid) |
|
550 | writepid(pid) | |
551 | finally: |
|
551 | finally: | |
552 | try: |
|
552 | try: | |
553 | os.unlink(lockpath) |
|
553 | os.unlink(lockpath) | |
554 | except OSError, e: |
|
554 | except OSError, e: | |
555 | if e.errno != errno.ENOENT: |
|
555 | if e.errno != errno.ENOENT: | |
556 | raise |
|
556 | raise | |
557 | if parentfn: |
|
557 | if parentfn: | |
558 | return parentfn(pid) |
|
558 | return parentfn(pid) | |
559 | else: |
|
559 | else: | |
560 | return |
|
560 | return | |
561 |
|
561 | |||
562 | if initfn: |
|
562 | if initfn: | |
563 | initfn() |
|
563 | initfn() | |
564 |
|
564 | |||
565 | if not opts['daemon']: |
|
565 | if not opts['daemon']: | |
566 | writepid(os.getpid()) |
|
566 | writepid(os.getpid()) | |
567 |
|
567 | |||
568 | if opts['daemon_pipefds']: |
|
568 | if opts['daemon_pipefds']: | |
569 | lockpath = opts['daemon_pipefds'] |
|
569 | lockpath = opts['daemon_pipefds'] | |
570 | try: |
|
570 | try: | |
571 | os.setsid() |
|
571 | os.setsid() | |
572 | except AttributeError: |
|
572 | except AttributeError: | |
573 | pass |
|
573 | pass | |
574 | os.unlink(lockpath) |
|
574 | os.unlink(lockpath) | |
575 | util.hidewindow() |
|
575 | util.hidewindow() | |
576 | sys.stdout.flush() |
|
576 | sys.stdout.flush() | |
577 | sys.stderr.flush() |
|
577 | sys.stderr.flush() | |
578 |
|
578 | |||
579 | nullfd = os.open(os.devnull, os.O_RDWR) |
|
579 | nullfd = os.open(os.devnull, os.O_RDWR) | |
580 | logfilefd = nullfd |
|
580 | logfilefd = nullfd | |
581 | if logfile: |
|
581 | if logfile: | |
582 | logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND) |
|
582 | logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND) | |
583 | os.dup2(nullfd, 0) |
|
583 | os.dup2(nullfd, 0) | |
584 | os.dup2(logfilefd, 1) |
|
584 | os.dup2(logfilefd, 1) | |
585 | os.dup2(logfilefd, 2) |
|
585 | os.dup2(logfilefd, 2) | |
586 | if nullfd not in (0, 1, 2): |
|
586 | if nullfd not in (0, 1, 2): | |
587 | os.close(nullfd) |
|
587 | os.close(nullfd) | |
588 | if logfile and logfilefd not in (0, 1, 2): |
|
588 | if logfile and logfilefd not in (0, 1, 2): | |
589 | os.close(logfilefd) |
|
589 | os.close(logfilefd) | |
590 |
|
590 | |||
591 | if runfn: |
|
591 | if runfn: | |
592 | return runfn() |
|
592 | return runfn() | |
593 |
|
593 | |||
594 | def tryimportone(ui, repo, hunk, parents, opts, msgs, updatefunc): |
|
594 | def tryimportone(ui, repo, hunk, parents, opts, msgs, updatefunc): | |
595 | """Utility function used by commands.import to import a single patch |
|
595 | """Utility function used by commands.import to import a single patch | |
596 |
|
596 | |||
597 | This function is explicitly defined here to help the evolve extension to |
|
597 | This function is explicitly defined here to help the evolve extension to | |
598 | wrap this part of the import logic. |
|
598 | wrap this part of the import logic. | |
599 |
|
599 | |||
600 | The API is currently a bit ugly because it a simple code translation from |
|
600 | The API is currently a bit ugly because it a simple code translation from | |
601 | the import command. Feel free to make it better. |
|
601 | the import command. Feel free to make it better. | |
602 |
|
602 | |||
603 | :hunk: a patch (as a binary string) |
|
603 | :hunk: a patch (as a binary string) | |
604 | :parents: nodes that will be parent of the created commit |
|
604 | :parents: nodes that will be parent of the created commit | |
605 | :opts: the full dict of option passed to the import command |
|
605 | :opts: the full dict of option passed to the import command | |
606 | :msgs: list to save commit message to. |
|
606 | :msgs: list to save commit message to. | |
607 | (used in case we need to save it when failing) |
|
607 | (used in case we need to save it when failing) | |
608 | :updatefunc: a function that update a repo to a given node |
|
608 | :updatefunc: a function that update a repo to a given node | |
609 | updatefunc(<repo>, <node>) |
|
609 | updatefunc(<repo>, <node>) | |
610 | """ |
|
610 | """ | |
611 | tmpname, message, user, date, branch, nodeid, p1, p2 = \ |
|
611 | tmpname, message, user, date, branch, nodeid, p1, p2 = \ | |
612 | patch.extract(ui, hunk) |
|
612 | patch.extract(ui, hunk) | |
613 |
|
613 | |||
614 | update = not opts.get('bypass') |
|
614 | update = not opts.get('bypass') | |
615 | strip = opts["strip"] |
|
615 | strip = opts["strip"] | |
616 | sim = float(opts.get('similarity') or 0) |
|
616 | sim = float(opts.get('similarity') or 0) | |
617 | if not tmpname: |
|
617 | if not tmpname: | |
618 | return (None, None, False) |
|
618 | return (None, None, False) | |
619 | msg = _('applied to working directory') |
|
619 | msg = _('applied to working directory') | |
620 |
|
620 | |||
621 | rejects = False |
|
621 | rejects = False | |
622 |
|
622 | |||
623 | try: |
|
623 | try: | |
624 | cmdline_message = logmessage(ui, opts) |
|
624 | cmdline_message = logmessage(ui, opts) | |
625 | if cmdline_message: |
|
625 | if cmdline_message: | |
626 | # pickup the cmdline msg |
|
626 | # pickup the cmdline msg | |
627 | message = cmdline_message |
|
627 | message = cmdline_message | |
628 | elif message: |
|
628 | elif message: | |
629 | # pickup the patch msg |
|
629 | # pickup the patch msg | |
630 | message = message.strip() |
|
630 | message = message.strip() | |
631 | else: |
|
631 | else: | |
632 | # launch the editor |
|
632 | # launch the editor | |
633 | message = None |
|
633 | message = None | |
634 | ui.debug('message:\n%s\n' % message) |
|
634 | ui.debug('message:\n%s\n' % message) | |
635 |
|
635 | |||
636 | if len(parents) == 1: |
|
636 | if len(parents) == 1: | |
637 | parents.append(repo[nullid]) |
|
637 | parents.append(repo[nullid]) | |
638 | if opts.get('exact'): |
|
638 | if opts.get('exact'): | |
639 | if not nodeid or not p1: |
|
639 | if not nodeid or not p1: | |
640 | raise util.Abort(_('not a Mercurial patch')) |
|
640 | raise util.Abort(_('not a Mercurial patch')) | |
641 | p1 = repo[p1] |
|
641 | p1 = repo[p1] | |
642 | p2 = repo[p2 or nullid] |
|
642 | p2 = repo[p2 or nullid] | |
643 | elif p2: |
|
643 | elif p2: | |
644 | try: |
|
644 | try: | |
645 | p1 = repo[p1] |
|
645 | p1 = repo[p1] | |
646 | p2 = repo[p2] |
|
646 | p2 = repo[p2] | |
647 | # Without any options, consider p2 only if the |
|
647 | # Without any options, consider p2 only if the | |
648 | # patch is being applied on top of the recorded |
|
648 | # patch is being applied on top of the recorded | |
649 | # first parent. |
|
649 | # first parent. | |
650 | if p1 != parents[0]: |
|
650 | if p1 != parents[0]: | |
651 | p1 = parents[0] |
|
651 | p1 = parents[0] | |
652 | p2 = repo[nullid] |
|
652 | p2 = repo[nullid] | |
653 | except error.RepoError: |
|
653 | except error.RepoError: | |
654 | p1, p2 = parents |
|
654 | p1, p2 = parents | |
655 | if p2.node() == nullid: |
|
655 | if p2.node() == nullid: | |
656 | ui.warn(_("warning: import the patch as a normal revision\n" |
|
656 | ui.warn(_("warning: import the patch as a normal revision\n" | |
657 | "(use --exact to import the patch as a merge)\n")) |
|
657 | "(use --exact to import the patch as a merge)\n")) | |
658 | else: |
|
658 | else: | |
659 | p1, p2 = parents |
|
659 | p1, p2 = parents | |
660 |
|
660 | |||
661 | n = None |
|
661 | n = None | |
662 | if update: |
|
662 | if update: | |
663 | repo.dirstate.beginparentchange() |
|
663 | repo.dirstate.beginparentchange() | |
664 | if p1 != parents[0]: |
|
664 | if p1 != parents[0]: | |
665 | updatefunc(repo, p1.node()) |
|
665 | updatefunc(repo, p1.node()) | |
666 | if p2 != parents[1]: |
|
666 | if p2 != parents[1]: | |
667 | repo.setparents(p1.node(), p2.node()) |
|
667 | repo.setparents(p1.node(), p2.node()) | |
668 |
|
668 | |||
669 | if opts.get('exact') or opts.get('import_branch'): |
|
669 | if opts.get('exact') or opts.get('import_branch'): | |
670 | repo.dirstate.setbranch(branch or 'default') |
|
670 | repo.dirstate.setbranch(branch or 'default') | |
671 |
|
671 | |||
672 | partial = opts.get('partial', False) |
|
672 | partial = opts.get('partial', False) | |
673 | files = set() |
|
673 | files = set() | |
674 | try: |
|
674 | try: | |
675 | patch.patch(ui, repo, tmpname, strip=strip, files=files, |
|
675 | patch.patch(ui, repo, tmpname, strip=strip, files=files, | |
676 | eolmode=None, similarity=sim / 100.0) |
|
676 | eolmode=None, similarity=sim / 100.0) | |
677 | except patch.PatchError, e: |
|
677 | except patch.PatchError, e: | |
678 | if not partial: |
|
678 | if not partial: | |
679 | raise util.Abort(str(e)) |
|
679 | raise util.Abort(str(e)) | |
680 | if partial: |
|
680 | if partial: | |
681 | rejects = True |
|
681 | rejects = True | |
682 |
|
682 | |||
683 | files = list(files) |
|
683 | files = list(files) | |
684 | if opts.get('no_commit'): |
|
684 | if opts.get('no_commit'): | |
685 | if message: |
|
685 | if message: | |
686 | msgs.append(message) |
|
686 | msgs.append(message) | |
687 | else: |
|
687 | else: | |
688 | if opts.get('exact') or p2: |
|
688 | if opts.get('exact') or p2: | |
689 | # If you got here, you either use --force and know what |
|
689 | # If you got here, you either use --force and know what | |
690 | # you are doing or used --exact or a merge patch while |
|
690 | # you are doing or used --exact or a merge patch while | |
691 | # being updated to its first parent. |
|
691 | # being updated to its first parent. | |
692 | m = None |
|
692 | m = None | |
693 | else: |
|
693 | else: | |
694 | m = scmutil.matchfiles(repo, files or []) |
|
694 | m = scmutil.matchfiles(repo, files or []) | |
695 | editform = mergeeditform(repo[None], 'import.normal') |
|
695 | editform = mergeeditform(repo[None], 'import.normal') | |
696 | if opts.get('exact'): |
|
696 | if opts.get('exact'): | |
697 | editor = None |
|
697 | editor = None | |
698 | else: |
|
698 | else: | |
699 | editor = getcommiteditor(editform=editform, **opts) |
|
699 | editor = getcommiteditor(editform=editform, **opts) | |
700 | n = repo.commit(message, opts.get('user') or user, |
|
700 | n = repo.commit(message, opts.get('user') or user, | |
701 | opts.get('date') or date, match=m, |
|
701 | opts.get('date') or date, match=m, | |
702 | editor=editor, force=partial) |
|
702 | editor=editor, force=partial) | |
703 | repo.dirstate.endparentchange() |
|
703 | repo.dirstate.endparentchange() | |
704 | else: |
|
704 | else: | |
705 | if opts.get('exact') or opts.get('import_branch'): |
|
705 | if opts.get('exact') or opts.get('import_branch'): | |
706 | branch = branch or 'default' |
|
706 | branch = branch or 'default' | |
707 | else: |
|
707 | else: | |
708 | branch = p1.branch() |
|
708 | branch = p1.branch() | |
709 | store = patch.filestore() |
|
709 | store = patch.filestore() | |
710 | try: |
|
710 | try: | |
711 | files = set() |
|
711 | files = set() | |
712 | try: |
|
712 | try: | |
713 | patch.patchrepo(ui, repo, p1, store, tmpname, strip, |
|
713 | patch.patchrepo(ui, repo, p1, store, tmpname, strip, | |
714 | files, eolmode=None) |
|
714 | files, eolmode=None) | |
715 | except patch.PatchError, e: |
|
715 | except patch.PatchError, e: | |
716 | raise util.Abort(str(e)) |
|
716 | raise util.Abort(str(e)) | |
717 | if opts.get('exact'): |
|
717 | if opts.get('exact'): | |
718 | editor = None |
|
718 | editor = None | |
719 | else: |
|
719 | else: | |
720 | editor = getcommiteditor(editform='import.bypass') |
|
720 | editor = getcommiteditor(editform='import.bypass') | |
721 | memctx = context.makememctx(repo, (p1.node(), p2.node()), |
|
721 | memctx = context.makememctx(repo, (p1.node(), p2.node()), | |
722 | message, |
|
722 | message, | |
723 | opts.get('user') or user, |
|
723 | opts.get('user') or user, | |
724 | opts.get('date') or date, |
|
724 | opts.get('date') or date, | |
725 | branch, files, store, |
|
725 | branch, files, store, | |
726 | editor=editor) |
|
726 | editor=editor) | |
727 | n = memctx.commit() |
|
727 | n = memctx.commit() | |
728 | finally: |
|
728 | finally: | |
729 | store.close() |
|
729 | store.close() | |
730 | if opts.get('exact') and opts.get('no_commit'): |
|
730 | if opts.get('exact') and opts.get('no_commit'): | |
731 | # --exact with --no-commit is still useful in that it does merge |
|
731 | # --exact with --no-commit is still useful in that it does merge | |
732 | # and branch bits |
|
732 | # and branch bits | |
733 | ui.warn(_("warning: can't check exact import with --no-commit\n")) |
|
733 | ui.warn(_("warning: can't check exact import with --no-commit\n")) | |
734 | elif opts.get('exact') and hex(n) != nodeid: |
|
734 | elif opts.get('exact') and hex(n) != nodeid: | |
735 | raise util.Abort(_('patch is damaged or loses information')) |
|
735 | raise util.Abort(_('patch is damaged or loses information')) | |
736 | if n: |
|
736 | if n: | |
737 | # i18n: refers to a short changeset id |
|
737 | # i18n: refers to a short changeset id | |
738 | msg = _('created %s') % short(n) |
|
738 | msg = _('created %s') % short(n) | |
739 | return (msg, n, rejects) |
|
739 | return (msg, n, rejects) | |
740 | finally: |
|
740 | finally: | |
741 | os.unlink(tmpname) |
|
741 | os.unlink(tmpname) | |
742 |
|
742 | |||
743 | def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False, |
|
743 | def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False, | |
744 | opts=None): |
|
744 | opts=None): | |
745 | '''export changesets as hg patches.''' |
|
745 | '''export changesets as hg patches.''' | |
746 |
|
746 | |||
747 | total = len(revs) |
|
747 | total = len(revs) | |
748 | revwidth = max([len(str(rev)) for rev in revs]) |
|
748 | revwidth = max([len(str(rev)) for rev in revs]) | |
749 | filemode = {} |
|
749 | filemode = {} | |
750 |
|
750 | |||
751 | def single(rev, seqno, fp): |
|
751 | def single(rev, seqno, fp): | |
752 | ctx = repo[rev] |
|
752 | ctx = repo[rev] | |
753 | node = ctx.node() |
|
753 | node = ctx.node() | |
754 | parents = [p.node() for p in ctx.parents() if p] |
|
754 | parents = [p.node() for p in ctx.parents() if p] | |
755 | branch = ctx.branch() |
|
755 | branch = ctx.branch() | |
756 | if switch_parent: |
|
756 | if switch_parent: | |
757 | parents.reverse() |
|
757 | parents.reverse() | |
758 | prev = (parents and parents[0]) or nullid |
|
758 | prev = (parents and parents[0]) or nullid | |
759 |
|
759 | |||
760 | shouldclose = False |
|
760 | shouldclose = False | |
761 | if not fp and len(template) > 0: |
|
761 | if not fp and len(template) > 0: | |
762 | desc_lines = ctx.description().rstrip().split('\n') |
|
762 | desc_lines = ctx.description().rstrip().split('\n') | |
763 | desc = desc_lines[0] #Commit always has a first line. |
|
763 | desc = desc_lines[0] #Commit always has a first line. | |
764 | fp = makefileobj(repo, template, node, desc=desc, total=total, |
|
764 | fp = makefileobj(repo, template, node, desc=desc, total=total, | |
765 | seqno=seqno, revwidth=revwidth, mode='wb', |
|
765 | seqno=seqno, revwidth=revwidth, mode='wb', | |
766 | modemap=filemode) |
|
766 | modemap=filemode) | |
767 | if fp != template: |
|
767 | if fp != template: | |
768 | shouldclose = True |
|
768 | shouldclose = True | |
769 | if fp and fp != sys.stdout and util.safehasattr(fp, 'name'): |
|
769 | if fp and fp != sys.stdout and util.safehasattr(fp, 'name'): | |
770 | repo.ui.note("%s\n" % fp.name) |
|
770 | repo.ui.note("%s\n" % fp.name) | |
771 |
|
771 | |||
772 | if not fp: |
|
772 | if not fp: | |
773 | write = repo.ui.write |
|
773 | write = repo.ui.write | |
774 | else: |
|
774 | else: | |
775 | def write(s, **kw): |
|
775 | def write(s, **kw): | |
776 | fp.write(s) |
|
776 | fp.write(s) | |
777 |
|
777 | |||
778 |
|
778 | |||
779 | write("# HG changeset patch\n") |
|
779 | write("# HG changeset patch\n") | |
780 | write("# User %s\n" % ctx.user()) |
|
780 | write("# User %s\n" % ctx.user()) | |
781 | write("# Date %d %d\n" % ctx.date()) |
|
781 | write("# Date %d %d\n" % ctx.date()) | |
782 | write("# %s\n" % util.datestr(ctx.date())) |
|
782 | write("# %s\n" % util.datestr(ctx.date())) | |
783 | if branch and branch != 'default': |
|
783 | if branch and branch != 'default': | |
784 | write("# Branch %s\n" % branch) |
|
784 | write("# Branch %s\n" % branch) | |
785 | write("# Node ID %s\n" % hex(node)) |
|
785 | write("# Node ID %s\n" % hex(node)) | |
786 | write("# Parent %s\n" % hex(prev)) |
|
786 | write("# Parent %s\n" % hex(prev)) | |
787 | if len(parents) > 1: |
|
787 | if len(parents) > 1: | |
788 | write("# Parent %s\n" % hex(parents[1])) |
|
788 | write("# Parent %s\n" % hex(parents[1])) | |
789 | write(ctx.description().rstrip()) |
|
789 | write(ctx.description().rstrip()) | |
790 | write("\n\n") |
|
790 | write("\n\n") | |
791 |
|
791 | |||
792 | for chunk, label in patch.diffui(repo, prev, node, opts=opts): |
|
792 | for chunk, label in patch.diffui(repo, prev, node, opts=opts): | |
793 | write(chunk, label=label) |
|
793 | write(chunk, label=label) | |
794 |
|
794 | |||
795 | if shouldclose: |
|
795 | if shouldclose: | |
796 | fp.close() |
|
796 | fp.close() | |
797 |
|
797 | |||
798 | for seqno, rev in enumerate(revs): |
|
798 | for seqno, rev in enumerate(revs): | |
799 | single(rev, seqno + 1, fp) |
|
799 | single(rev, seqno + 1, fp) | |
800 |
|
800 | |||
801 | def diffordiffstat(ui, repo, diffopts, node1, node2, match, |
|
801 | def diffordiffstat(ui, repo, diffopts, node1, node2, match, | |
802 | changes=None, stat=False, fp=None, prefix='', |
|
802 | changes=None, stat=False, fp=None, prefix='', | |
803 | listsubrepos=False): |
|
803 | listsubrepos=False): | |
804 | '''show diff or diffstat.''' |
|
804 | '''show diff or diffstat.''' | |
805 | if fp is None: |
|
805 | if fp is None: | |
806 | write = ui.write |
|
806 | write = ui.write | |
807 | else: |
|
807 | else: | |
808 | def write(s, **kw): |
|
808 | def write(s, **kw): | |
809 | fp.write(s) |
|
809 | fp.write(s) | |
810 |
|
810 | |||
811 | if stat: |
|
811 | if stat: | |
812 | diffopts = diffopts.copy(context=0) |
|
812 | diffopts = diffopts.copy(context=0) | |
813 | width = 80 |
|
813 | width = 80 | |
814 | if not ui.plain(): |
|
814 | if not ui.plain(): | |
815 | width = ui.termwidth() |
|
815 | width = ui.termwidth() | |
816 | chunks = patch.diff(repo, node1, node2, match, changes, diffopts, |
|
816 | chunks = patch.diff(repo, node1, node2, match, changes, diffopts, | |
817 | prefix=prefix) |
|
817 | prefix=prefix) | |
818 | for chunk, label in patch.diffstatui(util.iterlines(chunks), |
|
818 | for chunk, label in patch.diffstatui(util.iterlines(chunks), | |
819 | width=width, |
|
819 | width=width, | |
820 | git=diffopts.git): |
|
820 | git=diffopts.git): | |
821 | write(chunk, label=label) |
|
821 | write(chunk, label=label) | |
822 | else: |
|
822 | else: | |
823 | for chunk, label in patch.diffui(repo, node1, node2, match, |
|
823 | for chunk, label in patch.diffui(repo, node1, node2, match, | |
824 | changes, diffopts, prefix=prefix): |
|
824 | changes, diffopts, prefix=prefix): | |
825 | write(chunk, label=label) |
|
825 | write(chunk, label=label) | |
826 |
|
826 | |||
827 | if listsubrepos: |
|
827 | if listsubrepos: | |
828 | ctx1 = repo[node1] |
|
828 | ctx1 = repo[node1] | |
829 | ctx2 = repo[node2] |
|
829 | ctx2 = repo[node2] | |
830 | for subpath, sub in scmutil.itersubrepos(ctx1, ctx2): |
|
830 | for subpath, sub in scmutil.itersubrepos(ctx1, ctx2): | |
831 | tempnode2 = node2 |
|
831 | tempnode2 = node2 | |
832 | try: |
|
832 | try: | |
833 | if node2 is not None: |
|
833 | if node2 is not None: | |
834 | tempnode2 = ctx2.substate[subpath][1] |
|
834 | tempnode2 = ctx2.substate[subpath][1] | |
835 | except KeyError: |
|
835 | except KeyError: | |
836 | # A subrepo that existed in node1 was deleted between node1 and |
|
836 | # A subrepo that existed in node1 was deleted between node1 and | |
837 | # node2 (inclusive). Thus, ctx2's substate won't contain that |
|
837 | # node2 (inclusive). Thus, ctx2's substate won't contain that | |
838 | # subpath. The best we can do is to ignore it. |
|
838 | # subpath. The best we can do is to ignore it. | |
839 | tempnode2 = None |
|
839 | tempnode2 = None | |
840 | submatch = matchmod.narrowmatcher(subpath, match) |
|
840 | submatch = matchmod.narrowmatcher(subpath, match) | |
841 | sub.diff(ui, diffopts, tempnode2, submatch, changes=changes, |
|
841 | sub.diff(ui, diffopts, tempnode2, submatch, changes=changes, | |
842 | stat=stat, fp=fp, prefix=prefix) |
|
842 | stat=stat, fp=fp, prefix=prefix) | |
843 |
|
843 | |||
844 | class changeset_printer(object): |
|
844 | class changeset_printer(object): | |
845 | '''show changeset information when templating not requested.''' |
|
845 | '''show changeset information when templating not requested.''' | |
846 |
|
846 | |||
847 | def __init__(self, ui, repo, matchfn, diffopts, buffered): |
|
847 | def __init__(self, ui, repo, matchfn, diffopts, buffered): | |
848 | self.ui = ui |
|
848 | self.ui = ui | |
849 | self.repo = repo |
|
849 | self.repo = repo | |
850 | self.buffered = buffered |
|
850 | self.buffered = buffered | |
851 | self.matchfn = matchfn |
|
851 | self.matchfn = matchfn | |
852 | self.diffopts = diffopts |
|
852 | self.diffopts = diffopts | |
853 | self.header = {} |
|
853 | self.header = {} | |
854 | self.hunk = {} |
|
854 | self.hunk = {} | |
855 | self.lastheader = None |
|
855 | self.lastheader = None | |
856 | self.footer = None |
|
856 | self.footer = None | |
857 |
|
857 | |||
858 | def flush(self, rev): |
|
858 | def flush(self, rev): | |
859 | if rev in self.header: |
|
859 | if rev in self.header: | |
860 | h = self.header[rev] |
|
860 | h = self.header[rev] | |
861 | if h != self.lastheader: |
|
861 | if h != self.lastheader: | |
862 | self.lastheader = h |
|
862 | self.lastheader = h | |
863 | self.ui.write(h) |
|
863 | self.ui.write(h) | |
864 | del self.header[rev] |
|
864 | del self.header[rev] | |
865 | if rev in self.hunk: |
|
865 | if rev in self.hunk: | |
866 | self.ui.write(self.hunk[rev]) |
|
866 | self.ui.write(self.hunk[rev]) | |
867 | del self.hunk[rev] |
|
867 | del self.hunk[rev] | |
868 | return 1 |
|
868 | return 1 | |
869 | return 0 |
|
869 | return 0 | |
870 |
|
870 | |||
871 | def close(self): |
|
871 | def close(self): | |
872 | if self.footer: |
|
872 | if self.footer: | |
873 | self.ui.write(self.footer) |
|
873 | self.ui.write(self.footer) | |
874 |
|
874 | |||
875 | def show(self, ctx, copies=None, matchfn=None, **props): |
|
875 | def show(self, ctx, copies=None, matchfn=None, **props): | |
876 | if self.buffered: |
|
876 | if self.buffered: | |
877 | self.ui.pushbuffer() |
|
877 | self.ui.pushbuffer() | |
878 | self._show(ctx, copies, matchfn, props) |
|
878 | self._show(ctx, copies, matchfn, props) | |
879 | self.hunk[ctx.rev()] = self.ui.popbuffer(labeled=True) |
|
879 | self.hunk[ctx.rev()] = self.ui.popbuffer(labeled=True) | |
880 | else: |
|
880 | else: | |
881 | self._show(ctx, copies, matchfn, props) |
|
881 | self._show(ctx, copies, matchfn, props) | |
882 |
|
882 | |||
883 | def _show(self, ctx, copies, matchfn, props): |
|
883 | def _show(self, ctx, copies, matchfn, props): | |
884 | '''show a single changeset or file revision''' |
|
884 | '''show a single changeset or file revision''' | |
885 | changenode = ctx.node() |
|
885 | changenode = ctx.node() | |
886 | rev = ctx.rev() |
|
886 | rev = ctx.rev() | |
887 |
|
887 | |||
888 | if self.ui.quiet: |
|
888 | if self.ui.quiet: | |
889 | self.ui.write("%d:%s\n" % (rev, short(changenode)), |
|
889 | self.ui.write("%d:%s\n" % (rev, short(changenode)), | |
890 | label='log.node') |
|
890 | label='log.node') | |
891 | return |
|
891 | return | |
892 |
|
892 | |||
893 | log = self.repo.changelog |
|
893 | log = self.repo.changelog | |
894 | date = util.datestr(ctx.date()) |
|
894 | date = util.datestr(ctx.date()) | |
895 |
|
895 | |||
896 | hexfunc = self.ui.debugflag and hex or short |
|
896 | hexfunc = self.ui.debugflag and hex or short | |
897 |
|
897 | |||
898 | parents = [(p, hexfunc(log.node(p))) |
|
898 | parents = [(p, hexfunc(log.node(p))) | |
899 | for p in self._meaningful_parentrevs(log, rev)] |
|
899 | for p in self._meaningful_parentrevs(log, rev)] | |
900 |
|
900 | |||
901 | # i18n: column positioning for "hg log" |
|
901 | # i18n: column positioning for "hg log" | |
902 | self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)), |
|
902 | self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)), | |
903 | label='log.changeset changeset.%s' % ctx.phasestr()) |
|
903 | label='log.changeset changeset.%s' % ctx.phasestr()) | |
904 |
|
904 | |||
905 | # branches are shown first before any other names due to backwards |
|
905 | # branches are shown first before any other names due to backwards | |
906 | # compatibility |
|
906 | # compatibility | |
907 | branch = ctx.branch() |
|
907 | branch = ctx.branch() | |
908 | # don't show the default branch name |
|
908 | # don't show the default branch name | |
909 | if branch != 'default': |
|
909 | if branch != 'default': | |
910 | # i18n: column positioning for "hg log" |
|
910 | # i18n: column positioning for "hg log" | |
911 | self.ui.write(_("branch: %s\n") % branch, |
|
911 | self.ui.write(_("branch: %s\n") % branch, | |
912 | label='log.branch') |
|
912 | label='log.branch') | |
913 |
|
913 | |||
914 | for name, ns in self.repo.names.iteritems(): |
|
914 | for name, ns in self.repo.names.iteritems(): | |
915 | # branches has special logic already handled above, so here we just |
|
915 | # branches has special logic already handled above, so here we just | |
916 | # skip it |
|
916 | # skip it | |
917 | if name == 'branches': |
|
917 | if name == 'branches': | |
918 | continue |
|
918 | continue | |
919 | # we will use the templatename as the color name since those two |
|
919 | # we will use the templatename as the color name since those two | |
920 | # should be the same |
|
920 | # should be the same | |
921 | for name in ns.names(self.repo, changenode): |
|
921 | for name in ns.names(self.repo, changenode): | |
922 | # i18n: column positioning for "hg log" |
|
922 | self.ui.write(ns.logfmt % name, | |
923 | name = _(("%s:" % ns.logname).ljust(13) + "%s\n") % name |
|
923 | label='log.%s' % ns.colorname) | |
924 | self.ui.write("%s" % name, label='log.%s' % ns.colorname) |
|
|||
925 | if self.ui.debugflag: |
|
924 | if self.ui.debugflag: | |
926 | # i18n: column positioning for "hg log" |
|
925 | # i18n: column positioning for "hg log" | |
927 | self.ui.write(_("phase: %s\n") % _(ctx.phasestr()), |
|
926 | self.ui.write(_("phase: %s\n") % _(ctx.phasestr()), | |
928 | label='log.phase') |
|
927 | label='log.phase') | |
929 | for parent in parents: |
|
928 | for parent in parents: | |
930 | label = 'log.parent changeset.%s' % self.repo[parent[0]].phasestr() |
|
929 | label = 'log.parent changeset.%s' % self.repo[parent[0]].phasestr() | |
931 | # i18n: column positioning for "hg log" |
|
930 | # i18n: column positioning for "hg log" | |
932 | self.ui.write(_("parent: %d:%s\n") % parent, |
|
931 | self.ui.write(_("parent: %d:%s\n") % parent, | |
933 | label=label) |
|
932 | label=label) | |
934 |
|
933 | |||
935 | if self.ui.debugflag: |
|
934 | if self.ui.debugflag: | |
936 | mnode = ctx.manifestnode() |
|
935 | mnode = ctx.manifestnode() | |
937 | # i18n: column positioning for "hg log" |
|
936 | # i18n: column positioning for "hg log" | |
938 | self.ui.write(_("manifest: %d:%s\n") % |
|
937 | self.ui.write(_("manifest: %d:%s\n") % | |
939 | (self.repo.manifest.rev(mnode), hex(mnode)), |
|
938 | (self.repo.manifest.rev(mnode), hex(mnode)), | |
940 | label='ui.debug log.manifest') |
|
939 | label='ui.debug log.manifest') | |
941 | # i18n: column positioning for "hg log" |
|
940 | # i18n: column positioning for "hg log" | |
942 | self.ui.write(_("user: %s\n") % ctx.user(), |
|
941 | self.ui.write(_("user: %s\n") % ctx.user(), | |
943 | label='log.user') |
|
942 | label='log.user') | |
944 | # i18n: column positioning for "hg log" |
|
943 | # i18n: column positioning for "hg log" | |
945 | self.ui.write(_("date: %s\n") % date, |
|
944 | self.ui.write(_("date: %s\n") % date, | |
946 | label='log.date') |
|
945 | label='log.date') | |
947 |
|
946 | |||
948 | if self.ui.debugflag: |
|
947 | if self.ui.debugflag: | |
949 | files = self.repo.status(log.parents(changenode)[0], changenode)[:3] |
|
948 | files = self.repo.status(log.parents(changenode)[0], changenode)[:3] | |
950 | for key, value in zip([# i18n: column positioning for "hg log" |
|
949 | for key, value in zip([# i18n: column positioning for "hg log" | |
951 | _("files:"), |
|
950 | _("files:"), | |
952 | # i18n: column positioning for "hg log" |
|
951 | # i18n: column positioning for "hg log" | |
953 | _("files+:"), |
|
952 | _("files+:"), | |
954 | # i18n: column positioning for "hg log" |
|
953 | # i18n: column positioning for "hg log" | |
955 | _("files-:")], files): |
|
954 | _("files-:")], files): | |
956 | if value: |
|
955 | if value: | |
957 | self.ui.write("%-12s %s\n" % (key, " ".join(value)), |
|
956 | self.ui.write("%-12s %s\n" % (key, " ".join(value)), | |
958 | label='ui.debug log.files') |
|
957 | label='ui.debug log.files') | |
959 | elif ctx.files() and self.ui.verbose: |
|
958 | elif ctx.files() and self.ui.verbose: | |
960 | # i18n: column positioning for "hg log" |
|
959 | # i18n: column positioning for "hg log" | |
961 | self.ui.write(_("files: %s\n") % " ".join(ctx.files()), |
|
960 | self.ui.write(_("files: %s\n") % " ".join(ctx.files()), | |
962 | label='ui.note log.files') |
|
961 | label='ui.note log.files') | |
963 | if copies and self.ui.verbose: |
|
962 | if copies and self.ui.verbose: | |
964 | copies = ['%s (%s)' % c for c in copies] |
|
963 | copies = ['%s (%s)' % c for c in copies] | |
965 | # i18n: column positioning for "hg log" |
|
964 | # i18n: column positioning for "hg log" | |
966 | self.ui.write(_("copies: %s\n") % ' '.join(copies), |
|
965 | self.ui.write(_("copies: %s\n") % ' '.join(copies), | |
967 | label='ui.note log.copies') |
|
966 | label='ui.note log.copies') | |
968 |
|
967 | |||
969 | extra = ctx.extra() |
|
968 | extra = ctx.extra() | |
970 | if extra and self.ui.debugflag: |
|
969 | if extra and self.ui.debugflag: | |
971 | for key, value in sorted(extra.items()): |
|
970 | for key, value in sorted(extra.items()): | |
972 | # i18n: column positioning for "hg log" |
|
971 | # i18n: column positioning for "hg log" | |
973 | self.ui.write(_("extra: %s=%s\n") |
|
972 | self.ui.write(_("extra: %s=%s\n") | |
974 | % (key, value.encode('string_escape')), |
|
973 | % (key, value.encode('string_escape')), | |
975 | label='ui.debug log.extra') |
|
974 | label='ui.debug log.extra') | |
976 |
|
975 | |||
977 | description = ctx.description().strip() |
|
976 | description = ctx.description().strip() | |
978 | if description: |
|
977 | if description: | |
979 | if self.ui.verbose: |
|
978 | if self.ui.verbose: | |
980 | self.ui.write(_("description:\n"), |
|
979 | self.ui.write(_("description:\n"), | |
981 | label='ui.note log.description') |
|
980 | label='ui.note log.description') | |
982 | self.ui.write(description, |
|
981 | self.ui.write(description, | |
983 | label='ui.note log.description') |
|
982 | label='ui.note log.description') | |
984 | self.ui.write("\n\n") |
|
983 | self.ui.write("\n\n") | |
985 | else: |
|
984 | else: | |
986 | # i18n: column positioning for "hg log" |
|
985 | # i18n: column positioning for "hg log" | |
987 | self.ui.write(_("summary: %s\n") % |
|
986 | self.ui.write(_("summary: %s\n") % | |
988 | description.splitlines()[0], |
|
987 | description.splitlines()[0], | |
989 | label='log.summary') |
|
988 | label='log.summary') | |
990 | self.ui.write("\n") |
|
989 | self.ui.write("\n") | |
991 |
|
990 | |||
992 | self.showpatch(changenode, matchfn) |
|
991 | self.showpatch(changenode, matchfn) | |
993 |
|
992 | |||
994 | def showpatch(self, node, matchfn): |
|
993 | def showpatch(self, node, matchfn): | |
995 | if not matchfn: |
|
994 | if not matchfn: | |
996 | matchfn = self.matchfn |
|
995 | matchfn = self.matchfn | |
997 | if matchfn: |
|
996 | if matchfn: | |
998 | stat = self.diffopts.get('stat') |
|
997 | stat = self.diffopts.get('stat') | |
999 | diff = self.diffopts.get('patch') |
|
998 | diff = self.diffopts.get('patch') | |
1000 | diffopts = patch.diffallopts(self.ui, self.diffopts) |
|
999 | diffopts = patch.diffallopts(self.ui, self.diffopts) | |
1001 | prev = self.repo.changelog.parents(node)[0] |
|
1000 | prev = self.repo.changelog.parents(node)[0] | |
1002 | if stat: |
|
1001 | if stat: | |
1003 | diffordiffstat(self.ui, self.repo, diffopts, prev, node, |
|
1002 | diffordiffstat(self.ui, self.repo, diffopts, prev, node, | |
1004 | match=matchfn, stat=True) |
|
1003 | match=matchfn, stat=True) | |
1005 | if diff: |
|
1004 | if diff: | |
1006 | if stat: |
|
1005 | if stat: | |
1007 | self.ui.write("\n") |
|
1006 | self.ui.write("\n") | |
1008 | diffordiffstat(self.ui, self.repo, diffopts, prev, node, |
|
1007 | diffordiffstat(self.ui, self.repo, diffopts, prev, node, | |
1009 | match=matchfn, stat=False) |
|
1008 | match=matchfn, stat=False) | |
1010 | self.ui.write("\n") |
|
1009 | self.ui.write("\n") | |
1011 |
|
1010 | |||
1012 | def _meaningful_parentrevs(self, log, rev): |
|
1011 | def _meaningful_parentrevs(self, log, rev): | |
1013 | """Return list of meaningful (or all if debug) parentrevs for rev. |
|
1012 | """Return list of meaningful (or all if debug) parentrevs for rev. | |
1014 |
|
1013 | |||
1015 | For merges (two non-nullrev revisions) both parents are meaningful. |
|
1014 | For merges (two non-nullrev revisions) both parents are meaningful. | |
1016 | Otherwise the first parent revision is considered meaningful if it |
|
1015 | Otherwise the first parent revision is considered meaningful if it | |
1017 | is not the preceding revision. |
|
1016 | is not the preceding revision. | |
1018 | """ |
|
1017 | """ | |
1019 | parents = log.parentrevs(rev) |
|
1018 | parents = log.parentrevs(rev) | |
1020 | if not self.ui.debugflag and parents[1] == nullrev: |
|
1019 | if not self.ui.debugflag and parents[1] == nullrev: | |
1021 | if parents[0] >= rev - 1: |
|
1020 | if parents[0] >= rev - 1: | |
1022 | parents = [] |
|
1021 | parents = [] | |
1023 | else: |
|
1022 | else: | |
1024 | parents = [parents[0]] |
|
1023 | parents = [parents[0]] | |
1025 | return parents |
|
1024 | return parents | |
1026 |
|
1025 | |||
1027 | class jsonchangeset(changeset_printer): |
|
1026 | class jsonchangeset(changeset_printer): | |
1028 | '''format changeset information.''' |
|
1027 | '''format changeset information.''' | |
1029 |
|
1028 | |||
1030 | def __init__(self, ui, repo, matchfn, diffopts, buffered): |
|
1029 | def __init__(self, ui, repo, matchfn, diffopts, buffered): | |
1031 | changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered) |
|
1030 | changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered) | |
1032 | self.cache = {} |
|
1031 | self.cache = {} | |
1033 | self._first = True |
|
1032 | self._first = True | |
1034 |
|
1033 | |||
1035 | def close(self): |
|
1034 | def close(self): | |
1036 | if not self._first: |
|
1035 | if not self._first: | |
1037 | self.ui.write("\n]\n") |
|
1036 | self.ui.write("\n]\n") | |
1038 | else: |
|
1037 | else: | |
1039 | self.ui.write("[]\n") |
|
1038 | self.ui.write("[]\n") | |
1040 |
|
1039 | |||
1041 | def _show(self, ctx, copies, matchfn, props): |
|
1040 | def _show(self, ctx, copies, matchfn, props): | |
1042 | '''show a single changeset or file revision''' |
|
1041 | '''show a single changeset or file revision''' | |
1043 | hexnode = hex(ctx.node()) |
|
1042 | hexnode = hex(ctx.node()) | |
1044 | rev = ctx.rev() |
|
1043 | rev = ctx.rev() | |
1045 | j = encoding.jsonescape |
|
1044 | j = encoding.jsonescape | |
1046 |
|
1045 | |||
1047 | if self._first: |
|
1046 | if self._first: | |
1048 | self.ui.write("[\n {") |
|
1047 | self.ui.write("[\n {") | |
1049 | self._first = False |
|
1048 | self._first = False | |
1050 | else: |
|
1049 | else: | |
1051 | self.ui.write(",\n {") |
|
1050 | self.ui.write(",\n {") | |
1052 |
|
1051 | |||
1053 | if self.ui.quiet: |
|
1052 | if self.ui.quiet: | |
1054 | self.ui.write('\n "rev": %d' % rev) |
|
1053 | self.ui.write('\n "rev": %d' % rev) | |
1055 | self.ui.write(',\n "node": "%s"' % hexnode) |
|
1054 | self.ui.write(',\n "node": "%s"' % hexnode) | |
1056 | self.ui.write('\n }') |
|
1055 | self.ui.write('\n }') | |
1057 | return |
|
1056 | return | |
1058 |
|
1057 | |||
1059 | self.ui.write('\n "rev": %d' % rev) |
|
1058 | self.ui.write('\n "rev": %d' % rev) | |
1060 | self.ui.write(',\n "node": "%s"' % hexnode) |
|
1059 | self.ui.write(',\n "node": "%s"' % hexnode) | |
1061 | self.ui.write(',\n "branch": "%s"' % j(ctx.branch())) |
|
1060 | self.ui.write(',\n "branch": "%s"' % j(ctx.branch())) | |
1062 | self.ui.write(',\n "phase": "%s"' % ctx.phasestr()) |
|
1061 | self.ui.write(',\n "phase": "%s"' % ctx.phasestr()) | |
1063 | self.ui.write(',\n "user": "%s"' % j(ctx.user())) |
|
1062 | self.ui.write(',\n "user": "%s"' % j(ctx.user())) | |
1064 | self.ui.write(',\n "date": [%d, %d]' % ctx.date()) |
|
1063 | self.ui.write(',\n "date": [%d, %d]' % ctx.date()) | |
1065 | self.ui.write(',\n "desc": "%s"' % j(ctx.description())) |
|
1064 | self.ui.write(',\n "desc": "%s"' % j(ctx.description())) | |
1066 |
|
1065 | |||
1067 | self.ui.write(',\n "bookmarks": [%s]' % |
|
1066 | self.ui.write(',\n "bookmarks": [%s]' % | |
1068 | ", ".join('"%s"' % j(b) for b in ctx.bookmarks())) |
|
1067 | ", ".join('"%s"' % j(b) for b in ctx.bookmarks())) | |
1069 | self.ui.write(',\n "tags": [%s]' % |
|
1068 | self.ui.write(',\n "tags": [%s]' % | |
1070 | ", ".join('"%s"' % j(t) for t in ctx.tags())) |
|
1069 | ", ".join('"%s"' % j(t) for t in ctx.tags())) | |
1071 | self.ui.write(',\n "parents": [%s]' % |
|
1070 | self.ui.write(',\n "parents": [%s]' % | |
1072 | ", ".join('"%s"' % c.hex() for c in ctx.parents())) |
|
1071 | ", ".join('"%s"' % c.hex() for c in ctx.parents())) | |
1073 |
|
1072 | |||
1074 | if self.ui.debugflag: |
|
1073 | if self.ui.debugflag: | |
1075 | self.ui.write(',\n "manifest": "%s"' % hex(ctx.manifestnode())) |
|
1074 | self.ui.write(',\n "manifest": "%s"' % hex(ctx.manifestnode())) | |
1076 |
|
1075 | |||
1077 | self.ui.write(',\n "extra": {%s}' % |
|
1076 | self.ui.write(',\n "extra": {%s}' % | |
1078 | ", ".join('"%s": "%s"' % (j(k), j(v)) |
|
1077 | ", ".join('"%s": "%s"' % (j(k), j(v)) | |
1079 | for k, v in ctx.extra().items())) |
|
1078 | for k, v in ctx.extra().items())) | |
1080 |
|
1079 | |||
1081 | files = ctx.p1().status(ctx) |
|
1080 | files = ctx.p1().status(ctx) | |
1082 | self.ui.write(',\n "modified": [%s]' % |
|
1081 | self.ui.write(',\n "modified": [%s]' % | |
1083 | ", ".join('"%s"' % j(f) for f in files[0])) |
|
1082 | ", ".join('"%s"' % j(f) for f in files[0])) | |
1084 | self.ui.write(',\n "added": [%s]' % |
|
1083 | self.ui.write(',\n "added": [%s]' % | |
1085 | ", ".join('"%s"' % j(f) for f in files[1])) |
|
1084 | ", ".join('"%s"' % j(f) for f in files[1])) | |
1086 | self.ui.write(',\n "removed": [%s]' % |
|
1085 | self.ui.write(',\n "removed": [%s]' % | |
1087 | ", ".join('"%s"' % j(f) for f in files[2])) |
|
1086 | ", ".join('"%s"' % j(f) for f in files[2])) | |
1088 |
|
1087 | |||
1089 | elif self.ui.verbose: |
|
1088 | elif self.ui.verbose: | |
1090 | self.ui.write(',\n "files": [%s]' % |
|
1089 | self.ui.write(',\n "files": [%s]' % | |
1091 | ", ".join('"%s"' % j(f) for f in ctx.files())) |
|
1090 | ", ".join('"%s"' % j(f) for f in ctx.files())) | |
1092 |
|
1091 | |||
1093 | if copies: |
|
1092 | if copies: | |
1094 | self.ui.write(',\n "copies": {%s}' % |
|
1093 | self.ui.write(',\n "copies": {%s}' % | |
1095 | ", ".join('"%s": %s' % (j(k), j(copies[k])) |
|
1094 | ", ".join('"%s": %s' % (j(k), j(copies[k])) | |
1096 | for k in copies)) |
|
1095 | for k in copies)) | |
1097 |
|
1096 | |||
1098 | matchfn = self.matchfn |
|
1097 | matchfn = self.matchfn | |
1099 | if matchfn: |
|
1098 | if matchfn: | |
1100 | stat = self.diffopts.get('stat') |
|
1099 | stat = self.diffopts.get('stat') | |
1101 | diff = self.diffopts.get('patch') |
|
1100 | diff = self.diffopts.get('patch') | |
1102 | diffopts = patch.difffeatureopts(self.ui, self.diffopts, git=True) |
|
1101 | diffopts = patch.difffeatureopts(self.ui, self.diffopts, git=True) | |
1103 | node, prev = ctx.node(), ctx.p1().node() |
|
1102 | node, prev = ctx.node(), ctx.p1().node() | |
1104 | if stat: |
|
1103 | if stat: | |
1105 | self.ui.pushbuffer() |
|
1104 | self.ui.pushbuffer() | |
1106 | diffordiffstat(self.ui, self.repo, diffopts, prev, node, |
|
1105 | diffordiffstat(self.ui, self.repo, diffopts, prev, node, | |
1107 | match=matchfn, stat=True) |
|
1106 | match=matchfn, stat=True) | |
1108 | self.ui.write(',\n "diffstat": "%s"' % j(self.ui.popbuffer())) |
|
1107 | self.ui.write(',\n "diffstat": "%s"' % j(self.ui.popbuffer())) | |
1109 | if diff: |
|
1108 | if diff: | |
1110 | self.ui.pushbuffer() |
|
1109 | self.ui.pushbuffer() | |
1111 | diffordiffstat(self.ui, self.repo, diffopts, prev, node, |
|
1110 | diffordiffstat(self.ui, self.repo, diffopts, prev, node, | |
1112 | match=matchfn, stat=False) |
|
1111 | match=matchfn, stat=False) | |
1113 | self.ui.write(',\n "diff": "%s"' % j(self.ui.popbuffer())) |
|
1112 | self.ui.write(',\n "diff": "%s"' % j(self.ui.popbuffer())) | |
1114 |
|
1113 | |||
1115 | self.ui.write("\n }") |
|
1114 | self.ui.write("\n }") | |
1116 |
|
1115 | |||
1117 | class changeset_templater(changeset_printer): |
|
1116 | class changeset_templater(changeset_printer): | |
1118 | '''format changeset information.''' |
|
1117 | '''format changeset information.''' | |
1119 |
|
1118 | |||
1120 | def __init__(self, ui, repo, matchfn, diffopts, tmpl, mapfile, buffered): |
|
1119 | def __init__(self, ui, repo, matchfn, diffopts, tmpl, mapfile, buffered): | |
1121 | changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered) |
|
1120 | changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered) | |
1122 | formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12]) |
|
1121 | formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12]) | |
1123 | defaulttempl = { |
|
1122 | defaulttempl = { | |
1124 | 'parent': '{rev}:{node|formatnode} ', |
|
1123 | 'parent': '{rev}:{node|formatnode} ', | |
1125 | 'manifest': '{rev}:{node|formatnode}', |
|
1124 | 'manifest': '{rev}:{node|formatnode}', | |
1126 | 'file_copy': '{name} ({source})', |
|
1125 | 'file_copy': '{name} ({source})', | |
1127 | 'extra': '{key}={value|stringescape}' |
|
1126 | 'extra': '{key}={value|stringescape}' | |
1128 | } |
|
1127 | } | |
1129 | # filecopy is preserved for compatibility reasons |
|
1128 | # filecopy is preserved for compatibility reasons | |
1130 | defaulttempl['filecopy'] = defaulttempl['file_copy'] |
|
1129 | defaulttempl['filecopy'] = defaulttempl['file_copy'] | |
1131 | self.t = templater.templater(mapfile, {'formatnode': formatnode}, |
|
1130 | self.t = templater.templater(mapfile, {'formatnode': formatnode}, | |
1132 | cache=defaulttempl) |
|
1131 | cache=defaulttempl) | |
1133 | if tmpl: |
|
1132 | if tmpl: | |
1134 | self.t.cache['changeset'] = tmpl |
|
1133 | self.t.cache['changeset'] = tmpl | |
1135 |
|
1134 | |||
1136 | self.cache = {} |
|
1135 | self.cache = {} | |
1137 |
|
1136 | |||
1138 | def _meaningful_parentrevs(self, ctx): |
|
1137 | def _meaningful_parentrevs(self, ctx): | |
1139 | """Return list of meaningful (or all if debug) parentrevs for rev. |
|
1138 | """Return list of meaningful (or all if debug) parentrevs for rev. | |
1140 | """ |
|
1139 | """ | |
1141 | parents = ctx.parents() |
|
1140 | parents = ctx.parents() | |
1142 | if len(parents) > 1: |
|
1141 | if len(parents) > 1: | |
1143 | return parents |
|
1142 | return parents | |
1144 | if self.ui.debugflag: |
|
1143 | if self.ui.debugflag: | |
1145 | return [parents[0], self.repo['null']] |
|
1144 | return [parents[0], self.repo['null']] | |
1146 | if parents[0].rev() >= ctx.rev() - 1: |
|
1145 | if parents[0].rev() >= ctx.rev() - 1: | |
1147 | return [] |
|
1146 | return [] | |
1148 | return parents |
|
1147 | return parents | |
1149 |
|
1148 | |||
1150 | def _show(self, ctx, copies, matchfn, props): |
|
1149 | def _show(self, ctx, copies, matchfn, props): | |
1151 | '''show a single changeset or file revision''' |
|
1150 | '''show a single changeset or file revision''' | |
1152 |
|
1151 | |||
1153 | showlist = templatekw.showlist |
|
1152 | showlist = templatekw.showlist | |
1154 |
|
1153 | |||
1155 | # showparents() behaviour depends on ui trace level which |
|
1154 | # showparents() behaviour depends on ui trace level which | |
1156 | # causes unexpected behaviours at templating level and makes |
|
1155 | # causes unexpected behaviours at templating level and makes | |
1157 | # it harder to extract it in a standalone function. Its |
|
1156 | # it harder to extract it in a standalone function. Its | |
1158 | # behaviour cannot be changed so leave it here for now. |
|
1157 | # behaviour cannot be changed so leave it here for now. | |
1159 | def showparents(**args): |
|
1158 | def showparents(**args): | |
1160 | ctx = args['ctx'] |
|
1159 | ctx = args['ctx'] | |
1161 | parents = [[('rev', p.rev()), |
|
1160 | parents = [[('rev', p.rev()), | |
1162 | ('node', p.hex()), |
|
1161 | ('node', p.hex()), | |
1163 | ('phase', p.phasestr())] |
|
1162 | ('phase', p.phasestr())] | |
1164 | for p in self._meaningful_parentrevs(ctx)] |
|
1163 | for p in self._meaningful_parentrevs(ctx)] | |
1165 | return showlist('parent', parents, **args) |
|
1164 | return showlist('parent', parents, **args) | |
1166 |
|
1165 | |||
1167 | props = props.copy() |
|
1166 | props = props.copy() | |
1168 | props.update(templatekw.keywords) |
|
1167 | props.update(templatekw.keywords) | |
1169 | props['parents'] = showparents |
|
1168 | props['parents'] = showparents | |
1170 | props['templ'] = self.t |
|
1169 | props['templ'] = self.t | |
1171 | props['ctx'] = ctx |
|
1170 | props['ctx'] = ctx | |
1172 | props['repo'] = self.repo |
|
1171 | props['repo'] = self.repo | |
1173 | props['revcache'] = {'copies': copies} |
|
1172 | props['revcache'] = {'copies': copies} | |
1174 | props['cache'] = self.cache |
|
1173 | props['cache'] = self.cache | |
1175 |
|
1174 | |||
1176 | # find correct templates for current mode |
|
1175 | # find correct templates for current mode | |
1177 |
|
1176 | |||
1178 | tmplmodes = [ |
|
1177 | tmplmodes = [ | |
1179 | (True, None), |
|
1178 | (True, None), | |
1180 | (self.ui.verbose, 'verbose'), |
|
1179 | (self.ui.verbose, 'verbose'), | |
1181 | (self.ui.quiet, 'quiet'), |
|
1180 | (self.ui.quiet, 'quiet'), | |
1182 | (self.ui.debugflag, 'debug'), |
|
1181 | (self.ui.debugflag, 'debug'), | |
1183 | ] |
|
1182 | ] | |
1184 |
|
1183 | |||
1185 | types = {'header': '', 'footer':'', 'changeset': 'changeset'} |
|
1184 | types = {'header': '', 'footer':'', 'changeset': 'changeset'} | |
1186 | for mode, postfix in tmplmodes: |
|
1185 | for mode, postfix in tmplmodes: | |
1187 | for type in types: |
|
1186 | for type in types: | |
1188 | cur = postfix and ('%s_%s' % (type, postfix)) or type |
|
1187 | cur = postfix and ('%s_%s' % (type, postfix)) or type | |
1189 | if mode and cur in self.t: |
|
1188 | if mode and cur in self.t: | |
1190 | types[type] = cur |
|
1189 | types[type] = cur | |
1191 |
|
1190 | |||
1192 | try: |
|
1191 | try: | |
1193 |
|
1192 | |||
1194 | # write header |
|
1193 | # write header | |
1195 | if types['header']: |
|
1194 | if types['header']: | |
1196 | h = templater.stringify(self.t(types['header'], **props)) |
|
1195 | h = templater.stringify(self.t(types['header'], **props)) | |
1197 | if self.buffered: |
|
1196 | if self.buffered: | |
1198 | self.header[ctx.rev()] = h |
|
1197 | self.header[ctx.rev()] = h | |
1199 | else: |
|
1198 | else: | |
1200 | if self.lastheader != h: |
|
1199 | if self.lastheader != h: | |
1201 | self.lastheader = h |
|
1200 | self.lastheader = h | |
1202 | self.ui.write(h) |
|
1201 | self.ui.write(h) | |
1203 |
|
1202 | |||
1204 | # write changeset metadata, then patch if requested |
|
1203 | # write changeset metadata, then patch if requested | |
1205 | key = types['changeset'] |
|
1204 | key = types['changeset'] | |
1206 | self.ui.write(templater.stringify(self.t(key, **props))) |
|
1205 | self.ui.write(templater.stringify(self.t(key, **props))) | |
1207 | self.showpatch(ctx.node(), matchfn) |
|
1206 | self.showpatch(ctx.node(), matchfn) | |
1208 |
|
1207 | |||
1209 | if types['footer']: |
|
1208 | if types['footer']: | |
1210 | if not self.footer: |
|
1209 | if not self.footer: | |
1211 | self.footer = templater.stringify(self.t(types['footer'], |
|
1210 | self.footer = templater.stringify(self.t(types['footer'], | |
1212 | **props)) |
|
1211 | **props)) | |
1213 |
|
1212 | |||
1214 | except KeyError, inst: |
|
1213 | except KeyError, inst: | |
1215 | msg = _("%s: no key named '%s'") |
|
1214 | msg = _("%s: no key named '%s'") | |
1216 | raise util.Abort(msg % (self.t.mapfile, inst.args[0])) |
|
1215 | raise util.Abort(msg % (self.t.mapfile, inst.args[0])) | |
1217 | except SyntaxError, inst: |
|
1216 | except SyntaxError, inst: | |
1218 | raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0])) |
|
1217 | raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0])) | |
1219 |
|
1218 | |||
1220 | def gettemplate(ui, tmpl, style): |
|
1219 | def gettemplate(ui, tmpl, style): | |
1221 | """ |
|
1220 | """ | |
1222 | Find the template matching the given template spec or style. |
|
1221 | Find the template matching the given template spec or style. | |
1223 | """ |
|
1222 | """ | |
1224 |
|
1223 | |||
1225 | # ui settings |
|
1224 | # ui settings | |
1226 | if not tmpl and not style: # template are stronger than style |
|
1225 | if not tmpl and not style: # template are stronger than style | |
1227 | tmpl = ui.config('ui', 'logtemplate') |
|
1226 | tmpl = ui.config('ui', 'logtemplate') | |
1228 | if tmpl: |
|
1227 | if tmpl: | |
1229 | try: |
|
1228 | try: | |
1230 | tmpl = templater.parsestring(tmpl) |
|
1229 | tmpl = templater.parsestring(tmpl) | |
1231 | except SyntaxError: |
|
1230 | except SyntaxError: | |
1232 | tmpl = templater.parsestring(tmpl, quoted=False) |
|
1231 | tmpl = templater.parsestring(tmpl, quoted=False) | |
1233 | return tmpl, None |
|
1232 | return tmpl, None | |
1234 | else: |
|
1233 | else: | |
1235 | style = util.expandpath(ui.config('ui', 'style', '')) |
|
1234 | style = util.expandpath(ui.config('ui', 'style', '')) | |
1236 |
|
1235 | |||
1237 | if not tmpl and style: |
|
1236 | if not tmpl and style: | |
1238 | mapfile = style |
|
1237 | mapfile = style | |
1239 | if not os.path.split(mapfile)[0]: |
|
1238 | if not os.path.split(mapfile)[0]: | |
1240 | mapname = (templater.templatepath('map-cmdline.' + mapfile) |
|
1239 | mapname = (templater.templatepath('map-cmdline.' + mapfile) | |
1241 | or templater.templatepath(mapfile)) |
|
1240 | or templater.templatepath(mapfile)) | |
1242 | if mapname: |
|
1241 | if mapname: | |
1243 | mapfile = mapname |
|
1242 | mapfile = mapname | |
1244 | return None, mapfile |
|
1243 | return None, mapfile | |
1245 |
|
1244 | |||
1246 | if not tmpl: |
|
1245 | if not tmpl: | |
1247 | return None, None |
|
1246 | return None, None | |
1248 |
|
1247 | |||
1249 | # looks like a literal template? |
|
1248 | # looks like a literal template? | |
1250 | if '{' in tmpl: |
|
1249 | if '{' in tmpl: | |
1251 | return tmpl, None |
|
1250 | return tmpl, None | |
1252 |
|
1251 | |||
1253 | # perhaps a stock style? |
|
1252 | # perhaps a stock style? | |
1254 | if not os.path.split(tmpl)[0]: |
|
1253 | if not os.path.split(tmpl)[0]: | |
1255 | mapname = (templater.templatepath('map-cmdline.' + tmpl) |
|
1254 | mapname = (templater.templatepath('map-cmdline.' + tmpl) | |
1256 | or templater.templatepath(tmpl)) |
|
1255 | or templater.templatepath(tmpl)) | |
1257 | if mapname and os.path.isfile(mapname): |
|
1256 | if mapname and os.path.isfile(mapname): | |
1258 | return None, mapname |
|
1257 | return None, mapname | |
1259 |
|
1258 | |||
1260 | # perhaps it's a reference to [templates] |
|
1259 | # perhaps it's a reference to [templates] | |
1261 | t = ui.config('templates', tmpl) |
|
1260 | t = ui.config('templates', tmpl) | |
1262 | if t: |
|
1261 | if t: | |
1263 | try: |
|
1262 | try: | |
1264 | tmpl = templater.parsestring(t) |
|
1263 | tmpl = templater.parsestring(t) | |
1265 | except SyntaxError: |
|
1264 | except SyntaxError: | |
1266 | tmpl = templater.parsestring(t, quoted=False) |
|
1265 | tmpl = templater.parsestring(t, quoted=False) | |
1267 | return tmpl, None |
|
1266 | return tmpl, None | |
1268 |
|
1267 | |||
1269 | if tmpl == 'list': |
|
1268 | if tmpl == 'list': | |
1270 | ui.write(_("available styles: %s\n") % templater.stylelist()) |
|
1269 | ui.write(_("available styles: %s\n") % templater.stylelist()) | |
1271 | raise util.Abort(_("specify a template")) |
|
1270 | raise util.Abort(_("specify a template")) | |
1272 |
|
1271 | |||
1273 | # perhaps it's a path to a map or a template |
|
1272 | # perhaps it's a path to a map or a template | |
1274 | if ('/' in tmpl or '\\' in tmpl) and os.path.isfile(tmpl): |
|
1273 | if ('/' in tmpl or '\\' in tmpl) and os.path.isfile(tmpl): | |
1275 | # is it a mapfile for a style? |
|
1274 | # is it a mapfile for a style? | |
1276 | if os.path.basename(tmpl).startswith("map-"): |
|
1275 | if os.path.basename(tmpl).startswith("map-"): | |
1277 | return None, os.path.realpath(tmpl) |
|
1276 | return None, os.path.realpath(tmpl) | |
1278 | tmpl = open(tmpl).read() |
|
1277 | tmpl = open(tmpl).read() | |
1279 | return tmpl, None |
|
1278 | return tmpl, None | |
1280 |
|
1279 | |||
1281 | # constant string? |
|
1280 | # constant string? | |
1282 | return tmpl, None |
|
1281 | return tmpl, None | |
1283 |
|
1282 | |||
1284 | def show_changeset(ui, repo, opts, buffered=False): |
|
1283 | def show_changeset(ui, repo, opts, buffered=False): | |
1285 | """show one changeset using template or regular display. |
|
1284 | """show one changeset using template or regular display. | |
1286 |
|
1285 | |||
1287 | Display format will be the first non-empty hit of: |
|
1286 | Display format will be the first non-empty hit of: | |
1288 | 1. option 'template' |
|
1287 | 1. option 'template' | |
1289 | 2. option 'style' |
|
1288 | 2. option 'style' | |
1290 | 3. [ui] setting 'logtemplate' |
|
1289 | 3. [ui] setting 'logtemplate' | |
1291 | 4. [ui] setting 'style' |
|
1290 | 4. [ui] setting 'style' | |
1292 | If all of these values are either the unset or the empty string, |
|
1291 | If all of these values are either the unset or the empty string, | |
1293 | regular display via changeset_printer() is done. |
|
1292 | regular display via changeset_printer() is done. | |
1294 | """ |
|
1293 | """ | |
1295 | # options |
|
1294 | # options | |
1296 | matchfn = None |
|
1295 | matchfn = None | |
1297 | if opts.get('patch') or opts.get('stat'): |
|
1296 | if opts.get('patch') or opts.get('stat'): | |
1298 | matchfn = scmutil.matchall(repo) |
|
1297 | matchfn = scmutil.matchall(repo) | |
1299 |
|
1298 | |||
1300 | if opts.get('template') == 'json': |
|
1299 | if opts.get('template') == 'json': | |
1301 | return jsonchangeset(ui, repo, matchfn, opts, buffered) |
|
1300 | return jsonchangeset(ui, repo, matchfn, opts, buffered) | |
1302 |
|
1301 | |||
1303 | tmpl, mapfile = gettemplate(ui, opts.get('template'), opts.get('style')) |
|
1302 | tmpl, mapfile = gettemplate(ui, opts.get('template'), opts.get('style')) | |
1304 |
|
1303 | |||
1305 | if not tmpl and not mapfile: |
|
1304 | if not tmpl and not mapfile: | |
1306 | return changeset_printer(ui, repo, matchfn, opts, buffered) |
|
1305 | return changeset_printer(ui, repo, matchfn, opts, buffered) | |
1307 |
|
1306 | |||
1308 | try: |
|
1307 | try: | |
1309 | t = changeset_templater(ui, repo, matchfn, opts, tmpl, mapfile, |
|
1308 | t = changeset_templater(ui, repo, matchfn, opts, tmpl, mapfile, | |
1310 | buffered) |
|
1309 | buffered) | |
1311 | except SyntaxError, inst: |
|
1310 | except SyntaxError, inst: | |
1312 | raise util.Abort(inst.args[0]) |
|
1311 | raise util.Abort(inst.args[0]) | |
1313 | return t |
|
1312 | return t | |
1314 |
|
1313 | |||
1315 | def showmarker(ui, marker): |
|
1314 | def showmarker(ui, marker): | |
1316 | """utility function to display obsolescence marker in a readable way |
|
1315 | """utility function to display obsolescence marker in a readable way | |
1317 |
|
1316 | |||
1318 | To be used by debug function.""" |
|
1317 | To be used by debug function.""" | |
1319 | ui.write(hex(marker.precnode())) |
|
1318 | ui.write(hex(marker.precnode())) | |
1320 | for repl in marker.succnodes(): |
|
1319 | for repl in marker.succnodes(): | |
1321 | ui.write(' ') |
|
1320 | ui.write(' ') | |
1322 | ui.write(hex(repl)) |
|
1321 | ui.write(hex(repl)) | |
1323 | ui.write(' %X ' % marker.flags()) |
|
1322 | ui.write(' %X ' % marker.flags()) | |
1324 | parents = marker.parentnodes() |
|
1323 | parents = marker.parentnodes() | |
1325 | if parents is not None: |
|
1324 | if parents is not None: | |
1326 | ui.write('{%s} ' % ', '.join(hex(p) for p in parents)) |
|
1325 | ui.write('{%s} ' % ', '.join(hex(p) for p in parents)) | |
1327 | ui.write('(%s) ' % util.datestr(marker.date())) |
|
1326 | ui.write('(%s) ' % util.datestr(marker.date())) | |
1328 | ui.write('{%s}' % (', '.join('%r: %r' % t for t in |
|
1327 | ui.write('{%s}' % (', '.join('%r: %r' % t for t in | |
1329 | sorted(marker.metadata().items()) |
|
1328 | sorted(marker.metadata().items()) | |
1330 | if t[0] != 'date'))) |
|
1329 | if t[0] != 'date'))) | |
1331 | ui.write('\n') |
|
1330 | ui.write('\n') | |
1332 |
|
1331 | |||
1333 | def finddate(ui, repo, date): |
|
1332 | def finddate(ui, repo, date): | |
1334 | """Find the tipmost changeset that matches the given date spec""" |
|
1333 | """Find the tipmost changeset that matches the given date spec""" | |
1335 |
|
1334 | |||
1336 | df = util.matchdate(date) |
|
1335 | df = util.matchdate(date) | |
1337 | m = scmutil.matchall(repo) |
|
1336 | m = scmutil.matchall(repo) | |
1338 | results = {} |
|
1337 | results = {} | |
1339 |
|
1338 | |||
1340 | def prep(ctx, fns): |
|
1339 | def prep(ctx, fns): | |
1341 | d = ctx.date() |
|
1340 | d = ctx.date() | |
1342 | if df(d[0]): |
|
1341 | if df(d[0]): | |
1343 | results[ctx.rev()] = d |
|
1342 | results[ctx.rev()] = d | |
1344 |
|
1343 | |||
1345 | for ctx in walkchangerevs(repo, m, {'rev': None}, prep): |
|
1344 | for ctx in walkchangerevs(repo, m, {'rev': None}, prep): | |
1346 | rev = ctx.rev() |
|
1345 | rev = ctx.rev() | |
1347 | if rev in results: |
|
1346 | if rev in results: | |
1348 | ui.status(_("found revision %s from %s\n") % |
|
1347 | ui.status(_("found revision %s from %s\n") % | |
1349 | (rev, util.datestr(results[rev]))) |
|
1348 | (rev, util.datestr(results[rev]))) | |
1350 | return str(rev) |
|
1349 | return str(rev) | |
1351 |
|
1350 | |||
1352 | raise util.Abort(_("revision matching date not found")) |
|
1351 | raise util.Abort(_("revision matching date not found")) | |
1353 |
|
1352 | |||
1354 | def increasingwindows(windowsize=8, sizelimit=512): |
|
1353 | def increasingwindows(windowsize=8, sizelimit=512): | |
1355 | while True: |
|
1354 | while True: | |
1356 | yield windowsize |
|
1355 | yield windowsize | |
1357 | if windowsize < sizelimit: |
|
1356 | if windowsize < sizelimit: | |
1358 | windowsize *= 2 |
|
1357 | windowsize *= 2 | |
1359 |
|
1358 | |||
1360 | class FileWalkError(Exception): |
|
1359 | class FileWalkError(Exception): | |
1361 | pass |
|
1360 | pass | |
1362 |
|
1361 | |||
1363 | def walkfilerevs(repo, match, follow, revs, fncache): |
|
1362 | def walkfilerevs(repo, match, follow, revs, fncache): | |
1364 | '''Walks the file history for the matched files. |
|
1363 | '''Walks the file history for the matched files. | |
1365 |
|
1364 | |||
1366 | Returns the changeset revs that are involved in the file history. |
|
1365 | Returns the changeset revs that are involved in the file history. | |
1367 |
|
1366 | |||
1368 | Throws FileWalkError if the file history can't be walked using |
|
1367 | Throws FileWalkError if the file history can't be walked using | |
1369 | filelogs alone. |
|
1368 | filelogs alone. | |
1370 | ''' |
|
1369 | ''' | |
1371 | wanted = set() |
|
1370 | wanted = set() | |
1372 | copies = [] |
|
1371 | copies = [] | |
1373 | minrev, maxrev = min(revs), max(revs) |
|
1372 | minrev, maxrev = min(revs), max(revs) | |
1374 | def filerevgen(filelog, last): |
|
1373 | def filerevgen(filelog, last): | |
1375 | """ |
|
1374 | """ | |
1376 | Only files, no patterns. Check the history of each file. |
|
1375 | Only files, no patterns. Check the history of each file. | |
1377 |
|
1376 | |||
1378 | Examines filelog entries within minrev, maxrev linkrev range |
|
1377 | Examines filelog entries within minrev, maxrev linkrev range | |
1379 | Returns an iterator yielding (linkrev, parentlinkrevs, copied) |
|
1378 | Returns an iterator yielding (linkrev, parentlinkrevs, copied) | |
1380 | tuples in backwards order |
|
1379 | tuples in backwards order | |
1381 | """ |
|
1380 | """ | |
1382 | cl_count = len(repo) |
|
1381 | cl_count = len(repo) | |
1383 | revs = [] |
|
1382 | revs = [] | |
1384 | for j in xrange(0, last + 1): |
|
1383 | for j in xrange(0, last + 1): | |
1385 | linkrev = filelog.linkrev(j) |
|
1384 | linkrev = filelog.linkrev(j) | |
1386 | if linkrev < minrev: |
|
1385 | if linkrev < minrev: | |
1387 | continue |
|
1386 | continue | |
1388 | # only yield rev for which we have the changelog, it can |
|
1387 | # only yield rev for which we have the changelog, it can | |
1389 | # happen while doing "hg log" during a pull or commit |
|
1388 | # happen while doing "hg log" during a pull or commit | |
1390 | if linkrev >= cl_count: |
|
1389 | if linkrev >= cl_count: | |
1391 | break |
|
1390 | break | |
1392 |
|
1391 | |||
1393 | parentlinkrevs = [] |
|
1392 | parentlinkrevs = [] | |
1394 | for p in filelog.parentrevs(j): |
|
1393 | for p in filelog.parentrevs(j): | |
1395 | if p != nullrev: |
|
1394 | if p != nullrev: | |
1396 | parentlinkrevs.append(filelog.linkrev(p)) |
|
1395 | parentlinkrevs.append(filelog.linkrev(p)) | |
1397 | n = filelog.node(j) |
|
1396 | n = filelog.node(j) | |
1398 | revs.append((linkrev, parentlinkrevs, |
|
1397 | revs.append((linkrev, parentlinkrevs, | |
1399 | follow and filelog.renamed(n))) |
|
1398 | follow and filelog.renamed(n))) | |
1400 |
|
1399 | |||
1401 | return reversed(revs) |
|
1400 | return reversed(revs) | |
1402 | def iterfiles(): |
|
1401 | def iterfiles(): | |
1403 | pctx = repo['.'] |
|
1402 | pctx = repo['.'] | |
1404 | for filename in match.files(): |
|
1403 | for filename in match.files(): | |
1405 | if follow: |
|
1404 | if follow: | |
1406 | if filename not in pctx: |
|
1405 | if filename not in pctx: | |
1407 | raise util.Abort(_('cannot follow file not in parent ' |
|
1406 | raise util.Abort(_('cannot follow file not in parent ' | |
1408 | 'revision: "%s"') % filename) |
|
1407 | 'revision: "%s"') % filename) | |
1409 | yield filename, pctx[filename].filenode() |
|
1408 | yield filename, pctx[filename].filenode() | |
1410 | else: |
|
1409 | else: | |
1411 | yield filename, None |
|
1410 | yield filename, None | |
1412 | for filename_node in copies: |
|
1411 | for filename_node in copies: | |
1413 | yield filename_node |
|
1412 | yield filename_node | |
1414 |
|
1413 | |||
1415 | for file_, node in iterfiles(): |
|
1414 | for file_, node in iterfiles(): | |
1416 | filelog = repo.file(file_) |
|
1415 | filelog = repo.file(file_) | |
1417 | if not len(filelog): |
|
1416 | if not len(filelog): | |
1418 | if node is None: |
|
1417 | if node is None: | |
1419 | # A zero count may be a directory or deleted file, so |
|
1418 | # A zero count may be a directory or deleted file, so | |
1420 | # try to find matching entries on the slow path. |
|
1419 | # try to find matching entries on the slow path. | |
1421 | if follow: |
|
1420 | if follow: | |
1422 | raise util.Abort( |
|
1421 | raise util.Abort( | |
1423 | _('cannot follow nonexistent file: "%s"') % file_) |
|
1422 | _('cannot follow nonexistent file: "%s"') % file_) | |
1424 | raise FileWalkError("Cannot walk via filelog") |
|
1423 | raise FileWalkError("Cannot walk via filelog") | |
1425 | else: |
|
1424 | else: | |
1426 | continue |
|
1425 | continue | |
1427 |
|
1426 | |||
1428 | if node is None: |
|
1427 | if node is None: | |
1429 | last = len(filelog) - 1 |
|
1428 | last = len(filelog) - 1 | |
1430 | else: |
|
1429 | else: | |
1431 | last = filelog.rev(node) |
|
1430 | last = filelog.rev(node) | |
1432 |
|
1431 | |||
1433 |
|
1432 | |||
1434 | # keep track of all ancestors of the file |
|
1433 | # keep track of all ancestors of the file | |
1435 | ancestors = set([filelog.linkrev(last)]) |
|
1434 | ancestors = set([filelog.linkrev(last)]) | |
1436 |
|
1435 | |||
1437 | # iterate from latest to oldest revision |
|
1436 | # iterate from latest to oldest revision | |
1438 | for rev, flparentlinkrevs, copied in filerevgen(filelog, last): |
|
1437 | for rev, flparentlinkrevs, copied in filerevgen(filelog, last): | |
1439 | if not follow: |
|
1438 | if not follow: | |
1440 | if rev > maxrev: |
|
1439 | if rev > maxrev: | |
1441 | continue |
|
1440 | continue | |
1442 | else: |
|
1441 | else: | |
1443 | # Note that last might not be the first interesting |
|
1442 | # Note that last might not be the first interesting | |
1444 | # rev to us: |
|
1443 | # rev to us: | |
1445 | # if the file has been changed after maxrev, we'll |
|
1444 | # if the file has been changed after maxrev, we'll | |
1446 | # have linkrev(last) > maxrev, and we still need |
|
1445 | # have linkrev(last) > maxrev, and we still need | |
1447 | # to explore the file graph |
|
1446 | # to explore the file graph | |
1448 | if rev not in ancestors: |
|
1447 | if rev not in ancestors: | |
1449 | continue |
|
1448 | continue | |
1450 | # XXX insert 1327 fix here |
|
1449 | # XXX insert 1327 fix here | |
1451 | if flparentlinkrevs: |
|
1450 | if flparentlinkrevs: | |
1452 | ancestors.update(flparentlinkrevs) |
|
1451 | ancestors.update(flparentlinkrevs) | |
1453 |
|
1452 | |||
1454 | fncache.setdefault(rev, []).append(file_) |
|
1453 | fncache.setdefault(rev, []).append(file_) | |
1455 | wanted.add(rev) |
|
1454 | wanted.add(rev) | |
1456 | if copied: |
|
1455 | if copied: | |
1457 | copies.append(copied) |
|
1456 | copies.append(copied) | |
1458 |
|
1457 | |||
1459 | return wanted |
|
1458 | return wanted | |
1460 |
|
1459 | |||
1461 | def walkchangerevs(repo, match, opts, prepare): |
|
1460 | def walkchangerevs(repo, match, opts, prepare): | |
1462 | '''Iterate over files and the revs in which they changed. |
|
1461 | '''Iterate over files and the revs in which they changed. | |
1463 |
|
1462 | |||
1464 | Callers most commonly need to iterate backwards over the history |
|
1463 | Callers most commonly need to iterate backwards over the history | |
1465 | in which they are interested. Doing so has awful (quadratic-looking) |
|
1464 | in which they are interested. Doing so has awful (quadratic-looking) | |
1466 | performance, so we use iterators in a "windowed" way. |
|
1465 | performance, so we use iterators in a "windowed" way. | |
1467 |
|
1466 | |||
1468 | We walk a window of revisions in the desired order. Within the |
|
1467 | We walk a window of revisions in the desired order. Within the | |
1469 | window, we first walk forwards to gather data, then in the desired |
|
1468 | window, we first walk forwards to gather data, then in the desired | |
1470 | order (usually backwards) to display it. |
|
1469 | order (usually backwards) to display it. | |
1471 |
|
1470 | |||
1472 | This function returns an iterator yielding contexts. Before |
|
1471 | This function returns an iterator yielding contexts. Before | |
1473 | yielding each context, the iterator will first call the prepare |
|
1472 | yielding each context, the iterator will first call the prepare | |
1474 | function on each context in the window in forward order.''' |
|
1473 | function on each context in the window in forward order.''' | |
1475 |
|
1474 | |||
1476 | follow = opts.get('follow') or opts.get('follow_first') |
|
1475 | follow = opts.get('follow') or opts.get('follow_first') | |
1477 |
|
1476 | |||
1478 | if opts.get('rev'): |
|
1477 | if opts.get('rev'): | |
1479 | revs = scmutil.revrange(repo, opts.get('rev')) |
|
1478 | revs = scmutil.revrange(repo, opts.get('rev')) | |
1480 | elif follow: |
|
1479 | elif follow: | |
1481 | revs = repo.revs('reverse(:.)') |
|
1480 | revs = repo.revs('reverse(:.)') | |
1482 | else: |
|
1481 | else: | |
1483 | revs = revset.spanset(repo) |
|
1482 | revs = revset.spanset(repo) | |
1484 | revs.reverse() |
|
1483 | revs.reverse() | |
1485 | if not revs: |
|
1484 | if not revs: | |
1486 | return [] |
|
1485 | return [] | |
1487 | wanted = set() |
|
1486 | wanted = set() | |
1488 | slowpath = match.anypats() or (match.files() and opts.get('removed')) |
|
1487 | slowpath = match.anypats() or (match.files() and opts.get('removed')) | |
1489 | fncache = {} |
|
1488 | fncache = {} | |
1490 | change = repo.changectx |
|
1489 | change = repo.changectx | |
1491 |
|
1490 | |||
1492 | # First step is to fill wanted, the set of revisions that we want to yield. |
|
1491 | # First step is to fill wanted, the set of revisions that we want to yield. | |
1493 | # When it does not induce extra cost, we also fill fncache for revisions in |
|
1492 | # When it does not induce extra cost, we also fill fncache for revisions in | |
1494 | # wanted: a cache of filenames that were changed (ctx.files()) and that |
|
1493 | # wanted: a cache of filenames that were changed (ctx.files()) and that | |
1495 | # match the file filtering conditions. |
|
1494 | # match the file filtering conditions. | |
1496 |
|
1495 | |||
1497 | if not slowpath and not match.files(): |
|
1496 | if not slowpath and not match.files(): | |
1498 | # No files, no patterns. Display all revs. |
|
1497 | # No files, no patterns. Display all revs. | |
1499 | wanted = revs |
|
1498 | wanted = revs | |
1500 |
|
1499 | |||
1501 | if not slowpath and match.files(): |
|
1500 | if not slowpath and match.files(): | |
1502 | # We only have to read through the filelog to find wanted revisions |
|
1501 | # We only have to read through the filelog to find wanted revisions | |
1503 |
|
1502 | |||
1504 | try: |
|
1503 | try: | |
1505 | wanted = walkfilerevs(repo, match, follow, revs, fncache) |
|
1504 | wanted = walkfilerevs(repo, match, follow, revs, fncache) | |
1506 | except FileWalkError: |
|
1505 | except FileWalkError: | |
1507 | slowpath = True |
|
1506 | slowpath = True | |
1508 |
|
1507 | |||
1509 | # We decided to fall back to the slowpath because at least one |
|
1508 | # We decided to fall back to the slowpath because at least one | |
1510 | # of the paths was not a file. Check to see if at least one of them |
|
1509 | # of the paths was not a file. Check to see if at least one of them | |
1511 | # existed in history, otherwise simply return |
|
1510 | # existed in history, otherwise simply return | |
1512 | for path in match.files(): |
|
1511 | for path in match.files(): | |
1513 | if path == '.' or path in repo.store: |
|
1512 | if path == '.' or path in repo.store: | |
1514 | break |
|
1513 | break | |
1515 | else: |
|
1514 | else: | |
1516 | return [] |
|
1515 | return [] | |
1517 |
|
1516 | |||
1518 | if slowpath: |
|
1517 | if slowpath: | |
1519 | # We have to read the changelog to match filenames against |
|
1518 | # We have to read the changelog to match filenames against | |
1520 | # changed files |
|
1519 | # changed files | |
1521 |
|
1520 | |||
1522 | if follow: |
|
1521 | if follow: | |
1523 | raise util.Abort(_('can only follow copies/renames for explicit ' |
|
1522 | raise util.Abort(_('can only follow copies/renames for explicit ' | |
1524 | 'filenames')) |
|
1523 | 'filenames')) | |
1525 |
|
1524 | |||
1526 | # The slow path checks files modified in every changeset. |
|
1525 | # The slow path checks files modified in every changeset. | |
1527 | # This is really slow on large repos, so compute the set lazily. |
|
1526 | # This is really slow on large repos, so compute the set lazily. | |
1528 | class lazywantedset(object): |
|
1527 | class lazywantedset(object): | |
1529 | def __init__(self): |
|
1528 | def __init__(self): | |
1530 | self.set = set() |
|
1529 | self.set = set() | |
1531 | self.revs = set(revs) |
|
1530 | self.revs = set(revs) | |
1532 |
|
1531 | |||
1533 | # No need to worry about locality here because it will be accessed |
|
1532 | # No need to worry about locality here because it will be accessed | |
1534 | # in the same order as the increasing window below. |
|
1533 | # in the same order as the increasing window below. | |
1535 | def __contains__(self, value): |
|
1534 | def __contains__(self, value): | |
1536 | if value in self.set: |
|
1535 | if value in self.set: | |
1537 | return True |
|
1536 | return True | |
1538 | elif not value in self.revs: |
|
1537 | elif not value in self.revs: | |
1539 | return False |
|
1538 | return False | |
1540 | else: |
|
1539 | else: | |
1541 | self.revs.discard(value) |
|
1540 | self.revs.discard(value) | |
1542 | ctx = change(value) |
|
1541 | ctx = change(value) | |
1543 | matches = filter(match, ctx.files()) |
|
1542 | matches = filter(match, ctx.files()) | |
1544 | if matches: |
|
1543 | if matches: | |
1545 | fncache[value] = matches |
|
1544 | fncache[value] = matches | |
1546 | self.set.add(value) |
|
1545 | self.set.add(value) | |
1547 | return True |
|
1546 | return True | |
1548 | return False |
|
1547 | return False | |
1549 |
|
1548 | |||
1550 | def discard(self, value): |
|
1549 | def discard(self, value): | |
1551 | self.revs.discard(value) |
|
1550 | self.revs.discard(value) | |
1552 | self.set.discard(value) |
|
1551 | self.set.discard(value) | |
1553 |
|
1552 | |||
1554 | wanted = lazywantedset() |
|
1553 | wanted = lazywantedset() | |
1555 |
|
1554 | |||
1556 | class followfilter(object): |
|
1555 | class followfilter(object): | |
1557 | def __init__(self, onlyfirst=False): |
|
1556 | def __init__(self, onlyfirst=False): | |
1558 | self.startrev = nullrev |
|
1557 | self.startrev = nullrev | |
1559 | self.roots = set() |
|
1558 | self.roots = set() | |
1560 | self.onlyfirst = onlyfirst |
|
1559 | self.onlyfirst = onlyfirst | |
1561 |
|
1560 | |||
1562 | def match(self, rev): |
|
1561 | def match(self, rev): | |
1563 | def realparents(rev): |
|
1562 | def realparents(rev): | |
1564 | if self.onlyfirst: |
|
1563 | if self.onlyfirst: | |
1565 | return repo.changelog.parentrevs(rev)[0:1] |
|
1564 | return repo.changelog.parentrevs(rev)[0:1] | |
1566 | else: |
|
1565 | else: | |
1567 | return filter(lambda x: x != nullrev, |
|
1566 | return filter(lambda x: x != nullrev, | |
1568 | repo.changelog.parentrevs(rev)) |
|
1567 | repo.changelog.parentrevs(rev)) | |
1569 |
|
1568 | |||
1570 | if self.startrev == nullrev: |
|
1569 | if self.startrev == nullrev: | |
1571 | self.startrev = rev |
|
1570 | self.startrev = rev | |
1572 | return True |
|
1571 | return True | |
1573 |
|
1572 | |||
1574 | if rev > self.startrev: |
|
1573 | if rev > self.startrev: | |
1575 | # forward: all descendants |
|
1574 | # forward: all descendants | |
1576 | if not self.roots: |
|
1575 | if not self.roots: | |
1577 | self.roots.add(self.startrev) |
|
1576 | self.roots.add(self.startrev) | |
1578 | for parent in realparents(rev): |
|
1577 | for parent in realparents(rev): | |
1579 | if parent in self.roots: |
|
1578 | if parent in self.roots: | |
1580 | self.roots.add(rev) |
|
1579 | self.roots.add(rev) | |
1581 | return True |
|
1580 | return True | |
1582 | else: |
|
1581 | else: | |
1583 | # backwards: all parents |
|
1582 | # backwards: all parents | |
1584 | if not self.roots: |
|
1583 | if not self.roots: | |
1585 | self.roots.update(realparents(self.startrev)) |
|
1584 | self.roots.update(realparents(self.startrev)) | |
1586 | if rev in self.roots: |
|
1585 | if rev in self.roots: | |
1587 | self.roots.remove(rev) |
|
1586 | self.roots.remove(rev) | |
1588 | self.roots.update(realparents(rev)) |
|
1587 | self.roots.update(realparents(rev)) | |
1589 | return True |
|
1588 | return True | |
1590 |
|
1589 | |||
1591 | return False |
|
1590 | return False | |
1592 |
|
1591 | |||
1593 | # it might be worthwhile to do this in the iterator if the rev range |
|
1592 | # it might be worthwhile to do this in the iterator if the rev range | |
1594 | # is descending and the prune args are all within that range |
|
1593 | # is descending and the prune args are all within that range | |
1595 | for rev in opts.get('prune', ()): |
|
1594 | for rev in opts.get('prune', ()): | |
1596 | rev = repo[rev].rev() |
|
1595 | rev = repo[rev].rev() | |
1597 | ff = followfilter() |
|
1596 | ff = followfilter() | |
1598 | stop = min(revs[0], revs[-1]) |
|
1597 | stop = min(revs[0], revs[-1]) | |
1599 | for x in xrange(rev, stop - 1, -1): |
|
1598 | for x in xrange(rev, stop - 1, -1): | |
1600 | if ff.match(x): |
|
1599 | if ff.match(x): | |
1601 | wanted = wanted - [x] |
|
1600 | wanted = wanted - [x] | |
1602 |
|
1601 | |||
1603 | # Now that wanted is correctly initialized, we can iterate over the |
|
1602 | # Now that wanted is correctly initialized, we can iterate over the | |
1604 | # revision range, yielding only revisions in wanted. |
|
1603 | # revision range, yielding only revisions in wanted. | |
1605 | def iterate(): |
|
1604 | def iterate(): | |
1606 | if follow and not match.files(): |
|
1605 | if follow and not match.files(): | |
1607 | ff = followfilter(onlyfirst=opts.get('follow_first')) |
|
1606 | ff = followfilter(onlyfirst=opts.get('follow_first')) | |
1608 | def want(rev): |
|
1607 | def want(rev): | |
1609 | return ff.match(rev) and rev in wanted |
|
1608 | return ff.match(rev) and rev in wanted | |
1610 | else: |
|
1609 | else: | |
1611 | def want(rev): |
|
1610 | def want(rev): | |
1612 | return rev in wanted |
|
1611 | return rev in wanted | |
1613 |
|
1612 | |||
1614 | it = iter(revs) |
|
1613 | it = iter(revs) | |
1615 | stopiteration = False |
|
1614 | stopiteration = False | |
1616 | for windowsize in increasingwindows(): |
|
1615 | for windowsize in increasingwindows(): | |
1617 | nrevs = [] |
|
1616 | nrevs = [] | |
1618 | for i in xrange(windowsize): |
|
1617 | for i in xrange(windowsize): | |
1619 | try: |
|
1618 | try: | |
1620 | rev = it.next() |
|
1619 | rev = it.next() | |
1621 | if want(rev): |
|
1620 | if want(rev): | |
1622 | nrevs.append(rev) |
|
1621 | nrevs.append(rev) | |
1623 | except (StopIteration): |
|
1622 | except (StopIteration): | |
1624 | stopiteration = True |
|
1623 | stopiteration = True | |
1625 | break |
|
1624 | break | |
1626 | for rev in sorted(nrevs): |
|
1625 | for rev in sorted(nrevs): | |
1627 | fns = fncache.get(rev) |
|
1626 | fns = fncache.get(rev) | |
1628 | ctx = change(rev) |
|
1627 | ctx = change(rev) | |
1629 | if not fns: |
|
1628 | if not fns: | |
1630 | def fns_generator(): |
|
1629 | def fns_generator(): | |
1631 | for f in ctx.files(): |
|
1630 | for f in ctx.files(): | |
1632 | if match(f): |
|
1631 | if match(f): | |
1633 | yield f |
|
1632 | yield f | |
1634 | fns = fns_generator() |
|
1633 | fns = fns_generator() | |
1635 | prepare(ctx, fns) |
|
1634 | prepare(ctx, fns) | |
1636 | for rev in nrevs: |
|
1635 | for rev in nrevs: | |
1637 | yield change(rev) |
|
1636 | yield change(rev) | |
1638 |
|
1637 | |||
1639 | if stopiteration: |
|
1638 | if stopiteration: | |
1640 | break |
|
1639 | break | |
1641 |
|
1640 | |||
1642 | return iterate() |
|
1641 | return iterate() | |
1643 |
|
1642 | |||
1644 | def _makefollowlogfilematcher(repo, files, followfirst): |
|
1643 | def _makefollowlogfilematcher(repo, files, followfirst): | |
1645 | # When displaying a revision with --patch --follow FILE, we have |
|
1644 | # When displaying a revision with --patch --follow FILE, we have | |
1646 | # to know which file of the revision must be diffed. With |
|
1645 | # to know which file of the revision must be diffed. With | |
1647 | # --follow, we want the names of the ancestors of FILE in the |
|
1646 | # --follow, we want the names of the ancestors of FILE in the | |
1648 | # revision, stored in "fcache". "fcache" is populated by |
|
1647 | # revision, stored in "fcache". "fcache" is populated by | |
1649 | # reproducing the graph traversal already done by --follow revset |
|
1648 | # reproducing the graph traversal already done by --follow revset | |
1650 | # and relating linkrevs to file names (which is not "correct" but |
|
1649 | # and relating linkrevs to file names (which is not "correct" but | |
1651 | # good enough). |
|
1650 | # good enough). | |
1652 | fcache = {} |
|
1651 | fcache = {} | |
1653 | fcacheready = [False] |
|
1652 | fcacheready = [False] | |
1654 | pctx = repo['.'] |
|
1653 | pctx = repo['.'] | |
1655 |
|
1654 | |||
1656 | def populate(): |
|
1655 | def populate(): | |
1657 | for fn in files: |
|
1656 | for fn in files: | |
1658 | for i in ((pctx[fn],), pctx[fn].ancestors(followfirst=followfirst)): |
|
1657 | for i in ((pctx[fn],), pctx[fn].ancestors(followfirst=followfirst)): | |
1659 | for c in i: |
|
1658 | for c in i: | |
1660 | fcache.setdefault(c.linkrev(), set()).add(c.path()) |
|
1659 | fcache.setdefault(c.linkrev(), set()).add(c.path()) | |
1661 |
|
1660 | |||
1662 | def filematcher(rev): |
|
1661 | def filematcher(rev): | |
1663 | if not fcacheready[0]: |
|
1662 | if not fcacheready[0]: | |
1664 | # Lazy initialization |
|
1663 | # Lazy initialization | |
1665 | fcacheready[0] = True |
|
1664 | fcacheready[0] = True | |
1666 | populate() |
|
1665 | populate() | |
1667 | return scmutil.matchfiles(repo, fcache.get(rev, [])) |
|
1666 | return scmutil.matchfiles(repo, fcache.get(rev, [])) | |
1668 |
|
1667 | |||
1669 | return filematcher |
|
1668 | return filematcher | |
1670 |
|
1669 | |||
1671 | def _makenofollowlogfilematcher(repo, pats, opts): |
|
1670 | def _makenofollowlogfilematcher(repo, pats, opts): | |
1672 | '''hook for extensions to override the filematcher for non-follow cases''' |
|
1671 | '''hook for extensions to override the filematcher for non-follow cases''' | |
1673 | return None |
|
1672 | return None | |
1674 |
|
1673 | |||
1675 | def _makelogrevset(repo, pats, opts, revs): |
|
1674 | def _makelogrevset(repo, pats, opts, revs): | |
1676 | """Return (expr, filematcher) where expr is a revset string built |
|
1675 | """Return (expr, filematcher) where expr is a revset string built | |
1677 | from log options and file patterns or None. If --stat or --patch |
|
1676 | from log options and file patterns or None. If --stat or --patch | |
1678 | are not passed filematcher is None. Otherwise it is a callable |
|
1677 | are not passed filematcher is None. Otherwise it is a callable | |
1679 | taking a revision number and returning a match objects filtering |
|
1678 | taking a revision number and returning a match objects filtering | |
1680 | the files to be detailed when displaying the revision. |
|
1679 | the files to be detailed when displaying the revision. | |
1681 | """ |
|
1680 | """ | |
1682 | opt2revset = { |
|
1681 | opt2revset = { | |
1683 | 'no_merges': ('not merge()', None), |
|
1682 | 'no_merges': ('not merge()', None), | |
1684 | 'only_merges': ('merge()', None), |
|
1683 | 'only_merges': ('merge()', None), | |
1685 | '_ancestors': ('ancestors(%(val)s)', None), |
|
1684 | '_ancestors': ('ancestors(%(val)s)', None), | |
1686 | '_fancestors': ('_firstancestors(%(val)s)', None), |
|
1685 | '_fancestors': ('_firstancestors(%(val)s)', None), | |
1687 | '_descendants': ('descendants(%(val)s)', None), |
|
1686 | '_descendants': ('descendants(%(val)s)', None), | |
1688 | '_fdescendants': ('_firstdescendants(%(val)s)', None), |
|
1687 | '_fdescendants': ('_firstdescendants(%(val)s)', None), | |
1689 | '_matchfiles': ('_matchfiles(%(val)s)', None), |
|
1688 | '_matchfiles': ('_matchfiles(%(val)s)', None), | |
1690 | 'date': ('date(%(val)r)', None), |
|
1689 | 'date': ('date(%(val)r)', None), | |
1691 | 'branch': ('branch(%(val)r)', ' or '), |
|
1690 | 'branch': ('branch(%(val)r)', ' or '), | |
1692 | '_patslog': ('filelog(%(val)r)', ' or '), |
|
1691 | '_patslog': ('filelog(%(val)r)', ' or '), | |
1693 | '_patsfollow': ('follow(%(val)r)', ' or '), |
|
1692 | '_patsfollow': ('follow(%(val)r)', ' or '), | |
1694 | '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '), |
|
1693 | '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '), | |
1695 | 'keyword': ('keyword(%(val)r)', ' or '), |
|
1694 | 'keyword': ('keyword(%(val)r)', ' or '), | |
1696 | 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '), |
|
1695 | 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '), | |
1697 | 'user': ('user(%(val)r)', ' or '), |
|
1696 | 'user': ('user(%(val)r)', ' or '), | |
1698 | } |
|
1697 | } | |
1699 |
|
1698 | |||
1700 | opts = dict(opts) |
|
1699 | opts = dict(opts) | |
1701 | # follow or not follow? |
|
1700 | # follow or not follow? | |
1702 | follow = opts.get('follow') or opts.get('follow_first') |
|
1701 | follow = opts.get('follow') or opts.get('follow_first') | |
1703 | followfirst = opts.get('follow_first') and 1 or 0 |
|
1702 | followfirst = opts.get('follow_first') and 1 or 0 | |
1704 | # --follow with FILE behaviour depends on revs... |
|
1703 | # --follow with FILE behaviour depends on revs... | |
1705 | it = iter(revs) |
|
1704 | it = iter(revs) | |
1706 | startrev = it.next() |
|
1705 | startrev = it.next() | |
1707 | try: |
|
1706 | try: | |
1708 | followdescendants = startrev < it.next() |
|
1707 | followdescendants = startrev < it.next() | |
1709 | except (StopIteration): |
|
1708 | except (StopIteration): | |
1710 | followdescendants = False |
|
1709 | followdescendants = False | |
1711 |
|
1710 | |||
1712 | # branch and only_branch are really aliases and must be handled at |
|
1711 | # branch and only_branch are really aliases and must be handled at | |
1713 | # the same time |
|
1712 | # the same time | |
1714 | opts['branch'] = opts.get('branch', []) + opts.get('only_branch', []) |
|
1713 | opts['branch'] = opts.get('branch', []) + opts.get('only_branch', []) | |
1715 | opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']] |
|
1714 | opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']] | |
1716 | # pats/include/exclude are passed to match.match() directly in |
|
1715 | # pats/include/exclude are passed to match.match() directly in | |
1717 | # _matchfiles() revset but walkchangerevs() builds its matcher with |
|
1716 | # _matchfiles() revset but walkchangerevs() builds its matcher with | |
1718 | # scmutil.match(). The difference is input pats are globbed on |
|
1717 | # scmutil.match(). The difference is input pats are globbed on | |
1719 | # platforms without shell expansion (windows). |
|
1718 | # platforms without shell expansion (windows). | |
1720 | pctx = repo[None] |
|
1719 | pctx = repo[None] | |
1721 | match, pats = scmutil.matchandpats(pctx, pats, opts) |
|
1720 | match, pats = scmutil.matchandpats(pctx, pats, opts) | |
1722 | slowpath = match.anypats() or (match.files() and opts.get('removed')) |
|
1721 | slowpath = match.anypats() or (match.files() and opts.get('removed')) | |
1723 | if not slowpath: |
|
1722 | if not slowpath: | |
1724 | for f in match.files(): |
|
1723 | for f in match.files(): | |
1725 | if follow and f not in pctx: |
|
1724 | if follow and f not in pctx: | |
1726 | # If the file exists, it may be a directory, so let it |
|
1725 | # If the file exists, it may be a directory, so let it | |
1727 | # take the slow path. |
|
1726 | # take the slow path. | |
1728 | if os.path.exists(repo.wjoin(f)): |
|
1727 | if os.path.exists(repo.wjoin(f)): | |
1729 | slowpath = True |
|
1728 | slowpath = True | |
1730 | continue |
|
1729 | continue | |
1731 | else: |
|
1730 | else: | |
1732 | raise util.Abort(_('cannot follow file not in parent ' |
|
1731 | raise util.Abort(_('cannot follow file not in parent ' | |
1733 | 'revision: "%s"') % f) |
|
1732 | 'revision: "%s"') % f) | |
1734 | filelog = repo.file(f) |
|
1733 | filelog = repo.file(f) | |
1735 | if not filelog: |
|
1734 | if not filelog: | |
1736 | # A zero count may be a directory or deleted file, so |
|
1735 | # A zero count may be a directory or deleted file, so | |
1737 | # try to find matching entries on the slow path. |
|
1736 | # try to find matching entries on the slow path. | |
1738 | if follow: |
|
1737 | if follow: | |
1739 | raise util.Abort( |
|
1738 | raise util.Abort( | |
1740 | _('cannot follow nonexistent file: "%s"') % f) |
|
1739 | _('cannot follow nonexistent file: "%s"') % f) | |
1741 | slowpath = True |
|
1740 | slowpath = True | |
1742 |
|
1741 | |||
1743 | # We decided to fall back to the slowpath because at least one |
|
1742 | # We decided to fall back to the slowpath because at least one | |
1744 | # of the paths was not a file. Check to see if at least one of them |
|
1743 | # of the paths was not a file. Check to see if at least one of them | |
1745 | # existed in history - in that case, we'll continue down the |
|
1744 | # existed in history - in that case, we'll continue down the | |
1746 | # slowpath; otherwise, we can turn off the slowpath |
|
1745 | # slowpath; otherwise, we can turn off the slowpath | |
1747 | if slowpath: |
|
1746 | if slowpath: | |
1748 | for path in match.files(): |
|
1747 | for path in match.files(): | |
1749 | if path == '.' or path in repo.store: |
|
1748 | if path == '.' or path in repo.store: | |
1750 | break |
|
1749 | break | |
1751 | else: |
|
1750 | else: | |
1752 | slowpath = False |
|
1751 | slowpath = False | |
1753 |
|
1752 | |||
1754 | fpats = ('_patsfollow', '_patsfollowfirst') |
|
1753 | fpats = ('_patsfollow', '_patsfollowfirst') | |
1755 | fnopats = (('_ancestors', '_fancestors'), |
|
1754 | fnopats = (('_ancestors', '_fancestors'), | |
1756 | ('_descendants', '_fdescendants')) |
|
1755 | ('_descendants', '_fdescendants')) | |
1757 | if slowpath: |
|
1756 | if slowpath: | |
1758 | # See walkchangerevs() slow path. |
|
1757 | # See walkchangerevs() slow path. | |
1759 | # |
|
1758 | # | |
1760 | # pats/include/exclude cannot be represented as separate |
|
1759 | # pats/include/exclude cannot be represented as separate | |
1761 | # revset expressions as their filtering logic applies at file |
|
1760 | # revset expressions as their filtering logic applies at file | |
1762 | # level. For instance "-I a -X a" matches a revision touching |
|
1761 | # level. For instance "-I a -X a" matches a revision touching | |
1763 | # "a" and "b" while "file(a) and not file(b)" does |
|
1762 | # "a" and "b" while "file(a) and not file(b)" does | |
1764 | # not. Besides, filesets are evaluated against the working |
|
1763 | # not. Besides, filesets are evaluated against the working | |
1765 | # directory. |
|
1764 | # directory. | |
1766 | matchargs = ['r:', 'd:relpath'] |
|
1765 | matchargs = ['r:', 'd:relpath'] | |
1767 | for p in pats: |
|
1766 | for p in pats: | |
1768 | matchargs.append('p:' + p) |
|
1767 | matchargs.append('p:' + p) | |
1769 | for p in opts.get('include', []): |
|
1768 | for p in opts.get('include', []): | |
1770 | matchargs.append('i:' + p) |
|
1769 | matchargs.append('i:' + p) | |
1771 | for p in opts.get('exclude', []): |
|
1770 | for p in opts.get('exclude', []): | |
1772 | matchargs.append('x:' + p) |
|
1771 | matchargs.append('x:' + p) | |
1773 | matchargs = ','.join(('%r' % p) for p in matchargs) |
|
1772 | matchargs = ','.join(('%r' % p) for p in matchargs) | |
1774 | opts['_matchfiles'] = matchargs |
|
1773 | opts['_matchfiles'] = matchargs | |
1775 | if follow: |
|
1774 | if follow: | |
1776 | opts[fnopats[0][followfirst]] = '.' |
|
1775 | opts[fnopats[0][followfirst]] = '.' | |
1777 | else: |
|
1776 | else: | |
1778 | if follow: |
|
1777 | if follow: | |
1779 | if pats: |
|
1778 | if pats: | |
1780 | # follow() revset interprets its file argument as a |
|
1779 | # follow() revset interprets its file argument as a | |
1781 | # manifest entry, so use match.files(), not pats. |
|
1780 | # manifest entry, so use match.files(), not pats. | |
1782 | opts[fpats[followfirst]] = list(match.files()) |
|
1781 | opts[fpats[followfirst]] = list(match.files()) | |
1783 | else: |
|
1782 | else: | |
1784 | op = fnopats[followdescendants][followfirst] |
|
1783 | op = fnopats[followdescendants][followfirst] | |
1785 | opts[op] = 'rev(%d)' % startrev |
|
1784 | opts[op] = 'rev(%d)' % startrev | |
1786 | else: |
|
1785 | else: | |
1787 | opts['_patslog'] = list(pats) |
|
1786 | opts['_patslog'] = list(pats) | |
1788 |
|
1787 | |||
1789 | filematcher = None |
|
1788 | filematcher = None | |
1790 | if opts.get('patch') or opts.get('stat'): |
|
1789 | if opts.get('patch') or opts.get('stat'): | |
1791 | # When following files, track renames via a special matcher. |
|
1790 | # When following files, track renames via a special matcher. | |
1792 | # If we're forced to take the slowpath it means we're following |
|
1791 | # If we're forced to take the slowpath it means we're following | |
1793 | # at least one pattern/directory, so don't bother with rename tracking. |
|
1792 | # at least one pattern/directory, so don't bother with rename tracking. | |
1794 | if follow and not match.always() and not slowpath: |
|
1793 | if follow and not match.always() and not slowpath: | |
1795 | # _makefollowlogfilematcher expects its files argument to be |
|
1794 | # _makefollowlogfilematcher expects its files argument to be | |
1796 | # relative to the repo root, so use match.files(), not pats. |
|
1795 | # relative to the repo root, so use match.files(), not pats. | |
1797 | filematcher = _makefollowlogfilematcher(repo, match.files(), |
|
1796 | filematcher = _makefollowlogfilematcher(repo, match.files(), | |
1798 | followfirst) |
|
1797 | followfirst) | |
1799 | else: |
|
1798 | else: | |
1800 | filematcher = _makenofollowlogfilematcher(repo, pats, opts) |
|
1799 | filematcher = _makenofollowlogfilematcher(repo, pats, opts) | |
1801 | if filematcher is None: |
|
1800 | if filematcher is None: | |
1802 | filematcher = lambda rev: match |
|
1801 | filematcher = lambda rev: match | |
1803 |
|
1802 | |||
1804 | expr = [] |
|
1803 | expr = [] | |
1805 | for op, val in sorted(opts.iteritems()): |
|
1804 | for op, val in sorted(opts.iteritems()): | |
1806 | if not val: |
|
1805 | if not val: | |
1807 | continue |
|
1806 | continue | |
1808 | if op not in opt2revset: |
|
1807 | if op not in opt2revset: | |
1809 | continue |
|
1808 | continue | |
1810 | revop, andor = opt2revset[op] |
|
1809 | revop, andor = opt2revset[op] | |
1811 | if '%(val)' not in revop: |
|
1810 | if '%(val)' not in revop: | |
1812 | expr.append(revop) |
|
1811 | expr.append(revop) | |
1813 | else: |
|
1812 | else: | |
1814 | if not isinstance(val, list): |
|
1813 | if not isinstance(val, list): | |
1815 | e = revop % {'val': val} |
|
1814 | e = revop % {'val': val} | |
1816 | else: |
|
1815 | else: | |
1817 | e = '(' + andor.join((revop % {'val': v}) for v in val) + ')' |
|
1816 | e = '(' + andor.join((revop % {'val': v}) for v in val) + ')' | |
1818 | expr.append(e) |
|
1817 | expr.append(e) | |
1819 |
|
1818 | |||
1820 | if expr: |
|
1819 | if expr: | |
1821 | expr = '(' + ' and '.join(expr) + ')' |
|
1820 | expr = '(' + ' and '.join(expr) + ')' | |
1822 | else: |
|
1821 | else: | |
1823 | expr = None |
|
1822 | expr = None | |
1824 | return expr, filematcher |
|
1823 | return expr, filematcher | |
1825 |
|
1824 | |||
1826 | def getgraphlogrevs(repo, pats, opts): |
|
1825 | def getgraphlogrevs(repo, pats, opts): | |
1827 | """Return (revs, expr, filematcher) where revs is an iterable of |
|
1826 | """Return (revs, expr, filematcher) where revs is an iterable of | |
1828 | revision numbers, expr is a revset string built from log options |
|
1827 | revision numbers, expr is a revset string built from log options | |
1829 | and file patterns or None, and used to filter 'revs'. If --stat or |
|
1828 | and file patterns or None, and used to filter 'revs'. If --stat or | |
1830 | --patch are not passed filematcher is None. Otherwise it is a |
|
1829 | --patch are not passed filematcher is None. Otherwise it is a | |
1831 | callable taking a revision number and returning a match objects |
|
1830 | callable taking a revision number and returning a match objects | |
1832 | filtering the files to be detailed when displaying the revision. |
|
1831 | filtering the files to be detailed when displaying the revision. | |
1833 | """ |
|
1832 | """ | |
1834 | if not len(repo): |
|
1833 | if not len(repo): | |
1835 | return [], None, None |
|
1834 | return [], None, None | |
1836 | limit = loglimit(opts) |
|
1835 | limit = loglimit(opts) | |
1837 | # Default --rev value depends on --follow but --follow behaviour |
|
1836 | # Default --rev value depends on --follow but --follow behaviour | |
1838 | # depends on revisions resolved from --rev... |
|
1837 | # depends on revisions resolved from --rev... | |
1839 | follow = opts.get('follow') or opts.get('follow_first') |
|
1838 | follow = opts.get('follow') or opts.get('follow_first') | |
1840 | possiblyunsorted = False # whether revs might need sorting |
|
1839 | possiblyunsorted = False # whether revs might need sorting | |
1841 | if opts.get('rev'): |
|
1840 | if opts.get('rev'): | |
1842 | revs = scmutil.revrange(repo, opts['rev']) |
|
1841 | revs = scmutil.revrange(repo, opts['rev']) | |
1843 | # Don't sort here because _makelogrevset might depend on the |
|
1842 | # Don't sort here because _makelogrevset might depend on the | |
1844 | # order of revs |
|
1843 | # order of revs | |
1845 | possiblyunsorted = True |
|
1844 | possiblyunsorted = True | |
1846 | else: |
|
1845 | else: | |
1847 | if follow and len(repo) > 0: |
|
1846 | if follow and len(repo) > 0: | |
1848 | revs = repo.revs('reverse(:.)') |
|
1847 | revs = repo.revs('reverse(:.)') | |
1849 | else: |
|
1848 | else: | |
1850 | revs = revset.spanset(repo) |
|
1849 | revs = revset.spanset(repo) | |
1851 | revs.reverse() |
|
1850 | revs.reverse() | |
1852 | if not revs: |
|
1851 | if not revs: | |
1853 | return revset.baseset(), None, None |
|
1852 | return revset.baseset(), None, None | |
1854 | expr, filematcher = _makelogrevset(repo, pats, opts, revs) |
|
1853 | expr, filematcher = _makelogrevset(repo, pats, opts, revs) | |
1855 | if possiblyunsorted: |
|
1854 | if possiblyunsorted: | |
1856 | revs.sort(reverse=True) |
|
1855 | revs.sort(reverse=True) | |
1857 | if expr: |
|
1856 | if expr: | |
1858 | # Revset matchers often operate faster on revisions in changelog |
|
1857 | # Revset matchers often operate faster on revisions in changelog | |
1859 | # order, because most filters deal with the changelog. |
|
1858 | # order, because most filters deal with the changelog. | |
1860 | revs.reverse() |
|
1859 | revs.reverse() | |
1861 | matcher = revset.match(repo.ui, expr) |
|
1860 | matcher = revset.match(repo.ui, expr) | |
1862 | # Revset matches can reorder revisions. "A or B" typically returns |
|
1861 | # Revset matches can reorder revisions. "A or B" typically returns | |
1863 | # returns the revision matching A then the revision matching B. Sort |
|
1862 | # returns the revision matching A then the revision matching B. Sort | |
1864 | # again to fix that. |
|
1863 | # again to fix that. | |
1865 | revs = matcher(repo, revs) |
|
1864 | revs = matcher(repo, revs) | |
1866 | revs.sort(reverse=True) |
|
1865 | revs.sort(reverse=True) | |
1867 | if limit is not None: |
|
1866 | if limit is not None: | |
1868 | limitedrevs = [] |
|
1867 | limitedrevs = [] | |
1869 | for idx, rev in enumerate(revs): |
|
1868 | for idx, rev in enumerate(revs): | |
1870 | if idx >= limit: |
|
1869 | if idx >= limit: | |
1871 | break |
|
1870 | break | |
1872 | limitedrevs.append(rev) |
|
1871 | limitedrevs.append(rev) | |
1873 | revs = revset.baseset(limitedrevs) |
|
1872 | revs = revset.baseset(limitedrevs) | |
1874 |
|
1873 | |||
1875 | return revs, expr, filematcher |
|
1874 | return revs, expr, filematcher | |
1876 |
|
1875 | |||
1877 | def getlogrevs(repo, pats, opts): |
|
1876 | def getlogrevs(repo, pats, opts): | |
1878 | """Return (revs, expr, filematcher) where revs is an iterable of |
|
1877 | """Return (revs, expr, filematcher) where revs is an iterable of | |
1879 | revision numbers, expr is a revset string built from log options |
|
1878 | revision numbers, expr is a revset string built from log options | |
1880 | and file patterns or None, and used to filter 'revs'. If --stat or |
|
1879 | and file patterns or None, and used to filter 'revs'. If --stat or | |
1881 | --patch are not passed filematcher is None. Otherwise it is a |
|
1880 | --patch are not passed filematcher is None. Otherwise it is a | |
1882 | callable taking a revision number and returning a match objects |
|
1881 | callable taking a revision number and returning a match objects | |
1883 | filtering the files to be detailed when displaying the revision. |
|
1882 | filtering the files to be detailed when displaying the revision. | |
1884 | """ |
|
1883 | """ | |
1885 | limit = loglimit(opts) |
|
1884 | limit = loglimit(opts) | |
1886 | # Default --rev value depends on --follow but --follow behaviour |
|
1885 | # Default --rev value depends on --follow but --follow behaviour | |
1887 | # depends on revisions resolved from --rev... |
|
1886 | # depends on revisions resolved from --rev... | |
1888 | follow = opts.get('follow') or opts.get('follow_first') |
|
1887 | follow = opts.get('follow') or opts.get('follow_first') | |
1889 | if opts.get('rev'): |
|
1888 | if opts.get('rev'): | |
1890 | revs = scmutil.revrange(repo, opts['rev']) |
|
1889 | revs = scmutil.revrange(repo, opts['rev']) | |
1891 | elif follow: |
|
1890 | elif follow: | |
1892 | revs = repo.revs('reverse(:.)') |
|
1891 | revs = repo.revs('reverse(:.)') | |
1893 | else: |
|
1892 | else: | |
1894 | revs = revset.spanset(repo) |
|
1893 | revs = revset.spanset(repo) | |
1895 | revs.reverse() |
|
1894 | revs.reverse() | |
1896 | if not revs: |
|
1895 | if not revs: | |
1897 | return revset.baseset([]), None, None |
|
1896 | return revset.baseset([]), None, None | |
1898 | expr, filematcher = _makelogrevset(repo, pats, opts, revs) |
|
1897 | expr, filematcher = _makelogrevset(repo, pats, opts, revs) | |
1899 | if expr: |
|
1898 | if expr: | |
1900 | # Revset matchers often operate faster on revisions in changelog |
|
1899 | # Revset matchers often operate faster on revisions in changelog | |
1901 | # order, because most filters deal with the changelog. |
|
1900 | # order, because most filters deal with the changelog. | |
1902 | if not opts.get('rev'): |
|
1901 | if not opts.get('rev'): | |
1903 | revs.reverse() |
|
1902 | revs.reverse() | |
1904 | matcher = revset.match(repo.ui, expr) |
|
1903 | matcher = revset.match(repo.ui, expr) | |
1905 | # Revset matches can reorder revisions. "A or B" typically returns |
|
1904 | # Revset matches can reorder revisions. "A or B" typically returns | |
1906 | # returns the revision matching A then the revision matching B. Sort |
|
1905 | # returns the revision matching A then the revision matching B. Sort | |
1907 | # again to fix that. |
|
1906 | # again to fix that. | |
1908 | revs = matcher(repo, revs) |
|
1907 | revs = matcher(repo, revs) | |
1909 | if not opts.get('rev'): |
|
1908 | if not opts.get('rev'): | |
1910 | revs.sort(reverse=True) |
|
1909 | revs.sort(reverse=True) | |
1911 | if limit is not None: |
|
1910 | if limit is not None: | |
1912 | count = 0 |
|
1911 | count = 0 | |
1913 | limitedrevs = [] |
|
1912 | limitedrevs = [] | |
1914 | it = iter(revs) |
|
1913 | it = iter(revs) | |
1915 | while count < limit: |
|
1914 | while count < limit: | |
1916 | try: |
|
1915 | try: | |
1917 | limitedrevs.append(it.next()) |
|
1916 | limitedrevs.append(it.next()) | |
1918 | except (StopIteration): |
|
1917 | except (StopIteration): | |
1919 | break |
|
1918 | break | |
1920 | count += 1 |
|
1919 | count += 1 | |
1921 | revs = revset.baseset(limitedrevs) |
|
1920 | revs = revset.baseset(limitedrevs) | |
1922 |
|
1921 | |||
1923 | return revs, expr, filematcher |
|
1922 | return revs, expr, filematcher | |
1924 |
|
1923 | |||
1925 | def displaygraph(ui, dag, displayer, showparents, edgefn, getrenamed=None, |
|
1924 | def displaygraph(ui, dag, displayer, showparents, edgefn, getrenamed=None, | |
1926 | filematcher=None): |
|
1925 | filematcher=None): | |
1927 | seen, state = [], graphmod.asciistate() |
|
1926 | seen, state = [], graphmod.asciistate() | |
1928 | for rev, type, ctx, parents in dag: |
|
1927 | for rev, type, ctx, parents in dag: | |
1929 | char = 'o' |
|
1928 | char = 'o' | |
1930 | if ctx.node() in showparents: |
|
1929 | if ctx.node() in showparents: | |
1931 | char = '@' |
|
1930 | char = '@' | |
1932 | elif ctx.obsolete(): |
|
1931 | elif ctx.obsolete(): | |
1933 | char = 'x' |
|
1932 | char = 'x' | |
1934 | copies = None |
|
1933 | copies = None | |
1935 | if getrenamed and ctx.rev(): |
|
1934 | if getrenamed and ctx.rev(): | |
1936 | copies = [] |
|
1935 | copies = [] | |
1937 | for fn in ctx.files(): |
|
1936 | for fn in ctx.files(): | |
1938 | rename = getrenamed(fn, ctx.rev()) |
|
1937 | rename = getrenamed(fn, ctx.rev()) | |
1939 | if rename: |
|
1938 | if rename: | |
1940 | copies.append((fn, rename[0])) |
|
1939 | copies.append((fn, rename[0])) | |
1941 | revmatchfn = None |
|
1940 | revmatchfn = None | |
1942 | if filematcher is not None: |
|
1941 | if filematcher is not None: | |
1943 | revmatchfn = filematcher(ctx.rev()) |
|
1942 | revmatchfn = filematcher(ctx.rev()) | |
1944 | displayer.show(ctx, copies=copies, matchfn=revmatchfn) |
|
1943 | displayer.show(ctx, copies=copies, matchfn=revmatchfn) | |
1945 | lines = displayer.hunk.pop(rev).split('\n') |
|
1944 | lines = displayer.hunk.pop(rev).split('\n') | |
1946 | if not lines[-1]: |
|
1945 | if not lines[-1]: | |
1947 | del lines[-1] |
|
1946 | del lines[-1] | |
1948 | displayer.flush(rev) |
|
1947 | displayer.flush(rev) | |
1949 | edges = edgefn(type, char, lines, seen, rev, parents) |
|
1948 | edges = edgefn(type, char, lines, seen, rev, parents) | |
1950 | for type, char, lines, coldata in edges: |
|
1949 | for type, char, lines, coldata in edges: | |
1951 | graphmod.ascii(ui, state, type, char, lines, coldata) |
|
1950 | graphmod.ascii(ui, state, type, char, lines, coldata) | |
1952 | displayer.close() |
|
1951 | displayer.close() | |
1953 |
|
1952 | |||
1954 | def graphlog(ui, repo, *pats, **opts): |
|
1953 | def graphlog(ui, repo, *pats, **opts): | |
1955 | # Parameters are identical to log command ones |
|
1954 | # Parameters are identical to log command ones | |
1956 | revs, expr, filematcher = getgraphlogrevs(repo, pats, opts) |
|
1955 | revs, expr, filematcher = getgraphlogrevs(repo, pats, opts) | |
1957 | revdag = graphmod.dagwalker(repo, revs) |
|
1956 | revdag = graphmod.dagwalker(repo, revs) | |
1958 |
|
1957 | |||
1959 | getrenamed = None |
|
1958 | getrenamed = None | |
1960 | if opts.get('copies'): |
|
1959 | if opts.get('copies'): | |
1961 | endrev = None |
|
1960 | endrev = None | |
1962 | if opts.get('rev'): |
|
1961 | if opts.get('rev'): | |
1963 | endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1 |
|
1962 | endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1 | |
1964 | getrenamed = templatekw.getrenamedfn(repo, endrev=endrev) |
|
1963 | getrenamed = templatekw.getrenamedfn(repo, endrev=endrev) | |
1965 | displayer = show_changeset(ui, repo, opts, buffered=True) |
|
1964 | displayer = show_changeset(ui, repo, opts, buffered=True) | |
1966 | showparents = [ctx.node() for ctx in repo[None].parents()] |
|
1965 | showparents = [ctx.node() for ctx in repo[None].parents()] | |
1967 | displaygraph(ui, revdag, displayer, showparents, |
|
1966 | displaygraph(ui, revdag, displayer, showparents, | |
1968 | graphmod.asciiedges, getrenamed, filematcher) |
|
1967 | graphmod.asciiedges, getrenamed, filematcher) | |
1969 |
|
1968 | |||
1970 | def checkunsupportedgraphflags(pats, opts): |
|
1969 | def checkunsupportedgraphflags(pats, opts): | |
1971 | for op in ["newest_first"]: |
|
1970 | for op in ["newest_first"]: | |
1972 | if op in opts and opts[op]: |
|
1971 | if op in opts and opts[op]: | |
1973 | raise util.Abort(_("-G/--graph option is incompatible with --%s") |
|
1972 | raise util.Abort(_("-G/--graph option is incompatible with --%s") | |
1974 | % op.replace("_", "-")) |
|
1973 | % op.replace("_", "-")) | |
1975 |
|
1974 | |||
1976 | def graphrevs(repo, nodes, opts): |
|
1975 | def graphrevs(repo, nodes, opts): | |
1977 | limit = loglimit(opts) |
|
1976 | limit = loglimit(opts) | |
1978 | nodes.reverse() |
|
1977 | nodes.reverse() | |
1979 | if limit is not None: |
|
1978 | if limit is not None: | |
1980 | nodes = nodes[:limit] |
|
1979 | nodes = nodes[:limit] | |
1981 | return graphmod.nodes(repo, nodes) |
|
1980 | return graphmod.nodes(repo, nodes) | |
1982 |
|
1981 | |||
1983 | def add(ui, repo, match, prefix, explicitonly, **opts): |
|
1982 | def add(ui, repo, match, prefix, explicitonly, **opts): | |
1984 | join = lambda f: os.path.join(prefix, f) |
|
1983 | join = lambda f: os.path.join(prefix, f) | |
1985 | bad = [] |
|
1984 | bad = [] | |
1986 | oldbad = match.bad |
|
1985 | oldbad = match.bad | |
1987 | match.bad = lambda x, y: bad.append(x) or oldbad(x, y) |
|
1986 | match.bad = lambda x, y: bad.append(x) or oldbad(x, y) | |
1988 | names = [] |
|
1987 | names = [] | |
1989 | wctx = repo[None] |
|
1988 | wctx = repo[None] | |
1990 | cca = None |
|
1989 | cca = None | |
1991 | abort, warn = scmutil.checkportabilityalert(ui) |
|
1990 | abort, warn = scmutil.checkportabilityalert(ui) | |
1992 | if abort or warn: |
|
1991 | if abort or warn: | |
1993 | cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate) |
|
1992 | cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate) | |
1994 | for f in wctx.walk(match): |
|
1993 | for f in wctx.walk(match): | |
1995 | exact = match.exact(f) |
|
1994 | exact = match.exact(f) | |
1996 | if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f): |
|
1995 | if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f): | |
1997 | if cca: |
|
1996 | if cca: | |
1998 | cca(f) |
|
1997 | cca(f) | |
1999 | names.append(f) |
|
1998 | names.append(f) | |
2000 | if ui.verbose or not exact: |
|
1999 | if ui.verbose or not exact: | |
2001 | ui.status(_('adding %s\n') % match.rel(f)) |
|
2000 | ui.status(_('adding %s\n') % match.rel(f)) | |
2002 |
|
2001 | |||
2003 | for subpath in sorted(wctx.substate): |
|
2002 | for subpath in sorted(wctx.substate): | |
2004 | sub = wctx.sub(subpath) |
|
2003 | sub = wctx.sub(subpath) | |
2005 | try: |
|
2004 | try: | |
2006 | submatch = matchmod.narrowmatcher(subpath, match) |
|
2005 | submatch = matchmod.narrowmatcher(subpath, match) | |
2007 | if opts.get('subrepos'): |
|
2006 | if opts.get('subrepos'): | |
2008 | bad.extend(sub.add(ui, submatch, prefix, False, **opts)) |
|
2007 | bad.extend(sub.add(ui, submatch, prefix, False, **opts)) | |
2009 | else: |
|
2008 | else: | |
2010 | bad.extend(sub.add(ui, submatch, prefix, True, **opts)) |
|
2009 | bad.extend(sub.add(ui, submatch, prefix, True, **opts)) | |
2011 | except error.LookupError: |
|
2010 | except error.LookupError: | |
2012 | ui.status(_("skipping missing subrepository: %s\n") |
|
2011 | ui.status(_("skipping missing subrepository: %s\n") | |
2013 | % join(subpath)) |
|
2012 | % join(subpath)) | |
2014 |
|
2013 | |||
2015 | if not opts.get('dry_run'): |
|
2014 | if not opts.get('dry_run'): | |
2016 | rejected = wctx.add(names, prefix) |
|
2015 | rejected = wctx.add(names, prefix) | |
2017 | bad.extend(f for f in rejected if f in match.files()) |
|
2016 | bad.extend(f for f in rejected if f in match.files()) | |
2018 | return bad |
|
2017 | return bad | |
2019 |
|
2018 | |||
2020 | def forget(ui, repo, match, prefix, explicitonly): |
|
2019 | def forget(ui, repo, match, prefix, explicitonly): | |
2021 | join = lambda f: os.path.join(prefix, f) |
|
2020 | join = lambda f: os.path.join(prefix, f) | |
2022 | bad = [] |
|
2021 | bad = [] | |
2023 | oldbad = match.bad |
|
2022 | oldbad = match.bad | |
2024 | match.bad = lambda x, y: bad.append(x) or oldbad(x, y) |
|
2023 | match.bad = lambda x, y: bad.append(x) or oldbad(x, y) | |
2025 | wctx = repo[None] |
|
2024 | wctx = repo[None] | |
2026 | forgot = [] |
|
2025 | forgot = [] | |
2027 | s = repo.status(match=match, clean=True) |
|
2026 | s = repo.status(match=match, clean=True) | |
2028 | forget = sorted(s[0] + s[1] + s[3] + s[6]) |
|
2027 | forget = sorted(s[0] + s[1] + s[3] + s[6]) | |
2029 | if explicitonly: |
|
2028 | if explicitonly: | |
2030 | forget = [f for f in forget if match.exact(f)] |
|
2029 | forget = [f for f in forget if match.exact(f)] | |
2031 |
|
2030 | |||
2032 | for subpath in sorted(wctx.substate): |
|
2031 | for subpath in sorted(wctx.substate): | |
2033 | sub = wctx.sub(subpath) |
|
2032 | sub = wctx.sub(subpath) | |
2034 | try: |
|
2033 | try: | |
2035 | submatch = matchmod.narrowmatcher(subpath, match) |
|
2034 | submatch = matchmod.narrowmatcher(subpath, match) | |
2036 | subbad, subforgot = sub.forget(submatch, prefix) |
|
2035 | subbad, subforgot = sub.forget(submatch, prefix) | |
2037 | bad.extend([subpath + '/' + f for f in subbad]) |
|
2036 | bad.extend([subpath + '/' + f for f in subbad]) | |
2038 | forgot.extend([subpath + '/' + f for f in subforgot]) |
|
2037 | forgot.extend([subpath + '/' + f for f in subforgot]) | |
2039 | except error.LookupError: |
|
2038 | except error.LookupError: | |
2040 | ui.status(_("skipping missing subrepository: %s\n") |
|
2039 | ui.status(_("skipping missing subrepository: %s\n") | |
2041 | % join(subpath)) |
|
2040 | % join(subpath)) | |
2042 |
|
2041 | |||
2043 | if not explicitonly: |
|
2042 | if not explicitonly: | |
2044 | for f in match.files(): |
|
2043 | for f in match.files(): | |
2045 | if f not in repo.dirstate and not repo.wvfs.isdir(f): |
|
2044 | if f not in repo.dirstate and not repo.wvfs.isdir(f): | |
2046 | if f not in forgot: |
|
2045 | if f not in forgot: | |
2047 | if repo.wvfs.exists(f): |
|
2046 | if repo.wvfs.exists(f): | |
2048 | ui.warn(_('not removing %s: ' |
|
2047 | ui.warn(_('not removing %s: ' | |
2049 | 'file is already untracked\n') |
|
2048 | 'file is already untracked\n') | |
2050 | % match.rel(f)) |
|
2049 | % match.rel(f)) | |
2051 | bad.append(f) |
|
2050 | bad.append(f) | |
2052 |
|
2051 | |||
2053 | for f in forget: |
|
2052 | for f in forget: | |
2054 | if ui.verbose or not match.exact(f): |
|
2053 | if ui.verbose or not match.exact(f): | |
2055 | ui.status(_('removing %s\n') % match.rel(f)) |
|
2054 | ui.status(_('removing %s\n') % match.rel(f)) | |
2056 |
|
2055 | |||
2057 | rejected = wctx.forget(forget, prefix) |
|
2056 | rejected = wctx.forget(forget, prefix) | |
2058 | bad.extend(f for f in rejected if f in match.files()) |
|
2057 | bad.extend(f for f in rejected if f in match.files()) | |
2059 | forgot.extend(f for f in forget if f not in rejected) |
|
2058 | forgot.extend(f for f in forget if f not in rejected) | |
2060 | return bad, forgot |
|
2059 | return bad, forgot | |
2061 |
|
2060 | |||
2062 | def remove(ui, repo, m, prefix, after, force, subrepos): |
|
2061 | def remove(ui, repo, m, prefix, after, force, subrepos): | |
2063 | join = lambda f: os.path.join(prefix, f) |
|
2062 | join = lambda f: os.path.join(prefix, f) | |
2064 | ret = 0 |
|
2063 | ret = 0 | |
2065 | s = repo.status(match=m, clean=True) |
|
2064 | s = repo.status(match=m, clean=True) | |
2066 | modified, added, deleted, clean = s[0], s[1], s[3], s[6] |
|
2065 | modified, added, deleted, clean = s[0], s[1], s[3], s[6] | |
2067 |
|
2066 | |||
2068 | wctx = repo[None] |
|
2067 | wctx = repo[None] | |
2069 |
|
2068 | |||
2070 | for subpath in sorted(wctx.substate): |
|
2069 | for subpath in sorted(wctx.substate): | |
2071 | def matchessubrepo(matcher, subpath): |
|
2070 | def matchessubrepo(matcher, subpath): | |
2072 | if matcher.exact(subpath): |
|
2071 | if matcher.exact(subpath): | |
2073 | return True |
|
2072 | return True | |
2074 | for f in matcher.files(): |
|
2073 | for f in matcher.files(): | |
2075 | if f.startswith(subpath): |
|
2074 | if f.startswith(subpath): | |
2076 | return True |
|
2075 | return True | |
2077 | return False |
|
2076 | return False | |
2078 |
|
2077 | |||
2079 | if subrepos or matchessubrepo(m, subpath): |
|
2078 | if subrepos or matchessubrepo(m, subpath): | |
2080 | sub = wctx.sub(subpath) |
|
2079 | sub = wctx.sub(subpath) | |
2081 | try: |
|
2080 | try: | |
2082 | submatch = matchmod.narrowmatcher(subpath, m) |
|
2081 | submatch = matchmod.narrowmatcher(subpath, m) | |
2083 | if sub.removefiles(submatch, prefix, after, force, subrepos): |
|
2082 | if sub.removefiles(submatch, prefix, after, force, subrepos): | |
2084 | ret = 1 |
|
2083 | ret = 1 | |
2085 | except error.LookupError: |
|
2084 | except error.LookupError: | |
2086 | ui.status(_("skipping missing subrepository: %s\n") |
|
2085 | ui.status(_("skipping missing subrepository: %s\n") | |
2087 | % join(subpath)) |
|
2086 | % join(subpath)) | |
2088 |
|
2087 | |||
2089 | # warn about failure to delete explicit files/dirs |
|
2088 | # warn about failure to delete explicit files/dirs | |
2090 | for f in m.files(): |
|
2089 | for f in m.files(): | |
2091 | def insubrepo(): |
|
2090 | def insubrepo(): | |
2092 | for subpath in wctx.substate: |
|
2091 | for subpath in wctx.substate: | |
2093 | if f.startswith(subpath): |
|
2092 | if f.startswith(subpath): | |
2094 | return True |
|
2093 | return True | |
2095 | return False |
|
2094 | return False | |
2096 |
|
2095 | |||
2097 | if f in repo.dirstate or f in wctx.dirs() or f == '.' or insubrepo(): |
|
2096 | if f in repo.dirstate or f in wctx.dirs() or f == '.' or insubrepo(): | |
2098 | continue |
|
2097 | continue | |
2099 |
|
2098 | |||
2100 | if repo.wvfs.exists(f): |
|
2099 | if repo.wvfs.exists(f): | |
2101 | if repo.wvfs.isdir(f): |
|
2100 | if repo.wvfs.isdir(f): | |
2102 | ui.warn(_('not removing %s: no tracked files\n') |
|
2101 | ui.warn(_('not removing %s: no tracked files\n') | |
2103 | % m.rel(f)) |
|
2102 | % m.rel(f)) | |
2104 | else: |
|
2103 | else: | |
2105 | ui.warn(_('not removing %s: file is untracked\n') |
|
2104 | ui.warn(_('not removing %s: file is untracked\n') | |
2106 | % m.rel(f)) |
|
2105 | % m.rel(f)) | |
2107 | # missing files will generate a warning elsewhere |
|
2106 | # missing files will generate a warning elsewhere | |
2108 | ret = 1 |
|
2107 | ret = 1 | |
2109 |
|
2108 | |||
2110 | if force: |
|
2109 | if force: | |
2111 | list = modified + deleted + clean + added |
|
2110 | list = modified + deleted + clean + added | |
2112 | elif after: |
|
2111 | elif after: | |
2113 | list = deleted |
|
2112 | list = deleted | |
2114 | for f in modified + added + clean: |
|
2113 | for f in modified + added + clean: | |
2115 | ui.warn(_('not removing %s: file still exists\n') % m.rel(f)) |
|
2114 | ui.warn(_('not removing %s: file still exists\n') % m.rel(f)) | |
2116 | ret = 1 |
|
2115 | ret = 1 | |
2117 | else: |
|
2116 | else: | |
2118 | list = deleted + clean |
|
2117 | list = deleted + clean | |
2119 | for f in modified: |
|
2118 | for f in modified: | |
2120 | ui.warn(_('not removing %s: file is modified (use -f' |
|
2119 | ui.warn(_('not removing %s: file is modified (use -f' | |
2121 | ' to force removal)\n') % m.rel(f)) |
|
2120 | ' to force removal)\n') % m.rel(f)) | |
2122 | ret = 1 |
|
2121 | ret = 1 | |
2123 | for f in added: |
|
2122 | for f in added: | |
2124 | ui.warn(_('not removing %s: file has been marked for add' |
|
2123 | ui.warn(_('not removing %s: file has been marked for add' | |
2125 | ' (use forget to undo)\n') % m.rel(f)) |
|
2124 | ' (use forget to undo)\n') % m.rel(f)) | |
2126 | ret = 1 |
|
2125 | ret = 1 | |
2127 |
|
2126 | |||
2128 | for f in sorted(list): |
|
2127 | for f in sorted(list): | |
2129 | if ui.verbose or not m.exact(f): |
|
2128 | if ui.verbose or not m.exact(f): | |
2130 | ui.status(_('removing %s\n') % m.rel(f)) |
|
2129 | ui.status(_('removing %s\n') % m.rel(f)) | |
2131 |
|
2130 | |||
2132 | wlock = repo.wlock() |
|
2131 | wlock = repo.wlock() | |
2133 | try: |
|
2132 | try: | |
2134 | if not after: |
|
2133 | if not after: | |
2135 | for f in list: |
|
2134 | for f in list: | |
2136 | if f in added: |
|
2135 | if f in added: | |
2137 | continue # we never unlink added files on remove |
|
2136 | continue # we never unlink added files on remove | |
2138 | util.unlinkpath(repo.wjoin(f), ignoremissing=True) |
|
2137 | util.unlinkpath(repo.wjoin(f), ignoremissing=True) | |
2139 | repo[None].forget(list) |
|
2138 | repo[None].forget(list) | |
2140 | finally: |
|
2139 | finally: | |
2141 | wlock.release() |
|
2140 | wlock.release() | |
2142 |
|
2141 | |||
2143 | return ret |
|
2142 | return ret | |
2144 |
|
2143 | |||
2145 | def cat(ui, repo, ctx, matcher, prefix, **opts): |
|
2144 | def cat(ui, repo, ctx, matcher, prefix, **opts): | |
2146 | err = 1 |
|
2145 | err = 1 | |
2147 |
|
2146 | |||
2148 | def write(path): |
|
2147 | def write(path): | |
2149 | fp = makefileobj(repo, opts.get('output'), ctx.node(), |
|
2148 | fp = makefileobj(repo, opts.get('output'), ctx.node(), | |
2150 | pathname=os.path.join(prefix, path)) |
|
2149 | pathname=os.path.join(prefix, path)) | |
2151 | data = ctx[path].data() |
|
2150 | data = ctx[path].data() | |
2152 | if opts.get('decode'): |
|
2151 | if opts.get('decode'): | |
2153 | data = repo.wwritedata(path, data) |
|
2152 | data = repo.wwritedata(path, data) | |
2154 | fp.write(data) |
|
2153 | fp.write(data) | |
2155 | fp.close() |
|
2154 | fp.close() | |
2156 |
|
2155 | |||
2157 | # Automation often uses hg cat on single files, so special case it |
|
2156 | # Automation often uses hg cat on single files, so special case it | |
2158 | # for performance to avoid the cost of parsing the manifest. |
|
2157 | # for performance to avoid the cost of parsing the manifest. | |
2159 | if len(matcher.files()) == 1 and not matcher.anypats(): |
|
2158 | if len(matcher.files()) == 1 and not matcher.anypats(): | |
2160 | file = matcher.files()[0] |
|
2159 | file = matcher.files()[0] | |
2161 | mf = repo.manifest |
|
2160 | mf = repo.manifest | |
2162 | mfnode = ctx._changeset[0] |
|
2161 | mfnode = ctx._changeset[0] | |
2163 | if mf.find(mfnode, file)[0]: |
|
2162 | if mf.find(mfnode, file)[0]: | |
2164 | write(file) |
|
2163 | write(file) | |
2165 | return 0 |
|
2164 | return 0 | |
2166 |
|
2165 | |||
2167 | # Don't warn about "missing" files that are really in subrepos |
|
2166 | # Don't warn about "missing" files that are really in subrepos | |
2168 | bad = matcher.bad |
|
2167 | bad = matcher.bad | |
2169 |
|
2168 | |||
2170 | def badfn(path, msg): |
|
2169 | def badfn(path, msg): | |
2171 | for subpath in ctx.substate: |
|
2170 | for subpath in ctx.substate: | |
2172 | if path.startswith(subpath): |
|
2171 | if path.startswith(subpath): | |
2173 | return |
|
2172 | return | |
2174 | bad(path, msg) |
|
2173 | bad(path, msg) | |
2175 |
|
2174 | |||
2176 | matcher.bad = badfn |
|
2175 | matcher.bad = badfn | |
2177 |
|
2176 | |||
2178 | for abs in ctx.walk(matcher): |
|
2177 | for abs in ctx.walk(matcher): | |
2179 | write(abs) |
|
2178 | write(abs) | |
2180 | err = 0 |
|
2179 | err = 0 | |
2181 |
|
2180 | |||
2182 | matcher.bad = bad |
|
2181 | matcher.bad = bad | |
2183 |
|
2182 | |||
2184 | for subpath in sorted(ctx.substate): |
|
2183 | for subpath in sorted(ctx.substate): | |
2185 | sub = ctx.sub(subpath) |
|
2184 | sub = ctx.sub(subpath) | |
2186 | try: |
|
2185 | try: | |
2187 | submatch = matchmod.narrowmatcher(subpath, matcher) |
|
2186 | submatch = matchmod.narrowmatcher(subpath, matcher) | |
2188 |
|
2187 | |||
2189 | if not sub.cat(submatch, os.path.join(prefix, sub._path), |
|
2188 | if not sub.cat(submatch, os.path.join(prefix, sub._path), | |
2190 | **opts): |
|
2189 | **opts): | |
2191 | err = 0 |
|
2190 | err = 0 | |
2192 | except error.RepoLookupError: |
|
2191 | except error.RepoLookupError: | |
2193 | ui.status(_("skipping missing subrepository: %s\n") |
|
2192 | ui.status(_("skipping missing subrepository: %s\n") | |
2194 | % os.path.join(prefix, subpath)) |
|
2193 | % os.path.join(prefix, subpath)) | |
2195 |
|
2194 | |||
2196 | return err |
|
2195 | return err | |
2197 |
|
2196 | |||
2198 | def commit(ui, repo, commitfunc, pats, opts): |
|
2197 | def commit(ui, repo, commitfunc, pats, opts): | |
2199 | '''commit the specified files or all outstanding changes''' |
|
2198 | '''commit the specified files or all outstanding changes''' | |
2200 | date = opts.get('date') |
|
2199 | date = opts.get('date') | |
2201 | if date: |
|
2200 | if date: | |
2202 | opts['date'] = util.parsedate(date) |
|
2201 | opts['date'] = util.parsedate(date) | |
2203 | message = logmessage(ui, opts) |
|
2202 | message = logmessage(ui, opts) | |
2204 | matcher = scmutil.match(repo[None], pats, opts) |
|
2203 | matcher = scmutil.match(repo[None], pats, opts) | |
2205 |
|
2204 | |||
2206 | # extract addremove carefully -- this function can be called from a command |
|
2205 | # extract addremove carefully -- this function can be called from a command | |
2207 | # that doesn't support addremove |
|
2206 | # that doesn't support addremove | |
2208 | if opts.get('addremove'): |
|
2207 | if opts.get('addremove'): | |
2209 | if scmutil.addremove(repo, matcher, "", opts) != 0: |
|
2208 | if scmutil.addremove(repo, matcher, "", opts) != 0: | |
2210 | raise util.Abort( |
|
2209 | raise util.Abort( | |
2211 | _("failed to mark all new/missing files as added/removed")) |
|
2210 | _("failed to mark all new/missing files as added/removed")) | |
2212 |
|
2211 | |||
2213 | return commitfunc(ui, repo, message, matcher, opts) |
|
2212 | return commitfunc(ui, repo, message, matcher, opts) | |
2214 |
|
2213 | |||
2215 | def amend(ui, repo, commitfunc, old, extra, pats, opts): |
|
2214 | def amend(ui, repo, commitfunc, old, extra, pats, opts): | |
2216 | # amend will reuse the existing user if not specified, but the obsolete |
|
2215 | # amend will reuse the existing user if not specified, but the obsolete | |
2217 | # marker creation requires that the current user's name is specified. |
|
2216 | # marker creation requires that the current user's name is specified. | |
2218 | if obsolete._enabled: |
|
2217 | if obsolete._enabled: | |
2219 | ui.username() # raise exception if username not set |
|
2218 | ui.username() # raise exception if username not set | |
2220 |
|
2219 | |||
2221 | ui.note(_('amending changeset %s\n') % old) |
|
2220 | ui.note(_('amending changeset %s\n') % old) | |
2222 | base = old.p1() |
|
2221 | base = old.p1() | |
2223 |
|
2222 | |||
2224 | wlock = lock = newid = None |
|
2223 | wlock = lock = newid = None | |
2225 | try: |
|
2224 | try: | |
2226 | wlock = repo.wlock() |
|
2225 | wlock = repo.wlock() | |
2227 | lock = repo.lock() |
|
2226 | lock = repo.lock() | |
2228 | tr = repo.transaction('amend') |
|
2227 | tr = repo.transaction('amend') | |
2229 | try: |
|
2228 | try: | |
2230 | # See if we got a message from -m or -l, if not, open the editor |
|
2229 | # See if we got a message from -m or -l, if not, open the editor | |
2231 | # with the message of the changeset to amend |
|
2230 | # with the message of the changeset to amend | |
2232 | message = logmessage(ui, opts) |
|
2231 | message = logmessage(ui, opts) | |
2233 | # ensure logfile does not conflict with later enforcement of the |
|
2232 | # ensure logfile does not conflict with later enforcement of the | |
2234 | # message. potential logfile content has been processed by |
|
2233 | # message. potential logfile content has been processed by | |
2235 | # `logmessage` anyway. |
|
2234 | # `logmessage` anyway. | |
2236 | opts.pop('logfile') |
|
2235 | opts.pop('logfile') | |
2237 | # First, do a regular commit to record all changes in the working |
|
2236 | # First, do a regular commit to record all changes in the working | |
2238 | # directory (if there are any) |
|
2237 | # directory (if there are any) | |
2239 | ui.callhooks = False |
|
2238 | ui.callhooks = False | |
2240 | currentbookmark = repo._bookmarkcurrent |
|
2239 | currentbookmark = repo._bookmarkcurrent | |
2241 | try: |
|
2240 | try: | |
2242 | repo._bookmarkcurrent = None |
|
2241 | repo._bookmarkcurrent = None | |
2243 | opts['message'] = 'temporary amend commit for %s' % old |
|
2242 | opts['message'] = 'temporary amend commit for %s' % old | |
2244 | node = commit(ui, repo, commitfunc, pats, opts) |
|
2243 | node = commit(ui, repo, commitfunc, pats, opts) | |
2245 | finally: |
|
2244 | finally: | |
2246 | repo._bookmarkcurrent = currentbookmark |
|
2245 | repo._bookmarkcurrent = currentbookmark | |
2247 | ui.callhooks = True |
|
2246 | ui.callhooks = True | |
2248 | ctx = repo[node] |
|
2247 | ctx = repo[node] | |
2249 |
|
2248 | |||
2250 | # Participating changesets: |
|
2249 | # Participating changesets: | |
2251 | # |
|
2250 | # | |
2252 | # node/ctx o - new (intermediate) commit that contains changes |
|
2251 | # node/ctx o - new (intermediate) commit that contains changes | |
2253 | # | from working dir to go into amending commit |
|
2252 | # | from working dir to go into amending commit | |
2254 | # | (or a workingctx if there were no changes) |
|
2253 | # | (or a workingctx if there were no changes) | |
2255 | # | |
|
2254 | # | | |
2256 | # old o - changeset to amend |
|
2255 | # old o - changeset to amend | |
2257 | # | |
|
2256 | # | | |
2258 | # base o - parent of amending changeset |
|
2257 | # base o - parent of amending changeset | |
2259 |
|
2258 | |||
2260 | # Update extra dict from amended commit (e.g. to preserve graft |
|
2259 | # Update extra dict from amended commit (e.g. to preserve graft | |
2261 | # source) |
|
2260 | # source) | |
2262 | extra.update(old.extra()) |
|
2261 | extra.update(old.extra()) | |
2263 |
|
2262 | |||
2264 | # Also update it from the intermediate commit or from the wctx |
|
2263 | # Also update it from the intermediate commit or from the wctx | |
2265 | extra.update(ctx.extra()) |
|
2264 | extra.update(ctx.extra()) | |
2266 |
|
2265 | |||
2267 | if len(old.parents()) > 1: |
|
2266 | if len(old.parents()) > 1: | |
2268 | # ctx.files() isn't reliable for merges, so fall back to the |
|
2267 | # ctx.files() isn't reliable for merges, so fall back to the | |
2269 | # slower repo.status() method |
|
2268 | # slower repo.status() method | |
2270 | files = set([fn for st in repo.status(base, old)[:3] |
|
2269 | files = set([fn for st in repo.status(base, old)[:3] | |
2271 | for fn in st]) |
|
2270 | for fn in st]) | |
2272 | else: |
|
2271 | else: | |
2273 | files = set(old.files()) |
|
2272 | files = set(old.files()) | |
2274 |
|
2273 | |||
2275 | # Second, we use either the commit we just did, or if there were no |
|
2274 | # Second, we use either the commit we just did, or if there were no | |
2276 | # changes the parent of the working directory as the version of the |
|
2275 | # changes the parent of the working directory as the version of the | |
2277 | # files in the final amend commit |
|
2276 | # files in the final amend commit | |
2278 | if node: |
|
2277 | if node: | |
2279 | ui.note(_('copying changeset %s to %s\n') % (ctx, base)) |
|
2278 | ui.note(_('copying changeset %s to %s\n') % (ctx, base)) | |
2280 |
|
2279 | |||
2281 | user = ctx.user() |
|
2280 | user = ctx.user() | |
2282 | date = ctx.date() |
|
2281 | date = ctx.date() | |
2283 | # Recompute copies (avoid recording a -> b -> a) |
|
2282 | # Recompute copies (avoid recording a -> b -> a) | |
2284 | copied = copies.pathcopies(base, ctx) |
|
2283 | copied = copies.pathcopies(base, ctx) | |
2285 |
|
2284 | |||
2286 | # Prune files which were reverted by the updates: if old |
|
2285 | # Prune files which were reverted by the updates: if old | |
2287 | # introduced file X and our intermediate commit, node, |
|
2286 | # introduced file X and our intermediate commit, node, | |
2288 | # renamed that file, then those two files are the same and |
|
2287 | # renamed that file, then those two files are the same and | |
2289 | # we can discard X from our list of files. Likewise if X |
|
2288 | # we can discard X from our list of files. Likewise if X | |
2290 | # was deleted, it's no longer relevant |
|
2289 | # was deleted, it's no longer relevant | |
2291 | files.update(ctx.files()) |
|
2290 | files.update(ctx.files()) | |
2292 |
|
2291 | |||
2293 | def samefile(f): |
|
2292 | def samefile(f): | |
2294 | if f in ctx.manifest(): |
|
2293 | if f in ctx.manifest(): | |
2295 | a = ctx.filectx(f) |
|
2294 | a = ctx.filectx(f) | |
2296 | if f in base.manifest(): |
|
2295 | if f in base.manifest(): | |
2297 | b = base.filectx(f) |
|
2296 | b = base.filectx(f) | |
2298 | return (not a.cmp(b) |
|
2297 | return (not a.cmp(b) | |
2299 | and a.flags() == b.flags()) |
|
2298 | and a.flags() == b.flags()) | |
2300 | else: |
|
2299 | else: | |
2301 | return False |
|
2300 | return False | |
2302 | else: |
|
2301 | else: | |
2303 | return f not in base.manifest() |
|
2302 | return f not in base.manifest() | |
2304 | files = [f for f in files if not samefile(f)] |
|
2303 | files = [f for f in files if not samefile(f)] | |
2305 |
|
2304 | |||
2306 | def filectxfn(repo, ctx_, path): |
|
2305 | def filectxfn(repo, ctx_, path): | |
2307 | try: |
|
2306 | try: | |
2308 | fctx = ctx[path] |
|
2307 | fctx = ctx[path] | |
2309 | flags = fctx.flags() |
|
2308 | flags = fctx.flags() | |
2310 | mctx = context.memfilectx(repo, |
|
2309 | mctx = context.memfilectx(repo, | |
2311 | fctx.path(), fctx.data(), |
|
2310 | fctx.path(), fctx.data(), | |
2312 | islink='l' in flags, |
|
2311 | islink='l' in flags, | |
2313 | isexec='x' in flags, |
|
2312 | isexec='x' in flags, | |
2314 | copied=copied.get(path)) |
|
2313 | copied=copied.get(path)) | |
2315 | return mctx |
|
2314 | return mctx | |
2316 | except KeyError: |
|
2315 | except KeyError: | |
2317 | return None |
|
2316 | return None | |
2318 | else: |
|
2317 | else: | |
2319 | ui.note(_('copying changeset %s to %s\n') % (old, base)) |
|
2318 | ui.note(_('copying changeset %s to %s\n') % (old, base)) | |
2320 |
|
2319 | |||
2321 | # Use version of files as in the old cset |
|
2320 | # Use version of files as in the old cset | |
2322 | def filectxfn(repo, ctx_, path): |
|
2321 | def filectxfn(repo, ctx_, path): | |
2323 | try: |
|
2322 | try: | |
2324 | return old.filectx(path) |
|
2323 | return old.filectx(path) | |
2325 | except KeyError: |
|
2324 | except KeyError: | |
2326 | return None |
|
2325 | return None | |
2327 |
|
2326 | |||
2328 | user = opts.get('user') or old.user() |
|
2327 | user = opts.get('user') or old.user() | |
2329 | date = opts.get('date') or old.date() |
|
2328 | date = opts.get('date') or old.date() | |
2330 | editform = mergeeditform(old, 'commit.amend') |
|
2329 | editform = mergeeditform(old, 'commit.amend') | |
2331 | editor = getcommiteditor(editform=editform, **opts) |
|
2330 | editor = getcommiteditor(editform=editform, **opts) | |
2332 | if not message: |
|
2331 | if not message: | |
2333 | editor = getcommiteditor(edit=True, editform=editform) |
|
2332 | editor = getcommiteditor(edit=True, editform=editform) | |
2334 | message = old.description() |
|
2333 | message = old.description() | |
2335 |
|
2334 | |||
2336 | pureextra = extra.copy() |
|
2335 | pureextra = extra.copy() | |
2337 | extra['amend_source'] = old.hex() |
|
2336 | extra['amend_source'] = old.hex() | |
2338 |
|
2337 | |||
2339 | new = context.memctx(repo, |
|
2338 | new = context.memctx(repo, | |
2340 | parents=[base.node(), old.p2().node()], |
|
2339 | parents=[base.node(), old.p2().node()], | |
2341 | text=message, |
|
2340 | text=message, | |
2342 | files=files, |
|
2341 | files=files, | |
2343 | filectxfn=filectxfn, |
|
2342 | filectxfn=filectxfn, | |
2344 | user=user, |
|
2343 | user=user, | |
2345 | date=date, |
|
2344 | date=date, | |
2346 | extra=extra, |
|
2345 | extra=extra, | |
2347 | editor=editor) |
|
2346 | editor=editor) | |
2348 |
|
2347 | |||
2349 | newdesc = changelog.stripdesc(new.description()) |
|
2348 | newdesc = changelog.stripdesc(new.description()) | |
2350 | if ((not node) |
|
2349 | if ((not node) | |
2351 | and newdesc == old.description() |
|
2350 | and newdesc == old.description() | |
2352 | and user == old.user() |
|
2351 | and user == old.user() | |
2353 | and date == old.date() |
|
2352 | and date == old.date() | |
2354 | and pureextra == old.extra()): |
|
2353 | and pureextra == old.extra()): | |
2355 | # nothing changed. continuing here would create a new node |
|
2354 | # nothing changed. continuing here would create a new node | |
2356 | # anyway because of the amend_source noise. |
|
2355 | # anyway because of the amend_source noise. | |
2357 | # |
|
2356 | # | |
2358 | # This not what we expect from amend. |
|
2357 | # This not what we expect from amend. | |
2359 | return old.node() |
|
2358 | return old.node() | |
2360 |
|
2359 | |||
2361 | ph = repo.ui.config('phases', 'new-commit', phases.draft) |
|
2360 | ph = repo.ui.config('phases', 'new-commit', phases.draft) | |
2362 | try: |
|
2361 | try: | |
2363 | if opts.get('secret'): |
|
2362 | if opts.get('secret'): | |
2364 | commitphase = 'secret' |
|
2363 | commitphase = 'secret' | |
2365 | else: |
|
2364 | else: | |
2366 | commitphase = old.phase() |
|
2365 | commitphase = old.phase() | |
2367 | repo.ui.setconfig('phases', 'new-commit', commitphase, 'amend') |
|
2366 | repo.ui.setconfig('phases', 'new-commit', commitphase, 'amend') | |
2368 | newid = repo.commitctx(new) |
|
2367 | newid = repo.commitctx(new) | |
2369 | finally: |
|
2368 | finally: | |
2370 | repo.ui.setconfig('phases', 'new-commit', ph, 'amend') |
|
2369 | repo.ui.setconfig('phases', 'new-commit', ph, 'amend') | |
2371 | if newid != old.node(): |
|
2370 | if newid != old.node(): | |
2372 | # Reroute the working copy parent to the new changeset |
|
2371 | # Reroute the working copy parent to the new changeset | |
2373 | repo.setparents(newid, nullid) |
|
2372 | repo.setparents(newid, nullid) | |
2374 |
|
2373 | |||
2375 | # Move bookmarks from old parent to amend commit |
|
2374 | # Move bookmarks from old parent to amend commit | |
2376 | bms = repo.nodebookmarks(old.node()) |
|
2375 | bms = repo.nodebookmarks(old.node()) | |
2377 | if bms: |
|
2376 | if bms: | |
2378 | marks = repo._bookmarks |
|
2377 | marks = repo._bookmarks | |
2379 | for bm in bms: |
|
2378 | for bm in bms: | |
2380 | marks[bm] = newid |
|
2379 | marks[bm] = newid | |
2381 | marks.write() |
|
2380 | marks.write() | |
2382 | #commit the whole amend process |
|
2381 | #commit the whole amend process | |
2383 | createmarkers = obsolete.isenabled(repo, obsolete.createmarkersopt) |
|
2382 | createmarkers = obsolete.isenabled(repo, obsolete.createmarkersopt) | |
2384 | if createmarkers and newid != old.node(): |
|
2383 | if createmarkers and newid != old.node(): | |
2385 | # mark the new changeset as successor of the rewritten one |
|
2384 | # mark the new changeset as successor of the rewritten one | |
2386 | new = repo[newid] |
|
2385 | new = repo[newid] | |
2387 | obs = [(old, (new,))] |
|
2386 | obs = [(old, (new,))] | |
2388 | if node: |
|
2387 | if node: | |
2389 | obs.append((ctx, ())) |
|
2388 | obs.append((ctx, ())) | |
2390 |
|
2389 | |||
2391 | obsolete.createmarkers(repo, obs) |
|
2390 | obsolete.createmarkers(repo, obs) | |
2392 | tr.close() |
|
2391 | tr.close() | |
2393 | finally: |
|
2392 | finally: | |
2394 | tr.release() |
|
2393 | tr.release() | |
2395 | if not createmarkers and newid != old.node(): |
|
2394 | if not createmarkers and newid != old.node(): | |
2396 | # Strip the intermediate commit (if there was one) and the amended |
|
2395 | # Strip the intermediate commit (if there was one) and the amended | |
2397 | # commit |
|
2396 | # commit | |
2398 | if node: |
|
2397 | if node: | |
2399 | ui.note(_('stripping intermediate changeset %s\n') % ctx) |
|
2398 | ui.note(_('stripping intermediate changeset %s\n') % ctx) | |
2400 | ui.note(_('stripping amended changeset %s\n') % old) |
|
2399 | ui.note(_('stripping amended changeset %s\n') % old) | |
2401 | repair.strip(ui, repo, old.node(), topic='amend-backup') |
|
2400 | repair.strip(ui, repo, old.node(), topic='amend-backup') | |
2402 | finally: |
|
2401 | finally: | |
2403 | if newid is None: |
|
2402 | if newid is None: | |
2404 | repo.dirstate.invalidate() |
|
2403 | repo.dirstate.invalidate() | |
2405 | lockmod.release(lock, wlock) |
|
2404 | lockmod.release(lock, wlock) | |
2406 | return newid |
|
2405 | return newid | |
2407 |
|
2406 | |||
2408 | def commiteditor(repo, ctx, subs, editform=''): |
|
2407 | def commiteditor(repo, ctx, subs, editform=''): | |
2409 | if ctx.description(): |
|
2408 | if ctx.description(): | |
2410 | return ctx.description() |
|
2409 | return ctx.description() | |
2411 | return commitforceeditor(repo, ctx, subs, editform=editform) |
|
2410 | return commitforceeditor(repo, ctx, subs, editform=editform) | |
2412 |
|
2411 | |||
2413 | def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None, |
|
2412 | def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None, | |
2414 | editform=''): |
|
2413 | editform=''): | |
2415 | if not extramsg: |
|
2414 | if not extramsg: | |
2416 | extramsg = _("Leave message empty to abort commit.") |
|
2415 | extramsg = _("Leave message empty to abort commit.") | |
2417 |
|
2416 | |||
2418 | forms = [e for e in editform.split('.') if e] |
|
2417 | forms = [e for e in editform.split('.') if e] | |
2419 | forms.insert(0, 'changeset') |
|
2418 | forms.insert(0, 'changeset') | |
2420 | while forms: |
|
2419 | while forms: | |
2421 | tmpl = repo.ui.config('committemplate', '.'.join(forms)) |
|
2420 | tmpl = repo.ui.config('committemplate', '.'.join(forms)) | |
2422 | if tmpl: |
|
2421 | if tmpl: | |
2423 | committext = buildcommittemplate(repo, ctx, subs, extramsg, tmpl) |
|
2422 | committext = buildcommittemplate(repo, ctx, subs, extramsg, tmpl) | |
2424 | break |
|
2423 | break | |
2425 | forms.pop() |
|
2424 | forms.pop() | |
2426 | else: |
|
2425 | else: | |
2427 | committext = buildcommittext(repo, ctx, subs, extramsg) |
|
2426 | committext = buildcommittext(repo, ctx, subs, extramsg) | |
2428 |
|
2427 | |||
2429 | # run editor in the repository root |
|
2428 | # run editor in the repository root | |
2430 | olddir = os.getcwd() |
|
2429 | olddir = os.getcwd() | |
2431 | os.chdir(repo.root) |
|
2430 | os.chdir(repo.root) | |
2432 | text = repo.ui.edit(committext, ctx.user(), ctx.extra(), editform=editform) |
|
2431 | text = repo.ui.edit(committext, ctx.user(), ctx.extra(), editform=editform) | |
2433 | text = re.sub("(?m)^HG:.*(\n|$)", "", text) |
|
2432 | text = re.sub("(?m)^HG:.*(\n|$)", "", text) | |
2434 | os.chdir(olddir) |
|
2433 | os.chdir(olddir) | |
2435 |
|
2434 | |||
2436 | if finishdesc: |
|
2435 | if finishdesc: | |
2437 | text = finishdesc(text) |
|
2436 | text = finishdesc(text) | |
2438 | if not text.strip(): |
|
2437 | if not text.strip(): | |
2439 | raise util.Abort(_("empty commit message")) |
|
2438 | raise util.Abort(_("empty commit message")) | |
2440 |
|
2439 | |||
2441 | return text |
|
2440 | return text | |
2442 |
|
2441 | |||
2443 | def buildcommittemplate(repo, ctx, subs, extramsg, tmpl): |
|
2442 | def buildcommittemplate(repo, ctx, subs, extramsg, tmpl): | |
2444 | ui = repo.ui |
|
2443 | ui = repo.ui | |
2445 | tmpl, mapfile = gettemplate(ui, tmpl, None) |
|
2444 | tmpl, mapfile = gettemplate(ui, tmpl, None) | |
2446 |
|
2445 | |||
2447 | try: |
|
2446 | try: | |
2448 | t = changeset_templater(ui, repo, None, {}, tmpl, mapfile, False) |
|
2447 | t = changeset_templater(ui, repo, None, {}, tmpl, mapfile, False) | |
2449 | except SyntaxError, inst: |
|
2448 | except SyntaxError, inst: | |
2450 | raise util.Abort(inst.args[0]) |
|
2449 | raise util.Abort(inst.args[0]) | |
2451 |
|
2450 | |||
2452 | for k, v in repo.ui.configitems('committemplate'): |
|
2451 | for k, v in repo.ui.configitems('committemplate'): | |
2453 | if k != 'changeset': |
|
2452 | if k != 'changeset': | |
2454 | t.t.cache[k] = v |
|
2453 | t.t.cache[k] = v | |
2455 |
|
2454 | |||
2456 | if not extramsg: |
|
2455 | if not extramsg: | |
2457 | extramsg = '' # ensure that extramsg is string |
|
2456 | extramsg = '' # ensure that extramsg is string | |
2458 |
|
2457 | |||
2459 | ui.pushbuffer() |
|
2458 | ui.pushbuffer() | |
2460 | t.show(ctx, extramsg=extramsg) |
|
2459 | t.show(ctx, extramsg=extramsg) | |
2461 | return ui.popbuffer() |
|
2460 | return ui.popbuffer() | |
2462 |
|
2461 | |||
2463 | def buildcommittext(repo, ctx, subs, extramsg): |
|
2462 | def buildcommittext(repo, ctx, subs, extramsg): | |
2464 | edittext = [] |
|
2463 | edittext = [] | |
2465 | modified, added, removed = ctx.modified(), ctx.added(), ctx.removed() |
|
2464 | modified, added, removed = ctx.modified(), ctx.added(), ctx.removed() | |
2466 | if ctx.description(): |
|
2465 | if ctx.description(): | |
2467 | edittext.append(ctx.description()) |
|
2466 | edittext.append(ctx.description()) | |
2468 | edittext.append("") |
|
2467 | edittext.append("") | |
2469 | edittext.append("") # Empty line between message and comments. |
|
2468 | edittext.append("") # Empty line between message and comments. | |
2470 | edittext.append(_("HG: Enter commit message." |
|
2469 | edittext.append(_("HG: Enter commit message." | |
2471 | " Lines beginning with 'HG:' are removed.")) |
|
2470 | " Lines beginning with 'HG:' are removed.")) | |
2472 | edittext.append("HG: %s" % extramsg) |
|
2471 | edittext.append("HG: %s" % extramsg) | |
2473 | edittext.append("HG: --") |
|
2472 | edittext.append("HG: --") | |
2474 | edittext.append(_("HG: user: %s") % ctx.user()) |
|
2473 | edittext.append(_("HG: user: %s") % ctx.user()) | |
2475 | if ctx.p2(): |
|
2474 | if ctx.p2(): | |
2476 | edittext.append(_("HG: branch merge")) |
|
2475 | edittext.append(_("HG: branch merge")) | |
2477 | if ctx.branch(): |
|
2476 | if ctx.branch(): | |
2478 | edittext.append(_("HG: branch '%s'") % ctx.branch()) |
|
2477 | edittext.append(_("HG: branch '%s'") % ctx.branch()) | |
2479 | if bookmarks.iscurrent(repo): |
|
2478 | if bookmarks.iscurrent(repo): | |
2480 | edittext.append(_("HG: bookmark '%s'") % repo._bookmarkcurrent) |
|
2479 | edittext.append(_("HG: bookmark '%s'") % repo._bookmarkcurrent) | |
2481 | edittext.extend([_("HG: subrepo %s") % s for s in subs]) |
|
2480 | edittext.extend([_("HG: subrepo %s") % s for s in subs]) | |
2482 | edittext.extend([_("HG: added %s") % f for f in added]) |
|
2481 | edittext.extend([_("HG: added %s") % f for f in added]) | |
2483 | edittext.extend([_("HG: changed %s") % f for f in modified]) |
|
2482 | edittext.extend([_("HG: changed %s") % f for f in modified]) | |
2484 | edittext.extend([_("HG: removed %s") % f for f in removed]) |
|
2483 | edittext.extend([_("HG: removed %s") % f for f in removed]) | |
2485 | if not added and not modified and not removed: |
|
2484 | if not added and not modified and not removed: | |
2486 | edittext.append(_("HG: no files changed")) |
|
2485 | edittext.append(_("HG: no files changed")) | |
2487 | edittext.append("") |
|
2486 | edittext.append("") | |
2488 |
|
2487 | |||
2489 | return "\n".join(edittext) |
|
2488 | return "\n".join(edittext) | |
2490 |
|
2489 | |||
2491 | def commitstatus(repo, node, branch, bheads=None, opts={}): |
|
2490 | def commitstatus(repo, node, branch, bheads=None, opts={}): | |
2492 | ctx = repo[node] |
|
2491 | ctx = repo[node] | |
2493 | parents = ctx.parents() |
|
2492 | parents = ctx.parents() | |
2494 |
|
2493 | |||
2495 | if (not opts.get('amend') and bheads and node not in bheads and not |
|
2494 | if (not opts.get('amend') and bheads and node not in bheads and not | |
2496 | [x for x in parents if x.node() in bheads and x.branch() == branch]): |
|
2495 | [x for x in parents if x.node() in bheads and x.branch() == branch]): | |
2497 | repo.ui.status(_('created new head\n')) |
|
2496 | repo.ui.status(_('created new head\n')) | |
2498 | # The message is not printed for initial roots. For the other |
|
2497 | # The message is not printed for initial roots. For the other | |
2499 | # changesets, it is printed in the following situations: |
|
2498 | # changesets, it is printed in the following situations: | |
2500 | # |
|
2499 | # | |
2501 | # Par column: for the 2 parents with ... |
|
2500 | # Par column: for the 2 parents with ... | |
2502 | # N: null or no parent |
|
2501 | # N: null or no parent | |
2503 | # B: parent is on another named branch |
|
2502 | # B: parent is on another named branch | |
2504 | # C: parent is a regular non head changeset |
|
2503 | # C: parent is a regular non head changeset | |
2505 | # H: parent was a branch head of the current branch |
|
2504 | # H: parent was a branch head of the current branch | |
2506 | # Msg column: whether we print "created new head" message |
|
2505 | # Msg column: whether we print "created new head" message | |
2507 | # In the following, it is assumed that there already exists some |
|
2506 | # In the following, it is assumed that there already exists some | |
2508 | # initial branch heads of the current branch, otherwise nothing is |
|
2507 | # initial branch heads of the current branch, otherwise nothing is | |
2509 | # printed anyway. |
|
2508 | # printed anyway. | |
2510 | # |
|
2509 | # | |
2511 | # Par Msg Comment |
|
2510 | # Par Msg Comment | |
2512 | # N N y additional topo root |
|
2511 | # N N y additional topo root | |
2513 | # |
|
2512 | # | |
2514 | # B N y additional branch root |
|
2513 | # B N y additional branch root | |
2515 | # C N y additional topo head |
|
2514 | # C N y additional topo head | |
2516 | # H N n usual case |
|
2515 | # H N n usual case | |
2517 | # |
|
2516 | # | |
2518 | # B B y weird additional branch root |
|
2517 | # B B y weird additional branch root | |
2519 | # C B y branch merge |
|
2518 | # C B y branch merge | |
2520 | # H B n merge with named branch |
|
2519 | # H B n merge with named branch | |
2521 | # |
|
2520 | # | |
2522 | # C C y additional head from merge |
|
2521 | # C C y additional head from merge | |
2523 | # C H n merge with a head |
|
2522 | # C H n merge with a head | |
2524 | # |
|
2523 | # | |
2525 | # H H n head merge: head count decreases |
|
2524 | # H H n head merge: head count decreases | |
2526 |
|
2525 | |||
2527 | if not opts.get('close_branch'): |
|
2526 | if not opts.get('close_branch'): | |
2528 | for r in parents: |
|
2527 | for r in parents: | |
2529 | if r.closesbranch() and r.branch() == branch: |
|
2528 | if r.closesbranch() and r.branch() == branch: | |
2530 | repo.ui.status(_('reopening closed branch head %d\n') % r) |
|
2529 | repo.ui.status(_('reopening closed branch head %d\n') % r) | |
2531 |
|
2530 | |||
2532 | if repo.ui.debugflag: |
|
2531 | if repo.ui.debugflag: | |
2533 | repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex())) |
|
2532 | repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex())) | |
2534 | elif repo.ui.verbose: |
|
2533 | elif repo.ui.verbose: | |
2535 | repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx)) |
|
2534 | repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx)) | |
2536 |
|
2535 | |||
2537 | def revert(ui, repo, ctx, parents, *pats, **opts): |
|
2536 | def revert(ui, repo, ctx, parents, *pats, **opts): | |
2538 | parent, p2 = parents |
|
2537 | parent, p2 = parents | |
2539 | node = ctx.node() |
|
2538 | node = ctx.node() | |
2540 |
|
2539 | |||
2541 | mf = ctx.manifest() |
|
2540 | mf = ctx.manifest() | |
2542 | if node == p2: |
|
2541 | if node == p2: | |
2543 | parent = p2 |
|
2542 | parent = p2 | |
2544 | if node == parent: |
|
2543 | if node == parent: | |
2545 | pmf = mf |
|
2544 | pmf = mf | |
2546 | else: |
|
2545 | else: | |
2547 | pmf = None |
|
2546 | pmf = None | |
2548 |
|
2547 | |||
2549 | # need all matching names in dirstate and manifest of target rev, |
|
2548 | # need all matching names in dirstate and manifest of target rev, | |
2550 | # so have to walk both. do not print errors if files exist in one |
|
2549 | # so have to walk both. do not print errors if files exist in one | |
2551 | # but not other. |
|
2550 | # but not other. | |
2552 |
|
2551 | |||
2553 | # `names` is a mapping for all elements in working copy and target revision |
|
2552 | # `names` is a mapping for all elements in working copy and target revision | |
2554 | # The mapping is in the form: |
|
2553 | # The mapping is in the form: | |
2555 | # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>) |
|
2554 | # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>) | |
2556 | names = {} |
|
2555 | names = {} | |
2557 |
|
2556 | |||
2558 | wlock = repo.wlock() |
|
2557 | wlock = repo.wlock() | |
2559 | try: |
|
2558 | try: | |
2560 | ## filling of the `names` mapping |
|
2559 | ## filling of the `names` mapping | |
2561 | # walk dirstate to fill `names` |
|
2560 | # walk dirstate to fill `names` | |
2562 |
|
2561 | |||
2563 | m = scmutil.match(repo[None], pats, opts) |
|
2562 | m = scmutil.match(repo[None], pats, opts) | |
2564 | if not m.always() or node != parent: |
|
2563 | if not m.always() or node != parent: | |
2565 | m.bad = lambda x, y: False |
|
2564 | m.bad = lambda x, y: False | |
2566 | for abs in repo.walk(m): |
|
2565 | for abs in repo.walk(m): | |
2567 | names[abs] = m.rel(abs), m.exact(abs) |
|
2566 | names[abs] = m.rel(abs), m.exact(abs) | |
2568 |
|
2567 | |||
2569 | # walk target manifest to fill `names` |
|
2568 | # walk target manifest to fill `names` | |
2570 |
|
2569 | |||
2571 | def badfn(path, msg): |
|
2570 | def badfn(path, msg): | |
2572 | if path in names: |
|
2571 | if path in names: | |
2573 | return |
|
2572 | return | |
2574 | if path in ctx.substate: |
|
2573 | if path in ctx.substate: | |
2575 | return |
|
2574 | return | |
2576 | path_ = path + '/' |
|
2575 | path_ = path + '/' | |
2577 | for f in names: |
|
2576 | for f in names: | |
2578 | if f.startswith(path_): |
|
2577 | if f.startswith(path_): | |
2579 | return |
|
2578 | return | |
2580 | ui.warn("%s: %s\n" % (m.rel(path), msg)) |
|
2579 | ui.warn("%s: %s\n" % (m.rel(path), msg)) | |
2581 |
|
2580 | |||
2582 | m = scmutil.match(ctx, pats, opts) |
|
2581 | m = scmutil.match(ctx, pats, opts) | |
2583 | m.bad = badfn |
|
2582 | m.bad = badfn | |
2584 | for abs in ctx.walk(m): |
|
2583 | for abs in ctx.walk(m): | |
2585 | if abs not in names: |
|
2584 | if abs not in names: | |
2586 | names[abs] = m.rel(abs), m.exact(abs) |
|
2585 | names[abs] = m.rel(abs), m.exact(abs) | |
2587 |
|
2586 | |||
2588 | # Find status of all file in `names`. |
|
2587 | # Find status of all file in `names`. | |
2589 | m = scmutil.matchfiles(repo, names) |
|
2588 | m = scmutil.matchfiles(repo, names) | |
2590 |
|
2589 | |||
2591 | changes = repo.status(node1=node, match=m, |
|
2590 | changes = repo.status(node1=node, match=m, | |
2592 | unknown=True, ignored=True, clean=True) |
|
2591 | unknown=True, ignored=True, clean=True) | |
2593 | else: |
|
2592 | else: | |
2594 | changes = repo.status(match=m) |
|
2593 | changes = repo.status(match=m) | |
2595 | for kind in changes: |
|
2594 | for kind in changes: | |
2596 | for abs in kind: |
|
2595 | for abs in kind: | |
2597 | names[abs] = m.rel(abs), m.exact(abs) |
|
2596 | names[abs] = m.rel(abs), m.exact(abs) | |
2598 |
|
2597 | |||
2599 | m = scmutil.matchfiles(repo, names) |
|
2598 | m = scmutil.matchfiles(repo, names) | |
2600 |
|
2599 | |||
2601 | modified = set(changes.modified) |
|
2600 | modified = set(changes.modified) | |
2602 | added = set(changes.added) |
|
2601 | added = set(changes.added) | |
2603 | removed = set(changes.removed) |
|
2602 | removed = set(changes.removed) | |
2604 | _deleted = set(changes.deleted) |
|
2603 | _deleted = set(changes.deleted) | |
2605 | unknown = set(changes.unknown) |
|
2604 | unknown = set(changes.unknown) | |
2606 | unknown.update(changes.ignored) |
|
2605 | unknown.update(changes.ignored) | |
2607 | clean = set(changes.clean) |
|
2606 | clean = set(changes.clean) | |
2608 | modadded = set() |
|
2607 | modadded = set() | |
2609 |
|
2608 | |||
2610 | # split between files known in target manifest and the others |
|
2609 | # split between files known in target manifest and the others | |
2611 | smf = set(mf) |
|
2610 | smf = set(mf) | |
2612 |
|
2611 | |||
2613 | # determine the exact nature of the deleted changesets |
|
2612 | # determine the exact nature of the deleted changesets | |
2614 | deladded = _deleted - smf |
|
2613 | deladded = _deleted - smf | |
2615 | deleted = _deleted - deladded |
|
2614 | deleted = _deleted - deladded | |
2616 |
|
2615 | |||
2617 | # We need to account for the state of file in the dirstate. |
|
2616 | # We need to account for the state of file in the dirstate. | |
2618 | # |
|
2617 | # | |
2619 | # Even, when we revert against something else than parent. This will |
|
2618 | # Even, when we revert against something else than parent. This will | |
2620 | # slightly alter the behavior of revert (doing back up or not, delete |
|
2619 | # slightly alter the behavior of revert (doing back up or not, delete | |
2621 | # or just forget etc). |
|
2620 | # or just forget etc). | |
2622 | if parent == node: |
|
2621 | if parent == node: | |
2623 | dsmodified = modified |
|
2622 | dsmodified = modified | |
2624 | dsadded = added |
|
2623 | dsadded = added | |
2625 | dsremoved = removed |
|
2624 | dsremoved = removed | |
2626 | # store all local modifications, useful later for rename detection |
|
2625 | # store all local modifications, useful later for rename detection | |
2627 | localchanges = dsmodified | dsadded |
|
2626 | localchanges = dsmodified | dsadded | |
2628 | modified, added, removed = set(), set(), set() |
|
2627 | modified, added, removed = set(), set(), set() | |
2629 | else: |
|
2628 | else: | |
2630 | changes = repo.status(node1=parent, match=m) |
|
2629 | changes = repo.status(node1=parent, match=m) | |
2631 | dsmodified = set(changes.modified) |
|
2630 | dsmodified = set(changes.modified) | |
2632 | dsadded = set(changes.added) |
|
2631 | dsadded = set(changes.added) | |
2633 | dsremoved = set(changes.removed) |
|
2632 | dsremoved = set(changes.removed) | |
2634 | # store all local modifications, useful later for rename detection |
|
2633 | # store all local modifications, useful later for rename detection | |
2635 | localchanges = dsmodified | dsadded |
|
2634 | localchanges = dsmodified | dsadded | |
2636 |
|
2635 | |||
2637 | # only take into account for removes between wc and target |
|
2636 | # only take into account for removes between wc and target | |
2638 | clean |= dsremoved - removed |
|
2637 | clean |= dsremoved - removed | |
2639 | dsremoved &= removed |
|
2638 | dsremoved &= removed | |
2640 | # distinct between dirstate remove and other |
|
2639 | # distinct between dirstate remove and other | |
2641 | removed -= dsremoved |
|
2640 | removed -= dsremoved | |
2642 |
|
2641 | |||
2643 | modadded = added & dsmodified |
|
2642 | modadded = added & dsmodified | |
2644 | added -= modadded |
|
2643 | added -= modadded | |
2645 |
|
2644 | |||
2646 | # tell newly modified apart. |
|
2645 | # tell newly modified apart. | |
2647 | dsmodified &= modified |
|
2646 | dsmodified &= modified | |
2648 | dsmodified |= modified & dsadded # dirstate added may needs backup |
|
2647 | dsmodified |= modified & dsadded # dirstate added may needs backup | |
2649 | modified -= dsmodified |
|
2648 | modified -= dsmodified | |
2650 |
|
2649 | |||
2651 | # We need to wait for some post-processing to update this set |
|
2650 | # We need to wait for some post-processing to update this set | |
2652 | # before making the distinction. The dirstate will be used for |
|
2651 | # before making the distinction. The dirstate will be used for | |
2653 | # that purpose. |
|
2652 | # that purpose. | |
2654 | dsadded = added |
|
2653 | dsadded = added | |
2655 |
|
2654 | |||
2656 | # in case of merge, files that are actually added can be reported as |
|
2655 | # in case of merge, files that are actually added can be reported as | |
2657 | # modified, we need to post process the result |
|
2656 | # modified, we need to post process the result | |
2658 | if p2 != nullid: |
|
2657 | if p2 != nullid: | |
2659 | if pmf is None: |
|
2658 | if pmf is None: | |
2660 | # only need parent manifest in the merge case, |
|
2659 | # only need parent manifest in the merge case, | |
2661 | # so do not read by default |
|
2660 | # so do not read by default | |
2662 | pmf = repo[parent].manifest() |
|
2661 | pmf = repo[parent].manifest() | |
2663 | mergeadd = dsmodified - set(pmf) |
|
2662 | mergeadd = dsmodified - set(pmf) | |
2664 | dsadded |= mergeadd |
|
2663 | dsadded |= mergeadd | |
2665 | dsmodified -= mergeadd |
|
2664 | dsmodified -= mergeadd | |
2666 |
|
2665 | |||
2667 | # if f is a rename, update `names` to also revert the source |
|
2666 | # if f is a rename, update `names` to also revert the source | |
2668 | cwd = repo.getcwd() |
|
2667 | cwd = repo.getcwd() | |
2669 | for f in localchanges: |
|
2668 | for f in localchanges: | |
2670 | src = repo.dirstate.copied(f) |
|
2669 | src = repo.dirstate.copied(f) | |
2671 | # XXX should we check for rename down to target node? |
|
2670 | # XXX should we check for rename down to target node? | |
2672 | if src and src not in names and repo.dirstate[src] == 'r': |
|
2671 | if src and src not in names and repo.dirstate[src] == 'r': | |
2673 | dsremoved.add(src) |
|
2672 | dsremoved.add(src) | |
2674 | names[src] = (repo.pathto(src, cwd), True) |
|
2673 | names[src] = (repo.pathto(src, cwd), True) | |
2675 |
|
2674 | |||
2676 | # distinguish between file to forget and the other |
|
2675 | # distinguish between file to forget and the other | |
2677 | added = set() |
|
2676 | added = set() | |
2678 | for abs in dsadded: |
|
2677 | for abs in dsadded: | |
2679 | if repo.dirstate[abs] != 'a': |
|
2678 | if repo.dirstate[abs] != 'a': | |
2680 | added.add(abs) |
|
2679 | added.add(abs) | |
2681 | dsadded -= added |
|
2680 | dsadded -= added | |
2682 |
|
2681 | |||
2683 | for abs in deladded: |
|
2682 | for abs in deladded: | |
2684 | if repo.dirstate[abs] == 'a': |
|
2683 | if repo.dirstate[abs] == 'a': | |
2685 | dsadded.add(abs) |
|
2684 | dsadded.add(abs) | |
2686 | deladded -= dsadded |
|
2685 | deladded -= dsadded | |
2687 |
|
2686 | |||
2688 | # For files marked as removed, we check if an unknown file is present at |
|
2687 | # For files marked as removed, we check if an unknown file is present at | |
2689 | # the same path. If a such file exists it may need to be backed up. |
|
2688 | # the same path. If a such file exists it may need to be backed up. | |
2690 | # Making the distinction at this stage helps have simpler backup |
|
2689 | # Making the distinction at this stage helps have simpler backup | |
2691 | # logic. |
|
2690 | # logic. | |
2692 | removunk = set() |
|
2691 | removunk = set() | |
2693 | for abs in removed: |
|
2692 | for abs in removed: | |
2694 | target = repo.wjoin(abs) |
|
2693 | target = repo.wjoin(abs) | |
2695 | if os.path.lexists(target): |
|
2694 | if os.path.lexists(target): | |
2696 | removunk.add(abs) |
|
2695 | removunk.add(abs) | |
2697 | removed -= removunk |
|
2696 | removed -= removunk | |
2698 |
|
2697 | |||
2699 | dsremovunk = set() |
|
2698 | dsremovunk = set() | |
2700 | for abs in dsremoved: |
|
2699 | for abs in dsremoved: | |
2701 | target = repo.wjoin(abs) |
|
2700 | target = repo.wjoin(abs) | |
2702 | if os.path.lexists(target): |
|
2701 | if os.path.lexists(target): | |
2703 | dsremovunk.add(abs) |
|
2702 | dsremovunk.add(abs) | |
2704 | dsremoved -= dsremovunk |
|
2703 | dsremoved -= dsremovunk | |
2705 |
|
2704 | |||
2706 | # action to be actually performed by revert |
|
2705 | # action to be actually performed by revert | |
2707 | # (<list of file>, message>) tuple |
|
2706 | # (<list of file>, message>) tuple | |
2708 | actions = {'revert': ([], _('reverting %s\n')), |
|
2707 | actions = {'revert': ([], _('reverting %s\n')), | |
2709 | 'add': ([], _('adding %s\n')), |
|
2708 | 'add': ([], _('adding %s\n')), | |
2710 | 'remove': ([], _('removing %s\n')), |
|
2709 | 'remove': ([], _('removing %s\n')), | |
2711 | 'drop': ([], _('removing %s\n')), |
|
2710 | 'drop': ([], _('removing %s\n')), | |
2712 | 'forget': ([], _('forgetting %s\n')), |
|
2711 | 'forget': ([], _('forgetting %s\n')), | |
2713 | 'undelete': ([], _('undeleting %s\n')), |
|
2712 | 'undelete': ([], _('undeleting %s\n')), | |
2714 | 'noop': (None, _('no changes needed to %s\n')), |
|
2713 | 'noop': (None, _('no changes needed to %s\n')), | |
2715 | 'unknown': (None, _('file not managed: %s\n')), |
|
2714 | 'unknown': (None, _('file not managed: %s\n')), | |
2716 | } |
|
2715 | } | |
2717 |
|
2716 | |||
2718 | # "constant" that convey the backup strategy. |
|
2717 | # "constant" that convey the backup strategy. | |
2719 | # All set to `discard` if `no-backup` is set do avoid checking |
|
2718 | # All set to `discard` if `no-backup` is set do avoid checking | |
2720 | # no_backup lower in the code. |
|
2719 | # no_backup lower in the code. | |
2721 | # These values are ordered for comparison purposes |
|
2720 | # These values are ordered for comparison purposes | |
2722 | backup = 2 # unconditionally do backup |
|
2721 | backup = 2 # unconditionally do backup | |
2723 | check = 1 # check if the existing file differs from target |
|
2722 | check = 1 # check if the existing file differs from target | |
2724 | discard = 0 # never do backup |
|
2723 | discard = 0 # never do backup | |
2725 | if opts.get('no_backup'): |
|
2724 | if opts.get('no_backup'): | |
2726 | backup = check = discard |
|
2725 | backup = check = discard | |
2727 |
|
2726 | |||
2728 | backupanddel = actions['remove'] |
|
2727 | backupanddel = actions['remove'] | |
2729 | if not opts.get('no_backup'): |
|
2728 | if not opts.get('no_backup'): | |
2730 | backupanddel = actions['drop'] |
|
2729 | backupanddel = actions['drop'] | |
2731 |
|
2730 | |||
2732 | disptable = ( |
|
2731 | disptable = ( | |
2733 | # dispatch table: |
|
2732 | # dispatch table: | |
2734 | # file state |
|
2733 | # file state | |
2735 | # action |
|
2734 | # action | |
2736 | # make backup |
|
2735 | # make backup | |
2737 |
|
2736 | |||
2738 | ## Sets that results that will change file on disk |
|
2737 | ## Sets that results that will change file on disk | |
2739 | # Modified compared to target, no local change |
|
2738 | # Modified compared to target, no local change | |
2740 | (modified, actions['revert'], discard), |
|
2739 | (modified, actions['revert'], discard), | |
2741 | # Modified compared to target, but local file is deleted |
|
2740 | # Modified compared to target, but local file is deleted | |
2742 | (deleted, actions['revert'], discard), |
|
2741 | (deleted, actions['revert'], discard), | |
2743 | # Modified compared to target, local change |
|
2742 | # Modified compared to target, local change | |
2744 | (dsmodified, actions['revert'], backup), |
|
2743 | (dsmodified, actions['revert'], backup), | |
2745 | # Added since target |
|
2744 | # Added since target | |
2746 | (added, actions['remove'], discard), |
|
2745 | (added, actions['remove'], discard), | |
2747 | # Added in working directory |
|
2746 | # Added in working directory | |
2748 | (dsadded, actions['forget'], discard), |
|
2747 | (dsadded, actions['forget'], discard), | |
2749 | # Added since target, have local modification |
|
2748 | # Added since target, have local modification | |
2750 | (modadded, backupanddel, backup), |
|
2749 | (modadded, backupanddel, backup), | |
2751 | # Added since target but file is missing in working directory |
|
2750 | # Added since target but file is missing in working directory | |
2752 | (deladded, actions['drop'], discard), |
|
2751 | (deladded, actions['drop'], discard), | |
2753 | # Removed since target, before working copy parent |
|
2752 | # Removed since target, before working copy parent | |
2754 | (removed, actions['add'], discard), |
|
2753 | (removed, actions['add'], discard), | |
2755 | # Same as `removed` but an unknown file exists at the same path |
|
2754 | # Same as `removed` but an unknown file exists at the same path | |
2756 | (removunk, actions['add'], check), |
|
2755 | (removunk, actions['add'], check), | |
2757 | # Removed since targe, marked as such in working copy parent |
|
2756 | # Removed since targe, marked as such in working copy parent | |
2758 | (dsremoved, actions['undelete'], discard), |
|
2757 | (dsremoved, actions['undelete'], discard), | |
2759 | # Same as `dsremoved` but an unknown file exists at the same path |
|
2758 | # Same as `dsremoved` but an unknown file exists at the same path | |
2760 | (dsremovunk, actions['undelete'], check), |
|
2759 | (dsremovunk, actions['undelete'], check), | |
2761 | ## the following sets does not result in any file changes |
|
2760 | ## the following sets does not result in any file changes | |
2762 | # File with no modification |
|
2761 | # File with no modification | |
2763 | (clean, actions['noop'], discard), |
|
2762 | (clean, actions['noop'], discard), | |
2764 | # Existing file, not tracked anywhere |
|
2763 | # Existing file, not tracked anywhere | |
2765 | (unknown, actions['unknown'], discard), |
|
2764 | (unknown, actions['unknown'], discard), | |
2766 | ) |
|
2765 | ) | |
2767 |
|
2766 | |||
2768 | wctx = repo[None] |
|
2767 | wctx = repo[None] | |
2769 | for abs, (rel, exact) in sorted(names.items()): |
|
2768 | for abs, (rel, exact) in sorted(names.items()): | |
2770 | # target file to be touch on disk (relative to cwd) |
|
2769 | # target file to be touch on disk (relative to cwd) | |
2771 | target = repo.wjoin(abs) |
|
2770 | target = repo.wjoin(abs) | |
2772 | # search the entry in the dispatch table. |
|
2771 | # search the entry in the dispatch table. | |
2773 | # if the file is in any of these sets, it was touched in the working |
|
2772 | # if the file is in any of these sets, it was touched in the working | |
2774 | # directory parent and we are sure it needs to be reverted. |
|
2773 | # directory parent and we are sure it needs to be reverted. | |
2775 | for table, (xlist, msg), dobackup in disptable: |
|
2774 | for table, (xlist, msg), dobackup in disptable: | |
2776 | if abs not in table: |
|
2775 | if abs not in table: | |
2777 | continue |
|
2776 | continue | |
2778 | if xlist is not None: |
|
2777 | if xlist is not None: | |
2779 | xlist.append(abs) |
|
2778 | xlist.append(abs) | |
2780 | if dobackup and (backup <= dobackup |
|
2779 | if dobackup and (backup <= dobackup | |
2781 | or wctx[abs].cmp(ctx[abs])): |
|
2780 | or wctx[abs].cmp(ctx[abs])): | |
2782 | bakname = "%s.orig" % rel |
|
2781 | bakname = "%s.orig" % rel | |
2783 | ui.note(_('saving current version of %s as %s\n') % |
|
2782 | ui.note(_('saving current version of %s as %s\n') % | |
2784 | (rel, bakname)) |
|
2783 | (rel, bakname)) | |
2785 | if not opts.get('dry_run'): |
|
2784 | if not opts.get('dry_run'): | |
2786 | util.rename(target, bakname) |
|
2785 | util.rename(target, bakname) | |
2787 | if ui.verbose or not exact: |
|
2786 | if ui.verbose or not exact: | |
2788 | if not isinstance(msg, basestring): |
|
2787 | if not isinstance(msg, basestring): | |
2789 | msg = msg(abs) |
|
2788 | msg = msg(abs) | |
2790 | ui.status(msg % rel) |
|
2789 | ui.status(msg % rel) | |
2791 | elif exact: |
|
2790 | elif exact: | |
2792 | ui.warn(msg % rel) |
|
2791 | ui.warn(msg % rel) | |
2793 | break |
|
2792 | break | |
2794 |
|
2793 | |||
2795 |
|
2794 | |||
2796 | if not opts.get('dry_run'): |
|
2795 | if not opts.get('dry_run'): | |
2797 | needdata = ('revert', 'add', 'undelete') |
|
2796 | needdata = ('revert', 'add', 'undelete') | |
2798 | _revertprefetch(repo, ctx, *[actions[name][0] for name in needdata]) |
|
2797 | _revertprefetch(repo, ctx, *[actions[name][0] for name in needdata]) | |
2799 |
|
2798 | |||
2800 | _performrevert(repo, parents, ctx, actions) |
|
2799 | _performrevert(repo, parents, ctx, actions) | |
2801 |
|
2800 | |||
2802 | # get the list of subrepos that must be reverted |
|
2801 | # get the list of subrepos that must be reverted | |
2803 | subrepomatch = scmutil.match(ctx, pats, opts) |
|
2802 | subrepomatch = scmutil.match(ctx, pats, opts) | |
2804 | targetsubs = sorted(s for s in ctx.substate if subrepomatch(s)) |
|
2803 | targetsubs = sorted(s for s in ctx.substate if subrepomatch(s)) | |
2805 |
|
2804 | |||
2806 | if targetsubs: |
|
2805 | if targetsubs: | |
2807 | # Revert the subrepos on the revert list |
|
2806 | # Revert the subrepos on the revert list | |
2808 | for sub in targetsubs: |
|
2807 | for sub in targetsubs: | |
2809 | ctx.sub(sub).revert(ctx.substate[sub], *pats, **opts) |
|
2808 | ctx.sub(sub).revert(ctx.substate[sub], *pats, **opts) | |
2810 | finally: |
|
2809 | finally: | |
2811 | wlock.release() |
|
2810 | wlock.release() | |
2812 |
|
2811 | |||
2813 | def _revertprefetch(repo, ctx, *files): |
|
2812 | def _revertprefetch(repo, ctx, *files): | |
2814 | """Let extension changing the storage layer prefetch content""" |
|
2813 | """Let extension changing the storage layer prefetch content""" | |
2815 | pass |
|
2814 | pass | |
2816 |
|
2815 | |||
2817 | def _performrevert(repo, parents, ctx, actions): |
|
2816 | def _performrevert(repo, parents, ctx, actions): | |
2818 | """function that actually perform all the actions computed for revert |
|
2817 | """function that actually perform all the actions computed for revert | |
2819 |
|
2818 | |||
2820 | This is an independent function to let extension to plug in and react to |
|
2819 | This is an independent function to let extension to plug in and react to | |
2821 | the imminent revert. |
|
2820 | the imminent revert. | |
2822 |
|
2821 | |||
2823 | Make sure you have the working directory locked when calling this function. |
|
2822 | Make sure you have the working directory locked when calling this function. | |
2824 | """ |
|
2823 | """ | |
2825 | parent, p2 = parents |
|
2824 | parent, p2 = parents | |
2826 | node = ctx.node() |
|
2825 | node = ctx.node() | |
2827 | def checkout(f): |
|
2826 | def checkout(f): | |
2828 | fc = ctx[f] |
|
2827 | fc = ctx[f] | |
2829 | repo.wwrite(f, fc.data(), fc.flags()) |
|
2828 | repo.wwrite(f, fc.data(), fc.flags()) | |
2830 |
|
2829 | |||
2831 | audit_path = pathutil.pathauditor(repo.root) |
|
2830 | audit_path = pathutil.pathauditor(repo.root) | |
2832 | for f in actions['forget'][0]: |
|
2831 | for f in actions['forget'][0]: | |
2833 | repo.dirstate.drop(f) |
|
2832 | repo.dirstate.drop(f) | |
2834 | for f in actions['remove'][0]: |
|
2833 | for f in actions['remove'][0]: | |
2835 | audit_path(f) |
|
2834 | audit_path(f) | |
2836 | util.unlinkpath(repo.wjoin(f)) |
|
2835 | util.unlinkpath(repo.wjoin(f)) | |
2837 | repo.dirstate.remove(f) |
|
2836 | repo.dirstate.remove(f) | |
2838 | for f in actions['drop'][0]: |
|
2837 | for f in actions['drop'][0]: | |
2839 | audit_path(f) |
|
2838 | audit_path(f) | |
2840 | repo.dirstate.remove(f) |
|
2839 | repo.dirstate.remove(f) | |
2841 |
|
2840 | |||
2842 | normal = None |
|
2841 | normal = None | |
2843 | if node == parent: |
|
2842 | if node == parent: | |
2844 | # We're reverting to our parent. If possible, we'd like status |
|
2843 | # We're reverting to our parent. If possible, we'd like status | |
2845 | # to report the file as clean. We have to use normallookup for |
|
2844 | # to report the file as clean. We have to use normallookup for | |
2846 | # merges to avoid losing information about merged/dirty files. |
|
2845 | # merges to avoid losing information about merged/dirty files. | |
2847 | if p2 != nullid: |
|
2846 | if p2 != nullid: | |
2848 | normal = repo.dirstate.normallookup |
|
2847 | normal = repo.dirstate.normallookup | |
2849 | else: |
|
2848 | else: | |
2850 | normal = repo.dirstate.normal |
|
2849 | normal = repo.dirstate.normal | |
2851 | for f in actions['revert'][0]: |
|
2850 | for f in actions['revert'][0]: | |
2852 | checkout(f) |
|
2851 | checkout(f) | |
2853 | if normal: |
|
2852 | if normal: | |
2854 | normal(f) |
|
2853 | normal(f) | |
2855 |
|
2854 | |||
2856 | for f in actions['add'][0]: |
|
2855 | for f in actions['add'][0]: | |
2857 | checkout(f) |
|
2856 | checkout(f) | |
2858 | repo.dirstate.add(f) |
|
2857 | repo.dirstate.add(f) | |
2859 |
|
2858 | |||
2860 | normal = repo.dirstate.normallookup |
|
2859 | normal = repo.dirstate.normallookup | |
2861 | if node == parent and p2 == nullid: |
|
2860 | if node == parent and p2 == nullid: | |
2862 | normal = repo.dirstate.normal |
|
2861 | normal = repo.dirstate.normal | |
2863 | for f in actions['undelete'][0]: |
|
2862 | for f in actions['undelete'][0]: | |
2864 | checkout(f) |
|
2863 | checkout(f) | |
2865 | normal(f) |
|
2864 | normal(f) | |
2866 |
|
2865 | |||
2867 | copied = copies.pathcopies(repo[parent], ctx) |
|
2866 | copied = copies.pathcopies(repo[parent], ctx) | |
2868 |
|
2867 | |||
2869 | for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]: |
|
2868 | for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]: | |
2870 | if f in copied: |
|
2869 | if f in copied: | |
2871 | repo.dirstate.copy(copied[f], f) |
|
2870 | repo.dirstate.copy(copied[f], f) | |
2872 |
|
2871 | |||
2873 | def command(table): |
|
2872 | def command(table): | |
2874 | """Returns a function object to be used as a decorator for making commands. |
|
2873 | """Returns a function object to be used as a decorator for making commands. | |
2875 |
|
2874 | |||
2876 | This function receives a command table as its argument. The table should |
|
2875 | This function receives a command table as its argument. The table should | |
2877 | be a dict. |
|
2876 | be a dict. | |
2878 |
|
2877 | |||
2879 | The returned function can be used as a decorator for adding commands |
|
2878 | The returned function can be used as a decorator for adding commands | |
2880 | to that command table. This function accepts multiple arguments to define |
|
2879 | to that command table. This function accepts multiple arguments to define | |
2881 | a command. |
|
2880 | a command. | |
2882 |
|
2881 | |||
2883 | The first argument is the command name. |
|
2882 | The first argument is the command name. | |
2884 |
|
2883 | |||
2885 | The options argument is an iterable of tuples defining command arguments. |
|
2884 | The options argument is an iterable of tuples defining command arguments. | |
2886 | See ``mercurial.fancyopts.fancyopts()`` for the format of each tuple. |
|
2885 | See ``mercurial.fancyopts.fancyopts()`` for the format of each tuple. | |
2887 |
|
2886 | |||
2888 | The synopsis argument defines a short, one line summary of how to use the |
|
2887 | The synopsis argument defines a short, one line summary of how to use the | |
2889 | command. This shows up in the help output. |
|
2888 | command. This shows up in the help output. | |
2890 |
|
2889 | |||
2891 | The norepo argument defines whether the command does not require a |
|
2890 | The norepo argument defines whether the command does not require a | |
2892 | local repository. Most commands operate against a repository, thus the |
|
2891 | local repository. Most commands operate against a repository, thus the | |
2893 | default is False. |
|
2892 | default is False. | |
2894 |
|
2893 | |||
2895 | The optionalrepo argument defines whether the command optionally requires |
|
2894 | The optionalrepo argument defines whether the command optionally requires | |
2896 | a local repository. |
|
2895 | a local repository. | |
2897 |
|
2896 | |||
2898 | The inferrepo argument defines whether to try to find a repository from the |
|
2897 | The inferrepo argument defines whether to try to find a repository from the | |
2899 | command line arguments. If True, arguments will be examined for potential |
|
2898 | command line arguments. If True, arguments will be examined for potential | |
2900 | repository locations. See ``findrepo()``. If a repository is found, it |
|
2899 | repository locations. See ``findrepo()``. If a repository is found, it | |
2901 | will be used. |
|
2900 | will be used. | |
2902 | """ |
|
2901 | """ | |
2903 | def cmd(name, options=(), synopsis=None, norepo=False, optionalrepo=False, |
|
2902 | def cmd(name, options=(), synopsis=None, norepo=False, optionalrepo=False, | |
2904 | inferrepo=False): |
|
2903 | inferrepo=False): | |
2905 | def decorator(func): |
|
2904 | def decorator(func): | |
2906 | if synopsis: |
|
2905 | if synopsis: | |
2907 | table[name] = func, list(options), synopsis |
|
2906 | table[name] = func, list(options), synopsis | |
2908 | else: |
|
2907 | else: | |
2909 | table[name] = func, list(options) |
|
2908 | table[name] = func, list(options) | |
2910 |
|
2909 | |||
2911 | if norepo: |
|
2910 | if norepo: | |
2912 | # Avoid import cycle. |
|
2911 | # Avoid import cycle. | |
2913 | import commands |
|
2912 | import commands | |
2914 | commands.norepo += ' %s' % ' '.join(parsealiases(name)) |
|
2913 | commands.norepo += ' %s' % ' '.join(parsealiases(name)) | |
2915 |
|
2914 | |||
2916 | if optionalrepo: |
|
2915 | if optionalrepo: | |
2917 | import commands |
|
2916 | import commands | |
2918 | commands.optionalrepo += ' %s' % ' '.join(parsealiases(name)) |
|
2917 | commands.optionalrepo += ' %s' % ' '.join(parsealiases(name)) | |
2919 |
|
2918 | |||
2920 | if inferrepo: |
|
2919 | if inferrepo: | |
2921 | import commands |
|
2920 | import commands | |
2922 | commands.inferrepo += ' %s' % ' '.join(parsealiases(name)) |
|
2921 | commands.inferrepo += ' %s' % ' '.join(parsealiases(name)) | |
2923 |
|
2922 | |||
2924 | return func |
|
2923 | return func | |
2925 | return decorator |
|
2924 | return decorator | |
2926 |
|
2925 | |||
2927 | return cmd |
|
2926 | return cmd | |
2928 |
|
2927 | |||
2929 | # a list of (ui, repo, otherpeer, opts, missing) functions called by |
|
2928 | # a list of (ui, repo, otherpeer, opts, missing) functions called by | |
2930 | # commands.outgoing. "missing" is "missing" of the result of |
|
2929 | # commands.outgoing. "missing" is "missing" of the result of | |
2931 | # "findcommonoutgoing()" |
|
2930 | # "findcommonoutgoing()" | |
2932 | outgoinghooks = util.hooks() |
|
2931 | outgoinghooks = util.hooks() | |
2933 |
|
2932 | |||
2934 | # a list of (ui, repo) functions called by commands.summary |
|
2933 | # a list of (ui, repo) functions called by commands.summary | |
2935 | summaryhooks = util.hooks() |
|
2934 | summaryhooks = util.hooks() | |
2936 |
|
2935 | |||
2937 | # a list of (ui, repo, opts, changes) functions called by commands.summary. |
|
2936 | # a list of (ui, repo, opts, changes) functions called by commands.summary. | |
2938 | # |
|
2937 | # | |
2939 | # functions should return tuple of booleans below, if 'changes' is None: |
|
2938 | # functions should return tuple of booleans below, if 'changes' is None: | |
2940 | # (whether-incomings-are-needed, whether-outgoings-are-needed) |
|
2939 | # (whether-incomings-are-needed, whether-outgoings-are-needed) | |
2941 | # |
|
2940 | # | |
2942 | # otherwise, 'changes' is a tuple of tuples below: |
|
2941 | # otherwise, 'changes' is a tuple of tuples below: | |
2943 | # - (sourceurl, sourcebranch, sourcepeer, incoming) |
|
2942 | # - (sourceurl, sourcebranch, sourcepeer, incoming) | |
2944 | # - (desturl, destbranch, destpeer, outgoing) |
|
2943 | # - (desturl, destbranch, destpeer, outgoing) | |
2945 | summaryremotehooks = util.hooks() |
|
2944 | summaryremotehooks = util.hooks() | |
2946 |
|
2945 | |||
2947 | # A list of state files kept by multistep operations like graft. |
|
2946 | # A list of state files kept by multistep operations like graft. | |
2948 | # Since graft cannot be aborted, it is considered 'clearable' by update. |
|
2947 | # Since graft cannot be aborted, it is considered 'clearable' by update. | |
2949 | # note: bisect is intentionally excluded |
|
2948 | # note: bisect is intentionally excluded | |
2950 | # (state file, clearable, allowcommit, error, hint) |
|
2949 | # (state file, clearable, allowcommit, error, hint) | |
2951 | unfinishedstates = [ |
|
2950 | unfinishedstates = [ | |
2952 | ('graftstate', True, False, _('graft in progress'), |
|
2951 | ('graftstate', True, False, _('graft in progress'), | |
2953 | _("use 'hg graft --continue' or 'hg update' to abort")), |
|
2952 | _("use 'hg graft --continue' or 'hg update' to abort")), | |
2954 | ('updatestate', True, False, _('last update was interrupted'), |
|
2953 | ('updatestate', True, False, _('last update was interrupted'), | |
2955 | _("use 'hg update' to get a consistent checkout")) |
|
2954 | _("use 'hg update' to get a consistent checkout")) | |
2956 | ] |
|
2955 | ] | |
2957 |
|
2956 | |||
2958 | def checkunfinished(repo, commit=False): |
|
2957 | def checkunfinished(repo, commit=False): | |
2959 | '''Look for an unfinished multistep operation, like graft, and abort |
|
2958 | '''Look for an unfinished multistep operation, like graft, and abort | |
2960 | if found. It's probably good to check this right before |
|
2959 | if found. It's probably good to check this right before | |
2961 | bailifchanged(). |
|
2960 | bailifchanged(). | |
2962 | ''' |
|
2961 | ''' | |
2963 | for f, clearable, allowcommit, msg, hint in unfinishedstates: |
|
2962 | for f, clearable, allowcommit, msg, hint in unfinishedstates: | |
2964 | if commit and allowcommit: |
|
2963 | if commit and allowcommit: | |
2965 | continue |
|
2964 | continue | |
2966 | if repo.vfs.exists(f): |
|
2965 | if repo.vfs.exists(f): | |
2967 | raise util.Abort(msg, hint=hint) |
|
2966 | raise util.Abort(msg, hint=hint) | |
2968 |
|
2967 | |||
2969 | def clearunfinished(repo): |
|
2968 | def clearunfinished(repo): | |
2970 | '''Check for unfinished operations (as above), and clear the ones |
|
2969 | '''Check for unfinished operations (as above), and clear the ones | |
2971 | that are clearable. |
|
2970 | that are clearable. | |
2972 | ''' |
|
2971 | ''' | |
2973 | for f, clearable, allowcommit, msg, hint in unfinishedstates: |
|
2972 | for f, clearable, allowcommit, msg, hint in unfinishedstates: | |
2974 | if not clearable and repo.vfs.exists(f): |
|
2973 | if not clearable and repo.vfs.exists(f): | |
2975 | raise util.Abort(msg, hint=hint) |
|
2974 | raise util.Abort(msg, hint=hint) | |
2976 | for f, clearable, allowcommit, msg, hint in unfinishedstates: |
|
2975 | for f, clearable, allowcommit, msg, hint in unfinishedstates: | |
2977 | if clearable and repo.vfs.exists(f): |
|
2976 | if clearable and repo.vfs.exists(f): | |
2978 | util.unlink(repo.join(f)) |
|
2977 | util.unlink(repo.join(f)) |
@@ -1,164 +1,181 | |||||
1 | from i18n import _ |
|
1 | from i18n import _ | |
2 | from mercurial import util |
|
2 | from mercurial import util | |
3 | import templatekw |
|
3 | import templatekw | |
4 |
|
4 | |||
5 | def tolist(val): |
|
5 | def tolist(val): | |
6 | """ |
|
6 | """ | |
7 | a convenience method to return an empty list instead of None |
|
7 | a convenience method to return an empty list instead of None | |
8 | """ |
|
8 | """ | |
9 | if val is None: |
|
9 | if val is None: | |
10 | return [] |
|
10 | return [] | |
11 | else: |
|
11 | else: | |
12 | return [val] |
|
12 | return [val] | |
13 |
|
13 | |||
14 | class namespaces(object): |
|
14 | class namespaces(object): | |
15 | """provides an interface to register and operate on multiple namespaces. See |
|
15 | """provides an interface to register and operate on multiple namespaces. See | |
16 | the namespace class below for details on the namespace object. |
|
16 | the namespace class below for details on the namespace object. | |
17 |
|
17 | |||
18 | """ |
|
18 | """ | |
19 |
|
19 | |||
20 | _names_version = 0 |
|
20 | _names_version = 0 | |
21 |
|
21 | |||
22 | def __init__(self): |
|
22 | def __init__(self): | |
23 | self._names = util.sortdict() |
|
23 | self._names = util.sortdict() | |
24 |
|
24 | |||
25 | # we need current mercurial named objects (bookmarks, tags, and |
|
25 | # we need current mercurial named objects (bookmarks, tags, and | |
26 | # branches) to be initialized somewhere, so that place is here |
|
26 | # branches) to be initialized somewhere, so that place is here | |
27 | bmknames = lambda repo: repo._bookmarks.keys() |
|
27 | bmknames = lambda repo: repo._bookmarks.keys() | |
28 | bmknamemap = lambda repo, name: tolist(repo._bookmarks.get(name)) |
|
28 | bmknamemap = lambda repo, name: tolist(repo._bookmarks.get(name)) | |
29 | bmknodemap = lambda repo, name: repo.nodebookmarks(name) |
|
29 | bmknodemap = lambda repo, name: repo.nodebookmarks(name) | |
30 |
n = namespace("bookmarks", templatename="bookmark", |
|
30 | n = namespace("bookmarks", templatename="bookmark", | |
|
31 | # i18n: column positioning for "hg log" | |||
|
32 | logfmt=_("bookmark: %s\n"), | |||
|
33 | listnames=bmknames, | |||
31 | namemap=bmknamemap, nodemap=bmknodemap) |
|
34 | namemap=bmknamemap, nodemap=bmknodemap) | |
32 | self.addnamespace(n) |
|
35 | self.addnamespace(n) | |
33 |
|
36 | |||
34 | tagnames = lambda repo: [t for t, n in repo.tagslist()] |
|
37 | tagnames = lambda repo: [t for t, n in repo.tagslist()] | |
35 | tagnamemap = lambda repo, name: tolist(repo._tagscache.tags.get(name)) |
|
38 | tagnamemap = lambda repo, name: tolist(repo._tagscache.tags.get(name)) | |
36 | tagnodemap = lambda repo, name: repo.nodetags(name) |
|
39 | tagnodemap = lambda repo, name: repo.nodetags(name) | |
37 |
n = namespace("tags", templatename="tag", |
|
40 | n = namespace("tags", templatename="tag", | |
|
41 | # i18n: column positioning for "hg log" | |||
|
42 | logfmt=_("tag: %s\n"), | |||
|
43 | listnames=tagnames, | |||
38 | namemap=tagnamemap, nodemap=tagnodemap) |
|
44 | namemap=tagnamemap, nodemap=tagnodemap) | |
39 | self.addnamespace(n) |
|
45 | self.addnamespace(n) | |
40 |
|
46 | |||
41 | bnames = lambda repo: repo.branchmap().keys() |
|
47 | bnames = lambda repo: repo.branchmap().keys() | |
42 | bnamemap = lambda repo, name: tolist(repo.branchtip(name, True)) |
|
48 | bnamemap = lambda repo, name: tolist(repo.branchtip(name, True)) | |
43 | bnodemap = lambda repo, node: [repo[node].branch()] |
|
49 | bnodemap = lambda repo, node: [repo[node].branch()] | |
44 |
n = namespace("branches", templatename="branch", |
|
50 | n = namespace("branches", templatename="branch", | |
|
51 | # i18n: column positioning for "hg log" | |||
|
52 | logfmt=_("branch: %s\n"), | |||
|
53 | listnames=bnames, | |||
45 | namemap=bnamemap, nodemap=bnodemap) |
|
54 | namemap=bnamemap, nodemap=bnodemap) | |
46 | self.addnamespace(n) |
|
55 | self.addnamespace(n) | |
47 |
|
56 | |||
48 | def __getitem__(self, namespace): |
|
57 | def __getitem__(self, namespace): | |
49 | """returns the namespace object""" |
|
58 | """returns the namespace object""" | |
50 | return self._names[namespace] |
|
59 | return self._names[namespace] | |
51 |
|
60 | |||
52 | def __iter__(self): |
|
61 | def __iter__(self): | |
53 | return self._names.__iter__() |
|
62 | return self._names.__iter__() | |
54 |
|
63 | |||
55 | def iteritems(self): |
|
64 | def iteritems(self): | |
56 | return self._names.iteritems() |
|
65 | return self._names.iteritems() | |
57 |
|
66 | |||
58 | def addnamespace(self, namespace, order=None): |
|
67 | def addnamespace(self, namespace, order=None): | |
59 | """register a namespace |
|
68 | """register a namespace | |
60 |
|
69 | |||
61 | namespace: the name to be registered (in plural form) |
|
70 | namespace: the name to be registered (in plural form) | |
62 | order: optional argument to specify the order of namespaces |
|
71 | order: optional argument to specify the order of namespaces | |
63 | (e.g. 'branches' should be listed before 'bookmarks') |
|
72 | (e.g. 'branches' should be listed before 'bookmarks') | |
64 |
|
73 | |||
65 | """ |
|
74 | """ | |
66 | if order is not None: |
|
75 | if order is not None: | |
67 | self._names.insert(order, namespace.name, namespace) |
|
76 | self._names.insert(order, namespace.name, namespace) | |
68 | else: |
|
77 | else: | |
69 | self._names[namespace.name] = namespace |
|
78 | self._names[namespace.name] = namespace | |
70 |
|
79 | |||
71 | # we only generate a template keyword if one does not already exist |
|
80 | # we only generate a template keyword if one does not already exist | |
72 | if namespace.name not in templatekw.keywords: |
|
81 | if namespace.name not in templatekw.keywords: | |
73 | def generatekw(**args): |
|
82 | def generatekw(**args): | |
74 | return templatekw.shownames(namespace.name, **args) |
|
83 | return templatekw.shownames(namespace.name, **args) | |
75 |
|
84 | |||
76 | templatekw.keywords[namespace.name] = generatekw |
|
85 | templatekw.keywords[namespace.name] = generatekw | |
77 |
|
86 | |||
78 | def singlenode(self, repo, name): |
|
87 | def singlenode(self, repo, name): | |
79 | """ |
|
88 | """ | |
80 | Return the 'best' node for the given name. Best means the first node |
|
89 | Return the 'best' node for the given name. Best means the first node | |
81 | in the first nonempty list returned by a name-to-nodes mapping function |
|
90 | in the first nonempty list returned by a name-to-nodes mapping function | |
82 | in the defined precedence order. |
|
91 | in the defined precedence order. | |
83 |
|
92 | |||
84 | Raises a KeyError if there is no such node. |
|
93 | Raises a KeyError if there is no such node. | |
85 | """ |
|
94 | """ | |
86 | for ns, v in self._names.iteritems(): |
|
95 | for ns, v in self._names.iteritems(): | |
87 | n = v.namemap(repo, name) |
|
96 | n = v.namemap(repo, name) | |
88 | if n: |
|
97 | if n: | |
89 | # return max revision number |
|
98 | # return max revision number | |
90 | if len(n) > 1: |
|
99 | if len(n) > 1: | |
91 | cl = repo.changelog |
|
100 | cl = repo.changelog | |
92 | maxrev = max(cl.rev(node) for node in n) |
|
101 | maxrev = max(cl.rev(node) for node in n) | |
93 | return cl.node(maxrev) |
|
102 | return cl.node(maxrev) | |
94 | return n[0] |
|
103 | return n[0] | |
95 | raise KeyError(_('no such name: %s') % name) |
|
104 | raise KeyError(_('no such name: %s') % name) | |
96 |
|
105 | |||
97 | class namespace(object): |
|
106 | class namespace(object): | |
98 | """provides an interface to a namespace |
|
107 | """provides an interface to a namespace | |
99 |
|
108 | |||
100 | Namespaces are basically generic many-to-many mapping between some |
|
109 | Namespaces are basically generic many-to-many mapping between some | |
101 | (namespaced) names and nodes. The goal here is to control the pollution of |
|
110 | (namespaced) names and nodes. The goal here is to control the pollution of | |
102 | jamming things into tags or bookmarks (in extension-land) and to simplify |
|
111 | jamming things into tags or bookmarks (in extension-land) and to simplify | |
103 | internal bits of mercurial: log output, tab completion, etc. |
|
112 | internal bits of mercurial: log output, tab completion, etc. | |
104 |
|
113 | |||
105 | More precisely, we define a mapping of names to nodes, and a mapping from |
|
114 | More precisely, we define a mapping of names to nodes, and a mapping from | |
106 | nodes to names. Each mapping returns a list. |
|
115 | nodes to names. Each mapping returns a list. | |
107 |
|
116 | |||
108 | Furthermore, each name mapping will be passed a name to lookup which might |
|
117 | Furthermore, each name mapping will be passed a name to lookup which might | |
109 | not be in its domain. In this case, each method should return an empty list |
|
118 | not be in its domain. In this case, each method should return an empty list | |
110 | and not raise an error. |
|
119 | and not raise an error. | |
111 |
|
120 | |||
112 | This namespace object will define the properties we need: |
|
121 | This namespace object will define the properties we need: | |
113 | 'name': the namespace (plural form) |
|
122 | 'name': the namespace (plural form) | |
114 | 'templatename': name to use for templating (usually the singular form |
|
123 | 'templatename': name to use for templating (usually the singular form | |
115 | of the plural namespace name) |
|
124 | of the plural namespace name) | |
116 | 'listnames': list of all names in the namespace (usually the keys of a |
|
125 | 'listnames': list of all names in the namespace (usually the keys of a | |
117 | dictionary) |
|
126 | dictionary) | |
118 | 'namemap': function that takes a name and returns a list of nodes |
|
127 | 'namemap': function that takes a name and returns a list of nodes | |
119 | 'nodemap': function that takes a node and returns a list of names |
|
128 | 'nodemap': function that takes a node and returns a list of names | |
120 |
|
129 | |||
121 | """ |
|
130 | """ | |
122 |
|
131 | |||
123 | def __init__(self, name, templatename=None, logname=None, colorname=None, |
|
132 | def __init__(self, name, templatename=None, logname=None, colorname=None, | |
124 | listnames=None, namemap=None, nodemap=None): |
|
133 | logfmt=None, listnames=None, namemap=None, nodemap=None): | |
125 | """create a namespace |
|
134 | """create a namespace | |
126 |
|
135 | |||
127 | name: the namespace to be registered (in plural form) |
|
136 | name: the namespace to be registered (in plural form) | |
128 | templatename: the name to use for templating |
|
137 | templatename: the name to use for templating | |
129 | logname: the name to use for log output; if not specified templatename |
|
138 | logname: the name to use for log output; if not specified templatename | |
130 | is used |
|
139 | is used | |
131 | colorname: the name to use for colored log output; if not specified |
|
140 | colorname: the name to use for colored log output; if not specified | |
132 | logname is used |
|
141 | logname is used | |
|
142 | logfmt: the format to use for (l10n-ed) log output; if not specified | |||
|
143 | it is composed from logname | |||
133 | listnames: function to list all names |
|
144 | listnames: function to list all names | |
134 | namemap: function that inputs a node, output name(s) |
|
145 | namemap: function that inputs a node, output name(s) | |
135 | nodemap: function that inputs a name, output node(s) |
|
146 | nodemap: function that inputs a name, output node(s) | |
136 |
|
147 | |||
137 | """ |
|
148 | """ | |
138 | self.name = name |
|
149 | self.name = name | |
139 | self.templatename = templatename |
|
150 | self.templatename = templatename | |
140 | self.logname = logname |
|
151 | self.logname = logname | |
141 | self.colorname = colorname |
|
152 | self.colorname = colorname | |
|
153 | self.logfmt = logfmt | |||
142 | self.listnames = listnames |
|
154 | self.listnames = listnames | |
143 | self.namemap = namemap |
|
155 | self.namemap = namemap | |
144 | self.nodemap = nodemap |
|
156 | self.nodemap = nodemap | |
145 |
|
157 | |||
146 | # if logname is not specified, use the template name as backup |
|
158 | # if logname is not specified, use the template name as backup | |
147 | if self.logname is None: |
|
159 | if self.logname is None: | |
148 | self.logname = self.templatename |
|
160 | self.logname = self.templatename | |
149 |
|
161 | |||
150 | # if colorname is not specified, just use the logname as a backup |
|
162 | # if colorname is not specified, just use the logname as a backup | |
151 | if self.colorname is None: |
|
163 | if self.colorname is None: | |
152 | self.colorname = self.logname |
|
164 | self.colorname = self.logname | |
153 |
|
165 | |||
|
166 | # if logfmt is not specified, compose it from logname as backup | |||
|
167 | if self.logfmt is None: | |||
|
168 | # i18n: column positioning for "hg log" | |||
|
169 | self.logfmt = ("%s:" % self.logname).ljust(13) + "%s\n" | |||
|
170 | ||||
154 | def names(self, repo, node): |
|
171 | def names(self, repo, node): | |
155 | """method that returns a (sorted) list of names in a namespace that |
|
172 | """method that returns a (sorted) list of names in a namespace that | |
156 | match a given node""" |
|
173 | match a given node""" | |
157 | return sorted(self.nodemap(repo, node)) |
|
174 | return sorted(self.nodemap(repo, node)) | |
158 |
|
175 | |||
159 | def nodes(self, repo, name): |
|
176 | def nodes(self, repo, name): | |
160 | """method that returns a list of nodes in a namespace that |
|
177 | """method that returns a list of nodes in a namespace that | |
161 | match a given name. |
|
178 | match a given name. | |
162 |
|
179 | |||
163 | """ |
|
180 | """ | |
164 | return sorted(self.namemap(repo, name)) |
|
181 | return sorted(self.namemap(repo, name)) |
General Comments 0
You need to be logged in to leave comments.
Login now