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