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