##// END OF EJS Templates
new command debugcomplete...
Benoit Boissinot -
r1887:913397c2 default
parent child Browse files
Show More
@@ -1,210 +1,172 b''
1 1 shopt -s extglob
2 2
3 _hg_command_list()
4 {
5 "$hg" --debug help 2>/dev/null | \
6 awk -F', ' '/^list of commands:/ {commands=1}
7 commands==1 && /^ [^ ]/ {
8 line = substr($0, 2)
9 colon = index(line, ":")
10 if (colon > 0)
11 line = substr(line, 1, colon-1)
12 n = split(line, aliases)
13 command = aliases[1]
14 if (index(command, "debug") == 1) {
15 for (i=1; i<=n; i++)
16 debug[j++] = aliases[i]
17 next
18 }
19 print command
20 for (i=2; i<=n; i++)
21 if (index(command, aliases[i]) != 1)
22 print aliases[i]
23 }
24 /^global options:/ {exit 0}
25 END {for (i in debug) print debug[i]}'
26 }
27
28 3 _hg_option_list()
29 4 {
30 5 "$hg" -v help $1 2>/dev/null | \
31 6 awk '/^ *-/ {
32 7 for (i = 1; i <= NF; i ++) {
33 8 if (index($i, "-") != 1)
34 9 break;
35 10 print $i;
36 11 }
37 12 }'
38 13 }
39 14
40 15
41 16 _hg_commands()
42 17 {
43 local all commands result
44
45 all=$(_hg_command_list)
46 commands=${all%%$'\n'debug*}
47 result=$(compgen -W '$commands' -- "$cur")
48
49 # hide debug commands from users, but complete them if
50 # there is no other possible command
51 if [ "$result" = "" ]; then
52 local debug
53 debug=debug${all#*$'\n'debug}
54 result=$(compgen -W '$debug' -- "$cur")
55 fi
56
57 COMPREPLY=(${COMPREPLY[@]:-} $result)
18 local commands="$("$hg" debugcomplete "$cur")"
19 COMPREPLY=(${COMPREPLY[@]:-} $(compgen -W '$commands' -- "$cur"))
58 20 }
59 21
60 22 _hg_paths()
61 23 {
62 24 local paths="$("$hg" paths 2>/dev/null | sed -e 's/ = .*$//')"
63 25 COMPREPLY=(${COMPREPLY[@]:-} $(compgen -W '$paths' -- "$cur"))
64 26 }
65 27
66 28 _hg_repos()
67 29 {
68 30 local i
69 31 for i in $(compgen -d -- "$cur"); do
70 32 test ! -d "$i"/.hg || COMPREPLY=(${COMPREPLY[@]:-} "$i")
71 33 done
72 34 }
73 35
74 36 _hg_status()
75 37 {
76 38 local files="$("$hg" status -n$1 . 2>/dev/null)"
77 39 COMPREPLY=(${COMPREPLY[@]:-} $(compgen -W '$files' -- "$cur"))
78 40 }
79 41
80 42 _hg_tags()
81 43 {
82 44 local tags="$("$hg" tags 2>/dev/null |
83 45 sed -e 's/[0-9]*:[a-f0-9]\{40\}$//; s/ *$//')"
84 46 COMPREPLY=(${COMPREPLY[@]:-} $(compgen -W '$tags' -- "$cur"))
85 47 }
86 48
87 49 # this is "kind of" ugly...
88 50 _hg_count_non_option()
89 51 {
90 52 local i count=0
91 53 local filters="$1"
92 54
93 55 for ((i=1; $i<=$COMP_CWORD; i++)); do
94 56 if [[ "${COMP_WORDS[i]}" != -* ]]; then
95 57 if [[ ${COMP_WORDS[i-1]} == @($filters|$global_args) ]]; then
96 58 continue
97 59 fi
98 60 count=$(($count + 1))
99 61 fi
100 62 done
101 63
102 64 echo $(($count - 1))
103 65 }
104 66
105 67 _hg()
106 68 {
107 69 local cur prev cmd opts i
108 70 # global options that receive an argument
109 71 local global_args='--cwd|-R|--repository'
110 72 local hg="$1"
111 73
112 74 COMPREPLY=()
113 75 cur="$2"
114 76 prev="$3"
115 77
116 78 # searching for the command
117 79 # (first non-option argument that doesn't follow a global option that
118 80 # receives an argument)
119 81 for ((i=1; $i<=$COMP_CWORD; i++)); do
120 82 if [[ ${COMP_WORDS[i]} != -* ]]; then
121 83 if [[ ${COMP_WORDS[i-1]} != @($global_args) ]]; then
122 84 cmd="${COMP_WORDS[i]}"
123 85 break
124 86 fi
125 87 fi
126 88 done
127 89
128 90 if [[ "$cur" == -* ]]; then
129 91 opts=$(_hg_option_list $cmd)
130 92
131 93 COMPREPLY=(${COMPREPLY[@]:-} $(compgen -W '$opts' -- "$cur"))
132 94 return
133 95 fi
134 96
135 97 # global options
136 98 case "$prev" in
137 99 -R|--repository)
138 100 _hg_repos
139 101 return
140 102 ;;
141 103 --cwd)
142 104 # Stick with default bash completion
143 105 return
144 106 ;;
145 107 esac
146 108
147 109 if [ -z "$cmd" ] || [ $COMP_CWORD -eq $i ]; then
148 110 _hg_commands
149 111 return
150 112 fi
151 113
152 114 # canonicalize command name
153 115 cmd=$("$hg" -q help "$cmd" 2>/dev/null | sed -e 's/^hg //; s/ .*//; 1q')
154 116
155 117 if [ "$cmd" != status ] && [ "$prev" = -r ] || [ "$prev" = --rev ]; then
156 118 _hg_tags
157 119 return
158 120 fi
159 121
160 122 case "$cmd" in
161 123 help)
162 124 _hg_commands
163 125 ;;
164 126 export|manifest|update)
165 127 _hg_tags
166 128 ;;
167 129 pull|push|outgoing|incoming)
168 130 _hg_paths
169 131 _hg_repos
170 132 ;;
171 133 paths)
172 134 _hg_paths
173 135 ;;
174 136 add)
175 137 _hg_status "u"
176 138 ;;
177 139 commit)
178 140 _hg_status "mar"
179 141 ;;
180 142 remove)
181 143 _hg_status "d"
182 144 ;;
183 145 forget)
184 146 _hg_status "a"
185 147 ;;
186 148 diff)
187 149 _hg_status "mar"
188 150 ;;
189 151 revert)
190 152 _hg_status "mard"
191 153 ;;
192 154 clone)
193 155 local count=$(_hg_count_non_option)
194 156 if [ $count = 1 ]; then
195 157 _hg_paths
196 158 fi
197 159 _hg_repos
198 160 ;;
199 161 debugindex|debugindexdot)
200 162 COMPREPLY=(${COMPREPLY[@]:-} $(compgen -f -X "!*.i" -- "$cur"))
201 163 ;;
202 164 debugdata)
203 165 COMPREPLY=(${COMPREPLY[@]:-} $(compgen -f -X "!*.d" -- "$cur"))
204 166 ;;
205 167 esac
206 168
207 169 }
208 170
209 171 complete -o bashdefault -o default -F _hg hg 2>/dev/null \
210 172 || complete -o default -F _hg hg
@@ -1,2958 +1,2972 b''
1 1 # commands.py - command processing for mercurial
2 2 #
3 3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7
8 8 from demandload import demandload
9 9 from node import *
10 10 from i18n import gettext as _
11 11 demandload(globals(), "os re sys signal shutil imp urllib pdb")
12 12 demandload(globals(), "fancyopts ui hg util lock revlog")
13 13 demandload(globals(), "fnmatch hgweb mdiff random signal time traceback")
14 14 demandload(globals(), "errno socket version struct atexit sets bz2")
15 15
16 16 class UnknownCommand(Exception):
17 17 """Exception raised if command is not in the command table."""
18 18 class AmbiguousCommand(Exception):
19 19 """Exception raised if command shortcut matches more than one command."""
20 20
21 21 def filterfiles(filters, files):
22 22 l = [x for x in files if x in filters]
23 23
24 24 for t in filters:
25 25 if t and t[-1] != "/":
26 26 t += "/"
27 27 l += [x for x in files if x.startswith(t)]
28 28 return l
29 29
30 30 def relpath(repo, args):
31 31 cwd = repo.getcwd()
32 32 if cwd:
33 33 return [util.normpath(os.path.join(cwd, x)) for x in args]
34 34 return args
35 35
36 36 def matchpats(repo, pats=[], opts={}, head=''):
37 37 cwd = repo.getcwd()
38 38 if not pats and cwd:
39 39 opts['include'] = [os.path.join(cwd, i) for i in opts['include']]
40 40 opts['exclude'] = [os.path.join(cwd, x) for x in opts['exclude']]
41 41 cwd = ''
42 42 return util.cmdmatcher(repo.root, cwd, pats or ['.'], opts.get('include'),
43 43 opts.get('exclude'), head)
44 44
45 45 def makewalk(repo, pats, opts, node=None, head=''):
46 46 files, matchfn, anypats = matchpats(repo, pats, opts, head)
47 47 exact = dict(zip(files, files))
48 48 def walk():
49 49 for src, fn in repo.walk(node=node, files=files, match=matchfn):
50 50 yield src, fn, util.pathto(repo.getcwd(), fn), fn in exact
51 51 return files, matchfn, walk()
52 52
53 53 def walk(repo, pats, opts, node=None, head=''):
54 54 files, matchfn, results = makewalk(repo, pats, opts, node, head)
55 55 for r in results:
56 56 yield r
57 57
58 58 def walkchangerevs(ui, repo, pats, opts):
59 59 '''Iterate over files and the revs they changed in.
60 60
61 61 Callers most commonly need to iterate backwards over the history
62 62 it is interested in. Doing so has awful (quadratic-looking)
63 63 performance, so we use iterators in a "windowed" way.
64 64
65 65 We walk a window of revisions in the desired order. Within the
66 66 window, we first walk forwards to gather data, then in the desired
67 67 order (usually backwards) to display it.
68 68
69 69 This function returns an (iterator, getchange, matchfn) tuple. The
70 70 getchange function returns the changelog entry for a numeric
71 71 revision. The iterator yields 3-tuples. They will be of one of
72 72 the following forms:
73 73
74 74 "window", incrementing, lastrev: stepping through a window,
75 75 positive if walking forwards through revs, last rev in the
76 76 sequence iterated over - use to reset state for the current window
77 77
78 78 "add", rev, fns: out-of-order traversal of the given file names
79 79 fns, which changed during revision rev - use to gather data for
80 80 possible display
81 81
82 82 "iter", rev, None: in-order traversal of the revs earlier iterated
83 83 over with "add" - use to display data'''
84 84
85 85 def increasing_windows(start, end, windowsize=8, sizelimit=512):
86 86 if start < end:
87 87 while start < end:
88 88 yield start, min(windowsize, end-start)
89 89 start += windowsize
90 90 if windowsize < sizelimit:
91 91 windowsize *= 2
92 92 else:
93 93 while start > end:
94 94 yield start, min(windowsize, start-end-1)
95 95 start -= windowsize
96 96 if windowsize < sizelimit:
97 97 windowsize *= 2
98 98
99 99
100 100 files, matchfn, anypats = matchpats(repo, pats, opts)
101 101
102 102 if repo.changelog.count() == 0:
103 103 return [], False, matchfn
104 104
105 105 revs = map(int, revrange(ui, repo, opts['rev'] or ['tip:0']))
106 106 wanted = {}
107 107 slowpath = anypats
108 108 fncache = {}
109 109
110 110 chcache = {}
111 111 def getchange(rev):
112 112 ch = chcache.get(rev)
113 113 if ch is None:
114 114 chcache[rev] = ch = repo.changelog.read(repo.lookup(str(rev)))
115 115 return ch
116 116
117 117 if not slowpath and not files:
118 118 # No files, no patterns. Display all revs.
119 119 wanted = dict(zip(revs, revs))
120 120 if not slowpath:
121 121 # Only files, no patterns. Check the history of each file.
122 122 def filerevgen(filelog):
123 123 for i, window in increasing_windows(filelog.count()-1, -1):
124 124 revs = []
125 125 for j in xrange(i - window, i + 1):
126 126 revs.append(filelog.linkrev(filelog.node(j)))
127 127 revs.reverse()
128 128 for rev in revs:
129 129 yield rev
130 130
131 131 minrev, maxrev = min(revs), max(revs)
132 132 for file_ in files:
133 133 filelog = repo.file(file_)
134 134 # A zero count may be a directory or deleted file, so
135 135 # try to find matching entries on the slow path.
136 136 if filelog.count() == 0:
137 137 slowpath = True
138 138 break
139 139 for rev in filerevgen(filelog):
140 140 if rev <= maxrev:
141 141 if rev < minrev:
142 142 break
143 143 fncache.setdefault(rev, [])
144 144 fncache[rev].append(file_)
145 145 wanted[rev] = 1
146 146 if slowpath:
147 147 # The slow path checks files modified in every changeset.
148 148 def changerevgen():
149 149 for i, window in increasing_windows(repo.changelog.count()-1, -1):
150 150 for j in xrange(i - window, i + 1):
151 151 yield j, getchange(j)[3]
152 152
153 153 for rev, changefiles in changerevgen():
154 154 matches = filter(matchfn, changefiles)
155 155 if matches:
156 156 fncache[rev] = matches
157 157 wanted[rev] = 1
158 158
159 159 def iterate():
160 160 for i, window in increasing_windows(0, len(revs)):
161 161 yield 'window', revs[0] < revs[-1], revs[-1]
162 162 nrevs = [rev for rev in revs[i:i+window]
163 163 if rev in wanted]
164 164 srevs = list(nrevs)
165 165 srevs.sort()
166 166 for rev in srevs:
167 167 fns = fncache.get(rev) or filter(matchfn, getchange(rev)[3])
168 168 yield 'add', rev, fns
169 169 for rev in nrevs:
170 170 yield 'iter', rev, None
171 171 return iterate(), getchange, matchfn
172 172
173 173 revrangesep = ':'
174 174
175 175 def revrange(ui, repo, revs, revlog=None):
176 176 """Yield revision as strings from a list of revision specifications."""
177 177 if revlog is None:
178 178 revlog = repo.changelog
179 179 revcount = revlog.count()
180 180 def fix(val, defval):
181 181 if not val:
182 182 return defval
183 183 try:
184 184 num = int(val)
185 185 if str(num) != val:
186 186 raise ValueError
187 187 if num < 0:
188 188 num += revcount
189 189 if num < 0:
190 190 num = 0
191 191 elif num >= revcount:
192 192 raise ValueError
193 193 except ValueError:
194 194 try:
195 195 num = repo.changelog.rev(repo.lookup(val))
196 196 except KeyError:
197 197 try:
198 198 num = revlog.rev(revlog.lookup(val))
199 199 except KeyError:
200 200 raise util.Abort(_('invalid revision identifier %s'), val)
201 201 return num
202 202 seen = {}
203 203 for spec in revs:
204 204 if spec.find(revrangesep) >= 0:
205 205 start, end = spec.split(revrangesep, 1)
206 206 start = fix(start, 0)
207 207 end = fix(end, revcount - 1)
208 208 step = start > end and -1 or 1
209 209 for rev in xrange(start, end+step, step):
210 210 if rev in seen:
211 211 continue
212 212 seen[rev] = 1
213 213 yield str(rev)
214 214 else:
215 215 rev = fix(spec, None)
216 216 if rev in seen:
217 217 continue
218 218 seen[rev] = 1
219 219 yield str(rev)
220 220
221 221 def make_filename(repo, r, pat, node=None,
222 222 total=None, seqno=None, revwidth=None, pathname=None):
223 223 node_expander = {
224 224 'H': lambda: hex(node),
225 225 'R': lambda: str(r.rev(node)),
226 226 'h': lambda: short(node),
227 227 }
228 228 expander = {
229 229 '%': lambda: '%',
230 230 'b': lambda: os.path.basename(repo.root),
231 231 }
232 232
233 233 try:
234 234 if node:
235 235 expander.update(node_expander)
236 236 if node and revwidth is not None:
237 237 expander['r'] = lambda: str(r.rev(node)).zfill(revwidth)
238 238 if total is not None:
239 239 expander['N'] = lambda: str(total)
240 240 if seqno is not None:
241 241 expander['n'] = lambda: str(seqno)
242 242 if total is not None and seqno is not None:
243 243 expander['n'] = lambda:str(seqno).zfill(len(str(total)))
244 244 if pathname is not None:
245 245 expander['s'] = lambda: os.path.basename(pathname)
246 246 expander['d'] = lambda: os.path.dirname(pathname) or '.'
247 247 expander['p'] = lambda: pathname
248 248
249 249 newname = []
250 250 patlen = len(pat)
251 251 i = 0
252 252 while i < patlen:
253 253 c = pat[i]
254 254 if c == '%':
255 255 i += 1
256 256 c = pat[i]
257 257 c = expander[c]()
258 258 newname.append(c)
259 259 i += 1
260 260 return ''.join(newname)
261 261 except KeyError, inst:
262 262 raise util.Abort(_("invalid format spec '%%%s' in output file name"),
263 263 inst.args[0])
264 264
265 265 def make_file(repo, r, pat, node=None,
266 266 total=None, seqno=None, revwidth=None, mode='wb', pathname=None):
267 267 if not pat or pat == '-':
268 268 return 'w' in mode and sys.stdout or sys.stdin
269 269 if hasattr(pat, 'write') and 'w' in mode:
270 270 return pat
271 271 if hasattr(pat, 'read') and 'r' in mode:
272 272 return pat
273 273 return open(make_filename(repo, r, pat, node, total, seqno, revwidth,
274 274 pathname),
275 275 mode)
276 276
277 277 def dodiff(fp, ui, repo, node1, node2, files=None, match=util.always,
278 278 changes=None, text=False, opts={}):
279 279 if not node1:
280 280 node1 = repo.dirstate.parents()[0]
281 281 # reading the data for node1 early allows it to play nicely
282 282 # with repo.changes and the revlog cache.
283 283 change = repo.changelog.read(node1)
284 284 mmap = repo.manifest.read(change[0])
285 285 date1 = util.datestr(change[2])
286 286
287 287 if not changes:
288 288 changes = repo.changes(node1, node2, files, match=match)
289 289 modified, added, removed, deleted, unknown = changes
290 290 if files:
291 291 modified, added, removed = map(lambda x: filterfiles(files, x),
292 292 (modified, added, removed))
293 293
294 294 if not modified and not added and not removed:
295 295 return
296 296
297 297 if node2:
298 298 change = repo.changelog.read(node2)
299 299 mmap2 = repo.manifest.read(change[0])
300 300 date2 = util.datestr(change[2])
301 301 def read(f):
302 302 return repo.file(f).read(mmap2[f])
303 303 else:
304 304 date2 = util.datestr()
305 305 def read(f):
306 306 return repo.wread(f)
307 307
308 308 if ui.quiet:
309 309 r = None
310 310 else:
311 311 hexfunc = ui.verbose and hex or short
312 312 r = [hexfunc(node) for node in [node1, node2] if node]
313 313
314 314 diffopts = ui.diffopts()
315 315 showfunc = opts.get('show_function') or diffopts['showfunc']
316 316 ignorews = opts.get('ignore_all_space') or diffopts['ignorews']
317 317 for f in modified:
318 318 to = None
319 319 if f in mmap:
320 320 to = repo.file(f).read(mmap[f])
321 321 tn = read(f)
322 322 fp.write(mdiff.unidiff(to, date1, tn, date2, f, r, text=text,
323 323 showfunc=showfunc, ignorews=ignorews))
324 324 for f in added:
325 325 to = None
326 326 tn = read(f)
327 327 fp.write(mdiff.unidiff(to, date1, tn, date2, f, r, text=text,
328 328 showfunc=showfunc, ignorews=ignorews))
329 329 for f in removed:
330 330 to = repo.file(f).read(mmap[f])
331 331 tn = None
332 332 fp.write(mdiff.unidiff(to, date1, tn, date2, f, r, text=text,
333 333 showfunc=showfunc, ignorews=ignorews))
334 334
335 335 def trimuser(ui, name, rev, revcache):
336 336 """trim the name of the user who committed a change"""
337 337 user = revcache.get(rev)
338 338 if user is None:
339 339 user = revcache[rev] = ui.shortuser(name)
340 340 return user
341 341
342 342 def show_changeset(ui, repo, rev=0, changenode=None, brinfo=None):
343 343 """show a single changeset or file revision"""
344 344 log = repo.changelog
345 345 if changenode is None:
346 346 changenode = log.node(rev)
347 347 elif not rev:
348 348 rev = log.rev(changenode)
349 349
350 350 if ui.quiet:
351 351 ui.write("%d:%s\n" % (rev, short(changenode)))
352 352 return
353 353
354 354 changes = log.read(changenode)
355 355 date = util.datestr(changes[2])
356 356
357 357 parents = [(log.rev(p), ui.verbose and hex(p) or short(p))
358 358 for p in log.parents(changenode)
359 359 if ui.debugflag or p != nullid]
360 360 if not ui.debugflag and len(parents) == 1 and parents[0][0] == rev-1:
361 361 parents = []
362 362
363 363 if ui.verbose:
364 364 ui.write(_("changeset: %d:%s\n") % (rev, hex(changenode)))
365 365 else:
366 366 ui.write(_("changeset: %d:%s\n") % (rev, short(changenode)))
367 367
368 368 for tag in repo.nodetags(changenode):
369 369 ui.status(_("tag: %s\n") % tag)
370 370 for parent in parents:
371 371 ui.write(_("parent: %d:%s\n") % parent)
372 372
373 373 if brinfo and changenode in brinfo:
374 374 br = brinfo[changenode]
375 375 ui.write(_("branch: %s\n") % " ".join(br))
376 376
377 377 ui.debug(_("manifest: %d:%s\n") % (repo.manifest.rev(changes[0]),
378 378 hex(changes[0])))
379 379 ui.status(_("user: %s\n") % changes[1])
380 380 ui.status(_("date: %s\n") % date)
381 381
382 382 if ui.debugflag:
383 383 files = repo.changes(log.parents(changenode)[0], changenode)
384 384 for key, value in zip([_("files:"), _("files+:"), _("files-:")], files):
385 385 if value:
386 386 ui.note("%-12s %s\n" % (key, " ".join(value)))
387 387 else:
388 388 ui.note(_("files: %s\n") % " ".join(changes[3]))
389 389
390 390 description = changes[4].strip()
391 391 if description:
392 392 if ui.verbose:
393 393 ui.status(_("description:\n"))
394 394 ui.status(description)
395 395 ui.status("\n\n")
396 396 else:
397 397 ui.status(_("summary: %s\n") % description.splitlines()[0])
398 398 ui.status("\n")
399 399
400 400 def show_version(ui):
401 401 """output version and copyright information"""
402 402 ui.write(_("Mercurial Distributed SCM (version %s)\n")
403 403 % version.get_version())
404 404 ui.status(_(
405 405 "\nCopyright (C) 2005 Matt Mackall <mpm@selenic.com>\n"
406 406 "This is free software; see the source for copying conditions. "
407 407 "There is NO\nwarranty; "
408 408 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
409 409 ))
410 410
411 411 def help_(ui, cmd=None, with_version=False):
412 412 """show help for a given command or all commands"""
413 413 option_lists = []
414 414 if cmd and cmd != 'shortlist':
415 415 if with_version:
416 416 show_version(ui)
417 417 ui.write('\n')
418 418 aliases, i = find(cmd)
419 419 # synopsis
420 420 ui.write("%s\n\n" % i[2])
421 421
422 422 # description
423 423 doc = i[0].__doc__
424 424 if not doc:
425 425 doc = _("(No help text available)")
426 426 if ui.quiet:
427 427 doc = doc.splitlines(0)[0]
428 428 ui.write("%s\n" % doc.rstrip())
429 429
430 430 if not ui.quiet:
431 431 # aliases
432 432 if len(aliases) > 1:
433 433 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
434 434
435 435 # options
436 436 if i[1]:
437 437 option_lists.append(("options", i[1]))
438 438
439 439 else:
440 440 # program name
441 441 if ui.verbose or with_version:
442 442 show_version(ui)
443 443 else:
444 444 ui.status(_("Mercurial Distributed SCM\n"))
445 445 ui.status('\n')
446 446
447 447 # list of commands
448 448 if cmd == "shortlist":
449 449 ui.status(_('basic commands (use "hg help" '
450 450 'for the full list or option "-v" for details):\n\n'))
451 451 elif ui.verbose:
452 452 ui.status(_('list of commands:\n\n'))
453 453 else:
454 454 ui.status(_('list of commands (use "hg help -v" '
455 455 'to show aliases and global options):\n\n'))
456 456
457 457 h = {}
458 458 cmds = {}
459 459 for c, e in table.items():
460 460 f = c.split("|")[0]
461 461 if cmd == "shortlist" and not f.startswith("^"):
462 462 continue
463 463 f = f.lstrip("^")
464 464 if not ui.debugflag and f.startswith("debug"):
465 465 continue
466 466 doc = e[0].__doc__
467 467 if not doc:
468 468 doc = _("(No help text available)")
469 469 h[f] = doc.splitlines(0)[0].rstrip()
470 470 cmds[f] = c.lstrip("^")
471 471
472 472 fns = h.keys()
473 473 fns.sort()
474 474 m = max(map(len, fns))
475 475 for f in fns:
476 476 if ui.verbose:
477 477 commands = cmds[f].replace("|",", ")
478 478 ui.write(" %s:\n %s\n"%(commands, h[f]))
479 479 else:
480 480 ui.write(' %-*s %s\n' % (m, f, h[f]))
481 481
482 482 # global options
483 483 if ui.verbose:
484 484 option_lists.append(("global options", globalopts))
485 485
486 486 # list all option lists
487 487 opt_output = []
488 488 for title, options in option_lists:
489 489 opt_output.append(("\n%s:\n" % title, None))
490 490 for shortopt, longopt, default, desc in options:
491 491 opt_output.append(("%2s%s" % (shortopt and "-%s" % shortopt,
492 492 longopt and " --%s" % longopt),
493 493 "%s%s" % (desc,
494 494 default
495 495 and _(" (default: %s)") % default
496 496 or "")))
497 497
498 498 if opt_output:
499 499 opts_len = max([len(line[0]) for line in opt_output if line[1]])
500 500 for first, second in opt_output:
501 501 if second:
502 502 ui.write(" %-*s %s\n" % (opts_len, first, second))
503 503 else:
504 504 ui.write("%s\n" % first)
505 505
506 506 # Commands start here, listed alphabetically
507 507
508 508 def add(ui, repo, *pats, **opts):
509 509 """add the specified files on the next commit
510 510
511 511 Schedule files to be version controlled and added to the repository.
512 512
513 513 The files will be added to the repository at the next commit.
514 514
515 515 If no names are given, add all files in the repository.
516 516 """
517 517
518 518 names = []
519 519 for src, abs, rel, exact in walk(repo, pats, opts):
520 520 if exact:
521 521 if ui.verbose:
522 522 ui.status(_('adding %s\n') % rel)
523 523 names.append(abs)
524 524 elif repo.dirstate.state(abs) == '?':
525 525 ui.status(_('adding %s\n') % rel)
526 526 names.append(abs)
527 527 repo.add(names)
528 528
529 529 def addremove(ui, repo, *pats, **opts):
530 530 """add all new files, delete all missing files
531 531
532 532 Add all new files and remove all missing files from the repository.
533 533
534 534 New files are ignored if they match any of the patterns in .hgignore. As
535 535 with add, these changes take effect at the next commit.
536 536 """
537 537 return addremove_lock(ui, repo, pats, opts)
538 538
539 539 def addremove_lock(ui, repo, pats, opts, wlock=None):
540 540 add, remove = [], []
541 541 for src, abs, rel, exact in walk(repo, pats, opts):
542 542 if src == 'f' and repo.dirstate.state(abs) == '?':
543 543 add.append(abs)
544 544 if ui.verbose or not exact:
545 545 ui.status(_('adding %s\n') % ((pats and rel) or abs))
546 546 if repo.dirstate.state(abs) != 'r' and not os.path.exists(rel):
547 547 remove.append(abs)
548 548 if ui.verbose or not exact:
549 549 ui.status(_('removing %s\n') % ((pats and rel) or abs))
550 550 repo.add(add, wlock=wlock)
551 551 repo.remove(remove, wlock=wlock)
552 552
553 553 def annotate(ui, repo, *pats, **opts):
554 554 """show changeset information per file line
555 555
556 556 List changes in files, showing the revision id responsible for each line
557 557
558 558 This command is useful to discover who did a change or when a change took
559 559 place.
560 560
561 561 Without the -a option, annotate will avoid processing files it
562 562 detects as binary. With -a, annotate will generate an annotation
563 563 anyway, probably with undesirable results.
564 564 """
565 565 def getnode(rev):
566 566 return short(repo.changelog.node(rev))
567 567
568 568 ucache = {}
569 569 def getname(rev):
570 570 cl = repo.changelog.read(repo.changelog.node(rev))
571 571 return trimuser(ui, cl[1], rev, ucache)
572 572
573 573 dcache = {}
574 574 def getdate(rev):
575 575 datestr = dcache.get(rev)
576 576 if datestr is None:
577 577 cl = repo.changelog.read(repo.changelog.node(rev))
578 578 datestr = dcache[rev] = util.datestr(cl[2])
579 579 return datestr
580 580
581 581 if not pats:
582 582 raise util.Abort(_('at least one file name or pattern required'))
583 583
584 584 opmap = [['user', getname], ['number', str], ['changeset', getnode],
585 585 ['date', getdate]]
586 586 if not opts['user'] and not opts['changeset'] and not opts['date']:
587 587 opts['number'] = 1
588 588
589 589 if opts['rev']:
590 590 node = repo.changelog.lookup(opts['rev'])
591 591 else:
592 592 node = repo.dirstate.parents()[0]
593 593 change = repo.changelog.read(node)
594 594 mmap = repo.manifest.read(change[0])
595 595
596 596 for src, abs, rel, exact in walk(repo, pats, opts, node=node):
597 597 f = repo.file(abs)
598 598 if not opts['text'] and util.binary(f.read(mmap[abs])):
599 599 ui.write(_("%s: binary file\n") % ((pats and rel) or abs))
600 600 continue
601 601
602 602 lines = f.annotate(mmap[abs])
603 603 pieces = []
604 604
605 605 for o, f in opmap:
606 606 if opts[o]:
607 607 l = [f(n) for n, dummy in lines]
608 608 if l:
609 609 m = max(map(len, l))
610 610 pieces.append(["%*s" % (m, x) for x in l])
611 611
612 612 if pieces:
613 613 for p, l in zip(zip(*pieces), lines):
614 614 ui.write("%s: %s" % (" ".join(p), l[1]))
615 615
616 616 def bundle(ui, repo, fname, dest="default-push", **opts):
617 617 """create a changegroup file
618 618
619 619 Generate a compressed changegroup file collecting all changesets
620 620 not found in the other repository.
621 621
622 622 This file can then be transferred using conventional means and
623 623 applied to another repository with the unbundle command. This is
624 624 useful when native push and pull are not available or when
625 625 exporting an entire repository is undesirable. The standard file
626 626 extension is ".hg".
627 627
628 628 Unlike import/export, this exactly preserves all changeset
629 629 contents including permissions, rename data, and revision history.
630 630 """
631 631 f = open(fname, "wb")
632 632 dest = ui.expandpath(dest, repo.root)
633 633 other = hg.repository(ui, dest)
634 634 o = repo.findoutgoing(other)
635 635 cg = repo.changegroup(o, 'bundle')
636 636
637 637 try:
638 638 f.write("HG10")
639 639 z = bz2.BZ2Compressor(9)
640 640 while 1:
641 641 chunk = cg.read(4096)
642 642 if not chunk:
643 643 break
644 644 f.write(z.compress(chunk))
645 645 f.write(z.flush())
646 646 except:
647 647 os.unlink(fname)
648 648 raise
649 649
650 650 def cat(ui, repo, file1, *pats, **opts):
651 651 """output the latest or given revisions of files
652 652
653 653 Print the specified files as they were at the given revision.
654 654 If no revision is given then the tip is used.
655 655
656 656 Output may be to a file, in which case the name of the file is
657 657 given using a format string. The formatting rules are the same as
658 658 for the export command, with the following additions:
659 659
660 660 %s basename of file being printed
661 661 %d dirname of file being printed, or '.' if in repo root
662 662 %p root-relative path name of file being printed
663 663 """
664 664 mf = {}
665 665 rev = opts['rev']
666 666 if rev:
667 667 node = repo.lookup(rev)
668 668 else:
669 669 node = repo.changelog.tip()
670 670 change = repo.changelog.read(node)
671 671 mf = repo.manifest.read(change[0])
672 672 for src, abs, rel, exact in walk(repo, (file1,) + pats, opts, node):
673 673 r = repo.file(abs)
674 674 n = mf[abs]
675 675 fp = make_file(repo, r, opts['output'], node=n, pathname=abs)
676 676 fp.write(r.read(n))
677 677
678 678 def clone(ui, source, dest=None, **opts):
679 679 """make a copy of an existing repository
680 680
681 681 Create a copy of an existing repository in a new directory.
682 682
683 683 If no destination directory name is specified, it defaults to the
684 684 basename of the source.
685 685
686 686 The location of the source is added to the new repository's
687 687 .hg/hgrc file, as the default to be used for future pulls.
688 688
689 689 For efficiency, hardlinks are used for cloning whenever the source
690 690 and destination are on the same filesystem. Some filesystems,
691 691 such as AFS, implement hardlinking incorrectly, but do not report
692 692 errors. In these cases, use the --pull option to avoid
693 693 hardlinking.
694 694
695 695 See pull for valid source format details.
696 696 """
697 697 if dest is None:
698 698 dest = os.path.basename(os.path.normpath(source))
699 699
700 700 if os.path.exists(dest):
701 701 raise util.Abort(_("destination '%s' already exists"), dest)
702 702
703 703 dest = os.path.realpath(dest)
704 704
705 705 class Dircleanup(object):
706 706 def __init__(self, dir_):
707 707 self.rmtree = shutil.rmtree
708 708 self.dir_ = dir_
709 709 os.mkdir(dir_)
710 710 def close(self):
711 711 self.dir_ = None
712 712 def __del__(self):
713 713 if self.dir_:
714 714 self.rmtree(self.dir_, True)
715 715
716 716 if opts['ssh']:
717 717 ui.setconfig("ui", "ssh", opts['ssh'])
718 718 if opts['remotecmd']:
719 719 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
720 720
721 721 if not os.path.exists(source):
722 722 source = ui.expandpath(source)
723 723
724 724 d = Dircleanup(dest)
725 725 abspath = source
726 726 other = hg.repository(ui, source)
727 727
728 728 copy = False
729 729 if other.dev() != -1:
730 730 abspath = os.path.abspath(source)
731 731 if not opts['pull'] and not opts['rev']:
732 732 copy = True
733 733
734 734 if copy:
735 735 try:
736 736 # we use a lock here because if we race with commit, we
737 737 # can end up with extra data in the cloned revlogs that's
738 738 # not pointed to by changesets, thus causing verify to
739 739 # fail
740 740 l1 = other.lock()
741 741 except lock.LockException:
742 742 copy = False
743 743
744 744 if copy:
745 745 # we lock here to avoid premature writing to the target
746 746 os.mkdir(os.path.join(dest, ".hg"))
747 747 l2 = lock.lock(os.path.join(dest, ".hg", "lock"))
748 748
749 749 files = "data 00manifest.d 00manifest.i 00changelog.d 00changelog.i"
750 750 for f in files.split():
751 751 src = os.path.join(source, ".hg", f)
752 752 dst = os.path.join(dest, ".hg", f)
753 753 try:
754 754 util.copyfiles(src, dst)
755 755 except OSError, inst:
756 756 if inst.errno != errno.ENOENT:
757 757 raise
758 758
759 759 repo = hg.repository(ui, dest)
760 760
761 761 else:
762 762 revs = None
763 763 if opts['rev']:
764 764 if not other.local():
765 765 error = _("clone -r not supported yet for remote repositories.")
766 766 raise util.Abort(error)
767 767 else:
768 768 revs = [other.lookup(rev) for rev in opts['rev']]
769 769 repo = hg.repository(ui, dest, create=1)
770 770 repo.pull(other, heads = revs)
771 771
772 772 f = repo.opener("hgrc", "w", text=True)
773 773 f.write("[paths]\n")
774 774 f.write("default = %s\n" % abspath)
775 775 f.close()
776 776
777 777 if not opts['noupdate']:
778 778 update(repo.ui, repo)
779 779
780 780 d.close()
781 781
782 782 def commit(ui, repo, *pats, **opts):
783 783 """commit the specified files or all outstanding changes
784 784
785 785 Commit changes to the given files into the repository.
786 786
787 787 If a list of files is omitted, all changes reported by "hg status"
788 788 will be commited.
789 789
790 790 The HGEDITOR or EDITOR environment variables are used to start an
791 791 editor to add a commit comment.
792 792 """
793 793 message = opts['message']
794 794 logfile = opts['logfile']
795 795
796 796 if message and logfile:
797 797 raise util.Abort(_('options --message and --logfile are mutually '
798 798 'exclusive'))
799 799 if not message and logfile:
800 800 try:
801 801 if logfile == '-':
802 802 message = sys.stdin.read()
803 803 else:
804 804 message = open(logfile).read()
805 805 except IOError, inst:
806 806 raise util.Abort(_("can't read commit message '%s': %s") %
807 807 (logfile, inst.strerror))
808 808
809 809 if opts['addremove']:
810 810 addremove(ui, repo, *pats, **opts)
811 811 fns, match, anypats = matchpats(repo, pats, opts)
812 812 if pats:
813 813 modified, added, removed, deleted, unknown = (
814 814 repo.changes(files=fns, match=match))
815 815 files = modified + added + removed
816 816 else:
817 817 files = []
818 818 try:
819 819 repo.commit(files, message, opts['user'], opts['date'], match)
820 820 except ValueError, inst:
821 821 raise util.Abort(str(inst))
822 822
823 823 def docopy(ui, repo, pats, opts, wlock):
824 824 # called with the repo lock held
825 825 cwd = repo.getcwd()
826 826 errors = 0
827 827 copied = []
828 828 targets = {}
829 829
830 830 def okaytocopy(abs, rel, exact):
831 831 reasons = {'?': _('is not managed'),
832 832 'a': _('has been marked for add'),
833 833 'r': _('has been marked for remove')}
834 834 state = repo.dirstate.state(abs)
835 835 reason = reasons.get(state)
836 836 if reason:
837 837 if state == 'a':
838 838 origsrc = repo.dirstate.copied(abs)
839 839 if origsrc is not None:
840 840 return origsrc
841 841 if exact:
842 842 ui.warn(_('%s: not copying - file %s\n') % (rel, reason))
843 843 else:
844 844 return abs
845 845
846 846 def copy(origsrc, abssrc, relsrc, target, exact):
847 847 abstarget = util.canonpath(repo.root, cwd, target)
848 848 reltarget = util.pathto(cwd, abstarget)
849 849 prevsrc = targets.get(abstarget)
850 850 if prevsrc is not None:
851 851 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
852 852 (reltarget, abssrc, prevsrc))
853 853 return
854 854 if (not opts['after'] and os.path.exists(reltarget) or
855 855 opts['after'] and repo.dirstate.state(abstarget) not in '?r'):
856 856 if not opts['force']:
857 857 ui.warn(_('%s: not overwriting - file exists\n') %
858 858 reltarget)
859 859 return
860 860 if not opts['after']:
861 861 os.unlink(reltarget)
862 862 if opts['after']:
863 863 if not os.path.exists(reltarget):
864 864 return
865 865 else:
866 866 targetdir = os.path.dirname(reltarget) or '.'
867 867 if not os.path.isdir(targetdir):
868 868 os.makedirs(targetdir)
869 869 try:
870 870 restore = repo.dirstate.state(abstarget) == 'r'
871 871 if restore:
872 872 repo.undelete([abstarget], wlock)
873 873 try:
874 874 shutil.copyfile(relsrc, reltarget)
875 875 shutil.copymode(relsrc, reltarget)
876 876 restore = False
877 877 finally:
878 878 if restore:
879 879 repo.remove([abstarget], wlock)
880 880 except shutil.Error, inst:
881 881 raise util.Abort(str(inst))
882 882 except IOError, inst:
883 883 if inst.errno == errno.ENOENT:
884 884 ui.warn(_('%s: deleted in working copy\n') % relsrc)
885 885 else:
886 886 ui.warn(_('%s: cannot copy - %s\n') %
887 887 (relsrc, inst.strerror))
888 888 errors += 1
889 889 return
890 890 if ui.verbose or not exact:
891 891 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
892 892 targets[abstarget] = abssrc
893 893 if abstarget != origsrc:
894 894 repo.copy(origsrc, abstarget, wlock)
895 895 copied.append((abssrc, relsrc, exact))
896 896
897 897 def targetpathfn(pat, dest, srcs):
898 898 if os.path.isdir(pat):
899 899 abspfx = util.canonpath(repo.root, cwd, pat)
900 900 if destdirexists:
901 901 striplen = len(os.path.split(abspfx)[0])
902 902 else:
903 903 striplen = len(abspfx)
904 904 if striplen:
905 905 striplen += len(os.sep)
906 906 res = lambda p: os.path.join(dest, p[striplen:])
907 907 elif destdirexists:
908 908 res = lambda p: os.path.join(dest, os.path.basename(p))
909 909 else:
910 910 res = lambda p: dest
911 911 return res
912 912
913 913 def targetpathafterfn(pat, dest, srcs):
914 914 if util.patkind(pat, None)[0]:
915 915 # a mercurial pattern
916 916 res = lambda p: os.path.join(dest, os.path.basename(p))
917 917 else:
918 918 abspfx = util.canonpath(repo.root, cwd, pat)
919 919 if len(abspfx) < len(srcs[0][0]):
920 920 # A directory. Either the target path contains the last
921 921 # component of the source path or it does not.
922 922 def evalpath(striplen):
923 923 score = 0
924 924 for s in srcs:
925 925 t = os.path.join(dest, s[0][striplen:])
926 926 if os.path.exists(t):
927 927 score += 1
928 928 return score
929 929
930 930 striplen = len(abspfx)
931 931 if striplen:
932 932 striplen += len(os.sep)
933 933 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
934 934 score = evalpath(striplen)
935 935 striplen1 = len(os.path.split(abspfx)[0])
936 936 if striplen1:
937 937 striplen1 += len(os.sep)
938 938 if evalpath(striplen1) > score:
939 939 striplen = striplen1
940 940 res = lambda p: os.path.join(dest, p[striplen:])
941 941 else:
942 942 # a file
943 943 if destdirexists:
944 944 res = lambda p: os.path.join(dest, os.path.basename(p))
945 945 else:
946 946 res = lambda p: dest
947 947 return res
948 948
949 949
950 950 pats = list(pats)
951 951 if not pats:
952 952 raise util.Abort(_('no source or destination specified'))
953 953 if len(pats) == 1:
954 954 raise util.Abort(_('no destination specified'))
955 955 dest = pats.pop()
956 956 destdirexists = os.path.isdir(dest)
957 957 if (len(pats) > 1 or util.patkind(pats[0], None)[0]) and not destdirexists:
958 958 raise util.Abort(_('with multiple sources, destination must be an '
959 959 'existing directory'))
960 960 if opts['after']:
961 961 tfn = targetpathafterfn
962 962 else:
963 963 tfn = targetpathfn
964 964 copylist = []
965 965 for pat in pats:
966 966 srcs = []
967 967 for tag, abssrc, relsrc, exact in walk(repo, [pat], opts):
968 968 origsrc = okaytocopy(abssrc, relsrc, exact)
969 969 if origsrc:
970 970 srcs.append((origsrc, abssrc, relsrc, exact))
971 971 if not srcs:
972 972 continue
973 973 copylist.append((tfn(pat, dest, srcs), srcs))
974 974 if not copylist:
975 975 raise util.Abort(_('no files to copy'))
976 976
977 977 for targetpath, srcs in copylist:
978 978 for origsrc, abssrc, relsrc, exact in srcs:
979 979 copy(origsrc, abssrc, relsrc, targetpath(abssrc), exact)
980 980
981 981 if errors:
982 982 ui.warn(_('(consider using --after)\n'))
983 983 return errors, copied
984 984
985 985 def copy(ui, repo, *pats, **opts):
986 986 """mark files as copied for the next commit
987 987
988 988 Mark dest as having copies of source files. If dest is a
989 989 directory, copies are put in that directory. If dest is a file,
990 990 there can only be one source.
991 991
992 992 By default, this command copies the contents of files as they
993 993 stand in the working directory. If invoked with --after, the
994 994 operation is recorded, but no copying is performed.
995 995
996 996 This command takes effect in the next commit.
997 997
998 998 NOTE: This command should be treated as experimental. While it
999 999 should properly record copied files, this information is not yet
1000 1000 fully used by merge, nor fully reported by log.
1001 1001 """
1002 1002 try:
1003 1003 wlock = repo.wlock(0)
1004 1004 errs, copied = docopy(ui, repo, pats, opts, wlock)
1005 1005 except lock.LockHeld, inst:
1006 1006 ui.warn(_("repository lock held by %s\n") % inst.args[0])
1007 1007 errs = 1
1008 1008 return errs
1009 1009
1010 1010 def debugancestor(ui, index, rev1, rev2):
1011 1011 """find the ancestor revision of two revisions in a given index"""
1012 1012 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index, "")
1013 1013 a = r.ancestor(r.lookup(rev1), r.lookup(rev2))
1014 1014 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1015 1015
1016 def debugcomplete(ui, cmd):
1017 """returns the completion list associated with the given command"""
1018 clist = findpossible(cmd).keys()
1019 clist.sort()
1020 ui.write("%s\n" % " ".join(clist))
1021
1016 1022 def debugrebuildstate(ui, repo, rev=None):
1017 1023 """rebuild the dirstate as it would look like for the given revision"""
1018 1024 if not rev:
1019 1025 rev = repo.changelog.tip()
1020 1026 else:
1021 1027 rev = repo.lookup(rev)
1022 1028 change = repo.changelog.read(rev)
1023 1029 n = change[0]
1024 1030 files = repo.manifest.readflags(n)
1025 1031 wlock = repo.wlock()
1026 1032 repo.dirstate.rebuild(rev, files.iteritems())
1027 1033
1028 1034 def debugcheckstate(ui, repo):
1029 1035 """validate the correctness of the current dirstate"""
1030 1036 parent1, parent2 = repo.dirstate.parents()
1031 1037 repo.dirstate.read()
1032 1038 dc = repo.dirstate.map
1033 1039 keys = dc.keys()
1034 1040 keys.sort()
1035 1041 m1n = repo.changelog.read(parent1)[0]
1036 1042 m2n = repo.changelog.read(parent2)[0]
1037 1043 m1 = repo.manifest.read(m1n)
1038 1044 m2 = repo.manifest.read(m2n)
1039 1045 errors = 0
1040 1046 for f in dc:
1041 1047 state = repo.dirstate.state(f)
1042 1048 if state in "nr" and f not in m1:
1043 1049 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1044 1050 errors += 1
1045 1051 if state in "a" and f in m1:
1046 1052 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1047 1053 errors += 1
1048 1054 if state in "m" and f not in m1 and f not in m2:
1049 1055 ui.warn(_("%s in state %s, but not in either manifest\n") %
1050 1056 (f, state))
1051 1057 errors += 1
1052 1058 for f in m1:
1053 1059 state = repo.dirstate.state(f)
1054 1060 if state not in "nrm":
1055 1061 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1056 1062 errors += 1
1057 1063 if errors:
1058 1064 error = _(".hg/dirstate inconsistent with current parent's manifest")
1059 1065 raise util.Abort(error)
1060 1066
1061 1067 def debugconfig(ui, repo):
1062 1068 """show combined config settings from all hgrc files"""
1063 1069 for section, name, value in ui.walkconfig():
1064 1070 ui.write('%s.%s=%s\n' % (section, name, value))
1065 1071
1066 1072 def debugsetparents(ui, repo, rev1, rev2=None):
1067 1073 """manually set the parents of the current working directory
1068 1074
1069 1075 This is useful for writing repository conversion tools, but should
1070 1076 be used with care.
1071 1077 """
1072 1078
1073 1079 if not rev2:
1074 1080 rev2 = hex(nullid)
1075 1081
1076 1082 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
1077 1083
1078 1084 def debugstate(ui, repo):
1079 1085 """show the contents of the current dirstate"""
1080 1086 repo.dirstate.read()
1081 1087 dc = repo.dirstate.map
1082 1088 keys = dc.keys()
1083 1089 keys.sort()
1084 1090 for file_ in keys:
1085 1091 ui.write("%c %3o %10d %s %s\n"
1086 1092 % (dc[file_][0], dc[file_][1] & 0777, dc[file_][2],
1087 1093 time.strftime("%x %X",
1088 1094 time.localtime(dc[file_][3])), file_))
1089 1095 for f in repo.dirstate.copies:
1090 1096 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copies[f], f))
1091 1097
1092 1098 def debugdata(ui, file_, rev):
1093 1099 """dump the contents of an data file revision"""
1094 1100 r = revlog.revlog(util.opener(os.getcwd(), audit=False),
1095 1101 file_[:-2] + ".i", file_)
1096 1102 try:
1097 1103 ui.write(r.revision(r.lookup(rev)))
1098 1104 except KeyError:
1099 1105 raise util.Abort(_('invalid revision identifier %s'), rev)
1100 1106
1101 1107 def debugindex(ui, file_):
1102 1108 """dump the contents of an index file"""
1103 1109 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_, "")
1104 1110 ui.write(" rev offset length base linkrev" +
1105 1111 " nodeid p1 p2\n")
1106 1112 for i in range(r.count()):
1107 1113 e = r.index[i]
1108 1114 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1109 1115 i, e[0], e[1], e[2], e[3],
1110 1116 short(e[6]), short(e[4]), short(e[5])))
1111 1117
1112 1118 def debugindexdot(ui, file_):
1113 1119 """dump an index DAG as a .dot file"""
1114 1120 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_, "")
1115 1121 ui.write("digraph G {\n")
1116 1122 for i in range(r.count()):
1117 1123 e = r.index[i]
1118 1124 ui.write("\t%d -> %d\n" % (r.rev(e[4]), i))
1119 1125 if e[5] != nullid:
1120 1126 ui.write("\t%d -> %d\n" % (r.rev(e[5]), i))
1121 1127 ui.write("}\n")
1122 1128
1123 1129 def debugrename(ui, repo, file, rev=None):
1124 1130 """dump rename information"""
1125 1131 r = repo.file(relpath(repo, [file])[0])
1126 1132 if rev:
1127 1133 try:
1128 1134 # assume all revision numbers are for changesets
1129 1135 n = repo.lookup(rev)
1130 1136 change = repo.changelog.read(n)
1131 1137 m = repo.manifest.read(change[0])
1132 1138 n = m[relpath(repo, [file])[0]]
1133 1139 except (hg.RepoError, KeyError):
1134 1140 n = r.lookup(rev)
1135 1141 else:
1136 1142 n = r.tip()
1137 1143 m = r.renamed(n)
1138 1144 if m:
1139 1145 ui.write(_("renamed from %s:%s\n") % (m[0], hex(m[1])))
1140 1146 else:
1141 1147 ui.write(_("not renamed\n"))
1142 1148
1143 1149 def debugwalk(ui, repo, *pats, **opts):
1144 1150 """show how files match on given patterns"""
1145 1151 items = list(walk(repo, pats, opts))
1146 1152 if not items:
1147 1153 return
1148 1154 fmt = '%%s %%-%ds %%-%ds %%s' % (
1149 1155 max([len(abs) for (src, abs, rel, exact) in items]),
1150 1156 max([len(rel) for (src, abs, rel, exact) in items]))
1151 1157 for src, abs, rel, exact in items:
1152 1158 line = fmt % (src, abs, rel, exact and 'exact' or '')
1153 1159 ui.write("%s\n" % line.rstrip())
1154 1160
1155 1161 def diff(ui, repo, *pats, **opts):
1156 1162 """diff repository (or selected files)
1157 1163
1158 1164 Show differences between revisions for the specified files.
1159 1165
1160 1166 Differences between files are shown using the unified diff format.
1161 1167
1162 1168 When two revision arguments are given, then changes are shown
1163 1169 between those revisions. If only one revision is specified then
1164 1170 that revision is compared to the working directory, and, when no
1165 1171 revisions are specified, the working directory files are compared
1166 1172 to its parent.
1167 1173
1168 1174 Without the -a option, diff will avoid generating diffs of files
1169 1175 it detects as binary. With -a, diff will generate a diff anyway,
1170 1176 probably with undesirable results.
1171 1177 """
1172 1178 node1, node2 = None, None
1173 1179 revs = [repo.lookup(x) for x in opts['rev']]
1174 1180
1175 1181 if len(revs) > 0:
1176 1182 node1 = revs[0]
1177 1183 if len(revs) > 1:
1178 1184 node2 = revs[1]
1179 1185 if len(revs) > 2:
1180 1186 raise util.Abort(_("too many revisions to diff"))
1181 1187
1182 1188 fns, matchfn, anypats = matchpats(repo, pats, opts)
1183 1189
1184 1190 dodiff(sys.stdout, ui, repo, node1, node2, fns, match=matchfn,
1185 1191 text=opts['text'], opts=opts)
1186 1192
1187 1193 def doexport(ui, repo, changeset, seqno, total, revwidth, opts):
1188 1194 node = repo.lookup(changeset)
1189 1195 parents = [p for p in repo.changelog.parents(node) if p != nullid]
1190 1196 if opts['switch_parent']:
1191 1197 parents.reverse()
1192 1198 prev = (parents and parents[0]) or nullid
1193 1199 change = repo.changelog.read(node)
1194 1200
1195 1201 fp = make_file(repo, repo.changelog, opts['output'],
1196 1202 node=node, total=total, seqno=seqno,
1197 1203 revwidth=revwidth)
1198 1204 if fp != sys.stdout:
1199 1205 ui.note("%s\n" % fp.name)
1200 1206
1201 1207 fp.write("# HG changeset patch\n")
1202 1208 fp.write("# User %s\n" % change[1])
1203 1209 fp.write("# Node ID %s\n" % hex(node))
1204 1210 fp.write("# Parent %s\n" % hex(prev))
1205 1211 if len(parents) > 1:
1206 1212 fp.write("# Parent %s\n" % hex(parents[1]))
1207 1213 fp.write(change[4].rstrip())
1208 1214 fp.write("\n\n")
1209 1215
1210 1216 dodiff(fp, ui, repo, prev, node, text=opts['text'])
1211 1217 if fp != sys.stdout:
1212 1218 fp.close()
1213 1219
1214 1220 def export(ui, repo, *changesets, **opts):
1215 1221 """dump the header and diffs for one or more changesets
1216 1222
1217 1223 Print the changeset header and diffs for one or more revisions.
1218 1224
1219 1225 The information shown in the changeset header is: author,
1220 1226 changeset hash, parent and commit comment.
1221 1227
1222 1228 Output may be to a file, in which case the name of the file is
1223 1229 given using a format string. The formatting rules are as follows:
1224 1230
1225 1231 %% literal "%" character
1226 1232 %H changeset hash (40 bytes of hexadecimal)
1227 1233 %N number of patches being generated
1228 1234 %R changeset revision number
1229 1235 %b basename of the exporting repository
1230 1236 %h short-form changeset hash (12 bytes of hexadecimal)
1231 1237 %n zero-padded sequence number, starting at 1
1232 1238 %r zero-padded changeset revision number
1233 1239
1234 1240 Without the -a option, export will avoid generating diffs of files
1235 1241 it detects as binary. With -a, export will generate a diff anyway,
1236 1242 probably with undesirable results.
1237 1243
1238 1244 With the --switch-parent option, the diff will be against the second
1239 1245 parent. It can be useful to review a merge.
1240 1246 """
1241 1247 if not changesets:
1242 1248 raise util.Abort(_("export requires at least one changeset"))
1243 1249 seqno = 0
1244 1250 revs = list(revrange(ui, repo, changesets))
1245 1251 total = len(revs)
1246 1252 revwidth = max(map(len, revs))
1247 1253 msg = len(revs) > 1 and _("Exporting patches:\n") or _("Exporting patch:\n")
1248 1254 ui.note(msg)
1249 1255 for cset in revs:
1250 1256 seqno += 1
1251 1257 doexport(ui, repo, cset, seqno, total, revwidth, opts)
1252 1258
1253 1259 def forget(ui, repo, *pats, **opts):
1254 1260 """don't add the specified files on the next commit
1255 1261
1256 1262 Undo an 'hg add' scheduled for the next commit.
1257 1263 """
1258 1264 forget = []
1259 1265 for src, abs, rel, exact in walk(repo, pats, opts):
1260 1266 if repo.dirstate.state(abs) == 'a':
1261 1267 forget.append(abs)
1262 1268 if ui.verbose or not exact:
1263 1269 ui.status(_('forgetting %s\n') % ((pats and rel) or abs))
1264 1270 repo.forget(forget)
1265 1271
1266 1272 def grep(ui, repo, pattern, *pats, **opts):
1267 1273 """search for a pattern in specified files and revisions
1268 1274
1269 1275 Search revisions of files for a regular expression.
1270 1276
1271 1277 This command behaves differently than Unix grep. It only accepts
1272 1278 Python/Perl regexps. It searches repository history, not the
1273 1279 working directory. It always prints the revision number in which
1274 1280 a match appears.
1275 1281
1276 1282 By default, grep only prints output for the first revision of a
1277 1283 file in which it finds a match. To get it to print every revision
1278 1284 that contains a change in match status ("-" for a match that
1279 1285 becomes a non-match, or "+" for a non-match that becomes a match),
1280 1286 use the --all flag.
1281 1287 """
1282 1288 reflags = 0
1283 1289 if opts['ignore_case']:
1284 1290 reflags |= re.I
1285 1291 regexp = re.compile(pattern, reflags)
1286 1292 sep, eol = ':', '\n'
1287 1293 if opts['print0']:
1288 1294 sep = eol = '\0'
1289 1295
1290 1296 fcache = {}
1291 1297 def getfile(fn):
1292 1298 if fn not in fcache:
1293 1299 fcache[fn] = repo.file(fn)
1294 1300 return fcache[fn]
1295 1301
1296 1302 def matchlines(body):
1297 1303 begin = 0
1298 1304 linenum = 0
1299 1305 while True:
1300 1306 match = regexp.search(body, begin)
1301 1307 if not match:
1302 1308 break
1303 1309 mstart, mend = match.span()
1304 1310 linenum += body.count('\n', begin, mstart) + 1
1305 1311 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1306 1312 lend = body.find('\n', mend)
1307 1313 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1308 1314 begin = lend + 1
1309 1315
1310 1316 class linestate(object):
1311 1317 def __init__(self, line, linenum, colstart, colend):
1312 1318 self.line = line
1313 1319 self.linenum = linenum
1314 1320 self.colstart = colstart
1315 1321 self.colend = colend
1316 1322 def __eq__(self, other):
1317 1323 return self.line == other.line
1318 1324 def __hash__(self):
1319 1325 return hash(self.line)
1320 1326
1321 1327 matches = {}
1322 1328 def grepbody(fn, rev, body):
1323 1329 matches[rev].setdefault(fn, {})
1324 1330 m = matches[rev][fn]
1325 1331 for lnum, cstart, cend, line in matchlines(body):
1326 1332 s = linestate(line, lnum, cstart, cend)
1327 1333 m[s] = s
1328 1334
1329 1335 # FIXME: prev isn't used, why ?
1330 1336 prev = {}
1331 1337 ucache = {}
1332 1338 def display(fn, rev, states, prevstates):
1333 1339 diff = list(sets.Set(states).symmetric_difference(sets.Set(prevstates)))
1334 1340 diff.sort(lambda x, y: cmp(x.linenum, y.linenum))
1335 1341 counts = {'-': 0, '+': 0}
1336 1342 filerevmatches = {}
1337 1343 for l in diff:
1338 1344 if incrementing or not opts['all']:
1339 1345 change = ((l in prevstates) and '-') or '+'
1340 1346 r = rev
1341 1347 else:
1342 1348 change = ((l in states) and '-') or '+'
1343 1349 r = prev[fn]
1344 1350 cols = [fn, str(rev)]
1345 1351 if opts['line_number']:
1346 1352 cols.append(str(l.linenum))
1347 1353 if opts['all']:
1348 1354 cols.append(change)
1349 1355 if opts['user']:
1350 1356 cols.append(trimuser(ui, getchange(rev)[1], rev,
1351 1357 ucache))
1352 1358 if opts['files_with_matches']:
1353 1359 c = (fn, rev)
1354 1360 if c in filerevmatches:
1355 1361 continue
1356 1362 filerevmatches[c] = 1
1357 1363 else:
1358 1364 cols.append(l.line)
1359 1365 ui.write(sep.join(cols), eol)
1360 1366 counts[change] += 1
1361 1367 return counts['+'], counts['-']
1362 1368
1363 1369 fstate = {}
1364 1370 skip = {}
1365 1371 changeiter, getchange, matchfn = walkchangerevs(ui, repo, pats, opts)
1366 1372 count = 0
1367 1373 incrementing = False
1368 1374 for st, rev, fns in changeiter:
1369 1375 if st == 'window':
1370 1376 incrementing = rev
1371 1377 matches.clear()
1372 1378 elif st == 'add':
1373 1379 change = repo.changelog.read(repo.lookup(str(rev)))
1374 1380 mf = repo.manifest.read(change[0])
1375 1381 matches[rev] = {}
1376 1382 for fn in fns:
1377 1383 if fn in skip:
1378 1384 continue
1379 1385 fstate.setdefault(fn, {})
1380 1386 try:
1381 1387 grepbody(fn, rev, getfile(fn).read(mf[fn]))
1382 1388 except KeyError:
1383 1389 pass
1384 1390 elif st == 'iter':
1385 1391 states = matches[rev].items()
1386 1392 states.sort()
1387 1393 for fn, m in states:
1388 1394 if fn in skip:
1389 1395 continue
1390 1396 if incrementing or not opts['all'] or fstate[fn]:
1391 1397 pos, neg = display(fn, rev, m, fstate[fn])
1392 1398 count += pos + neg
1393 1399 if pos and not opts['all']:
1394 1400 skip[fn] = True
1395 1401 fstate[fn] = m
1396 1402 prev[fn] = rev
1397 1403
1398 1404 if not incrementing:
1399 1405 fstate = fstate.items()
1400 1406 fstate.sort()
1401 1407 for fn, state in fstate:
1402 1408 if fn in skip:
1403 1409 continue
1404 1410 display(fn, rev, {}, state)
1405 1411 return (count == 0 and 1) or 0
1406 1412
1407 1413 def heads(ui, repo, **opts):
1408 1414 """show current repository heads
1409 1415
1410 1416 Show all repository head changesets.
1411 1417
1412 1418 Repository "heads" are changesets that don't have children
1413 1419 changesets. They are where development generally takes place and
1414 1420 are the usual targets for update and merge operations.
1415 1421 """
1416 1422 if opts['rev']:
1417 1423 heads = repo.heads(repo.lookup(opts['rev']))
1418 1424 else:
1419 1425 heads = repo.heads()
1420 1426 br = None
1421 1427 if opts['branches']:
1422 1428 br = repo.branchlookup(heads)
1423 1429 for n in heads:
1424 1430 show_changeset(ui, repo, changenode=n, brinfo=br)
1425 1431
1426 1432 def identify(ui, repo):
1427 1433 """print information about the working copy
1428 1434
1429 1435 Print a short summary of the current state of the repo.
1430 1436
1431 1437 This summary identifies the repository state using one or two parent
1432 1438 hash identifiers, followed by a "+" if there are uncommitted changes
1433 1439 in the working directory, followed by a list of tags for this revision.
1434 1440 """
1435 1441 parents = [p for p in repo.dirstate.parents() if p != nullid]
1436 1442 if not parents:
1437 1443 ui.write(_("unknown\n"))
1438 1444 return
1439 1445
1440 1446 hexfunc = ui.verbose and hex or short
1441 1447 modified, added, removed, deleted, unknown = repo.changes()
1442 1448 output = ["%s%s" %
1443 1449 ('+'.join([hexfunc(parent) for parent in parents]),
1444 1450 (modified or added or removed or deleted) and "+" or "")]
1445 1451
1446 1452 if not ui.quiet:
1447 1453 # multiple tags for a single parent separated by '/'
1448 1454 parenttags = ['/'.join(tags)
1449 1455 for tags in map(repo.nodetags, parents) if tags]
1450 1456 # tags for multiple parents separated by ' + '
1451 1457 if parenttags:
1452 1458 output.append(' + '.join(parenttags))
1453 1459
1454 1460 ui.write("%s\n" % ' '.join(output))
1455 1461
1456 1462 def import_(ui, repo, patch1, *patches, **opts):
1457 1463 """import an ordered set of patches
1458 1464
1459 1465 Import a list of patches and commit them individually.
1460 1466
1461 1467 If there are outstanding changes in the working directory, import
1462 1468 will abort unless given the -f flag.
1463 1469
1464 1470 If a patch looks like a mail message (its first line starts with
1465 1471 "From " or looks like an RFC822 header), it will not be applied
1466 1472 unless the -f option is used. The importer neither parses nor
1467 1473 discards mail headers, so use -f only to override the "mailness"
1468 1474 safety check, not to import a real mail message.
1469 1475 """
1470 1476 patches = (patch1,) + patches
1471 1477
1472 1478 if not opts['force']:
1473 1479 modified, added, removed, deleted, unknown = repo.changes()
1474 1480 if modified or added or removed or deleted:
1475 1481 raise util.Abort(_("outstanding uncommitted changes"))
1476 1482
1477 1483 d = opts["base"]
1478 1484 strip = opts["strip"]
1479 1485
1480 1486 mailre = re.compile(r'(?:From |[\w-]+:)')
1481 1487
1482 1488 # attempt to detect the start of a patch
1483 1489 # (this heuristic is borrowed from quilt)
1484 1490 diffre = re.compile(r'(?:Index:[ \t]|diff[ \t]|RCS file: |' +
1485 1491 'retrieving revision [0-9]+(\.[0-9]+)*$|' +
1486 1492 '(---|\*\*\*)[ \t])')
1487 1493
1488 1494 for patch in patches:
1489 1495 ui.status(_("applying %s\n") % patch)
1490 1496 pf = os.path.join(d, patch)
1491 1497
1492 1498 message = []
1493 1499 user = None
1494 1500 hgpatch = False
1495 1501 for line in file(pf):
1496 1502 line = line.rstrip()
1497 1503 if (not message and not hgpatch and
1498 1504 mailre.match(line) and not opts['force']):
1499 1505 if len(line) > 35:
1500 1506 line = line[:32] + '...'
1501 1507 raise util.Abort(_('first line looks like a '
1502 1508 'mail header: ') + line)
1503 1509 if diffre.match(line):
1504 1510 break
1505 1511 elif hgpatch:
1506 1512 # parse values when importing the result of an hg export
1507 1513 if line.startswith("# User "):
1508 1514 user = line[7:]
1509 1515 ui.debug(_('User: %s\n') % user)
1510 1516 elif not line.startswith("# ") and line:
1511 1517 message.append(line)
1512 1518 hgpatch = False
1513 1519 elif line == '# HG changeset patch':
1514 1520 hgpatch = True
1515 1521 message = [] # We may have collected garbage
1516 1522 else:
1517 1523 message.append(line)
1518 1524
1519 1525 # make sure message isn't empty
1520 1526 if not message:
1521 1527 message = _("imported patch %s\n") % patch
1522 1528 else:
1523 1529 message = "%s\n" % '\n'.join(message)
1524 1530 ui.debug(_('message:\n%s\n') % message)
1525 1531
1526 1532 files = util.patch(strip, pf, ui)
1527 1533
1528 1534 if len(files) > 0:
1529 1535 addremove(ui, repo, *files)
1530 1536 repo.commit(files, message, user)
1531 1537
1532 1538 def incoming(ui, repo, source="default", **opts):
1533 1539 """show new changesets found in source
1534 1540
1535 1541 Show new changesets found in the specified repo or the default
1536 1542 pull repo. These are the changesets that would be pulled if a pull
1537 1543 was requested.
1538 1544
1539 1545 Currently only local repositories are supported.
1540 1546 """
1541 1547 source = ui.expandpath(source, repo.root)
1542 1548 other = hg.repository(ui, source)
1543 1549 if not other.local():
1544 1550 raise util.Abort(_("incoming doesn't work for remote repositories yet"))
1545 1551 o = repo.findincoming(other)
1546 1552 if not o:
1547 1553 return
1548 1554 o = other.changelog.nodesbetween(o)[0]
1549 1555 if opts['newest_first']:
1550 1556 o.reverse()
1551 1557 for n in o:
1552 1558 parents = [p for p in other.changelog.parents(n) if p != nullid]
1553 1559 if opts['no_merges'] and len(parents) == 2:
1554 1560 continue
1555 1561 show_changeset(ui, other, changenode=n)
1556 1562 if opts['patch']:
1557 1563 prev = (parents and parents[0]) or nullid
1558 1564 dodiff(ui, ui, other, prev, n)
1559 1565 ui.write("\n")
1560 1566
1561 1567 def init(ui, dest="."):
1562 1568 """create a new repository in the given directory
1563 1569
1564 1570 Initialize a new repository in the given directory. If the given
1565 1571 directory does not exist, it is created.
1566 1572
1567 1573 If no directory is given, the current directory is used.
1568 1574 """
1569 1575 if not os.path.exists(dest):
1570 1576 os.mkdir(dest)
1571 1577 hg.repository(ui, dest, create=1)
1572 1578
1573 1579 def locate(ui, repo, *pats, **opts):
1574 1580 """locate files matching specific patterns
1575 1581
1576 1582 Print all files under Mercurial control whose names match the
1577 1583 given patterns.
1578 1584
1579 1585 This command searches the current directory and its
1580 1586 subdirectories. To search an entire repository, move to the root
1581 1587 of the repository.
1582 1588
1583 1589 If no patterns are given to match, this command prints all file
1584 1590 names.
1585 1591
1586 1592 If you want to feed the output of this command into the "xargs"
1587 1593 command, use the "-0" option to both this command and "xargs".
1588 1594 This will avoid the problem of "xargs" treating single filenames
1589 1595 that contain white space as multiple filenames.
1590 1596 """
1591 1597 end = opts['print0'] and '\0' or '\n'
1592 1598 rev = opts['rev']
1593 1599 if rev:
1594 1600 node = repo.lookup(rev)
1595 1601 else:
1596 1602 node = None
1597 1603
1598 1604 for src, abs, rel, exact in walk(repo, pats, opts, node=node,
1599 1605 head='(?:.*/|)'):
1600 1606 if not node and repo.dirstate.state(abs) == '?':
1601 1607 continue
1602 1608 if opts['fullpath']:
1603 1609 ui.write(os.path.join(repo.root, abs), end)
1604 1610 else:
1605 1611 ui.write(((pats and rel) or abs), end)
1606 1612
1607 1613 def log(ui, repo, *pats, **opts):
1608 1614 """show revision history of entire repository or files
1609 1615
1610 1616 Print the revision history of the specified files or the entire project.
1611 1617
1612 1618 By default this command outputs: changeset id and hash, tags,
1613 1619 non-trivial parents, user, date and time, and a summary for each
1614 1620 commit. When the -v/--verbose switch is used, the list of changed
1615 1621 files and full commit message is shown.
1616 1622 """
1617 1623 class dui(object):
1618 1624 # Implement and delegate some ui protocol. Save hunks of
1619 1625 # output for later display in the desired order.
1620 1626 def __init__(self, ui):
1621 1627 self.ui = ui
1622 1628 self.hunk = {}
1623 1629 def bump(self, rev):
1624 1630 self.rev = rev
1625 1631 self.hunk[rev] = []
1626 1632 def note(self, *args):
1627 1633 if self.verbose:
1628 1634 self.write(*args)
1629 1635 def status(self, *args):
1630 1636 if not self.quiet:
1631 1637 self.write(*args)
1632 1638 def write(self, *args):
1633 1639 self.hunk[self.rev].append(args)
1634 1640 def debug(self, *args):
1635 1641 if self.debugflag:
1636 1642 self.write(*args)
1637 1643 def __getattr__(self, key):
1638 1644 return getattr(self.ui, key)
1639 1645
1640 1646 changeiter, getchange, matchfn = walkchangerevs(ui, repo, pats, opts)
1641 1647
1642 1648 if opts['limit']:
1643 1649 try:
1644 1650 limit = int(opts['limit'])
1645 1651 except ValueError:
1646 1652 raise util.Abort(_('limit must be a positive integer'))
1647 1653 if limit <= 0: raise util.Abort(_('limit must be positive'))
1648 1654 else:
1649 1655 limit = sys.maxint
1650 1656 count = 0
1651 1657
1652 1658 for st, rev, fns in changeiter:
1653 1659 if st == 'window':
1654 1660 du = dui(ui)
1655 1661 elif st == 'add':
1656 1662 du.bump(rev)
1657 1663 changenode = repo.changelog.node(rev)
1658 1664 parents = [p for p in repo.changelog.parents(changenode)
1659 1665 if p != nullid]
1660 1666 if opts['no_merges'] and len(parents) == 2:
1661 1667 continue
1662 1668 if opts['only_merges'] and len(parents) != 2:
1663 1669 continue
1664 1670
1665 1671 if opts['keyword']:
1666 1672 changes = getchange(rev)
1667 1673 miss = 0
1668 1674 for k in [kw.lower() for kw in opts['keyword']]:
1669 1675 if not (k in changes[1].lower() or
1670 1676 k in changes[4].lower() or
1671 1677 k in " ".join(changes[3][:20]).lower()):
1672 1678 miss = 1
1673 1679 break
1674 1680 if miss:
1675 1681 continue
1676 1682
1677 1683 br = None
1678 1684 if opts['branches']:
1679 1685 br = repo.branchlookup([repo.changelog.node(rev)])
1680 1686
1681 1687 show_changeset(du, repo, rev, brinfo=br)
1682 1688 if opts['patch']:
1683 1689 prev = (parents and parents[0]) or nullid
1684 1690 dodiff(du, du, repo, prev, changenode, match=matchfn)
1685 1691 du.write("\n\n")
1686 1692 elif st == 'iter':
1687 1693 if count == limit: break
1688 1694 if du.hunk[rev]:
1689 1695 count += 1
1690 1696 for args in du.hunk[rev]:
1691 1697 ui.write(*args)
1692 1698
1693 1699 def manifest(ui, repo, rev=None):
1694 1700 """output the latest or given revision of the project manifest
1695 1701
1696 1702 Print a list of version controlled files for the given revision.
1697 1703
1698 1704 The manifest is the list of files being version controlled. If no revision
1699 1705 is given then the tip is used.
1700 1706 """
1701 1707 if rev:
1702 1708 try:
1703 1709 # assume all revision numbers are for changesets
1704 1710 n = repo.lookup(rev)
1705 1711 change = repo.changelog.read(n)
1706 1712 n = change[0]
1707 1713 except hg.RepoError:
1708 1714 n = repo.manifest.lookup(rev)
1709 1715 else:
1710 1716 n = repo.manifest.tip()
1711 1717 m = repo.manifest.read(n)
1712 1718 mf = repo.manifest.readflags(n)
1713 1719 files = m.keys()
1714 1720 files.sort()
1715 1721
1716 1722 for f in files:
1717 1723 ui.write("%40s %3s %s\n" % (hex(m[f]), mf[f] and "755" or "644", f))
1718 1724
1719 1725 def outgoing(ui, repo, dest="default-push", **opts):
1720 1726 """show changesets not found in destination
1721 1727
1722 1728 Show changesets not found in the specified destination repo or the
1723 1729 default push repo. These are the changesets that would be pushed
1724 1730 if a push was requested.
1725 1731
1726 1732 See pull for valid source format details.
1727 1733 """
1728 1734 dest = ui.expandpath(dest, repo.root)
1729 1735 other = hg.repository(ui, dest)
1730 1736 o = repo.findoutgoing(other)
1731 1737 o = repo.changelog.nodesbetween(o)[0]
1732 1738 if opts['newest_first']:
1733 1739 o.reverse()
1734 1740 for n in o:
1735 1741 parents = [p for p in repo.changelog.parents(n) if p != nullid]
1736 1742 if opts['no_merges'] and len(parents) == 2:
1737 1743 continue
1738 1744 show_changeset(ui, repo, changenode=n)
1739 1745 if opts['patch']:
1740 1746 prev = (parents and parents[0]) or nullid
1741 1747 dodiff(ui, ui, repo, prev, n)
1742 1748 ui.write("\n")
1743 1749
1744 1750 def parents(ui, repo, rev=None, branches=None):
1745 1751 """show the parents of the working dir or revision
1746 1752
1747 1753 Print the working directory's parent revisions.
1748 1754 """
1749 1755 if rev:
1750 1756 p = repo.changelog.parents(repo.lookup(rev))
1751 1757 else:
1752 1758 p = repo.dirstate.parents()
1753 1759
1754 1760 br = None
1755 1761 if branches is not None:
1756 1762 br = repo.branchlookup(p)
1757 1763 for n in p:
1758 1764 if n != nullid:
1759 1765 show_changeset(ui, repo, changenode=n, brinfo=br)
1760 1766
1761 1767 def paths(ui, repo, search=None):
1762 1768 """show definition of symbolic path names
1763 1769
1764 1770 Show definition of symbolic path name NAME. If no name is given, show
1765 1771 definition of available names.
1766 1772
1767 1773 Path names are defined in the [paths] section of /etc/mercurial/hgrc
1768 1774 and $HOME/.hgrc. If run inside a repository, .hg/hgrc is used, too.
1769 1775 """
1770 1776 if search:
1771 1777 for name, path in ui.configitems("paths"):
1772 1778 if name == search:
1773 1779 ui.write("%s\n" % path)
1774 1780 return
1775 1781 ui.warn(_("not found!\n"))
1776 1782 return 1
1777 1783 else:
1778 1784 for name, path in ui.configitems("paths"):
1779 1785 ui.write("%s = %s\n" % (name, path))
1780 1786
1781 1787 def pull(ui, repo, source="default", **opts):
1782 1788 """pull changes from the specified source
1783 1789
1784 1790 Pull changes from a remote repository to a local one.
1785 1791
1786 1792 This finds all changes from the repository at the specified path
1787 1793 or URL and adds them to the local repository. By default, this
1788 1794 does not update the copy of the project in the working directory.
1789 1795
1790 1796 Valid URLs are of the form:
1791 1797
1792 1798 local/filesystem/path
1793 1799 http://[user@]host[:port][/path]
1794 1800 https://[user@]host[:port][/path]
1795 1801 ssh://[user@]host[:port][/path]
1796 1802
1797 1803 SSH requires an accessible shell account on the destination machine
1798 1804 and a copy of hg in the remote path. With SSH, paths are relative
1799 1805 to the remote user's home directory by default; use two slashes at
1800 1806 the start of a path to specify it as relative to the filesystem root.
1801 1807 """
1802 1808 source = ui.expandpath(source, repo.root)
1803 1809 ui.status(_('pulling from %s\n') % (source))
1804 1810
1805 1811 if opts['ssh']:
1806 1812 ui.setconfig("ui", "ssh", opts['ssh'])
1807 1813 if opts['remotecmd']:
1808 1814 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
1809 1815
1810 1816 other = hg.repository(ui, source)
1811 1817 revs = None
1812 1818 if opts['rev'] and not other.local():
1813 1819 raise util.Abort(_("pull -r doesn't work for remote repositories yet"))
1814 1820 elif opts['rev']:
1815 1821 revs = [other.lookup(rev) for rev in opts['rev']]
1816 1822 r = repo.pull(other, heads=revs)
1817 1823 if not r:
1818 1824 if opts['update']:
1819 1825 return update(ui, repo)
1820 1826 else:
1821 1827 ui.status(_("(run 'hg update' to get a working copy)\n"))
1822 1828
1823 1829 return r
1824 1830
1825 1831 def push(ui, repo, dest="default-push", **opts):
1826 1832 """push changes to the specified destination
1827 1833
1828 1834 Push changes from the local repository to the given destination.
1829 1835
1830 1836 This is the symmetrical operation for pull. It helps to move
1831 1837 changes from the current repository to a different one. If the
1832 1838 destination is local this is identical to a pull in that directory
1833 1839 from the current one.
1834 1840
1835 1841 By default, push will refuse to run if it detects the result would
1836 1842 increase the number of remote heads. This generally indicates the
1837 1843 the client has forgotten to sync and merge before pushing.
1838 1844
1839 1845 Valid URLs are of the form:
1840 1846
1841 1847 local/filesystem/path
1842 1848 ssh://[user@]host[:port][/path]
1843 1849
1844 1850 SSH requires an accessible shell account on the destination
1845 1851 machine and a copy of hg in the remote path.
1846 1852 """
1847 1853 dest = ui.expandpath(dest, repo.root)
1848 1854 ui.status('pushing to %s\n' % (dest))
1849 1855
1850 1856 if opts['ssh']:
1851 1857 ui.setconfig("ui", "ssh", opts['ssh'])
1852 1858 if opts['remotecmd']:
1853 1859 ui.setconfig("ui", "remotecmd", opts['remotecmd'])
1854 1860
1855 1861 other = hg.repository(ui, dest)
1856 1862 revs = None
1857 1863 if opts['rev']:
1858 1864 revs = [repo.lookup(rev) for rev in opts['rev']]
1859 1865 r = repo.push(other, opts['force'], revs=revs)
1860 1866 return r
1861 1867
1862 1868 def rawcommit(ui, repo, *flist, **rc):
1863 1869 """raw commit interface (DEPRECATED)
1864 1870
1865 1871 (DEPRECATED)
1866 1872 Lowlevel commit, for use in helper scripts.
1867 1873
1868 1874 This command is not intended to be used by normal users, as it is
1869 1875 primarily useful for importing from other SCMs.
1870 1876
1871 1877 This command is now deprecated and will be removed in a future
1872 1878 release, please use debugsetparents and commit instead.
1873 1879 """
1874 1880
1875 1881 ui.warn(_("(the rawcommit command is deprecated)\n"))
1876 1882
1877 1883 message = rc['message']
1878 1884 if not message and rc['logfile']:
1879 1885 try:
1880 1886 message = open(rc['logfile']).read()
1881 1887 except IOError:
1882 1888 pass
1883 1889 if not message and not rc['logfile']:
1884 1890 raise util.Abort(_("missing commit message"))
1885 1891
1886 1892 files = relpath(repo, list(flist))
1887 1893 if rc['files']:
1888 1894 files += open(rc['files']).read().splitlines()
1889 1895
1890 1896 rc['parent'] = map(repo.lookup, rc['parent'])
1891 1897
1892 1898 try:
1893 1899 repo.rawcommit(files, message, rc['user'], rc['date'], *rc['parent'])
1894 1900 except ValueError, inst:
1895 1901 raise util.Abort(str(inst))
1896 1902
1897 1903 def recover(ui, repo):
1898 1904 """roll back an interrupted transaction
1899 1905
1900 1906 Recover from an interrupted commit or pull.
1901 1907
1902 1908 This command tries to fix the repository status after an interrupted
1903 1909 operation. It should only be necessary when Mercurial suggests it.
1904 1910 """
1905 1911 if repo.recover():
1906 1912 return repo.verify()
1907 1913 return False
1908 1914
1909 1915 def remove(ui, repo, pat, *pats, **opts):
1910 1916 """remove the specified files on the next commit
1911 1917
1912 1918 Schedule the indicated files for removal from the repository.
1913 1919
1914 1920 This command schedules the files to be removed at the next commit.
1915 1921 This only removes files from the current branch, not from the
1916 1922 entire project history. If the files still exist in the working
1917 1923 directory, they will be deleted from it.
1918 1924 """
1919 1925 names = []
1920 1926 def okaytoremove(abs, rel, exact):
1921 1927 modified, added, removed, deleted, unknown = repo.changes(files=[abs])
1922 1928 reason = None
1923 1929 if modified and not opts['force']:
1924 1930 reason = _('is modified')
1925 1931 elif added:
1926 1932 reason = _('has been marked for add')
1927 1933 elif unknown:
1928 1934 reason = _('is not managed')
1929 1935 if reason:
1930 1936 if exact:
1931 1937 ui.warn(_('not removing %s: file %s\n') % (rel, reason))
1932 1938 else:
1933 1939 return True
1934 1940 for src, abs, rel, exact in walk(repo, (pat,) + pats, opts):
1935 1941 if okaytoremove(abs, rel, exact):
1936 1942 if ui.verbose or not exact:
1937 1943 ui.status(_('removing %s\n') % rel)
1938 1944 names.append(abs)
1939 1945 repo.remove(names, unlink=True)
1940 1946
1941 1947 def rename(ui, repo, *pats, **opts):
1942 1948 """rename files; equivalent of copy + remove
1943 1949
1944 1950 Mark dest as copies of sources; mark sources for deletion. If
1945 1951 dest is a directory, copies are put in that directory. If dest is
1946 1952 a file, there can only be one source.
1947 1953
1948 1954 By default, this command copies the contents of files as they
1949 1955 stand in the working directory. If invoked with --after, the
1950 1956 operation is recorded, but no copying is performed.
1951 1957
1952 1958 This command takes effect in the next commit.
1953 1959
1954 1960 NOTE: This command should be treated as experimental. While it
1955 1961 should properly record rename files, this information is not yet
1956 1962 fully used by merge, nor fully reported by log.
1957 1963 """
1958 1964 try:
1959 1965 wlock = repo.wlock(0)
1960 1966 errs, copied = docopy(ui, repo, pats, opts, wlock)
1961 1967 names = []
1962 1968 for abs, rel, exact in copied:
1963 1969 if ui.verbose or not exact:
1964 1970 ui.status(_('removing %s\n') % rel)
1965 1971 names.append(abs)
1966 1972 repo.remove(names, True, wlock)
1967 1973 except lock.LockHeld, inst:
1968 1974 ui.warn(_("repository lock held by %s\n") % inst.args[0])
1969 1975 errs = 1
1970 1976 return errs
1971 1977
1972 1978 def revert(ui, repo, *pats, **opts):
1973 1979 """revert modified files or dirs back to their unmodified states
1974 1980
1975 1981 In its default mode, it reverts any uncommitted modifications made
1976 1982 to the named files or directories. This restores the contents of
1977 1983 the affected files to an unmodified state.
1978 1984
1979 1985 Using the -r option, it reverts the given files or directories to
1980 1986 their state as of an earlier revision. This can be helpful to "roll
1981 1987 back" some or all of a change that should not have been committed.
1982 1988
1983 1989 Revert modifies the working directory. It does not commit any
1984 1990 changes, or change the parent of the current working directory.
1985 1991
1986 1992 If a file has been deleted, it is recreated. If the executable
1987 1993 mode of a file was changed, it is reset.
1988 1994
1989 1995 If names are given, all files matching the names are reverted.
1990 1996
1991 1997 If no arguments are given, all files in the repository are reverted.
1992 1998 """
1993 1999 node = opts['rev'] and repo.lookup(opts['rev']) or \
1994 2000 repo.dirstate.parents()[0]
1995 2001
1996 2002 files, choose, anypats = matchpats(repo, pats, opts)
1997 2003 modified, added, removed, deleted, unknown = repo.changes(match=choose)
1998 2004 repo.forget(added)
1999 2005 repo.undelete(removed)
2000 2006
2001 2007 return repo.update(node, False, True, choose, False)
2002 2008
2003 2009 def root(ui, repo):
2004 2010 """print the root (top) of the current working dir
2005 2011
2006 2012 Print the root directory of the current repository.
2007 2013 """
2008 2014 ui.write(repo.root + "\n")
2009 2015
2010 2016 def serve(ui, repo, **opts):
2011 2017 """export the repository via HTTP
2012 2018
2013 2019 Start a local HTTP repository browser and pull server.
2014 2020
2015 2021 By default, the server logs accesses to stdout and errors to
2016 2022 stderr. Use the "-A" and "-E" options to log to files.
2017 2023 """
2018 2024
2019 2025 if opts["stdio"]:
2020 2026 fin, fout = sys.stdin, sys.stdout
2021 2027 sys.stdout = sys.stderr
2022 2028
2023 2029 # Prevent insertion/deletion of CRs
2024 2030 util.set_binary(fin)
2025 2031 util.set_binary(fout)
2026 2032
2027 2033 def getarg():
2028 2034 argline = fin.readline()[:-1]
2029 2035 arg, l = argline.split()
2030 2036 val = fin.read(int(l))
2031 2037 return arg, val
2032 2038 def respond(v):
2033 2039 fout.write("%d\n" % len(v))
2034 2040 fout.write(v)
2035 2041 fout.flush()
2036 2042
2037 2043 lock = None
2038 2044
2039 2045 while 1:
2040 2046 cmd = fin.readline()[:-1]
2041 2047 if cmd == '':
2042 2048 return
2043 2049 if cmd == "heads":
2044 2050 h = repo.heads()
2045 2051 respond(" ".join(map(hex, h)) + "\n")
2046 2052 if cmd == "lock":
2047 2053 lock = repo.lock()
2048 2054 respond("")
2049 2055 if cmd == "unlock":
2050 2056 if lock:
2051 2057 lock.release()
2052 2058 lock = None
2053 2059 respond("")
2054 2060 elif cmd == "branches":
2055 2061 arg, nodes = getarg()
2056 2062 nodes = map(bin, nodes.split(" "))
2057 2063 r = []
2058 2064 for b in repo.branches(nodes):
2059 2065 r.append(" ".join(map(hex, b)) + "\n")
2060 2066 respond("".join(r))
2061 2067 elif cmd == "between":
2062 2068 arg, pairs = getarg()
2063 2069 pairs = [map(bin, p.split("-")) for p in pairs.split(" ")]
2064 2070 r = []
2065 2071 for b in repo.between(pairs):
2066 2072 r.append(" ".join(map(hex, b)) + "\n")
2067 2073 respond("".join(r))
2068 2074 elif cmd == "changegroup":
2069 2075 nodes = []
2070 2076 arg, roots = getarg()
2071 2077 nodes = map(bin, roots.split(" "))
2072 2078
2073 2079 cg = repo.changegroup(nodes, 'serve')
2074 2080 while 1:
2075 2081 d = cg.read(4096)
2076 2082 if not d:
2077 2083 break
2078 2084 fout.write(d)
2079 2085
2080 2086 fout.flush()
2081 2087
2082 2088 elif cmd == "addchangegroup":
2083 2089 if not lock:
2084 2090 respond("not locked")
2085 2091 continue
2086 2092 respond("")
2087 2093
2088 2094 r = repo.addchangegroup(fin)
2089 2095 respond("")
2090 2096
2091 2097 optlist = "name templates style address port ipv6 accesslog errorlog"
2092 2098 for o in optlist.split():
2093 2099 if opts[o]:
2094 2100 ui.setconfig("web", o, opts[o])
2095 2101
2096 2102 if opts['daemon'] and not opts['daemon_pipefds']:
2097 2103 rfd, wfd = os.pipe()
2098 2104 args = sys.argv[:]
2099 2105 args.append('--daemon-pipefds=%d,%d' % (rfd, wfd))
2100 2106 pid = os.spawnvp(os.P_NOWAIT | getattr(os, 'P_DETACH', 0),
2101 2107 args[0], args)
2102 2108 os.close(wfd)
2103 2109 os.read(rfd, 1)
2104 2110 os._exit(0)
2105 2111
2106 2112 try:
2107 2113 httpd = hgweb.create_server(repo)
2108 2114 except socket.error, inst:
2109 2115 raise util.Abort(_('cannot start server: ') + inst.args[1])
2110 2116
2111 2117 if ui.verbose:
2112 2118 addr, port = httpd.socket.getsockname()
2113 2119 if addr == '0.0.0.0':
2114 2120 addr = socket.gethostname()
2115 2121 else:
2116 2122 try:
2117 2123 addr = socket.gethostbyaddr(addr)[0]
2118 2124 except socket.error:
2119 2125 pass
2120 2126 if port != 80:
2121 2127 ui.status(_('listening at http://%s:%d/\n') % (addr, port))
2122 2128 else:
2123 2129 ui.status(_('listening at http://%s/\n') % addr)
2124 2130
2125 2131 if opts['pid_file']:
2126 2132 fp = open(opts['pid_file'], 'w')
2127 2133 fp.write(str(os.getpid()))
2128 2134 fp.close()
2129 2135
2130 2136 if opts['daemon_pipefds']:
2131 2137 rfd, wfd = [int(x) for x in opts['daemon_pipefds'].split(',')]
2132 2138 os.close(rfd)
2133 2139 os.write(wfd, 'y')
2134 2140 os.close(wfd)
2135 2141 sys.stdout.flush()
2136 2142 sys.stderr.flush()
2137 2143 fd = os.open(util.nulldev, os.O_RDWR)
2138 2144 if fd != 0: os.dup2(fd, 0)
2139 2145 if fd != 1: os.dup2(fd, 1)
2140 2146 if fd != 2: os.dup2(fd, 2)
2141 2147 if fd not in (0, 1, 2): os.close(fd)
2142 2148
2143 2149 httpd.serve_forever()
2144 2150
2145 2151 def status(ui, repo, *pats, **opts):
2146 2152 """show changed files in the working directory
2147 2153
2148 2154 Show changed files in the repository. If names are
2149 2155 given, only files that match are shown.
2150 2156
2151 2157 The codes used to show the status of files are:
2152 2158 M = modified
2153 2159 A = added
2154 2160 R = removed
2155 2161 ! = deleted, but still tracked
2156 2162 ? = not tracked
2157 2163 """
2158 2164
2159 2165 files, matchfn, anypats = matchpats(repo, pats, opts)
2160 2166 cwd = (pats and repo.getcwd()) or ''
2161 2167 modified, added, removed, deleted, unknown = [
2162 2168 [util.pathto(cwd, x) for x in n]
2163 2169 for n in repo.changes(files=files, match=matchfn)]
2164 2170
2165 2171 changetypes = [(_('modified'), 'M', modified),
2166 2172 (_('added'), 'A', added),
2167 2173 (_('removed'), 'R', removed),
2168 2174 (_('deleted'), '!', deleted),
2169 2175 (_('unknown'), '?', unknown)]
2170 2176
2171 2177 end = opts['print0'] and '\0' or '\n'
2172 2178
2173 2179 for opt, char, changes in ([ct for ct in changetypes if opts[ct[0]]]
2174 2180 or changetypes):
2175 2181 if opts['no_status']:
2176 2182 format = "%%s%s" % end
2177 2183 else:
2178 2184 format = "%s %%s%s" % (char, end);
2179 2185
2180 2186 for f in changes:
2181 2187 ui.write(format % f)
2182 2188
2183 2189 def tag(ui, repo, name, rev_=None, **opts):
2184 2190 """add a tag for the current tip or a given revision
2185 2191
2186 2192 Name a particular revision using <name>.
2187 2193
2188 2194 Tags are used to name particular revisions of the repository and are
2189 2195 very useful to compare different revision, to go back to significant
2190 2196 earlier versions or to mark branch points as releases, etc.
2191 2197
2192 2198 If no revision is given, the tip is used.
2193 2199
2194 2200 To facilitate version control, distribution, and merging of tags,
2195 2201 they are stored as a file named ".hgtags" which is managed
2196 2202 similarly to other project files and can be hand-edited if
2197 2203 necessary. The file '.hg/localtags' is used for local tags (not
2198 2204 shared among repositories).
2199 2205 """
2200 2206 if name == "tip":
2201 2207 raise util.Abort(_("the name 'tip' is reserved"))
2202 2208 if rev_ is not None:
2203 2209 ui.warn(_("use of 'hg tag NAME [REV]' is deprecated, "
2204 2210 "please use 'hg tag [-r REV] NAME' instead\n"))
2205 2211 if opts['rev']:
2206 2212 raise util.Abort(_("use only one form to specify the revision"))
2207 2213 if opts['rev']:
2208 2214 rev_ = opts['rev']
2209 2215 if rev_:
2210 2216 r = hex(repo.lookup(rev_))
2211 2217 else:
2212 2218 r = hex(repo.changelog.tip())
2213 2219
2214 2220 disallowed = (revrangesep, '\r', '\n')
2215 2221 for c in disallowed:
2216 2222 if name.find(c) >= 0:
2217 2223 raise util.Abort(_("%s cannot be used in a tag name") % repr(c))
2218 2224
2219 2225 repo.hook('pretag', throw=True, node=r, tag=name,
2220 2226 local=int(not not opts['local']))
2221 2227
2222 2228 if opts['local']:
2223 2229 repo.opener("localtags", "a").write("%s %s\n" % (r, name))
2224 2230 repo.hook('tag', node=r, tag=name, local=1)
2225 2231 return
2226 2232
2227 2233 for x in repo.changes():
2228 2234 if ".hgtags" in x:
2229 2235 raise util.Abort(_("working copy of .hgtags is changed "
2230 2236 "(please commit .hgtags manually)"))
2231 2237
2232 2238 repo.wfile(".hgtags", "ab").write("%s %s\n" % (r, name))
2233 2239 if repo.dirstate.state(".hgtags") == '?':
2234 2240 repo.add([".hgtags"])
2235 2241
2236 2242 message = (opts['message'] or
2237 2243 _("Added tag %s for changeset %s") % (name, r))
2238 2244 try:
2239 2245 repo.commit([".hgtags"], message, opts['user'], opts['date'])
2240 2246 repo.hook('tag', node=r, tag=name, local=0)
2241 2247 except ValueError, inst:
2242 2248 raise util.Abort(str(inst))
2243 2249
2244 2250 def tags(ui, repo):
2245 2251 """list repository tags
2246 2252
2247 2253 List the repository tags.
2248 2254
2249 2255 This lists both regular and local tags.
2250 2256 """
2251 2257
2252 2258 l = repo.tagslist()
2253 2259 l.reverse()
2254 2260 for t, n in l:
2255 2261 try:
2256 2262 r = "%5d:%s" % (repo.changelog.rev(n), hex(n))
2257 2263 except KeyError:
2258 2264 r = " ?:?"
2259 2265 ui.write("%-30s %s\n" % (t, r))
2260 2266
2261 2267 def tip(ui, repo, **opts):
2262 2268 """show the tip revision
2263 2269
2264 2270 Show the tip revision.
2265 2271 """
2266 2272 n = repo.changelog.tip()
2267 2273 br = None
2268 2274 if opts['branches']:
2269 2275 br = repo.branchlookup([n])
2270 2276 show_changeset(ui, repo, changenode=n, brinfo=br)
2271 2277 if opts['patch']:
2272 2278 dodiff(ui, ui, repo, repo.changelog.parents(n)[0], n)
2273 2279
2274 2280 def unbundle(ui, repo, fname, **opts):
2275 2281 """apply a changegroup file
2276 2282
2277 2283 Apply a compressed changegroup file generated by the bundle
2278 2284 command.
2279 2285 """
2280 2286 f = urllib.urlopen(fname)
2281 2287
2282 2288 if f.read(4) != "HG10":
2283 2289 raise util.Abort(_("%s: not a Mercurial bundle file") % fname)
2284 2290
2285 2291 def bzgenerator(f):
2286 2292 zd = bz2.BZ2Decompressor()
2287 2293 for chunk in f:
2288 2294 yield zd.decompress(chunk)
2289 2295
2290 2296 bzgen = bzgenerator(util.filechunkiter(f, 4096))
2291 2297 if repo.addchangegroup(util.chunkbuffer(bzgen)):
2292 2298 return 1
2293 2299
2294 2300 if opts['update']:
2295 2301 return update(ui, repo)
2296 2302 else:
2297 2303 ui.status(_("(run 'hg update' to get a working copy)\n"))
2298 2304
2299 2305 def undo(ui, repo):
2300 2306 """undo the last commit or pull
2301 2307
2302 2308 Roll back the last pull or commit transaction on the
2303 2309 repository, restoring the project to its earlier state.
2304 2310
2305 2311 This command should be used with care. There is only one level of
2306 2312 undo and there is no redo.
2307 2313
2308 2314 This command is not intended for use on public repositories. Once
2309 2315 a change is visible for pull by other users, undoing it locally is
2310 2316 ineffective.
2311 2317 """
2312 2318 repo.undo()
2313 2319
2314 2320 def update(ui, repo, node=None, merge=False, clean=False, force=None,
2315 2321 branch=None):
2316 2322 """update or merge working directory
2317 2323
2318 2324 Update the working directory to the specified revision.
2319 2325
2320 2326 If there are no outstanding changes in the working directory and
2321 2327 there is a linear relationship between the current version and the
2322 2328 requested version, the result is the requested version.
2323 2329
2324 2330 Otherwise the result is a merge between the contents of the
2325 2331 current working directory and the requested version. Files that
2326 2332 changed between either parent are marked as changed for the next
2327 2333 commit and a commit must be performed before any further updates
2328 2334 are allowed.
2329 2335
2330 2336 By default, update will refuse to run if doing so would require
2331 2337 merging or discarding local changes.
2332 2338 """
2333 2339 if branch:
2334 2340 br = repo.branchlookup(branch=branch)
2335 2341 found = []
2336 2342 for x in br:
2337 2343 if branch in br[x]:
2338 2344 found.append(x)
2339 2345 if len(found) > 1:
2340 2346 ui.warn(_("Found multiple heads for %s\n") % branch)
2341 2347 for x in found:
2342 2348 show_changeset(ui, repo, changenode=x, brinfo=br)
2343 2349 return 1
2344 2350 if len(found) == 1:
2345 2351 node = found[0]
2346 2352 ui.warn(_("Using head %s for branch %s\n") % (short(node), branch))
2347 2353 else:
2348 2354 ui.warn(_("branch %s not found\n") % (branch))
2349 2355 return 1
2350 2356 else:
2351 2357 node = node and repo.lookup(node) or repo.changelog.tip()
2352 2358 return repo.update(node, allow=merge, force=clean, forcemerge=force)
2353 2359
2354 2360 def verify(ui, repo):
2355 2361 """verify the integrity of the repository
2356 2362
2357 2363 Verify the integrity of the current repository.
2358 2364
2359 2365 This will perform an extensive check of the repository's
2360 2366 integrity, validating the hashes and checksums of each entry in
2361 2367 the changelog, manifest, and tracked files, as well as the
2362 2368 integrity of their crosslinks and indices.
2363 2369 """
2364 2370 return repo.verify()
2365 2371
2366 2372 # Command options and aliases are listed here, alphabetically
2367 2373
2368 2374 table = {
2369 2375 "^add":
2370 2376 (add,
2371 2377 [('I', 'include', [], _('include names matching the given patterns')),
2372 2378 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2373 2379 _('hg add [OPTION]... [FILE]...')),
2374 2380 "addremove":
2375 2381 (addremove,
2376 2382 [('I', 'include', [], _('include names matching the given patterns')),
2377 2383 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2378 2384 _('hg addremove [OPTION]... [FILE]...')),
2379 2385 "^annotate":
2380 2386 (annotate,
2381 2387 [('r', 'rev', '', _('annotate the specified revision')),
2382 2388 ('a', 'text', None, _('treat all files as text')),
2383 2389 ('u', 'user', None, _('list the author')),
2384 2390 ('d', 'date', None, _('list the date')),
2385 2391 ('n', 'number', None, _('list the revision number (default)')),
2386 2392 ('c', 'changeset', None, _('list the changeset')),
2387 2393 ('I', 'include', [], _('include names matching the given patterns')),
2388 2394 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2389 2395 _('hg annotate [-r REV] [-a] [-u] [-d] [-n] [-c] FILE...')),
2390 2396 "bundle":
2391 2397 (bundle,
2392 2398 [],
2393 2399 _('hg bundle FILE DEST')),
2394 2400 "cat":
2395 2401 (cat,
2396 2402 [('o', 'output', '', _('print output to file with formatted name')),
2397 2403 ('r', 'rev', '', _('print the given revision')),
2398 2404 ('I', 'include', [], _('include names matching the given patterns')),
2399 2405 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2400 2406 _('hg cat [OPTION]... FILE...')),
2401 2407 "^clone":
2402 2408 (clone,
2403 2409 [('U', 'noupdate', None, _('do not update the new working directory')),
2404 2410 ('r', 'rev', [],
2405 2411 _('a changeset you would like to have after cloning')),
2406 2412 ('', 'pull', None, _('use pull protocol to copy metadata')),
2407 2413 ('e', 'ssh', '', _('specify ssh command to use')),
2408 2414 ('', 'remotecmd', '',
2409 2415 _('specify hg command to run on the remote side'))],
2410 2416 _('hg clone [OPTION]... SOURCE [DEST]')),
2411 2417 "^commit|ci":
2412 2418 (commit,
2413 2419 [('A', 'addremove', None, _('run addremove during commit')),
2414 2420 ('m', 'message', '', _('use <text> as commit message')),
2415 2421 ('l', 'logfile', '', _('read the commit message from <file>')),
2416 2422 ('d', 'date', '', _('record datecode as commit date')),
2417 2423 ('u', 'user', '', _('record user as commiter')),
2418 2424 ('I', 'include', [], _('include names matching the given patterns')),
2419 2425 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2420 2426 _('hg commit [OPTION]... [FILE]...')),
2421 2427 "copy|cp":
2422 2428 (copy,
2423 2429 [('A', 'after', None, _('record a copy that has already occurred')),
2424 2430 ('f', 'force', None,
2425 2431 _('forcibly copy over an existing managed file')),
2426 2432 ('I', 'include', [], _('include names matching the given patterns')),
2427 2433 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2428 2434 _('hg copy [OPTION]... [SOURCE]... DEST')),
2429 2435 "debugancestor": (debugancestor, [], _('debugancestor INDEX REV1 REV2')),
2436 "debugcomplete": (debugcomplete, [], _('debugcomplete CMD')),
2430 2437 "debugrebuildstate":
2431 2438 (debugrebuildstate,
2432 2439 [('r', 'rev', '', _('revision to rebuild to'))],
2433 2440 _('debugrebuildstate [-r REV] [REV]')),
2434 2441 "debugcheckstate": (debugcheckstate, [], _('debugcheckstate')),
2435 2442 "debugconfig": (debugconfig, [], _('debugconfig')),
2436 2443 "debugsetparents": (debugsetparents, [], _('debugsetparents REV1 [REV2]')),
2437 2444 "debugstate": (debugstate, [], _('debugstate')),
2438 2445 "debugdata": (debugdata, [], _('debugdata FILE REV')),
2439 2446 "debugindex": (debugindex, [], _('debugindex FILE')),
2440 2447 "debugindexdot": (debugindexdot, [], _('debugindexdot FILE')),
2441 2448 "debugrename": (debugrename, [], _('debugrename FILE [REV]')),
2442 2449 "debugwalk":
2443 2450 (debugwalk,
2444 2451 [('I', 'include', [], _('include names matching the given patterns')),
2445 2452 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2446 2453 _('debugwalk [OPTION]... [FILE]...')),
2447 2454 "^diff":
2448 2455 (diff,
2449 2456 [('r', 'rev', [], _('revision')),
2450 2457 ('a', 'text', None, _('treat all files as text')),
2451 2458 ('p', 'show-function', None,
2452 2459 _('show which function each change is in')),
2453 2460 ('w', 'ignore-all-space', None,
2454 2461 _('ignore white space when comparing lines')),
2455 2462 ('I', 'include', [], _('include names matching the given patterns')),
2456 2463 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2457 2464 _('hg diff [-a] [-I] [-X] [-r REV1 [-r REV2]] [FILE]...')),
2458 2465 "^export":
2459 2466 (export,
2460 2467 [('o', 'output', '', _('print output to file with formatted name')),
2461 2468 ('a', 'text', None, _('treat all files as text')),
2462 2469 ('', 'switch-parent', None, _('diff against the second parent'))],
2463 2470 _('hg export [-a] [-o OUTFILESPEC] REV...')),
2464 2471 "forget":
2465 2472 (forget,
2466 2473 [('I', 'include', [], _('include names matching the given patterns')),
2467 2474 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2468 2475 _('hg forget [OPTION]... FILE...')),
2469 2476 "grep":
2470 2477 (grep,
2471 2478 [('0', 'print0', None, _('end fields with NUL')),
2472 2479 ('', 'all', None, _('print all revisions that match')),
2473 2480 ('i', 'ignore-case', None, _('ignore case when matching')),
2474 2481 ('l', 'files-with-matches', None,
2475 2482 _('print only filenames and revs that match')),
2476 2483 ('n', 'line-number', None, _('print matching line numbers')),
2477 2484 ('r', 'rev', [], _('search in given revision range')),
2478 2485 ('u', 'user', None, _('print user who committed change')),
2479 2486 ('I', 'include', [], _('include names matching the given patterns')),
2480 2487 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2481 2488 _('hg grep [OPTION]... PATTERN [FILE]...')),
2482 2489 "heads":
2483 2490 (heads,
2484 2491 [('b', 'branches', None, _('show branches')),
2485 2492 ('r', 'rev', '', _('show only heads which are descendants of rev'))],
2486 2493 _('hg heads [-b] [-r <rev>]')),
2487 2494 "help": (help_, [], _('hg help [COMMAND]')),
2488 2495 "identify|id": (identify, [], _('hg identify')),
2489 2496 "import|patch":
2490 2497 (import_,
2491 2498 [('p', 'strip', 1,
2492 2499 _('directory strip option for patch. This has the same\n') +
2493 2500 _('meaning as the corresponding patch option')),
2494 2501 ('b', 'base', '', _('base path')),
2495 2502 ('f', 'force', None,
2496 2503 _('skip check for outstanding uncommitted changes'))],
2497 2504 _('hg import [-p NUM] [-b BASE] [-f] PATCH...')),
2498 2505 "incoming|in": (incoming,
2499 2506 [('M', 'no-merges', None, _('do not show merges')),
2500 2507 ('p', 'patch', None, _('show patch')),
2501 2508 ('n', 'newest-first', None, _('show newest record first'))],
2502 2509 _('hg incoming [-p] [-n] [-M] [SOURCE]')),
2503 2510 "^init": (init, [], _('hg init [DEST]')),
2504 2511 "locate":
2505 2512 (locate,
2506 2513 [('r', 'rev', '', _('search the repository as it stood at rev')),
2507 2514 ('0', 'print0', None,
2508 2515 _('end filenames with NUL, for use with xargs')),
2509 2516 ('f', 'fullpath', None,
2510 2517 _('print complete paths from the filesystem root')),
2511 2518 ('I', 'include', [], _('include names matching the given patterns')),
2512 2519 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2513 2520 _('hg locate [OPTION]... [PATTERN]...')),
2514 2521 "^log|history":
2515 2522 (log,
2516 2523 [('b', 'branches', None, _('show branches')),
2517 2524 ('k', 'keyword', [], _('search for a keyword')),
2518 2525 ('l', 'limit', '', _('limit number of changes displayed')),
2519 2526 ('r', 'rev', [], _('show the specified revision or range')),
2520 2527 ('M', 'no-merges', None, _('do not show merges')),
2521 2528 ('m', 'only-merges', None, _('show only merges')),
2522 2529 ('p', 'patch', None, _('show patch')),
2523 2530 ('I', 'include', [], _('include names matching the given patterns')),
2524 2531 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2525 2532 _('hg log [OPTION]... [FILE]')),
2526 2533 "manifest": (manifest, [], _('hg manifest [REV]')),
2527 2534 "outgoing|out": (outgoing,
2528 2535 [('M', 'no-merges', None, _('do not show merges')),
2529 2536 ('p', 'patch', None, _('show patch')),
2530 2537 ('n', 'newest-first', None, _('show newest record first'))],
2531 2538 _('hg outgoing [-M] [-p] [-n] [DEST]')),
2532 2539 "^parents":
2533 2540 (parents,
2534 2541 [('b', 'branches', None, _('show branches'))],
2535 2542 _('hg parents [-b] [REV]')),
2536 2543 "paths": (paths, [], _('hg paths [NAME]')),
2537 2544 "^pull":
2538 2545 (pull,
2539 2546 [('u', 'update', None,
2540 2547 _('update the working directory to tip after pull')),
2541 2548 ('e', 'ssh', '', _('specify ssh command to use')),
2542 2549 ('r', 'rev', [], _('a specific revision you would like to pull')),
2543 2550 ('', 'remotecmd', '',
2544 2551 _('specify hg command to run on the remote side'))],
2545 2552 _('hg pull [-u] [-e FILE] [-r REV]... [--remotecmd FILE] [SOURCE]')),
2546 2553 "^push":
2547 2554 (push,
2548 2555 [('f', 'force', None, _('force push')),
2549 2556 ('e', 'ssh', '', _('specify ssh command to use')),
2550 2557 ('r', 'rev', [], _('a specific revision you would like to push')),
2551 2558 ('', 'remotecmd', '',
2552 2559 _('specify hg command to run on the remote side'))],
2553 2560 _('hg push [-f] [-e FILE] [-r REV]... [--remotecmd FILE] [DEST]')),
2554 2561 "debugrawcommit|rawcommit":
2555 2562 (rawcommit,
2556 2563 [('p', 'parent', [], _('parent')),
2557 2564 ('d', 'date', '', _('date code')),
2558 2565 ('u', 'user', '', _('user')),
2559 2566 ('F', 'files', '', _('file list')),
2560 2567 ('m', 'message', '', _('commit message')),
2561 2568 ('l', 'logfile', '', _('commit message file'))],
2562 2569 _('hg debugrawcommit [OPTION]... [FILE]...')),
2563 2570 "recover": (recover, [], _('hg recover')),
2564 2571 "^remove|rm":
2565 2572 (remove,
2566 2573 [('f', 'force', None, _('remove file even if modified')),
2567 2574 ('I', 'include', [], _('include names matching the given patterns')),
2568 2575 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2569 2576 _('hg remove [OPTION]... FILE...')),
2570 2577 "rename|mv":
2571 2578 (rename,
2572 2579 [('A', 'after', None, _('record a rename that has already occurred')),
2573 2580 ('f', 'force', None,
2574 2581 _('forcibly copy over an existing managed file')),
2575 2582 ('I', 'include', [], _('include names matching the given patterns')),
2576 2583 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2577 2584 _('hg rename [OPTION]... SOURCE... DEST')),
2578 2585 "^revert":
2579 2586 (revert,
2580 2587 [('r', 'rev', '', _('revision to revert to')),
2581 2588 ('I', 'include', [], _('include names matching the given patterns')),
2582 2589 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2583 2590 _('hg revert [-r REV] [NAME]...')),
2584 2591 "root": (root, [], _('hg root')),
2585 2592 "^serve":
2586 2593 (serve,
2587 2594 [('A', 'accesslog', '', _('name of access log file to write to')),
2588 2595 ('d', 'daemon', None, _('run server in background')),
2589 2596 ('', 'daemon-pipefds', '', _('used internally by daemon mode')),
2590 2597 ('E', 'errorlog', '', _('name of error log file to write to')),
2591 2598 ('p', 'port', 0, _('port to use (default: 8000)')),
2592 2599 ('a', 'address', '', _('address to use')),
2593 2600 ('n', 'name', '',
2594 2601 _('name to show in web pages (default: working dir)')),
2595 2602 ('', 'pid-file', '', _('name of file to write process ID to')),
2596 2603 ('', 'stdio', None, _('for remote clients')),
2597 2604 ('t', 'templates', '', _('web templates to use')),
2598 2605 ('', 'style', '', _('template style to use')),
2599 2606 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4'))],
2600 2607 _('hg serve [OPTION]...')),
2601 2608 "^status|st":
2602 2609 (status,
2603 2610 [('m', 'modified', None, _('show only modified files')),
2604 2611 ('a', 'added', None, _('show only added files')),
2605 2612 ('r', 'removed', None, _('show only removed files')),
2606 2613 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
2607 2614 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
2608 2615 ('n', 'no-status', None, _('hide status prefix')),
2609 2616 ('0', 'print0', None,
2610 2617 _('end filenames with NUL, for use with xargs')),
2611 2618 ('I', 'include', [], _('include names matching the given patterns')),
2612 2619 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
2613 2620 _('hg status [OPTION]... [FILE]...')),
2614 2621 "tag":
2615 2622 (tag,
2616 2623 [('l', 'local', None, _('make the tag local')),
2617 2624 ('m', 'message', '', _('message for tag commit log entry')),
2618 2625 ('d', 'date', '', _('record datecode as commit date')),
2619 2626 ('u', 'user', '', _('record user as commiter')),
2620 2627 ('r', 'rev', '', _('revision to tag'))],
2621 2628 _('hg tag [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME')),
2622 2629 "tags": (tags, [], _('hg tags')),
2623 2630 "tip":
2624 2631 (tip,
2625 2632 [('b', 'branches', None, _('show branches')),
2626 2633 ('p', 'patch', None, _('show patch'))],
2627 2634 _('hg tip [-b] [-p]')),
2628 2635 "unbundle":
2629 2636 (unbundle,
2630 2637 [('u', 'update', None,
2631 2638 _('update the working directory to tip after unbundle'))],
2632 2639 _('hg unbundle [-u] FILE')),
2633 2640 "undo": (undo, [], _('hg undo')),
2634 2641 "^update|up|checkout|co":
2635 2642 (update,
2636 2643 [('b', 'branch', '', _('checkout the head of a specific branch')),
2637 2644 ('m', 'merge', None, _('allow merging of branches')),
2638 2645 ('C', 'clean', None, _('overwrite locally modified files')),
2639 2646 ('f', 'force', None, _('force a merge with outstanding changes'))],
2640 2647 _('hg update [-b TAG] [-m] [-C] [-f] [REV]')),
2641 2648 "verify": (verify, [], _('hg verify')),
2642 2649 "version": (show_version, [], _('hg version')),
2643 2650 }
2644 2651
2645 2652 globalopts = [
2646 2653 ('R', 'repository', '', _('repository root directory')),
2647 2654 ('', 'cwd', '', _('change working directory')),
2648 2655 ('y', 'noninteractive', None,
2649 2656 _('do not prompt, assume \'yes\' for any required answers')),
2650 2657 ('q', 'quiet', None, _('suppress output')),
2651 2658 ('v', 'verbose', None, _('enable additional output')),
2652 2659 ('', 'debug', None, _('enable debugging output')),
2653 2660 ('', 'debugger', None, _('start debugger')),
2654 2661 ('', 'traceback', None, _('print traceback on exception')),
2655 2662 ('', 'time', None, _('time how long the command takes')),
2656 2663 ('', 'profile', None, _('print command execution profile')),
2657 2664 ('', 'version', None, _('output version information and exit')),
2658 2665 ('h', 'help', None, _('display help and exit')),
2659 2666 ]
2660 2667
2661 norepo = ("clone init version help debugancestor debugdata"
2668 norepo = ("clone init version help debugancestor debugcomplete debugdata"
2662 2669 " debugindex debugindexdot")
2663 2670 optionalrepo = ("paths debugconfig")
2664 2671
2665 def find(cmd):
2666 """Return (aliases, command table entry) for command string."""
2667 choice = []
2668 debugchoice = []
2672 def findpossible(cmd):
2673 """
2674 Return cmd -> (aliases, command table entry)
2675 for each matching command
2676 """
2677 choice = {}
2678 debugchoice = {}
2669 2679 for e in table.keys():
2670 2680 aliases = e.lstrip("^").split("|")
2671 2681 if cmd in aliases:
2672 return aliases, table[e]
2682 choice[cmd] = (aliases, table[e])
2683 continue
2673 2684 for a in aliases:
2674 2685 if a.startswith(cmd):
2675 2686 if aliases[0].startswith("debug"):
2676 debugchoice.append([aliases, table[e]])
2687 debugchoice[a] = (aliases, table[e])
2677 2688 else:
2678 choice.append([aliases, table[e]])
2689 choice[a] = (aliases, table[e])
2679 2690 break
2680 2691
2681 2692 if not choice and debugchoice:
2682 2693 choice = debugchoice
2683 2694
2695 return choice
2696
2697 def find(cmd):
2698 """Return (aliases, command table entry) for command string."""
2699 choice = findpossible(cmd)
2700
2701 if choice.has_key(cmd):
2702 return choice[cmd]
2703
2684 2704 if len(choice) > 1:
2685 clist = []
2686 for aliases, table_e in choice:
2687 if aliases[0].startswith(cmd):
2688 clist.append(aliases[0])
2689 for a in aliases[1:]:
2690 if a.startswith(cmd) and not aliases[0].startswith(a):
2691 clist.append(a)
2705 clist = choice.keys()
2692 2706 clist.sort()
2693 2707 raise AmbiguousCommand(cmd, clist)
2694 2708
2695 2709 if choice:
2696 return choice[0]
2710 return choice.values()[0]
2697 2711
2698 2712 raise UnknownCommand(cmd)
2699 2713
2700 2714 class SignalInterrupt(Exception):
2701 2715 """Exception raised on SIGTERM and SIGHUP."""
2702 2716
2703 2717 def catchterm(*args):
2704 2718 raise SignalInterrupt
2705 2719
2706 2720 def run():
2707 2721 sys.exit(dispatch(sys.argv[1:]))
2708 2722
2709 2723 class ParseError(Exception):
2710 2724 """Exception raised on errors in parsing the command line."""
2711 2725
2712 2726 def parse(ui, args):
2713 2727 options = {}
2714 2728 cmdoptions = {}
2715 2729
2716 2730 try:
2717 2731 args = fancyopts.fancyopts(args, globalopts, options)
2718 2732 except fancyopts.getopt.GetoptError, inst:
2719 2733 raise ParseError(None, inst)
2720 2734
2721 2735 if args:
2722 2736 cmd, args = args[0], args[1:]
2723 2737 aliases, i = find(cmd)
2724 2738 cmd = aliases[0]
2725 2739 defaults = ui.config("defaults", cmd)
2726 2740 if defaults:
2727 2741 args = defaults.split() + args
2728 2742 c = list(i[1])
2729 2743 else:
2730 2744 cmd = None
2731 2745 c = []
2732 2746
2733 2747 # combine global options into local
2734 2748 for o in globalopts:
2735 2749 c.append((o[0], o[1], options[o[1]], o[3]))
2736 2750
2737 2751 try:
2738 2752 args = fancyopts.fancyopts(args, c, cmdoptions)
2739 2753 except fancyopts.getopt.GetoptError, inst:
2740 2754 raise ParseError(cmd, inst)
2741 2755
2742 2756 # separate global options back out
2743 2757 for o in globalopts:
2744 2758 n = o[1]
2745 2759 options[n] = cmdoptions[n]
2746 2760 del cmdoptions[n]
2747 2761
2748 2762 return (cmd, cmd and i[0] or None, args, options, cmdoptions)
2749 2763
2750 2764 def dispatch(args):
2751 2765 signal.signal(signal.SIGTERM, catchterm)
2752 2766 try:
2753 2767 signal.signal(signal.SIGHUP, catchterm)
2754 2768 except AttributeError:
2755 2769 pass
2756 2770
2757 2771 try:
2758 2772 u = ui.ui()
2759 2773 except util.Abort, inst:
2760 2774 sys.stderr.write(_("abort: %s\n") % inst)
2761 2775 sys.exit(1)
2762 2776
2763 2777 external = []
2764 2778 for x in u.extensions():
2765 2779 def on_exception(exc, inst):
2766 2780 u.warn(_("*** failed to import extension %s\n") % x[1])
2767 2781 u.warn("%s\n" % inst)
2768 2782 if "--traceback" in sys.argv[1:]:
2769 2783 traceback.print_exc()
2770 2784 if x[1]:
2771 2785 try:
2772 2786 mod = imp.load_source(x[0], x[1])
2773 2787 except Exception, inst:
2774 2788 on_exception(Exception, inst)
2775 2789 continue
2776 2790 else:
2777 2791 def importh(name):
2778 2792 mod = __import__(name)
2779 2793 components = name.split('.')
2780 2794 for comp in components[1:]:
2781 2795 mod = getattr(mod, comp)
2782 2796 return mod
2783 2797 try:
2784 2798 mod = importh(x[0])
2785 2799 except Exception, inst:
2786 2800 on_exception(Exception, inst)
2787 2801 continue
2788 2802
2789 2803 external.append(mod)
2790 2804 for x in external:
2791 2805 cmdtable = getattr(x, 'cmdtable', {})
2792 2806 for t in cmdtable:
2793 2807 if t in table:
2794 2808 u.warn(_("module %s overrides %s\n") % (x.__name__, t))
2795 2809 table.update(cmdtable)
2796 2810
2797 2811 try:
2798 2812 cmd, func, args, options, cmdoptions = parse(u, args)
2799 2813 if options["time"]:
2800 2814 def get_times():
2801 2815 t = os.times()
2802 2816 if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
2803 2817 t = (t[0], t[1], t[2], t[3], time.clock())
2804 2818 return t
2805 2819 s = get_times()
2806 2820 def print_time():
2807 2821 t = get_times()
2808 2822 u.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
2809 2823 (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
2810 2824 atexit.register(print_time)
2811 2825
2812 2826 u.updateopts(options["verbose"], options["debug"], options["quiet"],
2813 2827 not options["noninteractive"])
2814 2828
2815 2829 # enter the debugger before command execution
2816 2830 if options['debugger']:
2817 2831 pdb.set_trace()
2818 2832
2819 2833 try:
2820 2834 if options['cwd']:
2821 2835 try:
2822 2836 os.chdir(options['cwd'])
2823 2837 except OSError, inst:
2824 2838 raise util.Abort('%s: %s' %
2825 2839 (options['cwd'], inst.strerror))
2826 2840
2827 2841 path = options["repository"] or ""
2828 2842 repo = path and hg.repository(u, path=path) or None
2829 2843
2830 2844 if options['help']:
2831 2845 help_(u, cmd, options['version'])
2832 2846 sys.exit(0)
2833 2847 elif options['version']:
2834 2848 show_version(u)
2835 2849 sys.exit(0)
2836 2850 elif not cmd:
2837 2851 help_(u, 'shortlist')
2838 2852 sys.exit(0)
2839 2853
2840 2854 if cmd not in norepo.split():
2841 2855 try:
2842 2856 if not repo:
2843 2857 repo = hg.repository(u, path=path)
2844 2858 u = repo.ui
2845 2859 for x in external:
2846 2860 if hasattr(x, 'reposetup'):
2847 2861 x.reposetup(u, repo)
2848 2862 except hg.RepoError:
2849 2863 if cmd not in optionalrepo.split():
2850 2864 raise
2851 2865 d = lambda: func(u, repo, *args, **cmdoptions)
2852 2866 else:
2853 2867 d = lambda: func(u, *args, **cmdoptions)
2854 2868
2855 2869 try:
2856 2870 if options['profile']:
2857 2871 import hotshot, hotshot.stats
2858 2872 prof = hotshot.Profile("hg.prof")
2859 2873 try:
2860 2874 try:
2861 2875 return prof.runcall(d)
2862 2876 except:
2863 2877 try:
2864 2878 u.warn(_('exception raised - generating '
2865 2879 'profile anyway\n'))
2866 2880 except:
2867 2881 pass
2868 2882 raise
2869 2883 finally:
2870 2884 prof.close()
2871 2885 stats = hotshot.stats.load("hg.prof")
2872 2886 stats.strip_dirs()
2873 2887 stats.sort_stats('time', 'calls')
2874 2888 stats.print_stats(40)
2875 2889 else:
2876 2890 return d()
2877 2891 finally:
2878 2892 u.flush()
2879 2893 except:
2880 2894 # enter the debugger when we hit an exception
2881 2895 if options['debugger']:
2882 2896 pdb.post_mortem(sys.exc_info()[2])
2883 2897 if options['traceback']:
2884 2898 traceback.print_exc()
2885 2899 raise
2886 2900 except ParseError, inst:
2887 2901 if inst.args[0]:
2888 2902 u.warn(_("hg %s: %s\n") % (inst.args[0], inst.args[1]))
2889 2903 help_(u, inst.args[0])
2890 2904 else:
2891 2905 u.warn(_("hg: %s\n") % inst.args[1])
2892 2906 help_(u, 'shortlist')
2893 2907 sys.exit(-1)
2894 2908 except AmbiguousCommand, inst:
2895 2909 u.warn(_("hg: command '%s' is ambiguous:\n %s\n") %
2896 2910 (inst.args[0], " ".join(inst.args[1])))
2897 2911 sys.exit(1)
2898 2912 except UnknownCommand, inst:
2899 2913 u.warn(_("hg: unknown command '%s'\n") % inst.args[0])
2900 2914 help_(u, 'shortlist')
2901 2915 sys.exit(1)
2902 2916 except hg.RepoError, inst:
2903 2917 u.warn(_("abort: "), inst, "!\n")
2904 2918 except revlog.RevlogError, inst:
2905 2919 u.warn(_("abort: "), inst, "!\n")
2906 2920 except SignalInterrupt:
2907 2921 u.warn(_("killed!\n"))
2908 2922 except KeyboardInterrupt:
2909 2923 try:
2910 2924 u.warn(_("interrupted!\n"))
2911 2925 except IOError, inst:
2912 2926 if inst.errno == errno.EPIPE:
2913 2927 if u.debugflag:
2914 2928 u.warn(_("\nbroken pipe\n"))
2915 2929 else:
2916 2930 raise
2917 2931 except IOError, inst:
2918 2932 if hasattr(inst, "code"):
2919 2933 u.warn(_("abort: %s\n") % inst)
2920 2934 elif hasattr(inst, "reason"):
2921 2935 u.warn(_("abort: error: %s\n") % inst.reason[1])
2922 2936 elif hasattr(inst, "args") and inst[0] == errno.EPIPE:
2923 2937 if u.debugflag:
2924 2938 u.warn(_("broken pipe\n"))
2925 2939 elif getattr(inst, "strerror", None):
2926 2940 if getattr(inst, "filename", None):
2927 2941 u.warn(_("abort: %s - %s\n") % (inst.strerror, inst.filename))
2928 2942 else:
2929 2943 u.warn(_("abort: %s\n") % inst.strerror)
2930 2944 else:
2931 2945 raise
2932 2946 except OSError, inst:
2933 2947 if hasattr(inst, "filename"):
2934 2948 u.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
2935 2949 else:
2936 2950 u.warn(_("abort: %s\n") % inst.strerror)
2937 2951 except util.Abort, inst:
2938 2952 u.warn(_('abort: '), inst.args[0] % inst.args[1:], '\n')
2939 2953 sys.exit(1)
2940 2954 except TypeError, inst:
2941 2955 # was this an argument error?
2942 2956 tb = traceback.extract_tb(sys.exc_info()[2])
2943 2957 if len(tb) > 2: # no
2944 2958 raise
2945 2959 u.debug(inst, "\n")
2946 2960 u.warn(_("%s: invalid arguments\n") % cmd)
2947 2961 help_(u, cmd)
2948 2962 except SystemExit:
2949 2963 # don't catch this in the catch-all below
2950 2964 raise
2951 2965 except:
2952 2966 u.warn(_("** unknown exception encountered, details follow\n"))
2953 2967 u.warn(_("** report bug details to mercurial@selenic.com\n"))
2954 2968 u.warn(_("** Mercurial Distributed SCM (version %s)\n")
2955 2969 % version.get_version())
2956 2970 raise
2957 2971
2958 2972 sys.exit(-1)
General Comments 0
You need to be logged in to leave comments. Login now