##// END OF EJS Templates
extensions: drop maxlength from enabled and disabled...
Matt Mackall -
r14316:d5b52569 default
parent child Browse files
Show More
@@ -1,172 +1,163 b''
1 import os, sys, textwrap
1 import os, sys, textwrap
2 # import from the live mercurial repo
2 # import from the live mercurial repo
3 sys.path.insert(0, "..")
3 sys.path.insert(0, "..")
4 # fall back to pure modules if required C extensions are not available
4 # fall back to pure modules if required C extensions are not available
5 sys.path.append(os.path.join('..', 'mercurial', 'pure'))
5 sys.path.append(os.path.join('..', 'mercurial', 'pure'))
6 from mercurial import demandimport; demandimport.enable()
6 from mercurial import demandimport; demandimport.enable()
7 from mercurial import encoding
7 from mercurial import encoding
8 from mercurial.commands import table, globalopts
8 from mercurial.commands import table, globalopts
9 from mercurial.i18n import _
9 from mercurial.i18n import _
10 from mercurial.help import helptable
10 from mercurial.help import helptable
11 from mercurial import extensions
11 from mercurial import extensions
12
12
13 def get_desc(docstr):
13 def get_desc(docstr):
14 if not docstr:
14 if not docstr:
15 return "", ""
15 return "", ""
16 # sanitize
16 # sanitize
17 docstr = docstr.strip("\n")
17 docstr = docstr.strip("\n")
18 docstr = docstr.rstrip()
18 docstr = docstr.rstrip()
19 shortdesc = docstr.splitlines()[0].strip()
19 shortdesc = docstr.splitlines()[0].strip()
20
20
21 i = docstr.find("\n")
21 i = docstr.find("\n")
22 if i != -1:
22 if i != -1:
23 desc = docstr[i + 2:]
23 desc = docstr[i + 2:]
24 else:
24 else:
25 desc = shortdesc
25 desc = shortdesc
26
26
27 desc = textwrap.dedent(desc)
27 desc = textwrap.dedent(desc)
28
28
29 return (shortdesc, desc)
29 return (shortdesc, desc)
30
30
31 def get_opts(opts):
31 def get_opts(opts):
32 for opt in opts:
32 for opt in opts:
33 if len(opt) == 5:
33 if len(opt) == 5:
34 shortopt, longopt, default, desc, optlabel = opt
34 shortopt, longopt, default, desc, optlabel = opt
35 else:
35 else:
36 shortopt, longopt, default, desc = opt
36 shortopt, longopt, default, desc = opt
37 allopts = []
37 allopts = []
38 if shortopt:
38 if shortopt:
39 allopts.append("-%s" % shortopt)
39 allopts.append("-%s" % shortopt)
40 if longopt:
40 if longopt:
41 allopts.append("--%s" % longopt)
41 allopts.append("--%s" % longopt)
42 desc += default and _(" (default: %s)") % default or ""
42 desc += default and _(" (default: %s)") % default or ""
43 yield (", ".join(allopts), desc)
43 yield (", ".join(allopts), desc)
44
44
45 def get_cmd(cmd, cmdtable):
45 def get_cmd(cmd, cmdtable):
46 d = {}
46 d = {}
47 attr = cmdtable[cmd]
47 attr = cmdtable[cmd]
48 cmds = cmd.lstrip("^").split("|")
48 cmds = cmd.lstrip("^").split("|")
49
49
50 d['cmd'] = cmds[0]
50 d['cmd'] = cmds[0]
51 d['aliases'] = cmd.split("|")[1:]
51 d['aliases'] = cmd.split("|")[1:]
52 d['desc'] = get_desc(attr[0].__doc__)
52 d['desc'] = get_desc(attr[0].__doc__)
53 d['opts'] = list(get_opts(attr[1]))
53 d['opts'] = list(get_opts(attr[1]))
54
54
55 s = 'hg ' + cmds[0]
55 s = 'hg ' + cmds[0]
56 if len(attr) > 2:
56 if len(attr) > 2:
57 if not attr[2].startswith('hg'):
57 if not attr[2].startswith('hg'):
58 s += ' ' + attr[2]
58 s += ' ' + attr[2]
59 else:
59 else:
60 s = attr[2]
60 s = attr[2]
61 d['synopsis'] = s.strip()
61 d['synopsis'] = s.strip()
62
62
63 return d
63 return d
64
64
65 def section(ui, s):
65 def section(ui, s):
66 ui.write("%s\n%s\n\n" % (s, "-" * encoding.colwidth(s)))
66 ui.write("%s\n%s\n\n" % (s, "-" * encoding.colwidth(s)))
67
67
68 def subsection(ui, s):
68 def subsection(ui, s):
69 ui.write("%s\n%s\n\n" % (s, '"' * encoding.colwidth(s)))
69 ui.write("%s\n%s\n\n" % (s, '"' * encoding.colwidth(s)))
70
70
71 def subsubsection(ui, s):
71 def subsubsection(ui, s):
72 ui.write("%s\n%s\n\n" % (s, "." * encoding.colwidth(s)))
72 ui.write("%s\n%s\n\n" % (s, "." * encoding.colwidth(s)))
73
73
74 def subsubsubsection(ui, s):
74 def subsubsubsection(ui, s):
75 ui.write("%s\n%s\n\n" % (s, "#" * encoding.colwidth(s)))
75 ui.write("%s\n%s\n\n" % (s, "#" * encoding.colwidth(s)))
76
76
77
77
78 def show_doc(ui):
78 def show_doc(ui):
79 # print options
79 # print options
80 section(ui, _("Options"))
80 section(ui, _("Options"))
81 for optstr, desc in get_opts(globalopts):
81 for optstr, desc in get_opts(globalopts):
82 ui.write("%s\n %s\n\n" % (optstr, desc))
82 ui.write("%s\n %s\n\n" % (optstr, desc))
83
83
84 # print cmds
84 # print cmds
85 section(ui, _("Commands"))
85 section(ui, _("Commands"))
86 commandprinter(ui, table, subsection)
86 commandprinter(ui, table, subsection)
87
87
88 # print topics
88 # print topics
89 for names, sec, doc in helptable:
89 for names, sec, doc in helptable:
90 for name in names:
90 for name in names:
91 ui.write(".. _%s:\n" % name)
91 ui.write(".. _%s:\n" % name)
92 ui.write("\n")
92 ui.write("\n")
93 section(ui, sec)
93 section(ui, sec)
94 if hasattr(doc, '__call__'):
94 if hasattr(doc, '__call__'):
95 doc = doc()
95 doc = doc()
96 ui.write(doc)
96 ui.write(doc)
97 ui.write("\n")
97 ui.write("\n")
98
98
99 section(ui, _("Extensions"))
99 section(ui, _("Extensions"))
100 ui.write(_("This section contains help for extensions that are distributed "
100 ui.write(_("This section contains help for extensions that are distributed "
101 "together with Mercurial. Help for other extensions is available "
101 "together with Mercurial. Help for other extensions is available "
102 "in the help system."))
102 "in the help system."))
103 ui.write("\n\n"
103 ui.write("\n\n"
104 ".. contents::\n"
104 ".. contents::\n"
105 " :class: htmlonly\n"
105 " :class: htmlonly\n"
106 " :local:\n"
106 " :local:\n"
107 " :depth: 1\n\n")
107 " :depth: 1\n\n")
108
108
109 for extensionname in sorted(allextensionnames()):
109 for extensionname in sorted(allextensionnames()):
110 mod = extensions.load(None, extensionname, None)
110 mod = extensions.load(None, extensionname, None)
111 subsection(ui, extensionname)
111 subsection(ui, extensionname)
112 ui.write("%s\n\n" % mod.__doc__)
112 ui.write("%s\n\n" % mod.__doc__)
113 cmdtable = getattr(mod, 'cmdtable', None)
113 cmdtable = getattr(mod, 'cmdtable', None)
114 if cmdtable:
114 if cmdtable:
115 subsubsection(ui, _('Commands'))
115 subsubsection(ui, _('Commands'))
116 commandprinter(ui, cmdtable, subsubsubsection)
116 commandprinter(ui, cmdtable, subsubsubsection)
117
117
118 def commandprinter(ui, cmdtable, sectionfunc):
118 def commandprinter(ui, cmdtable, sectionfunc):
119 h = {}
119 h = {}
120 for c, attr in cmdtable.items():
120 for c, attr in cmdtable.items():
121 f = c.split("|")[0]
121 f = c.split("|")[0]
122 f = f.lstrip("^")
122 f = f.lstrip("^")
123 h[f] = c
123 h[f] = c
124 cmds = h.keys()
124 cmds = h.keys()
125 cmds.sort()
125 cmds.sort()
126
126
127 for f in cmds:
127 for f in cmds:
128 if f.startswith("debug"):
128 if f.startswith("debug"):
129 continue
129 continue
130 d = get_cmd(h[f], cmdtable)
130 d = get_cmd(h[f], cmdtable)
131 sectionfunc(ui, d['cmd'])
131 sectionfunc(ui, d['cmd'])
132 # synopsis
132 # synopsis
133 ui.write("::\n\n")
133 ui.write("::\n\n")
134 synopsislines = d['synopsis'].splitlines()
134 synopsislines = d['synopsis'].splitlines()
135 for line in synopsislines:
135 for line in synopsislines:
136 # some commands (such as rebase) have a multi-line
136 # some commands (such as rebase) have a multi-line
137 # synopsis
137 # synopsis
138 ui.write(" %s\n" % line)
138 ui.write(" %s\n" % line)
139 ui.write('\n')
139 ui.write('\n')
140 # description
140 # description
141 ui.write("%s\n\n" % d['desc'][1])
141 ui.write("%s\n\n" % d['desc'][1])
142 # options
142 # options
143 opt_output = list(d['opts'])
143 opt_output = list(d['opts'])
144 if opt_output:
144 if opt_output:
145 opts_len = max([len(line[0]) for line in opt_output])
145 opts_len = max([len(line[0]) for line in opt_output])
146 ui.write(_("Options:\n\n"))
146 ui.write(_("Options:\n\n"))
147 for optstr, desc in opt_output:
147 for optstr, desc in opt_output:
148 if desc:
148 if desc:
149 s = "%-*s %s" % (opts_len, optstr, desc)
149 s = "%-*s %s" % (opts_len, optstr, desc)
150 else:
150 else:
151 s = optstr
151 s = optstr
152 ui.write("%s\n" % s)
152 ui.write("%s\n" % s)
153 ui.write("\n")
153 ui.write("\n")
154 # aliases
154 # aliases
155 if d['aliases']:
155 if d['aliases']:
156 ui.write(_(" aliases: %s\n\n") % " ".join(d['aliases']))
156 ui.write(_(" aliases: %s\n\n") % " ".join(d['aliases']))
157
157
158
158
159 def allextensionnames():
159 def allextensionnames():
160 extensionnames = []
160 return extensions.enabled().keys() + extensions.disabled().keys()
161
162 extensionsdictionary = extensions.enabled()[0]
163 extensionnames.extend(extensionsdictionary.keys())
164
165 extensionsdictionary = extensions.disabled()[0]
166 extensionnames.extend(extensionsdictionary.keys())
167
168 return extensionnames
169
170
161
171 if __name__ == "__main__":
162 if __name__ == "__main__":
172 show_doc(sys.stdout)
163 show_doc(sys.stdout)
@@ -1,5028 +1,5026 b''
1 # commands.py - command processing for mercurial
1 # commands.py - command processing for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from node import hex, bin, nullid, nullrev, short
8 from node import hex, bin, nullid, nullrev, short
9 from lock import release
9 from lock import release
10 from i18n import _, gettext
10 from i18n import _, gettext
11 import os, re, sys, difflib, time, tempfile
11 import os, re, sys, difflib, time, tempfile
12 import hg, scmutil, util, revlog, extensions, copies, error, bookmarks
12 import hg, scmutil, util, revlog, extensions, copies, error, bookmarks
13 import patch, help, url, encoding, templatekw, discovery
13 import patch, help, url, encoding, templatekw, discovery
14 import archival, changegroup, cmdutil, sshserver, hbisect, hgweb, hgweb.server
14 import archival, changegroup, cmdutil, sshserver, hbisect, hgweb, hgweb.server
15 import merge as mergemod
15 import merge as mergemod
16 import minirst, revset, templatefilters
16 import minirst, revset, templatefilters
17 import dagparser, context, simplemerge
17 import dagparser, context, simplemerge
18 import random, setdiscovery, treediscovery, dagutil
18 import random, setdiscovery, treediscovery, dagutil
19
19
20 table = {}
20 table = {}
21
21
22 command = cmdutil.command(table)
22 command = cmdutil.command(table)
23
23
24 # common command options
24 # common command options
25
25
26 globalopts = [
26 globalopts = [
27 ('R', 'repository', '',
27 ('R', 'repository', '',
28 _('repository root directory or name of overlay bundle file'),
28 _('repository root directory or name of overlay bundle file'),
29 _('REPO')),
29 _('REPO')),
30 ('', 'cwd', '',
30 ('', 'cwd', '',
31 _('change working directory'), _('DIR')),
31 _('change working directory'), _('DIR')),
32 ('y', 'noninteractive', None,
32 ('y', 'noninteractive', None,
33 _('do not prompt, assume \'yes\' for any required answers')),
33 _('do not prompt, assume \'yes\' for any required answers')),
34 ('q', 'quiet', None, _('suppress output')),
34 ('q', 'quiet', None, _('suppress output')),
35 ('v', 'verbose', None, _('enable additional output')),
35 ('v', 'verbose', None, _('enable additional output')),
36 ('', 'config', [],
36 ('', 'config', [],
37 _('set/override config option (use \'section.name=value\')'),
37 _('set/override config option (use \'section.name=value\')'),
38 _('CONFIG')),
38 _('CONFIG')),
39 ('', 'debug', None, _('enable debugging output')),
39 ('', 'debug', None, _('enable debugging output')),
40 ('', 'debugger', None, _('start debugger')),
40 ('', 'debugger', None, _('start debugger')),
41 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
41 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
42 _('ENCODE')),
42 _('ENCODE')),
43 ('', 'encodingmode', encoding.encodingmode,
43 ('', 'encodingmode', encoding.encodingmode,
44 _('set the charset encoding mode'), _('MODE')),
44 _('set the charset encoding mode'), _('MODE')),
45 ('', 'traceback', None, _('always print a traceback on exception')),
45 ('', 'traceback', None, _('always print a traceback on exception')),
46 ('', 'time', None, _('time how long the command takes')),
46 ('', 'time', None, _('time how long the command takes')),
47 ('', 'profile', None, _('print command execution profile')),
47 ('', 'profile', None, _('print command execution profile')),
48 ('', 'version', None, _('output version information and exit')),
48 ('', 'version', None, _('output version information and exit')),
49 ('h', 'help', None, _('display help and exit')),
49 ('h', 'help', None, _('display help and exit')),
50 ]
50 ]
51
51
52 dryrunopts = [('n', 'dry-run', None,
52 dryrunopts = [('n', 'dry-run', None,
53 _('do not perform actions, just print output'))]
53 _('do not perform actions, just print output'))]
54
54
55 remoteopts = [
55 remoteopts = [
56 ('e', 'ssh', '',
56 ('e', 'ssh', '',
57 _('specify ssh command to use'), _('CMD')),
57 _('specify ssh command to use'), _('CMD')),
58 ('', 'remotecmd', '',
58 ('', 'remotecmd', '',
59 _('specify hg command to run on the remote side'), _('CMD')),
59 _('specify hg command to run on the remote side'), _('CMD')),
60 ('', 'insecure', None,
60 ('', 'insecure', None,
61 _('do not verify server certificate (ignoring web.cacerts config)')),
61 _('do not verify server certificate (ignoring web.cacerts config)')),
62 ]
62 ]
63
63
64 walkopts = [
64 walkopts = [
65 ('I', 'include', [],
65 ('I', 'include', [],
66 _('include names matching the given patterns'), _('PATTERN')),
66 _('include names matching the given patterns'), _('PATTERN')),
67 ('X', 'exclude', [],
67 ('X', 'exclude', [],
68 _('exclude names matching the given patterns'), _('PATTERN')),
68 _('exclude names matching the given patterns'), _('PATTERN')),
69 ]
69 ]
70
70
71 commitopts = [
71 commitopts = [
72 ('m', 'message', '',
72 ('m', 'message', '',
73 _('use text as commit message'), _('TEXT')),
73 _('use text as commit message'), _('TEXT')),
74 ('l', 'logfile', '',
74 ('l', 'logfile', '',
75 _('read commit message from file'), _('FILE')),
75 _('read commit message from file'), _('FILE')),
76 ]
76 ]
77
77
78 commitopts2 = [
78 commitopts2 = [
79 ('d', 'date', '',
79 ('d', 'date', '',
80 _('record the specified date as commit date'), _('DATE')),
80 _('record the specified date as commit date'), _('DATE')),
81 ('u', 'user', '',
81 ('u', 'user', '',
82 _('record the specified user as committer'), _('USER')),
82 _('record the specified user as committer'), _('USER')),
83 ]
83 ]
84
84
85 templateopts = [
85 templateopts = [
86 ('', 'style', '',
86 ('', 'style', '',
87 _('display using template map file'), _('STYLE')),
87 _('display using template map file'), _('STYLE')),
88 ('', 'template', '',
88 ('', 'template', '',
89 _('display with template'), _('TEMPLATE')),
89 _('display with template'), _('TEMPLATE')),
90 ]
90 ]
91
91
92 logopts = [
92 logopts = [
93 ('p', 'patch', None, _('show patch')),
93 ('p', 'patch', None, _('show patch')),
94 ('g', 'git', None, _('use git extended diff format')),
94 ('g', 'git', None, _('use git extended diff format')),
95 ('l', 'limit', '',
95 ('l', 'limit', '',
96 _('limit number of changes displayed'), _('NUM')),
96 _('limit number of changes displayed'), _('NUM')),
97 ('M', 'no-merges', None, _('do not show merges')),
97 ('M', 'no-merges', None, _('do not show merges')),
98 ('', 'stat', None, _('output diffstat-style summary of changes')),
98 ('', 'stat', None, _('output diffstat-style summary of changes')),
99 ] + templateopts
99 ] + templateopts
100
100
101 diffopts = [
101 diffopts = [
102 ('a', 'text', None, _('treat all files as text')),
102 ('a', 'text', None, _('treat all files as text')),
103 ('g', 'git', None, _('use git extended diff format')),
103 ('g', 'git', None, _('use git extended diff format')),
104 ('', 'nodates', None, _('omit dates from diff headers'))
104 ('', 'nodates', None, _('omit dates from diff headers'))
105 ]
105 ]
106
106
107 diffopts2 = [
107 diffopts2 = [
108 ('p', 'show-function', None, _('show which function each change is in')),
108 ('p', 'show-function', None, _('show which function each change is in')),
109 ('', 'reverse', None, _('produce a diff that undoes the changes')),
109 ('', 'reverse', None, _('produce a diff that undoes the changes')),
110 ('w', 'ignore-all-space', None,
110 ('w', 'ignore-all-space', None,
111 _('ignore white space when comparing lines')),
111 _('ignore white space when comparing lines')),
112 ('b', 'ignore-space-change', None,
112 ('b', 'ignore-space-change', None,
113 _('ignore changes in the amount of white space')),
113 _('ignore changes in the amount of white space')),
114 ('B', 'ignore-blank-lines', None,
114 ('B', 'ignore-blank-lines', None,
115 _('ignore changes whose lines are all blank')),
115 _('ignore changes whose lines are all blank')),
116 ('U', 'unified', '',
116 ('U', 'unified', '',
117 _('number of lines of context to show'), _('NUM')),
117 _('number of lines of context to show'), _('NUM')),
118 ('', 'stat', None, _('output diffstat-style summary of changes')),
118 ('', 'stat', None, _('output diffstat-style summary of changes')),
119 ]
119 ]
120
120
121 similarityopts = [
121 similarityopts = [
122 ('s', 'similarity', '',
122 ('s', 'similarity', '',
123 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
123 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
124 ]
124 ]
125
125
126 subrepoopts = [
126 subrepoopts = [
127 ('S', 'subrepos', None,
127 ('S', 'subrepos', None,
128 _('recurse into subrepositories'))
128 _('recurse into subrepositories'))
129 ]
129 ]
130
130
131 # Commands start here, listed alphabetically
131 # Commands start here, listed alphabetically
132
132
133 @command('^add',
133 @command('^add',
134 walkopts + subrepoopts + dryrunopts,
134 walkopts + subrepoopts + dryrunopts,
135 _('[OPTION]... [FILE]...'))
135 _('[OPTION]... [FILE]...'))
136 def add(ui, repo, *pats, **opts):
136 def add(ui, repo, *pats, **opts):
137 """add the specified files on the next commit
137 """add the specified files on the next commit
138
138
139 Schedule files to be version controlled and added to the
139 Schedule files to be version controlled and added to the
140 repository.
140 repository.
141
141
142 The files will be added to the repository at the next commit. To
142 The files will be added to the repository at the next commit. To
143 undo an add before that, see :hg:`forget`.
143 undo an add before that, see :hg:`forget`.
144
144
145 If no names are given, add all files to the repository.
145 If no names are given, add all files to the repository.
146
146
147 .. container:: verbose
147 .. container:: verbose
148
148
149 An example showing how new (unknown) files are added
149 An example showing how new (unknown) files are added
150 automatically by :hg:`add`::
150 automatically by :hg:`add`::
151
151
152 $ ls
152 $ ls
153 foo.c
153 foo.c
154 $ hg status
154 $ hg status
155 ? foo.c
155 ? foo.c
156 $ hg add
156 $ hg add
157 adding foo.c
157 adding foo.c
158 $ hg status
158 $ hg status
159 A foo.c
159 A foo.c
160
160
161 Returns 0 if all files are successfully added.
161 Returns 0 if all files are successfully added.
162 """
162 """
163
163
164 m = cmdutil.match(repo, pats, opts)
164 m = cmdutil.match(repo, pats, opts)
165 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
165 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
166 opts.get('subrepos'), prefix="")
166 opts.get('subrepos'), prefix="")
167 return rejected and 1 or 0
167 return rejected and 1 or 0
168
168
169 @command('addremove',
169 @command('addremove',
170 similarityopts + walkopts + dryrunopts,
170 similarityopts + walkopts + dryrunopts,
171 _('[OPTION]... [FILE]...'))
171 _('[OPTION]... [FILE]...'))
172 def addremove(ui, repo, *pats, **opts):
172 def addremove(ui, repo, *pats, **opts):
173 """add all new files, delete all missing files
173 """add all new files, delete all missing files
174
174
175 Add all new files and remove all missing files from the
175 Add all new files and remove all missing files from the
176 repository.
176 repository.
177
177
178 New files are ignored if they match any of the patterns in
178 New files are ignored if they match any of the patterns in
179 ``.hgignore``. As with add, these changes take effect at the next
179 ``.hgignore``. As with add, these changes take effect at the next
180 commit.
180 commit.
181
181
182 Use the -s/--similarity option to detect renamed files. With a
182 Use the -s/--similarity option to detect renamed files. With a
183 parameter greater than 0, this compares every removed file with
183 parameter greater than 0, this compares every removed file with
184 every added file and records those similar enough as renames. This
184 every added file and records those similar enough as renames. This
185 option takes a percentage between 0 (disabled) and 100 (files must
185 option takes a percentage between 0 (disabled) and 100 (files must
186 be identical) as its parameter. Detecting renamed files this way
186 be identical) as its parameter. Detecting renamed files this way
187 can be expensive. After using this option, :hg:`status -C` can be
187 can be expensive. After using this option, :hg:`status -C` can be
188 used to check which files were identified as moved or renamed.
188 used to check which files were identified as moved or renamed.
189
189
190 Returns 0 if all files are successfully added.
190 Returns 0 if all files are successfully added.
191 """
191 """
192 try:
192 try:
193 sim = float(opts.get('similarity') or 100)
193 sim = float(opts.get('similarity') or 100)
194 except ValueError:
194 except ValueError:
195 raise util.Abort(_('similarity must be a number'))
195 raise util.Abort(_('similarity must be a number'))
196 if sim < 0 or sim > 100:
196 if sim < 0 or sim > 100:
197 raise util.Abort(_('similarity must be between 0 and 100'))
197 raise util.Abort(_('similarity must be between 0 and 100'))
198 return cmdutil.addremove(repo, pats, opts, similarity=sim / 100.0)
198 return cmdutil.addremove(repo, pats, opts, similarity=sim / 100.0)
199
199
200 @command('^annotate|blame',
200 @command('^annotate|blame',
201 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
201 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
202 ('', 'follow', None,
202 ('', 'follow', None,
203 _('follow copies/renames and list the filename (DEPRECATED)')),
203 _('follow copies/renames and list the filename (DEPRECATED)')),
204 ('', 'no-follow', None, _("don't follow copies and renames")),
204 ('', 'no-follow', None, _("don't follow copies and renames")),
205 ('a', 'text', None, _('treat all files as text')),
205 ('a', 'text', None, _('treat all files as text')),
206 ('u', 'user', None, _('list the author (long with -v)')),
206 ('u', 'user', None, _('list the author (long with -v)')),
207 ('f', 'file', None, _('list the filename')),
207 ('f', 'file', None, _('list the filename')),
208 ('d', 'date', None, _('list the date (short with -q)')),
208 ('d', 'date', None, _('list the date (short with -q)')),
209 ('n', 'number', None, _('list the revision number (default)')),
209 ('n', 'number', None, _('list the revision number (default)')),
210 ('c', 'changeset', None, _('list the changeset')),
210 ('c', 'changeset', None, _('list the changeset')),
211 ('l', 'line-number', None, _('show line number at the first appearance'))
211 ('l', 'line-number', None, _('show line number at the first appearance'))
212 ] + walkopts,
212 ] + walkopts,
213 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
213 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
214 def annotate(ui, repo, *pats, **opts):
214 def annotate(ui, repo, *pats, **opts):
215 """show changeset information by line for each file
215 """show changeset information by line for each file
216
216
217 List changes in files, showing the revision id responsible for
217 List changes in files, showing the revision id responsible for
218 each line
218 each line
219
219
220 This command is useful for discovering when a change was made and
220 This command is useful for discovering when a change was made and
221 by whom.
221 by whom.
222
222
223 Without the -a/--text option, annotate will avoid processing files
223 Without the -a/--text option, annotate will avoid processing files
224 it detects as binary. With -a, annotate will annotate the file
224 it detects as binary. With -a, annotate will annotate the file
225 anyway, although the results will probably be neither useful
225 anyway, although the results will probably be neither useful
226 nor desirable.
226 nor desirable.
227
227
228 Returns 0 on success.
228 Returns 0 on success.
229 """
229 """
230 if opts.get('follow'):
230 if opts.get('follow'):
231 # --follow is deprecated and now just an alias for -f/--file
231 # --follow is deprecated and now just an alias for -f/--file
232 # to mimic the behavior of Mercurial before version 1.5
232 # to mimic the behavior of Mercurial before version 1.5
233 opts['file'] = True
233 opts['file'] = True
234
234
235 datefunc = ui.quiet and util.shortdate or util.datestr
235 datefunc = ui.quiet and util.shortdate or util.datestr
236 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
236 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
237
237
238 if not pats:
238 if not pats:
239 raise util.Abort(_('at least one filename or pattern is required'))
239 raise util.Abort(_('at least one filename or pattern is required'))
240
240
241 opmap = [('user', lambda x: ui.shortuser(x[0].user())),
241 opmap = [('user', lambda x: ui.shortuser(x[0].user())),
242 ('number', lambda x: str(x[0].rev())),
242 ('number', lambda x: str(x[0].rev())),
243 ('changeset', lambda x: short(x[0].node())),
243 ('changeset', lambda x: short(x[0].node())),
244 ('date', getdate),
244 ('date', getdate),
245 ('file', lambda x: x[0].path()),
245 ('file', lambda x: x[0].path()),
246 ]
246 ]
247
247
248 if (not opts.get('user') and not opts.get('changeset')
248 if (not opts.get('user') and not opts.get('changeset')
249 and not opts.get('date') and not opts.get('file')):
249 and not opts.get('date') and not opts.get('file')):
250 opts['number'] = True
250 opts['number'] = True
251
251
252 linenumber = opts.get('line_number') is not None
252 linenumber = opts.get('line_number') is not None
253 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
253 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
254 raise util.Abort(_('at least one of -n/-c is required for -l'))
254 raise util.Abort(_('at least one of -n/-c is required for -l'))
255
255
256 funcmap = [func for op, func in opmap if opts.get(op)]
256 funcmap = [func for op, func in opmap if opts.get(op)]
257 if linenumber:
257 if linenumber:
258 lastfunc = funcmap[-1]
258 lastfunc = funcmap[-1]
259 funcmap[-1] = lambda x: "%s:%s" % (lastfunc(x), x[1])
259 funcmap[-1] = lambda x: "%s:%s" % (lastfunc(x), x[1])
260
260
261 def bad(x, y):
261 def bad(x, y):
262 raise util.Abort("%s: %s" % (x, y))
262 raise util.Abort("%s: %s" % (x, y))
263
263
264 ctx = cmdutil.revsingle(repo, opts.get('rev'))
264 ctx = cmdutil.revsingle(repo, opts.get('rev'))
265 m = cmdutil.match(repo, pats, opts)
265 m = cmdutil.match(repo, pats, opts)
266 m.bad = bad
266 m.bad = bad
267 follow = not opts.get('no_follow')
267 follow = not opts.get('no_follow')
268 for abs in ctx.walk(m):
268 for abs in ctx.walk(m):
269 fctx = ctx[abs]
269 fctx = ctx[abs]
270 if not opts.get('text') and util.binary(fctx.data()):
270 if not opts.get('text') and util.binary(fctx.data()):
271 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
271 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
272 continue
272 continue
273
273
274 lines = fctx.annotate(follow=follow, linenumber=linenumber)
274 lines = fctx.annotate(follow=follow, linenumber=linenumber)
275 pieces = []
275 pieces = []
276
276
277 for f in funcmap:
277 for f in funcmap:
278 l = [f(n) for n, dummy in lines]
278 l = [f(n) for n, dummy in lines]
279 if l:
279 if l:
280 sized = [(x, encoding.colwidth(x)) for x in l]
280 sized = [(x, encoding.colwidth(x)) for x in l]
281 ml = max([w for x, w in sized])
281 ml = max([w for x, w in sized])
282 pieces.append(["%s%s" % (' ' * (ml - w), x) for x, w in sized])
282 pieces.append(["%s%s" % (' ' * (ml - w), x) for x, w in sized])
283
283
284 if pieces:
284 if pieces:
285 for p, l in zip(zip(*pieces), lines):
285 for p, l in zip(zip(*pieces), lines):
286 ui.write("%s: %s" % (" ".join(p), l[1]))
286 ui.write("%s: %s" % (" ".join(p), l[1]))
287
287
288 @command('archive',
288 @command('archive',
289 [('', 'no-decode', None, _('do not pass files through decoders')),
289 [('', 'no-decode', None, _('do not pass files through decoders')),
290 ('p', 'prefix', '', _('directory prefix for files in archive'),
290 ('p', 'prefix', '', _('directory prefix for files in archive'),
291 _('PREFIX')),
291 _('PREFIX')),
292 ('r', 'rev', '', _('revision to distribute'), _('REV')),
292 ('r', 'rev', '', _('revision to distribute'), _('REV')),
293 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
293 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
294 ] + subrepoopts + walkopts,
294 ] + subrepoopts + walkopts,
295 _('[OPTION]... DEST'))
295 _('[OPTION]... DEST'))
296 def archive(ui, repo, dest, **opts):
296 def archive(ui, repo, dest, **opts):
297 '''create an unversioned archive of a repository revision
297 '''create an unversioned archive of a repository revision
298
298
299 By default, the revision used is the parent of the working
299 By default, the revision used is the parent of the working
300 directory; use -r/--rev to specify a different revision.
300 directory; use -r/--rev to specify a different revision.
301
301
302 The archive type is automatically detected based on file
302 The archive type is automatically detected based on file
303 extension (or override using -t/--type).
303 extension (or override using -t/--type).
304
304
305 Valid types are:
305 Valid types are:
306
306
307 :``files``: a directory full of files (default)
307 :``files``: a directory full of files (default)
308 :``tar``: tar archive, uncompressed
308 :``tar``: tar archive, uncompressed
309 :``tbz2``: tar archive, compressed using bzip2
309 :``tbz2``: tar archive, compressed using bzip2
310 :``tgz``: tar archive, compressed using gzip
310 :``tgz``: tar archive, compressed using gzip
311 :``uzip``: zip archive, uncompressed
311 :``uzip``: zip archive, uncompressed
312 :``zip``: zip archive, compressed using deflate
312 :``zip``: zip archive, compressed using deflate
313
313
314 The exact name of the destination archive or directory is given
314 The exact name of the destination archive or directory is given
315 using a format string; see :hg:`help export` for details.
315 using a format string; see :hg:`help export` for details.
316
316
317 Each member added to an archive file has a directory prefix
317 Each member added to an archive file has a directory prefix
318 prepended. Use -p/--prefix to specify a format string for the
318 prepended. Use -p/--prefix to specify a format string for the
319 prefix. The default is the basename of the archive, with suffixes
319 prefix. The default is the basename of the archive, with suffixes
320 removed.
320 removed.
321
321
322 Returns 0 on success.
322 Returns 0 on success.
323 '''
323 '''
324
324
325 ctx = cmdutil.revsingle(repo, opts.get('rev'))
325 ctx = cmdutil.revsingle(repo, opts.get('rev'))
326 if not ctx:
326 if not ctx:
327 raise util.Abort(_('no working directory: please specify a revision'))
327 raise util.Abort(_('no working directory: please specify a revision'))
328 node = ctx.node()
328 node = ctx.node()
329 dest = cmdutil.makefilename(repo, dest, node)
329 dest = cmdutil.makefilename(repo, dest, node)
330 if os.path.realpath(dest) == repo.root:
330 if os.path.realpath(dest) == repo.root:
331 raise util.Abort(_('repository root cannot be destination'))
331 raise util.Abort(_('repository root cannot be destination'))
332
332
333 kind = opts.get('type') or archival.guesskind(dest) or 'files'
333 kind = opts.get('type') or archival.guesskind(dest) or 'files'
334 prefix = opts.get('prefix')
334 prefix = opts.get('prefix')
335
335
336 if dest == '-':
336 if dest == '-':
337 if kind == 'files':
337 if kind == 'files':
338 raise util.Abort(_('cannot archive plain files to stdout'))
338 raise util.Abort(_('cannot archive plain files to stdout'))
339 dest = sys.stdout
339 dest = sys.stdout
340 if not prefix:
340 if not prefix:
341 prefix = os.path.basename(repo.root) + '-%h'
341 prefix = os.path.basename(repo.root) + '-%h'
342
342
343 prefix = cmdutil.makefilename(repo, prefix, node)
343 prefix = cmdutil.makefilename(repo, prefix, node)
344 matchfn = cmdutil.match(repo, [], opts)
344 matchfn = cmdutil.match(repo, [], opts)
345 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
345 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
346 matchfn, prefix, subrepos=opts.get('subrepos'))
346 matchfn, prefix, subrepos=opts.get('subrepos'))
347
347
348 @command('backout',
348 @command('backout',
349 [('', 'merge', None, _('merge with old dirstate parent after backout')),
349 [('', 'merge', None, _('merge with old dirstate parent after backout')),
350 ('', 'parent', '', _('parent to choose when backing out merge'), _('REV')),
350 ('', 'parent', '', _('parent to choose when backing out merge'), _('REV')),
351 ('t', 'tool', '', _('specify merge tool')),
351 ('t', 'tool', '', _('specify merge tool')),
352 ('r', 'rev', '', _('revision to backout'), _('REV')),
352 ('r', 'rev', '', _('revision to backout'), _('REV')),
353 ] + walkopts + commitopts + commitopts2,
353 ] + walkopts + commitopts + commitopts2,
354 _('[OPTION]... [-r] REV'))
354 _('[OPTION]... [-r] REV'))
355 def backout(ui, repo, node=None, rev=None, **opts):
355 def backout(ui, repo, node=None, rev=None, **opts):
356 '''reverse effect of earlier changeset
356 '''reverse effect of earlier changeset
357
357
358 Prepare a new changeset with the effect of REV undone in the
358 Prepare a new changeset with the effect of REV undone in the
359 current working directory.
359 current working directory.
360
360
361 If REV is the parent of the working directory, then this new changeset
361 If REV is the parent of the working directory, then this new changeset
362 is committed automatically. Otherwise, hg needs to merge the
362 is committed automatically. Otherwise, hg needs to merge the
363 changes and the merged result is left uncommitted.
363 changes and the merged result is left uncommitted.
364
364
365 By default, the pending changeset will have one parent,
365 By default, the pending changeset will have one parent,
366 maintaining a linear history. With --merge, the pending changeset
366 maintaining a linear history. With --merge, the pending changeset
367 will instead have two parents: the old parent of the working
367 will instead have two parents: the old parent of the working
368 directory and a new child of REV that simply undoes REV.
368 directory and a new child of REV that simply undoes REV.
369
369
370 Before version 1.7, the behavior without --merge was equivalent to
370 Before version 1.7, the behavior without --merge was equivalent to
371 specifying --merge followed by :hg:`update --clean .` to cancel
371 specifying --merge followed by :hg:`update --clean .` to cancel
372 the merge and leave the child of REV as a head to be merged
372 the merge and leave the child of REV as a head to be merged
373 separately.
373 separately.
374
374
375 See :hg:`help dates` for a list of formats valid for -d/--date.
375 See :hg:`help dates` for a list of formats valid for -d/--date.
376
376
377 Returns 0 on success.
377 Returns 0 on success.
378 '''
378 '''
379 if rev and node:
379 if rev and node:
380 raise util.Abort(_("please specify just one revision"))
380 raise util.Abort(_("please specify just one revision"))
381
381
382 if not rev:
382 if not rev:
383 rev = node
383 rev = node
384
384
385 if not rev:
385 if not rev:
386 raise util.Abort(_("please specify a revision to backout"))
386 raise util.Abort(_("please specify a revision to backout"))
387
387
388 date = opts.get('date')
388 date = opts.get('date')
389 if date:
389 if date:
390 opts['date'] = util.parsedate(date)
390 opts['date'] = util.parsedate(date)
391
391
392 cmdutil.bailifchanged(repo)
392 cmdutil.bailifchanged(repo)
393 node = cmdutil.revsingle(repo, rev).node()
393 node = cmdutil.revsingle(repo, rev).node()
394
394
395 op1, op2 = repo.dirstate.parents()
395 op1, op2 = repo.dirstate.parents()
396 a = repo.changelog.ancestor(op1, node)
396 a = repo.changelog.ancestor(op1, node)
397 if a != node:
397 if a != node:
398 raise util.Abort(_('cannot backout change on a different branch'))
398 raise util.Abort(_('cannot backout change on a different branch'))
399
399
400 p1, p2 = repo.changelog.parents(node)
400 p1, p2 = repo.changelog.parents(node)
401 if p1 == nullid:
401 if p1 == nullid:
402 raise util.Abort(_('cannot backout a change with no parents'))
402 raise util.Abort(_('cannot backout a change with no parents'))
403 if p2 != nullid:
403 if p2 != nullid:
404 if not opts.get('parent'):
404 if not opts.get('parent'):
405 raise util.Abort(_('cannot backout a merge changeset without '
405 raise util.Abort(_('cannot backout a merge changeset without '
406 '--parent'))
406 '--parent'))
407 p = repo.lookup(opts['parent'])
407 p = repo.lookup(opts['parent'])
408 if p not in (p1, p2):
408 if p not in (p1, p2):
409 raise util.Abort(_('%s is not a parent of %s') %
409 raise util.Abort(_('%s is not a parent of %s') %
410 (short(p), short(node)))
410 (short(p), short(node)))
411 parent = p
411 parent = p
412 else:
412 else:
413 if opts.get('parent'):
413 if opts.get('parent'):
414 raise util.Abort(_('cannot use --parent on non-merge changeset'))
414 raise util.Abort(_('cannot use --parent on non-merge changeset'))
415 parent = p1
415 parent = p1
416
416
417 # the backout should appear on the same branch
417 # the backout should appear on the same branch
418 branch = repo.dirstate.branch()
418 branch = repo.dirstate.branch()
419 hg.clean(repo, node, show_stats=False)
419 hg.clean(repo, node, show_stats=False)
420 repo.dirstate.setbranch(branch)
420 repo.dirstate.setbranch(branch)
421 revert_opts = opts.copy()
421 revert_opts = opts.copy()
422 revert_opts['date'] = None
422 revert_opts['date'] = None
423 revert_opts['all'] = True
423 revert_opts['all'] = True
424 revert_opts['rev'] = hex(parent)
424 revert_opts['rev'] = hex(parent)
425 revert_opts['no_backup'] = None
425 revert_opts['no_backup'] = None
426 revert(ui, repo, **revert_opts)
426 revert(ui, repo, **revert_opts)
427 if not opts.get('merge') and op1 != node:
427 if not opts.get('merge') and op1 != node:
428 try:
428 try:
429 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
429 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
430 return hg.update(repo, op1)
430 return hg.update(repo, op1)
431 finally:
431 finally:
432 ui.setconfig('ui', 'forcemerge', '')
432 ui.setconfig('ui', 'forcemerge', '')
433
433
434 commit_opts = opts.copy()
434 commit_opts = opts.copy()
435 commit_opts['addremove'] = False
435 commit_opts['addremove'] = False
436 if not commit_opts['message'] and not commit_opts['logfile']:
436 if not commit_opts['message'] and not commit_opts['logfile']:
437 # we don't translate commit messages
437 # we don't translate commit messages
438 commit_opts['message'] = "Backed out changeset %s" % short(node)
438 commit_opts['message'] = "Backed out changeset %s" % short(node)
439 commit_opts['force_editor'] = True
439 commit_opts['force_editor'] = True
440 commit(ui, repo, **commit_opts)
440 commit(ui, repo, **commit_opts)
441 def nice(node):
441 def nice(node):
442 return '%d:%s' % (repo.changelog.rev(node), short(node))
442 return '%d:%s' % (repo.changelog.rev(node), short(node))
443 ui.status(_('changeset %s backs out changeset %s\n') %
443 ui.status(_('changeset %s backs out changeset %s\n') %
444 (nice(repo.changelog.tip()), nice(node)))
444 (nice(repo.changelog.tip()), nice(node)))
445 if opts.get('merge') and op1 != node:
445 if opts.get('merge') and op1 != node:
446 hg.clean(repo, op1, show_stats=False)
446 hg.clean(repo, op1, show_stats=False)
447 ui.status(_('merging with changeset %s\n')
447 ui.status(_('merging with changeset %s\n')
448 % nice(repo.changelog.tip()))
448 % nice(repo.changelog.tip()))
449 try:
449 try:
450 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
450 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
451 return hg.merge(repo, hex(repo.changelog.tip()))
451 return hg.merge(repo, hex(repo.changelog.tip()))
452 finally:
452 finally:
453 ui.setconfig('ui', 'forcemerge', '')
453 ui.setconfig('ui', 'forcemerge', '')
454 return 0
454 return 0
455
455
456 @command('bisect',
456 @command('bisect',
457 [('r', 'reset', False, _('reset bisect state')),
457 [('r', 'reset', False, _('reset bisect state')),
458 ('g', 'good', False, _('mark changeset good')),
458 ('g', 'good', False, _('mark changeset good')),
459 ('b', 'bad', False, _('mark changeset bad')),
459 ('b', 'bad', False, _('mark changeset bad')),
460 ('s', 'skip', False, _('skip testing changeset')),
460 ('s', 'skip', False, _('skip testing changeset')),
461 ('e', 'extend', False, _('extend the bisect range')),
461 ('e', 'extend', False, _('extend the bisect range')),
462 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
462 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
463 ('U', 'noupdate', False, _('do not update to target'))],
463 ('U', 'noupdate', False, _('do not update to target'))],
464 _("[-gbsr] [-U] [-c CMD] [REV]"))
464 _("[-gbsr] [-U] [-c CMD] [REV]"))
465 def bisect(ui, repo, rev=None, extra=None, command=None,
465 def bisect(ui, repo, rev=None, extra=None, command=None,
466 reset=None, good=None, bad=None, skip=None, extend=None,
466 reset=None, good=None, bad=None, skip=None, extend=None,
467 noupdate=None):
467 noupdate=None):
468 """subdivision search of changesets
468 """subdivision search of changesets
469
469
470 This command helps to find changesets which introduce problems. To
470 This command helps to find changesets which introduce problems. To
471 use, mark the earliest changeset you know exhibits the problem as
471 use, mark the earliest changeset you know exhibits the problem as
472 bad, then mark the latest changeset which is free from the problem
472 bad, then mark the latest changeset which is free from the problem
473 as good. Bisect will update your working directory to a revision
473 as good. Bisect will update your working directory to a revision
474 for testing (unless the -U/--noupdate option is specified). Once
474 for testing (unless the -U/--noupdate option is specified). Once
475 you have performed tests, mark the working directory as good or
475 you have performed tests, mark the working directory as good or
476 bad, and bisect will either update to another candidate changeset
476 bad, and bisect will either update to another candidate changeset
477 or announce that it has found the bad revision.
477 or announce that it has found the bad revision.
478
478
479 As a shortcut, you can also use the revision argument to mark a
479 As a shortcut, you can also use the revision argument to mark a
480 revision as good or bad without checking it out first.
480 revision as good or bad without checking it out first.
481
481
482 If you supply a command, it will be used for automatic bisection.
482 If you supply a command, it will be used for automatic bisection.
483 Its exit status will be used to mark revisions as good or bad:
483 Its exit status will be used to mark revisions as good or bad:
484 status 0 means good, 125 means to skip the revision, 127
484 status 0 means good, 125 means to skip the revision, 127
485 (command not found) will abort the bisection, and any other
485 (command not found) will abort the bisection, and any other
486 non-zero exit status means the revision is bad.
486 non-zero exit status means the revision is bad.
487
487
488 Returns 0 on success.
488 Returns 0 on success.
489 """
489 """
490 def extendbisectrange(nodes, good):
490 def extendbisectrange(nodes, good):
491 # bisect is incomplete when it ends on a merge node and
491 # bisect is incomplete when it ends on a merge node and
492 # one of the parent was not checked.
492 # one of the parent was not checked.
493 parents = repo[nodes[0]].parents()
493 parents = repo[nodes[0]].parents()
494 if len(parents) > 1:
494 if len(parents) > 1:
495 side = good and state['bad'] or state['good']
495 side = good and state['bad'] or state['good']
496 num = len(set(i.node() for i in parents) & set(side))
496 num = len(set(i.node() for i in parents) & set(side))
497 if num == 1:
497 if num == 1:
498 return parents[0].ancestor(parents[1])
498 return parents[0].ancestor(parents[1])
499 return None
499 return None
500
500
501 def print_result(nodes, good):
501 def print_result(nodes, good):
502 displayer = cmdutil.show_changeset(ui, repo, {})
502 displayer = cmdutil.show_changeset(ui, repo, {})
503 if len(nodes) == 1:
503 if len(nodes) == 1:
504 # narrowed it down to a single revision
504 # narrowed it down to a single revision
505 if good:
505 if good:
506 ui.write(_("The first good revision is:\n"))
506 ui.write(_("The first good revision is:\n"))
507 else:
507 else:
508 ui.write(_("The first bad revision is:\n"))
508 ui.write(_("The first bad revision is:\n"))
509 displayer.show(repo[nodes[0]])
509 displayer.show(repo[nodes[0]])
510 extendnode = extendbisectrange(nodes, good)
510 extendnode = extendbisectrange(nodes, good)
511 if extendnode is not None:
511 if extendnode is not None:
512 ui.write(_('Not all ancestors of this changeset have been'
512 ui.write(_('Not all ancestors of this changeset have been'
513 ' checked.\nUse bisect --extend to continue the '
513 ' checked.\nUse bisect --extend to continue the '
514 'bisection from\nthe common ancestor, %s.\n')
514 'bisection from\nthe common ancestor, %s.\n')
515 % extendnode)
515 % extendnode)
516 else:
516 else:
517 # multiple possible revisions
517 # multiple possible revisions
518 if good:
518 if good:
519 ui.write(_("Due to skipped revisions, the first "
519 ui.write(_("Due to skipped revisions, the first "
520 "good revision could be any of:\n"))
520 "good revision could be any of:\n"))
521 else:
521 else:
522 ui.write(_("Due to skipped revisions, the first "
522 ui.write(_("Due to skipped revisions, the first "
523 "bad revision could be any of:\n"))
523 "bad revision could be any of:\n"))
524 for n in nodes:
524 for n in nodes:
525 displayer.show(repo[n])
525 displayer.show(repo[n])
526 displayer.close()
526 displayer.close()
527
527
528 def check_state(state, interactive=True):
528 def check_state(state, interactive=True):
529 if not state['good'] or not state['bad']:
529 if not state['good'] or not state['bad']:
530 if (good or bad or skip or reset) and interactive:
530 if (good or bad or skip or reset) and interactive:
531 return
531 return
532 if not state['good']:
532 if not state['good']:
533 raise util.Abort(_('cannot bisect (no known good revisions)'))
533 raise util.Abort(_('cannot bisect (no known good revisions)'))
534 else:
534 else:
535 raise util.Abort(_('cannot bisect (no known bad revisions)'))
535 raise util.Abort(_('cannot bisect (no known bad revisions)'))
536 return True
536 return True
537
537
538 # backward compatibility
538 # backward compatibility
539 if rev in "good bad reset init".split():
539 if rev in "good bad reset init".split():
540 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
540 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
541 cmd, rev, extra = rev, extra, None
541 cmd, rev, extra = rev, extra, None
542 if cmd == "good":
542 if cmd == "good":
543 good = True
543 good = True
544 elif cmd == "bad":
544 elif cmd == "bad":
545 bad = True
545 bad = True
546 else:
546 else:
547 reset = True
547 reset = True
548 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
548 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
549 raise util.Abort(_('incompatible arguments'))
549 raise util.Abort(_('incompatible arguments'))
550
550
551 if reset:
551 if reset:
552 p = repo.join("bisect.state")
552 p = repo.join("bisect.state")
553 if os.path.exists(p):
553 if os.path.exists(p):
554 os.unlink(p)
554 os.unlink(p)
555 return
555 return
556
556
557 state = hbisect.load_state(repo)
557 state = hbisect.load_state(repo)
558
558
559 if command:
559 if command:
560 changesets = 1
560 changesets = 1
561 try:
561 try:
562 while changesets:
562 while changesets:
563 # update state
563 # update state
564 status = util.system(command)
564 status = util.system(command)
565 if status == 125:
565 if status == 125:
566 transition = "skip"
566 transition = "skip"
567 elif status == 0:
567 elif status == 0:
568 transition = "good"
568 transition = "good"
569 # status < 0 means process was killed
569 # status < 0 means process was killed
570 elif status == 127:
570 elif status == 127:
571 raise util.Abort(_("failed to execute %s") % command)
571 raise util.Abort(_("failed to execute %s") % command)
572 elif status < 0:
572 elif status < 0:
573 raise util.Abort(_("%s killed") % command)
573 raise util.Abort(_("%s killed") % command)
574 else:
574 else:
575 transition = "bad"
575 transition = "bad"
576 ctx = cmdutil.revsingle(repo, rev)
576 ctx = cmdutil.revsingle(repo, rev)
577 rev = None # clear for future iterations
577 rev = None # clear for future iterations
578 state[transition].append(ctx.node())
578 state[transition].append(ctx.node())
579 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
579 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
580 check_state(state, interactive=False)
580 check_state(state, interactive=False)
581 # bisect
581 # bisect
582 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
582 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
583 # update to next check
583 # update to next check
584 cmdutil.bailifchanged(repo)
584 cmdutil.bailifchanged(repo)
585 hg.clean(repo, nodes[0], show_stats=False)
585 hg.clean(repo, nodes[0], show_stats=False)
586 finally:
586 finally:
587 hbisect.save_state(repo, state)
587 hbisect.save_state(repo, state)
588 print_result(nodes, good)
588 print_result(nodes, good)
589 return
589 return
590
590
591 # update state
591 # update state
592
592
593 if rev:
593 if rev:
594 nodes = [repo.lookup(i) for i in cmdutil.revrange(repo, [rev])]
594 nodes = [repo.lookup(i) for i in cmdutil.revrange(repo, [rev])]
595 else:
595 else:
596 nodes = [repo.lookup('.')]
596 nodes = [repo.lookup('.')]
597
597
598 if good or bad or skip:
598 if good or bad or skip:
599 if good:
599 if good:
600 state['good'] += nodes
600 state['good'] += nodes
601 elif bad:
601 elif bad:
602 state['bad'] += nodes
602 state['bad'] += nodes
603 elif skip:
603 elif skip:
604 state['skip'] += nodes
604 state['skip'] += nodes
605 hbisect.save_state(repo, state)
605 hbisect.save_state(repo, state)
606
606
607 if not check_state(state):
607 if not check_state(state):
608 return
608 return
609
609
610 # actually bisect
610 # actually bisect
611 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
611 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
612 if extend:
612 if extend:
613 if not changesets:
613 if not changesets:
614 extendnode = extendbisectrange(nodes, good)
614 extendnode = extendbisectrange(nodes, good)
615 if extendnode is not None:
615 if extendnode is not None:
616 ui.write(_("Extending search to changeset %d:%s\n"
616 ui.write(_("Extending search to changeset %d:%s\n"
617 % (extendnode.rev(), extendnode)))
617 % (extendnode.rev(), extendnode)))
618 if noupdate:
618 if noupdate:
619 return
619 return
620 cmdutil.bailifchanged(repo)
620 cmdutil.bailifchanged(repo)
621 return hg.clean(repo, extendnode.node())
621 return hg.clean(repo, extendnode.node())
622 raise util.Abort(_("nothing to extend"))
622 raise util.Abort(_("nothing to extend"))
623
623
624 if changesets == 0:
624 if changesets == 0:
625 print_result(nodes, good)
625 print_result(nodes, good)
626 else:
626 else:
627 assert len(nodes) == 1 # only a single node can be tested next
627 assert len(nodes) == 1 # only a single node can be tested next
628 node = nodes[0]
628 node = nodes[0]
629 # compute the approximate number of remaining tests
629 # compute the approximate number of remaining tests
630 tests, size = 0, 2
630 tests, size = 0, 2
631 while size <= changesets:
631 while size <= changesets:
632 tests, size = tests + 1, size * 2
632 tests, size = tests + 1, size * 2
633 rev = repo.changelog.rev(node)
633 rev = repo.changelog.rev(node)
634 ui.write(_("Testing changeset %d:%s "
634 ui.write(_("Testing changeset %d:%s "
635 "(%d changesets remaining, ~%d tests)\n")
635 "(%d changesets remaining, ~%d tests)\n")
636 % (rev, short(node), changesets, tests))
636 % (rev, short(node), changesets, tests))
637 if not noupdate:
637 if not noupdate:
638 cmdutil.bailifchanged(repo)
638 cmdutil.bailifchanged(repo)
639 return hg.clean(repo, node)
639 return hg.clean(repo, node)
640
640
641 @command('bookmarks',
641 @command('bookmarks',
642 [('f', 'force', False, _('force')),
642 [('f', 'force', False, _('force')),
643 ('r', 'rev', '', _('revision'), _('REV')),
643 ('r', 'rev', '', _('revision'), _('REV')),
644 ('d', 'delete', False, _('delete a given bookmark')),
644 ('d', 'delete', False, _('delete a given bookmark')),
645 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
645 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
646 ('i', 'inactive', False, _('do not mark a new bookmark active'))],
646 ('i', 'inactive', False, _('do not mark a new bookmark active'))],
647 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
647 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
648 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
648 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
649 rename=None, inactive=False):
649 rename=None, inactive=False):
650 '''track a line of development with movable markers
650 '''track a line of development with movable markers
651
651
652 Bookmarks are pointers to certain commits that move when
652 Bookmarks are pointers to certain commits that move when
653 committing. Bookmarks are local. They can be renamed, copied and
653 committing. Bookmarks are local. They can be renamed, copied and
654 deleted. It is possible to use bookmark names in :hg:`merge` and
654 deleted. It is possible to use bookmark names in :hg:`merge` and
655 :hg:`update` to merge and update respectively to a given bookmark.
655 :hg:`update` to merge and update respectively to a given bookmark.
656
656
657 You can use :hg:`bookmark NAME` to set a bookmark on the working
657 You can use :hg:`bookmark NAME` to set a bookmark on the working
658 directory's parent revision with the given name. If you specify
658 directory's parent revision with the given name. If you specify
659 a revision using -r REV (where REV may be an existing bookmark),
659 a revision using -r REV (where REV may be an existing bookmark),
660 the bookmark is assigned to that revision.
660 the bookmark is assigned to that revision.
661
661
662 Bookmarks can be pushed and pulled between repositories (see :hg:`help
662 Bookmarks can be pushed and pulled between repositories (see :hg:`help
663 push` and :hg:`help pull`). This requires both the local and remote
663 push` and :hg:`help pull`). This requires both the local and remote
664 repositories to support bookmarks. For versions prior to 1.8, this means
664 repositories to support bookmarks. For versions prior to 1.8, this means
665 the bookmarks extension must be enabled.
665 the bookmarks extension must be enabled.
666 '''
666 '''
667 hexfn = ui.debugflag and hex or short
667 hexfn = ui.debugflag and hex or short
668 marks = repo._bookmarks
668 marks = repo._bookmarks
669 cur = repo.changectx('.').node()
669 cur = repo.changectx('.').node()
670
670
671 if rename:
671 if rename:
672 if rename not in marks:
672 if rename not in marks:
673 raise util.Abort(_("bookmark '%s' does not exist") % rename)
673 raise util.Abort(_("bookmark '%s' does not exist") % rename)
674 if mark in marks and not force:
674 if mark in marks and not force:
675 raise util.Abort(_("bookmark '%s' already exists "
675 raise util.Abort(_("bookmark '%s' already exists "
676 "(use -f to force)") % mark)
676 "(use -f to force)") % mark)
677 if mark is None:
677 if mark is None:
678 raise util.Abort(_("new bookmark name required"))
678 raise util.Abort(_("new bookmark name required"))
679 marks[mark] = marks[rename]
679 marks[mark] = marks[rename]
680 if repo._bookmarkcurrent == rename and not inactive:
680 if repo._bookmarkcurrent == rename and not inactive:
681 bookmarks.setcurrent(repo, mark)
681 bookmarks.setcurrent(repo, mark)
682 del marks[rename]
682 del marks[rename]
683 bookmarks.write(repo)
683 bookmarks.write(repo)
684 return
684 return
685
685
686 if delete:
686 if delete:
687 if mark is None:
687 if mark is None:
688 raise util.Abort(_("bookmark name required"))
688 raise util.Abort(_("bookmark name required"))
689 if mark not in marks:
689 if mark not in marks:
690 raise util.Abort(_("bookmark '%s' does not exist") % mark)
690 raise util.Abort(_("bookmark '%s' does not exist") % mark)
691 if mark == repo._bookmarkcurrent:
691 if mark == repo._bookmarkcurrent:
692 bookmarks.setcurrent(repo, None)
692 bookmarks.setcurrent(repo, None)
693 del marks[mark]
693 del marks[mark]
694 bookmarks.write(repo)
694 bookmarks.write(repo)
695 return
695 return
696
696
697 if mark is not None:
697 if mark is not None:
698 if "\n" in mark:
698 if "\n" in mark:
699 raise util.Abort(_("bookmark name cannot contain newlines"))
699 raise util.Abort(_("bookmark name cannot contain newlines"))
700 mark = mark.strip()
700 mark = mark.strip()
701 if not mark:
701 if not mark:
702 raise util.Abort(_("bookmark names cannot consist entirely of "
702 raise util.Abort(_("bookmark names cannot consist entirely of "
703 "whitespace"))
703 "whitespace"))
704 if inactive and mark == repo._bookmarkcurrent:
704 if inactive and mark == repo._bookmarkcurrent:
705 bookmarks.setcurrent(repo, None)
705 bookmarks.setcurrent(repo, None)
706 return
706 return
707 if mark in marks and not force:
707 if mark in marks and not force:
708 raise util.Abort(_("bookmark '%s' already exists "
708 raise util.Abort(_("bookmark '%s' already exists "
709 "(use -f to force)") % mark)
709 "(use -f to force)") % mark)
710 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
710 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
711 and not force):
711 and not force):
712 raise util.Abort(
712 raise util.Abort(
713 _("a bookmark cannot have the name of an existing branch"))
713 _("a bookmark cannot have the name of an existing branch"))
714 if rev:
714 if rev:
715 marks[mark] = repo.lookup(rev)
715 marks[mark] = repo.lookup(rev)
716 else:
716 else:
717 marks[mark] = repo.changectx('.').node()
717 marks[mark] = repo.changectx('.').node()
718 if not inactive and repo.changectx('.').node() == marks[mark]:
718 if not inactive and repo.changectx('.').node() == marks[mark]:
719 bookmarks.setcurrent(repo, mark)
719 bookmarks.setcurrent(repo, mark)
720 bookmarks.write(repo)
720 bookmarks.write(repo)
721 return
721 return
722
722
723 if mark is None:
723 if mark is None:
724 if rev:
724 if rev:
725 raise util.Abort(_("bookmark name required"))
725 raise util.Abort(_("bookmark name required"))
726 if len(marks) == 0:
726 if len(marks) == 0:
727 ui.status(_("no bookmarks set\n"))
727 ui.status(_("no bookmarks set\n"))
728 else:
728 else:
729 for bmark, n in sorted(marks.iteritems()):
729 for bmark, n in sorted(marks.iteritems()):
730 current = repo._bookmarkcurrent
730 current = repo._bookmarkcurrent
731 if bmark == current and n == cur:
731 if bmark == current and n == cur:
732 prefix, label = '*', 'bookmarks.current'
732 prefix, label = '*', 'bookmarks.current'
733 else:
733 else:
734 prefix, label = ' ', ''
734 prefix, label = ' ', ''
735
735
736 if ui.quiet:
736 if ui.quiet:
737 ui.write("%s\n" % bmark, label=label)
737 ui.write("%s\n" % bmark, label=label)
738 else:
738 else:
739 ui.write(" %s %-25s %d:%s\n" % (
739 ui.write(" %s %-25s %d:%s\n" % (
740 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
740 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
741 label=label)
741 label=label)
742 return
742 return
743
743
744 @command('branch',
744 @command('branch',
745 [('f', 'force', None,
745 [('f', 'force', None,
746 _('set branch name even if it shadows an existing branch')),
746 _('set branch name even if it shadows an existing branch')),
747 ('C', 'clean', None, _('reset branch name to parent branch name'))],
747 ('C', 'clean', None, _('reset branch name to parent branch name'))],
748 _('[-fC] [NAME]'))
748 _('[-fC] [NAME]'))
749 def branch(ui, repo, label=None, **opts):
749 def branch(ui, repo, label=None, **opts):
750 """set or show the current branch name
750 """set or show the current branch name
751
751
752 With no argument, show the current branch name. With one argument,
752 With no argument, show the current branch name. With one argument,
753 set the working directory branch name (the branch will not exist
753 set the working directory branch name (the branch will not exist
754 in the repository until the next commit). Standard practice
754 in the repository until the next commit). Standard practice
755 recommends that primary development take place on the 'default'
755 recommends that primary development take place on the 'default'
756 branch.
756 branch.
757
757
758 Unless -f/--force is specified, branch will not let you set a
758 Unless -f/--force is specified, branch will not let you set a
759 branch name that already exists, even if it's inactive.
759 branch name that already exists, even if it's inactive.
760
760
761 Use -C/--clean to reset the working directory branch to that of
761 Use -C/--clean to reset the working directory branch to that of
762 the parent of the working directory, negating a previous branch
762 the parent of the working directory, negating a previous branch
763 change.
763 change.
764
764
765 Use the command :hg:`update` to switch to an existing branch. Use
765 Use the command :hg:`update` to switch to an existing branch. Use
766 :hg:`commit --close-branch` to mark this branch as closed.
766 :hg:`commit --close-branch` to mark this branch as closed.
767
767
768 Returns 0 on success.
768 Returns 0 on success.
769 """
769 """
770
770
771 if opts.get('clean'):
771 if opts.get('clean'):
772 label = repo[None].p1().branch()
772 label = repo[None].p1().branch()
773 repo.dirstate.setbranch(label)
773 repo.dirstate.setbranch(label)
774 ui.status(_('reset working directory to branch %s\n') % label)
774 ui.status(_('reset working directory to branch %s\n') % label)
775 elif label:
775 elif label:
776 if not opts.get('force') and label in repo.branchtags():
776 if not opts.get('force') and label in repo.branchtags():
777 if label not in [p.branch() for p in repo.parents()]:
777 if label not in [p.branch() for p in repo.parents()]:
778 raise util.Abort(_('a branch of the same name already exists'),
778 raise util.Abort(_('a branch of the same name already exists'),
779 # i18n: "it" refers to an existing branch
779 # i18n: "it" refers to an existing branch
780 hint=_("use 'hg update' to switch to it"))
780 hint=_("use 'hg update' to switch to it"))
781 repo.dirstate.setbranch(label)
781 repo.dirstate.setbranch(label)
782 ui.status(_('marked working directory as branch %s\n') % label)
782 ui.status(_('marked working directory as branch %s\n') % label)
783 else:
783 else:
784 ui.write("%s\n" % repo.dirstate.branch())
784 ui.write("%s\n" % repo.dirstate.branch())
785
785
786 @command('branches',
786 @command('branches',
787 [('a', 'active', False, _('show only branches that have unmerged heads')),
787 [('a', 'active', False, _('show only branches that have unmerged heads')),
788 ('c', 'closed', False, _('show normal and closed branches'))],
788 ('c', 'closed', False, _('show normal and closed branches'))],
789 _('[-ac]'))
789 _('[-ac]'))
790 def branches(ui, repo, active=False, closed=False):
790 def branches(ui, repo, active=False, closed=False):
791 """list repository named branches
791 """list repository named branches
792
792
793 List the repository's named branches, indicating which ones are
793 List the repository's named branches, indicating which ones are
794 inactive. If -c/--closed is specified, also list branches which have
794 inactive. If -c/--closed is specified, also list branches which have
795 been marked closed (see :hg:`commit --close-branch`).
795 been marked closed (see :hg:`commit --close-branch`).
796
796
797 If -a/--active is specified, only show active branches. A branch
797 If -a/--active is specified, only show active branches. A branch
798 is considered active if it contains repository heads.
798 is considered active if it contains repository heads.
799
799
800 Use the command :hg:`update` to switch to an existing branch.
800 Use the command :hg:`update` to switch to an existing branch.
801
801
802 Returns 0.
802 Returns 0.
803 """
803 """
804
804
805 hexfunc = ui.debugflag and hex or short
805 hexfunc = ui.debugflag and hex or short
806 activebranches = [repo[n].branch() for n in repo.heads()]
806 activebranches = [repo[n].branch() for n in repo.heads()]
807 def testactive(tag, node):
807 def testactive(tag, node):
808 realhead = tag in activebranches
808 realhead = tag in activebranches
809 open = node in repo.branchheads(tag, closed=False)
809 open = node in repo.branchheads(tag, closed=False)
810 return realhead and open
810 return realhead and open
811 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
811 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
812 for tag, node in repo.branchtags().items()],
812 for tag, node in repo.branchtags().items()],
813 reverse=True)
813 reverse=True)
814
814
815 for isactive, node, tag in branches:
815 for isactive, node, tag in branches:
816 if (not active) or isactive:
816 if (not active) or isactive:
817 if ui.quiet:
817 if ui.quiet:
818 ui.write("%s\n" % tag)
818 ui.write("%s\n" % tag)
819 else:
819 else:
820 hn = repo.lookup(node)
820 hn = repo.lookup(node)
821 if isactive:
821 if isactive:
822 label = 'branches.active'
822 label = 'branches.active'
823 notice = ''
823 notice = ''
824 elif hn not in repo.branchheads(tag, closed=False):
824 elif hn not in repo.branchheads(tag, closed=False):
825 if not closed:
825 if not closed:
826 continue
826 continue
827 label = 'branches.closed'
827 label = 'branches.closed'
828 notice = _(' (closed)')
828 notice = _(' (closed)')
829 else:
829 else:
830 label = 'branches.inactive'
830 label = 'branches.inactive'
831 notice = _(' (inactive)')
831 notice = _(' (inactive)')
832 if tag == repo.dirstate.branch():
832 if tag == repo.dirstate.branch():
833 label = 'branches.current'
833 label = 'branches.current'
834 rev = str(node).rjust(31 - encoding.colwidth(tag))
834 rev = str(node).rjust(31 - encoding.colwidth(tag))
835 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
835 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
836 tag = ui.label(tag, label)
836 tag = ui.label(tag, label)
837 ui.write("%s %s%s\n" % (tag, rev, notice))
837 ui.write("%s %s%s\n" % (tag, rev, notice))
838
838
839 @command('bundle',
839 @command('bundle',
840 [('f', 'force', None, _('run even when the destination is unrelated')),
840 [('f', 'force', None, _('run even when the destination is unrelated')),
841 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
841 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
842 _('REV')),
842 _('REV')),
843 ('b', 'branch', [], _('a specific branch you would like to bundle'),
843 ('b', 'branch', [], _('a specific branch you would like to bundle'),
844 _('BRANCH')),
844 _('BRANCH')),
845 ('', 'base', [],
845 ('', 'base', [],
846 _('a base changeset assumed to be available at the destination'),
846 _('a base changeset assumed to be available at the destination'),
847 _('REV')),
847 _('REV')),
848 ('a', 'all', None, _('bundle all changesets in the repository')),
848 ('a', 'all', None, _('bundle all changesets in the repository')),
849 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
849 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
850 ] + remoteopts,
850 ] + remoteopts,
851 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
851 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
852 def bundle(ui, repo, fname, dest=None, **opts):
852 def bundle(ui, repo, fname, dest=None, **opts):
853 """create a changegroup file
853 """create a changegroup file
854
854
855 Generate a compressed changegroup file collecting changesets not
855 Generate a compressed changegroup file collecting changesets not
856 known to be in another repository.
856 known to be in another repository.
857
857
858 If you omit the destination repository, then hg assumes the
858 If you omit the destination repository, then hg assumes the
859 destination will have all the nodes you specify with --base
859 destination will have all the nodes you specify with --base
860 parameters. To create a bundle containing all changesets, use
860 parameters. To create a bundle containing all changesets, use
861 -a/--all (or --base null).
861 -a/--all (or --base null).
862
862
863 You can change compression method with the -t/--type option.
863 You can change compression method with the -t/--type option.
864 The available compression methods are: none, bzip2, and
864 The available compression methods are: none, bzip2, and
865 gzip (by default, bundles are compressed using bzip2).
865 gzip (by default, bundles are compressed using bzip2).
866
866
867 The bundle file can then be transferred using conventional means
867 The bundle file can then be transferred using conventional means
868 and applied to another repository with the unbundle or pull
868 and applied to another repository with the unbundle or pull
869 command. This is useful when direct push and pull are not
869 command. This is useful when direct push and pull are not
870 available or when exporting an entire repository is undesirable.
870 available or when exporting an entire repository is undesirable.
871
871
872 Applying bundles preserves all changeset contents including
872 Applying bundles preserves all changeset contents including
873 permissions, copy/rename information, and revision history.
873 permissions, copy/rename information, and revision history.
874
874
875 Returns 0 on success, 1 if no changes found.
875 Returns 0 on success, 1 if no changes found.
876 """
876 """
877 revs = None
877 revs = None
878 if 'rev' in opts:
878 if 'rev' in opts:
879 revs = cmdutil.revrange(repo, opts['rev'])
879 revs = cmdutil.revrange(repo, opts['rev'])
880
880
881 if opts.get('all'):
881 if opts.get('all'):
882 base = ['null']
882 base = ['null']
883 else:
883 else:
884 base = cmdutil.revrange(repo, opts.get('base'))
884 base = cmdutil.revrange(repo, opts.get('base'))
885 if base:
885 if base:
886 if dest:
886 if dest:
887 raise util.Abort(_("--base is incompatible with specifying "
887 raise util.Abort(_("--base is incompatible with specifying "
888 "a destination"))
888 "a destination"))
889 common = [repo.lookup(rev) for rev in base]
889 common = [repo.lookup(rev) for rev in base]
890 heads = revs and map(repo.lookup, revs) or revs
890 heads = revs and map(repo.lookup, revs) or revs
891 else:
891 else:
892 dest = ui.expandpath(dest or 'default-push', dest or 'default')
892 dest = ui.expandpath(dest or 'default-push', dest or 'default')
893 dest, branches = hg.parseurl(dest, opts.get('branch'))
893 dest, branches = hg.parseurl(dest, opts.get('branch'))
894 other = hg.repository(hg.remoteui(repo, opts), dest)
894 other = hg.repository(hg.remoteui(repo, opts), dest)
895 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
895 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
896 heads = revs and map(repo.lookup, revs) or revs
896 heads = revs and map(repo.lookup, revs) or revs
897 common, outheads = discovery.findcommonoutgoing(repo, other,
897 common, outheads = discovery.findcommonoutgoing(repo, other,
898 onlyheads=heads,
898 onlyheads=heads,
899 force=opts.get('force'))
899 force=opts.get('force'))
900
900
901 cg = repo.getbundle('bundle', common=common, heads=heads)
901 cg = repo.getbundle('bundle', common=common, heads=heads)
902 if not cg:
902 if not cg:
903 ui.status(_("no changes found\n"))
903 ui.status(_("no changes found\n"))
904 return 1
904 return 1
905
905
906 bundletype = opts.get('type', 'bzip2').lower()
906 bundletype = opts.get('type', 'bzip2').lower()
907 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
907 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
908 bundletype = btypes.get(bundletype)
908 bundletype = btypes.get(bundletype)
909 if bundletype not in changegroup.bundletypes:
909 if bundletype not in changegroup.bundletypes:
910 raise util.Abort(_('unknown bundle type specified with --type'))
910 raise util.Abort(_('unknown bundle type specified with --type'))
911
911
912 changegroup.writebundle(cg, fname, bundletype)
912 changegroup.writebundle(cg, fname, bundletype)
913
913
914 @command('cat',
914 @command('cat',
915 [('o', 'output', '',
915 [('o', 'output', '',
916 _('print output to file with formatted name'), _('FORMAT')),
916 _('print output to file with formatted name'), _('FORMAT')),
917 ('r', 'rev', '', _('print the given revision'), _('REV')),
917 ('r', 'rev', '', _('print the given revision'), _('REV')),
918 ('', 'decode', None, _('apply any matching decode filter')),
918 ('', 'decode', None, _('apply any matching decode filter')),
919 ] + walkopts,
919 ] + walkopts,
920 _('[OPTION]... FILE...'))
920 _('[OPTION]... FILE...'))
921 def cat(ui, repo, file1, *pats, **opts):
921 def cat(ui, repo, file1, *pats, **opts):
922 """output the current or given revision of files
922 """output the current or given revision of files
923
923
924 Print the specified files as they were at the given revision. If
924 Print the specified files as they were at the given revision. If
925 no revision is given, the parent of the working directory is used,
925 no revision is given, the parent of the working directory is used,
926 or tip if no revision is checked out.
926 or tip if no revision is checked out.
927
927
928 Output may be to a file, in which case the name of the file is
928 Output may be to a file, in which case the name of the file is
929 given using a format string. The formatting rules are the same as
929 given using a format string. The formatting rules are the same as
930 for the export command, with the following additions:
930 for the export command, with the following additions:
931
931
932 :``%s``: basename of file being printed
932 :``%s``: basename of file being printed
933 :``%d``: dirname of file being printed, or '.' if in repository root
933 :``%d``: dirname of file being printed, or '.' if in repository root
934 :``%p``: root-relative path name of file being printed
934 :``%p``: root-relative path name of file being printed
935
935
936 Returns 0 on success.
936 Returns 0 on success.
937 """
937 """
938 ctx = cmdutil.revsingle(repo, opts.get('rev'))
938 ctx = cmdutil.revsingle(repo, opts.get('rev'))
939 err = 1
939 err = 1
940 m = cmdutil.match(repo, (file1,) + pats, opts)
940 m = cmdutil.match(repo, (file1,) + pats, opts)
941 for abs in ctx.walk(m):
941 for abs in ctx.walk(m):
942 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
942 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
943 pathname=abs)
943 pathname=abs)
944 data = ctx[abs].data()
944 data = ctx[abs].data()
945 if opts.get('decode'):
945 if opts.get('decode'):
946 data = repo.wwritedata(abs, data)
946 data = repo.wwritedata(abs, data)
947 fp.write(data)
947 fp.write(data)
948 fp.close()
948 fp.close()
949 err = 0
949 err = 0
950 return err
950 return err
951
951
952 @command('^clone',
952 @command('^clone',
953 [('U', 'noupdate', None,
953 [('U', 'noupdate', None,
954 _('the clone will include an empty working copy (only a repository)')),
954 _('the clone will include an empty working copy (only a repository)')),
955 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
955 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
956 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
956 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
957 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
957 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
958 ('', 'pull', None, _('use pull protocol to copy metadata')),
958 ('', 'pull', None, _('use pull protocol to copy metadata')),
959 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
959 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
960 ] + remoteopts,
960 ] + remoteopts,
961 _('[OPTION]... SOURCE [DEST]'))
961 _('[OPTION]... SOURCE [DEST]'))
962 def clone(ui, source, dest=None, **opts):
962 def clone(ui, source, dest=None, **opts):
963 """make a copy of an existing repository
963 """make a copy of an existing repository
964
964
965 Create a copy of an existing repository in a new directory.
965 Create a copy of an existing repository in a new directory.
966
966
967 If no destination directory name is specified, it defaults to the
967 If no destination directory name is specified, it defaults to the
968 basename of the source.
968 basename of the source.
969
969
970 The location of the source is added to the new repository's
970 The location of the source is added to the new repository's
971 ``.hg/hgrc`` file, as the default to be used for future pulls.
971 ``.hg/hgrc`` file, as the default to be used for future pulls.
972
972
973 See :hg:`help urls` for valid source format details.
973 See :hg:`help urls` for valid source format details.
974
974
975 It is possible to specify an ``ssh://`` URL as the destination, but no
975 It is possible to specify an ``ssh://`` URL as the destination, but no
976 ``.hg/hgrc`` and working directory will be created on the remote side.
976 ``.hg/hgrc`` and working directory will be created on the remote side.
977 Please see :hg:`help urls` for important details about ``ssh://`` URLs.
977 Please see :hg:`help urls` for important details about ``ssh://`` URLs.
978
978
979 A set of changesets (tags, or branch names) to pull may be specified
979 A set of changesets (tags, or branch names) to pull may be specified
980 by listing each changeset (tag, or branch name) with -r/--rev.
980 by listing each changeset (tag, or branch name) with -r/--rev.
981 If -r/--rev is used, the cloned repository will contain only a subset
981 If -r/--rev is used, the cloned repository will contain only a subset
982 of the changesets of the source repository. Only the set of changesets
982 of the changesets of the source repository. Only the set of changesets
983 defined by all -r/--rev options (including all their ancestors)
983 defined by all -r/--rev options (including all their ancestors)
984 will be pulled into the destination repository.
984 will be pulled into the destination repository.
985 No subsequent changesets (including subsequent tags) will be present
985 No subsequent changesets (including subsequent tags) will be present
986 in the destination.
986 in the destination.
987
987
988 Using -r/--rev (or 'clone src#rev dest') implies --pull, even for
988 Using -r/--rev (or 'clone src#rev dest') implies --pull, even for
989 local source repositories.
989 local source repositories.
990
990
991 For efficiency, hardlinks are used for cloning whenever the source
991 For efficiency, hardlinks are used for cloning whenever the source
992 and destination are on the same filesystem (note this applies only
992 and destination are on the same filesystem (note this applies only
993 to the repository data, not to the working directory). Some
993 to the repository data, not to the working directory). Some
994 filesystems, such as AFS, implement hardlinking incorrectly, but
994 filesystems, such as AFS, implement hardlinking incorrectly, but
995 do not report errors. In these cases, use the --pull option to
995 do not report errors. In these cases, use the --pull option to
996 avoid hardlinking.
996 avoid hardlinking.
997
997
998 In some cases, you can clone repositories and the working directory
998 In some cases, you can clone repositories and the working directory
999 using full hardlinks with ::
999 using full hardlinks with ::
1000
1000
1001 $ cp -al REPO REPOCLONE
1001 $ cp -al REPO REPOCLONE
1002
1002
1003 This is the fastest way to clone, but it is not always safe. The
1003 This is the fastest way to clone, but it is not always safe. The
1004 operation is not atomic (making sure REPO is not modified during
1004 operation is not atomic (making sure REPO is not modified during
1005 the operation is up to you) and you have to make sure your editor
1005 the operation is up to you) and you have to make sure your editor
1006 breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
1006 breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
1007 this is not compatible with certain extensions that place their
1007 this is not compatible with certain extensions that place their
1008 metadata under the .hg directory, such as mq.
1008 metadata under the .hg directory, such as mq.
1009
1009
1010 Mercurial will update the working directory to the first applicable
1010 Mercurial will update the working directory to the first applicable
1011 revision from this list:
1011 revision from this list:
1012
1012
1013 a) null if -U or the source repository has no changesets
1013 a) null if -U or the source repository has no changesets
1014 b) if -u . and the source repository is local, the first parent of
1014 b) if -u . and the source repository is local, the first parent of
1015 the source repository's working directory
1015 the source repository's working directory
1016 c) the changeset specified with -u (if a branch name, this means the
1016 c) the changeset specified with -u (if a branch name, this means the
1017 latest head of that branch)
1017 latest head of that branch)
1018 d) the changeset specified with -r
1018 d) the changeset specified with -r
1019 e) the tipmost head specified with -b
1019 e) the tipmost head specified with -b
1020 f) the tipmost head specified with the url#branch source syntax
1020 f) the tipmost head specified with the url#branch source syntax
1021 g) the tipmost head of the default branch
1021 g) the tipmost head of the default branch
1022 h) tip
1022 h) tip
1023
1023
1024 Returns 0 on success.
1024 Returns 0 on success.
1025 """
1025 """
1026 if opts.get('noupdate') and opts.get('updaterev'):
1026 if opts.get('noupdate') and opts.get('updaterev'):
1027 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1027 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1028
1028
1029 r = hg.clone(hg.remoteui(ui, opts), source, dest,
1029 r = hg.clone(hg.remoteui(ui, opts), source, dest,
1030 pull=opts.get('pull'),
1030 pull=opts.get('pull'),
1031 stream=opts.get('uncompressed'),
1031 stream=opts.get('uncompressed'),
1032 rev=opts.get('rev'),
1032 rev=opts.get('rev'),
1033 update=opts.get('updaterev') or not opts.get('noupdate'),
1033 update=opts.get('updaterev') or not opts.get('noupdate'),
1034 branch=opts.get('branch'))
1034 branch=opts.get('branch'))
1035
1035
1036 return r is None
1036 return r is None
1037
1037
1038 @command('^commit|ci',
1038 @command('^commit|ci',
1039 [('A', 'addremove', None,
1039 [('A', 'addremove', None,
1040 _('mark new/missing files as added/removed before committing')),
1040 _('mark new/missing files as added/removed before committing')),
1041 ('', 'close-branch', None,
1041 ('', 'close-branch', None,
1042 _('mark a branch as closed, hiding it from the branch list')),
1042 _('mark a branch as closed, hiding it from the branch list')),
1043 ] + walkopts + commitopts + commitopts2,
1043 ] + walkopts + commitopts + commitopts2,
1044 _('[OPTION]... [FILE]...'))
1044 _('[OPTION]... [FILE]...'))
1045 def commit(ui, repo, *pats, **opts):
1045 def commit(ui, repo, *pats, **opts):
1046 """commit the specified files or all outstanding changes
1046 """commit the specified files or all outstanding changes
1047
1047
1048 Commit changes to the given files into the repository. Unlike a
1048 Commit changes to the given files into the repository. Unlike a
1049 centralized SCM, this operation is a local operation. See
1049 centralized SCM, this operation is a local operation. See
1050 :hg:`push` for a way to actively distribute your changes.
1050 :hg:`push` for a way to actively distribute your changes.
1051
1051
1052 If a list of files is omitted, all changes reported by :hg:`status`
1052 If a list of files is omitted, all changes reported by :hg:`status`
1053 will be committed.
1053 will be committed.
1054
1054
1055 If you are committing the result of a merge, do not provide any
1055 If you are committing the result of a merge, do not provide any
1056 filenames or -I/-X filters.
1056 filenames or -I/-X filters.
1057
1057
1058 If no commit message is specified, Mercurial starts your
1058 If no commit message is specified, Mercurial starts your
1059 configured editor where you can enter a message. In case your
1059 configured editor where you can enter a message. In case your
1060 commit fails, you will find a backup of your message in
1060 commit fails, you will find a backup of your message in
1061 ``.hg/last-message.txt``.
1061 ``.hg/last-message.txt``.
1062
1062
1063 See :hg:`help dates` for a list of formats valid for -d/--date.
1063 See :hg:`help dates` for a list of formats valid for -d/--date.
1064
1064
1065 Returns 0 on success, 1 if nothing changed.
1065 Returns 0 on success, 1 if nothing changed.
1066 """
1066 """
1067 extra = {}
1067 extra = {}
1068 if opts.get('close_branch'):
1068 if opts.get('close_branch'):
1069 if repo['.'].node() not in repo.branchheads():
1069 if repo['.'].node() not in repo.branchheads():
1070 # The topo heads set is included in the branch heads set of the
1070 # The topo heads set is included in the branch heads set of the
1071 # current branch, so it's sufficient to test branchheads
1071 # current branch, so it's sufficient to test branchheads
1072 raise util.Abort(_('can only close branch heads'))
1072 raise util.Abort(_('can only close branch heads'))
1073 extra['close'] = 1
1073 extra['close'] = 1
1074 e = cmdutil.commiteditor
1074 e = cmdutil.commiteditor
1075 if opts.get('force_editor'):
1075 if opts.get('force_editor'):
1076 e = cmdutil.commitforceeditor
1076 e = cmdutil.commitforceeditor
1077
1077
1078 def commitfunc(ui, repo, message, match, opts):
1078 def commitfunc(ui, repo, message, match, opts):
1079 return repo.commit(message, opts.get('user'), opts.get('date'), match,
1079 return repo.commit(message, opts.get('user'), opts.get('date'), match,
1080 editor=e, extra=extra)
1080 editor=e, extra=extra)
1081
1081
1082 branch = repo[None].branch()
1082 branch = repo[None].branch()
1083 bheads = repo.branchheads(branch)
1083 bheads = repo.branchheads(branch)
1084
1084
1085 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1085 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1086 if not node:
1086 if not node:
1087 stat = repo.status(match=cmdutil.match(repo, pats, opts))
1087 stat = repo.status(match=cmdutil.match(repo, pats, opts))
1088 if stat[3]:
1088 if stat[3]:
1089 ui.status(_("nothing changed (%d missing files, see 'hg status')\n")
1089 ui.status(_("nothing changed (%d missing files, see 'hg status')\n")
1090 % len(stat[3]))
1090 % len(stat[3]))
1091 else:
1091 else:
1092 ui.status(_("nothing changed\n"))
1092 ui.status(_("nothing changed\n"))
1093 return 1
1093 return 1
1094
1094
1095 ctx = repo[node]
1095 ctx = repo[node]
1096 parents = ctx.parents()
1096 parents = ctx.parents()
1097
1097
1098 if bheads and not [x for x in parents
1098 if bheads and not [x for x in parents
1099 if x.node() in bheads and x.branch() == branch]:
1099 if x.node() in bheads and x.branch() == branch]:
1100 ui.status(_('created new head\n'))
1100 ui.status(_('created new head\n'))
1101 # The message is not printed for initial roots. For the other
1101 # The message is not printed for initial roots. For the other
1102 # changesets, it is printed in the following situations:
1102 # changesets, it is printed in the following situations:
1103 #
1103 #
1104 # Par column: for the 2 parents with ...
1104 # Par column: for the 2 parents with ...
1105 # N: null or no parent
1105 # N: null or no parent
1106 # B: parent is on another named branch
1106 # B: parent is on another named branch
1107 # C: parent is a regular non head changeset
1107 # C: parent is a regular non head changeset
1108 # H: parent was a branch head of the current branch
1108 # H: parent was a branch head of the current branch
1109 # Msg column: whether we print "created new head" message
1109 # Msg column: whether we print "created new head" message
1110 # In the following, it is assumed that there already exists some
1110 # In the following, it is assumed that there already exists some
1111 # initial branch heads of the current branch, otherwise nothing is
1111 # initial branch heads of the current branch, otherwise nothing is
1112 # printed anyway.
1112 # printed anyway.
1113 #
1113 #
1114 # Par Msg Comment
1114 # Par Msg Comment
1115 # NN y additional topo root
1115 # NN y additional topo root
1116 #
1116 #
1117 # BN y additional branch root
1117 # BN y additional branch root
1118 # CN y additional topo head
1118 # CN y additional topo head
1119 # HN n usual case
1119 # HN n usual case
1120 #
1120 #
1121 # BB y weird additional branch root
1121 # BB y weird additional branch root
1122 # CB y branch merge
1122 # CB y branch merge
1123 # HB n merge with named branch
1123 # HB n merge with named branch
1124 #
1124 #
1125 # CC y additional head from merge
1125 # CC y additional head from merge
1126 # CH n merge with a head
1126 # CH n merge with a head
1127 #
1127 #
1128 # HH n head merge: head count decreases
1128 # HH n head merge: head count decreases
1129
1129
1130 if not opts.get('close_branch'):
1130 if not opts.get('close_branch'):
1131 for r in parents:
1131 for r in parents:
1132 if r.extra().get('close') and r.branch() == branch:
1132 if r.extra().get('close') and r.branch() == branch:
1133 ui.status(_('reopening closed branch head %d\n') % r)
1133 ui.status(_('reopening closed branch head %d\n') % r)
1134
1134
1135 if ui.debugflag:
1135 if ui.debugflag:
1136 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1136 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1137 elif ui.verbose:
1137 elif ui.verbose:
1138 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1138 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1139
1139
1140 @command('copy|cp',
1140 @command('copy|cp',
1141 [('A', 'after', None, _('record a copy that has already occurred')),
1141 [('A', 'after', None, _('record a copy that has already occurred')),
1142 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1142 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1143 ] + walkopts + dryrunopts,
1143 ] + walkopts + dryrunopts,
1144 _('[OPTION]... [SOURCE]... DEST'))
1144 _('[OPTION]... [SOURCE]... DEST'))
1145 def copy(ui, repo, *pats, **opts):
1145 def copy(ui, repo, *pats, **opts):
1146 """mark files as copied for the next commit
1146 """mark files as copied for the next commit
1147
1147
1148 Mark dest as having copies of source files. If dest is a
1148 Mark dest as having copies of source files. If dest is a
1149 directory, copies are put in that directory. If dest is a file,
1149 directory, copies are put in that directory. If dest is a file,
1150 the source must be a single file.
1150 the source must be a single file.
1151
1151
1152 By default, this command copies the contents of files as they
1152 By default, this command copies the contents of files as they
1153 exist in the working directory. If invoked with -A/--after, the
1153 exist in the working directory. If invoked with -A/--after, the
1154 operation is recorded, but no copying is performed.
1154 operation is recorded, but no copying is performed.
1155
1155
1156 This command takes effect with the next commit. To undo a copy
1156 This command takes effect with the next commit. To undo a copy
1157 before that, see :hg:`revert`.
1157 before that, see :hg:`revert`.
1158
1158
1159 Returns 0 on success, 1 if errors are encountered.
1159 Returns 0 on success, 1 if errors are encountered.
1160 """
1160 """
1161 wlock = repo.wlock(False)
1161 wlock = repo.wlock(False)
1162 try:
1162 try:
1163 return cmdutil.copy(ui, repo, pats, opts)
1163 return cmdutil.copy(ui, repo, pats, opts)
1164 finally:
1164 finally:
1165 wlock.release()
1165 wlock.release()
1166
1166
1167 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1167 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1168 def debugancestor(ui, repo, *args):
1168 def debugancestor(ui, repo, *args):
1169 """find the ancestor revision of two revisions in a given index"""
1169 """find the ancestor revision of two revisions in a given index"""
1170 if len(args) == 3:
1170 if len(args) == 3:
1171 index, rev1, rev2 = args
1171 index, rev1, rev2 = args
1172 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1172 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1173 lookup = r.lookup
1173 lookup = r.lookup
1174 elif len(args) == 2:
1174 elif len(args) == 2:
1175 if not repo:
1175 if not repo:
1176 raise util.Abort(_("there is no Mercurial repository here "
1176 raise util.Abort(_("there is no Mercurial repository here "
1177 "(.hg not found)"))
1177 "(.hg not found)"))
1178 rev1, rev2 = args
1178 rev1, rev2 = args
1179 r = repo.changelog
1179 r = repo.changelog
1180 lookup = repo.lookup
1180 lookup = repo.lookup
1181 else:
1181 else:
1182 raise util.Abort(_('either two or three arguments required'))
1182 raise util.Abort(_('either two or three arguments required'))
1183 a = r.ancestor(lookup(rev1), lookup(rev2))
1183 a = r.ancestor(lookup(rev1), lookup(rev2))
1184 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1184 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1185
1185
1186 @command('debugbuilddag',
1186 @command('debugbuilddag',
1187 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1187 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1188 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1188 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1189 ('n', 'new-file', None, _('add new file at each rev'))],
1189 ('n', 'new-file', None, _('add new file at each rev'))],
1190 _('[OPTION]... [TEXT]'))
1190 _('[OPTION]... [TEXT]'))
1191 def debugbuilddag(ui, repo, text=None,
1191 def debugbuilddag(ui, repo, text=None,
1192 mergeable_file=False,
1192 mergeable_file=False,
1193 overwritten_file=False,
1193 overwritten_file=False,
1194 new_file=False):
1194 new_file=False):
1195 """builds a repo with a given DAG from scratch in the current empty repo
1195 """builds a repo with a given DAG from scratch in the current empty repo
1196
1196
1197 The description of the DAG is read from stdin if not given on the
1197 The description of the DAG is read from stdin if not given on the
1198 command line.
1198 command line.
1199
1199
1200 Elements:
1200 Elements:
1201
1201
1202 - "+n" is a linear run of n nodes based on the current default parent
1202 - "+n" is a linear run of n nodes based on the current default parent
1203 - "." is a single node based on the current default parent
1203 - "." is a single node based on the current default parent
1204 - "$" resets the default parent to null (implied at the start);
1204 - "$" resets the default parent to null (implied at the start);
1205 otherwise the default parent is always the last node created
1205 otherwise the default parent is always the last node created
1206 - "<p" sets the default parent to the backref p
1206 - "<p" sets the default parent to the backref p
1207 - "*p" is a fork at parent p, which is a backref
1207 - "*p" is a fork at parent p, which is a backref
1208 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1208 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1209 - "/p2" is a merge of the preceding node and p2
1209 - "/p2" is a merge of the preceding node and p2
1210 - ":tag" defines a local tag for the preceding node
1210 - ":tag" defines a local tag for the preceding node
1211 - "@branch" sets the named branch for subsequent nodes
1211 - "@branch" sets the named branch for subsequent nodes
1212 - "#...\\n" is a comment up to the end of the line
1212 - "#...\\n" is a comment up to the end of the line
1213
1213
1214 Whitespace between the above elements is ignored.
1214 Whitespace between the above elements is ignored.
1215
1215
1216 A backref is either
1216 A backref is either
1217
1217
1218 - a number n, which references the node curr-n, where curr is the current
1218 - a number n, which references the node curr-n, where curr is the current
1219 node, or
1219 node, or
1220 - the name of a local tag you placed earlier using ":tag", or
1220 - the name of a local tag you placed earlier using ":tag", or
1221 - empty to denote the default parent.
1221 - empty to denote the default parent.
1222
1222
1223 All string valued-elements are either strictly alphanumeric, or must
1223 All string valued-elements are either strictly alphanumeric, or must
1224 be enclosed in double quotes ("..."), with "\\" as escape character.
1224 be enclosed in double quotes ("..."), with "\\" as escape character.
1225 """
1225 """
1226
1226
1227 if text is None:
1227 if text is None:
1228 ui.status(_("reading DAG from stdin\n"))
1228 ui.status(_("reading DAG from stdin\n"))
1229 text = sys.stdin.read()
1229 text = sys.stdin.read()
1230
1230
1231 cl = repo.changelog
1231 cl = repo.changelog
1232 if len(cl) > 0:
1232 if len(cl) > 0:
1233 raise util.Abort(_('repository is not empty'))
1233 raise util.Abort(_('repository is not empty'))
1234
1234
1235 # determine number of revs in DAG
1235 # determine number of revs in DAG
1236 total = 0
1236 total = 0
1237 for type, data in dagparser.parsedag(text):
1237 for type, data in dagparser.parsedag(text):
1238 if type == 'n':
1238 if type == 'n':
1239 total += 1
1239 total += 1
1240
1240
1241 if mergeable_file:
1241 if mergeable_file:
1242 linesperrev = 2
1242 linesperrev = 2
1243 # make a file with k lines per rev
1243 # make a file with k lines per rev
1244 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1244 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1245 initialmergedlines.append("")
1245 initialmergedlines.append("")
1246
1246
1247 tags = []
1247 tags = []
1248
1248
1249 tr = repo.transaction("builddag")
1249 tr = repo.transaction("builddag")
1250 try:
1250 try:
1251
1251
1252 at = -1
1252 at = -1
1253 atbranch = 'default'
1253 atbranch = 'default'
1254 nodeids = []
1254 nodeids = []
1255 ui.progress(_('building'), 0, unit=_('revisions'), total=total)
1255 ui.progress(_('building'), 0, unit=_('revisions'), total=total)
1256 for type, data in dagparser.parsedag(text):
1256 for type, data in dagparser.parsedag(text):
1257 if type == 'n':
1257 if type == 'n':
1258 ui.note('node %s\n' % str(data))
1258 ui.note('node %s\n' % str(data))
1259 id, ps = data
1259 id, ps = data
1260
1260
1261 files = []
1261 files = []
1262 fctxs = {}
1262 fctxs = {}
1263
1263
1264 p2 = None
1264 p2 = None
1265 if mergeable_file:
1265 if mergeable_file:
1266 fn = "mf"
1266 fn = "mf"
1267 p1 = repo[ps[0]]
1267 p1 = repo[ps[0]]
1268 if len(ps) > 1:
1268 if len(ps) > 1:
1269 p2 = repo[ps[1]]
1269 p2 = repo[ps[1]]
1270 pa = p1.ancestor(p2)
1270 pa = p1.ancestor(p2)
1271 base, local, other = [x[fn].data() for x in pa, p1, p2]
1271 base, local, other = [x[fn].data() for x in pa, p1, p2]
1272 m3 = simplemerge.Merge3Text(base, local, other)
1272 m3 = simplemerge.Merge3Text(base, local, other)
1273 ml = [l.strip() for l in m3.merge_lines()]
1273 ml = [l.strip() for l in m3.merge_lines()]
1274 ml.append("")
1274 ml.append("")
1275 elif at > 0:
1275 elif at > 0:
1276 ml = p1[fn].data().split("\n")
1276 ml = p1[fn].data().split("\n")
1277 else:
1277 else:
1278 ml = initialmergedlines
1278 ml = initialmergedlines
1279 ml[id * linesperrev] += " r%i" % id
1279 ml[id * linesperrev] += " r%i" % id
1280 mergedtext = "\n".join(ml)
1280 mergedtext = "\n".join(ml)
1281 files.append(fn)
1281 files.append(fn)
1282 fctxs[fn] = context.memfilectx(fn, mergedtext)
1282 fctxs[fn] = context.memfilectx(fn, mergedtext)
1283
1283
1284 if overwritten_file:
1284 if overwritten_file:
1285 fn = "of"
1285 fn = "of"
1286 files.append(fn)
1286 files.append(fn)
1287 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1287 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1288
1288
1289 if new_file:
1289 if new_file:
1290 fn = "nf%i" % id
1290 fn = "nf%i" % id
1291 files.append(fn)
1291 files.append(fn)
1292 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1292 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1293 if len(ps) > 1:
1293 if len(ps) > 1:
1294 if not p2:
1294 if not p2:
1295 p2 = repo[ps[1]]
1295 p2 = repo[ps[1]]
1296 for fn in p2:
1296 for fn in p2:
1297 if fn.startswith("nf"):
1297 if fn.startswith("nf"):
1298 files.append(fn)
1298 files.append(fn)
1299 fctxs[fn] = p2[fn]
1299 fctxs[fn] = p2[fn]
1300
1300
1301 def fctxfn(repo, cx, path):
1301 def fctxfn(repo, cx, path):
1302 return fctxs.get(path)
1302 return fctxs.get(path)
1303
1303
1304 if len(ps) == 0 or ps[0] < 0:
1304 if len(ps) == 0 or ps[0] < 0:
1305 pars = [None, None]
1305 pars = [None, None]
1306 elif len(ps) == 1:
1306 elif len(ps) == 1:
1307 pars = [nodeids[ps[0]], None]
1307 pars = [nodeids[ps[0]], None]
1308 else:
1308 else:
1309 pars = [nodeids[p] for p in ps]
1309 pars = [nodeids[p] for p in ps]
1310 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1310 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1311 date=(id, 0),
1311 date=(id, 0),
1312 user="debugbuilddag",
1312 user="debugbuilddag",
1313 extra={'branch': atbranch})
1313 extra={'branch': atbranch})
1314 nodeid = repo.commitctx(cx)
1314 nodeid = repo.commitctx(cx)
1315 nodeids.append(nodeid)
1315 nodeids.append(nodeid)
1316 at = id
1316 at = id
1317 elif type == 'l':
1317 elif type == 'l':
1318 id, name = data
1318 id, name = data
1319 ui.note('tag %s\n' % name)
1319 ui.note('tag %s\n' % name)
1320 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1320 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1321 elif type == 'a':
1321 elif type == 'a':
1322 ui.note('branch %s\n' % data)
1322 ui.note('branch %s\n' % data)
1323 atbranch = data
1323 atbranch = data
1324 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1324 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1325 tr.close()
1325 tr.close()
1326 finally:
1326 finally:
1327 ui.progress(_('building'), None)
1327 ui.progress(_('building'), None)
1328 tr.release()
1328 tr.release()
1329
1329
1330 if tags:
1330 if tags:
1331 repo.opener.write("localtags", "".join(tags))
1331 repo.opener.write("localtags", "".join(tags))
1332
1332
1333 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1333 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1334 def debugbundle(ui, bundlepath, all=None, **opts):
1334 def debugbundle(ui, bundlepath, all=None, **opts):
1335 """lists the contents of a bundle"""
1335 """lists the contents of a bundle"""
1336 f = url.open(ui, bundlepath)
1336 f = url.open(ui, bundlepath)
1337 try:
1337 try:
1338 gen = changegroup.readbundle(f, bundlepath)
1338 gen = changegroup.readbundle(f, bundlepath)
1339 if all:
1339 if all:
1340 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1340 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1341
1341
1342 def showchunks(named):
1342 def showchunks(named):
1343 ui.write("\n%s\n" % named)
1343 ui.write("\n%s\n" % named)
1344 chain = None
1344 chain = None
1345 while 1:
1345 while 1:
1346 chunkdata = gen.deltachunk(chain)
1346 chunkdata = gen.deltachunk(chain)
1347 if not chunkdata:
1347 if not chunkdata:
1348 break
1348 break
1349 node = chunkdata['node']
1349 node = chunkdata['node']
1350 p1 = chunkdata['p1']
1350 p1 = chunkdata['p1']
1351 p2 = chunkdata['p2']
1351 p2 = chunkdata['p2']
1352 cs = chunkdata['cs']
1352 cs = chunkdata['cs']
1353 deltabase = chunkdata['deltabase']
1353 deltabase = chunkdata['deltabase']
1354 delta = chunkdata['delta']
1354 delta = chunkdata['delta']
1355 ui.write("%s %s %s %s %s %s\n" %
1355 ui.write("%s %s %s %s %s %s\n" %
1356 (hex(node), hex(p1), hex(p2),
1356 (hex(node), hex(p1), hex(p2),
1357 hex(cs), hex(deltabase), len(delta)))
1357 hex(cs), hex(deltabase), len(delta)))
1358 chain = node
1358 chain = node
1359
1359
1360 chunkdata = gen.changelogheader()
1360 chunkdata = gen.changelogheader()
1361 showchunks("changelog")
1361 showchunks("changelog")
1362 chunkdata = gen.manifestheader()
1362 chunkdata = gen.manifestheader()
1363 showchunks("manifest")
1363 showchunks("manifest")
1364 while 1:
1364 while 1:
1365 chunkdata = gen.filelogheader()
1365 chunkdata = gen.filelogheader()
1366 if not chunkdata:
1366 if not chunkdata:
1367 break
1367 break
1368 fname = chunkdata['filename']
1368 fname = chunkdata['filename']
1369 showchunks(fname)
1369 showchunks(fname)
1370 else:
1370 else:
1371 chunkdata = gen.changelogheader()
1371 chunkdata = gen.changelogheader()
1372 chain = None
1372 chain = None
1373 while 1:
1373 while 1:
1374 chunkdata = gen.deltachunk(chain)
1374 chunkdata = gen.deltachunk(chain)
1375 if not chunkdata:
1375 if not chunkdata:
1376 break
1376 break
1377 node = chunkdata['node']
1377 node = chunkdata['node']
1378 ui.write("%s\n" % hex(node))
1378 ui.write("%s\n" % hex(node))
1379 chain = node
1379 chain = node
1380 finally:
1380 finally:
1381 f.close()
1381 f.close()
1382
1382
1383 @command('debugcheckstate', [], '')
1383 @command('debugcheckstate', [], '')
1384 def debugcheckstate(ui, repo):
1384 def debugcheckstate(ui, repo):
1385 """validate the correctness of the current dirstate"""
1385 """validate the correctness of the current dirstate"""
1386 parent1, parent2 = repo.dirstate.parents()
1386 parent1, parent2 = repo.dirstate.parents()
1387 m1 = repo[parent1].manifest()
1387 m1 = repo[parent1].manifest()
1388 m2 = repo[parent2].manifest()
1388 m2 = repo[parent2].manifest()
1389 errors = 0
1389 errors = 0
1390 for f in repo.dirstate:
1390 for f in repo.dirstate:
1391 state = repo.dirstate[f]
1391 state = repo.dirstate[f]
1392 if state in "nr" and f not in m1:
1392 if state in "nr" and f not in m1:
1393 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1393 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1394 errors += 1
1394 errors += 1
1395 if state in "a" and f in m1:
1395 if state in "a" and f in m1:
1396 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1396 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1397 errors += 1
1397 errors += 1
1398 if state in "m" and f not in m1 and f not in m2:
1398 if state in "m" and f not in m1 and f not in m2:
1399 ui.warn(_("%s in state %s, but not in either manifest\n") %
1399 ui.warn(_("%s in state %s, but not in either manifest\n") %
1400 (f, state))
1400 (f, state))
1401 errors += 1
1401 errors += 1
1402 for f in m1:
1402 for f in m1:
1403 state = repo.dirstate[f]
1403 state = repo.dirstate[f]
1404 if state not in "nrm":
1404 if state not in "nrm":
1405 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1405 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1406 errors += 1
1406 errors += 1
1407 if errors:
1407 if errors:
1408 error = _(".hg/dirstate inconsistent with current parent's manifest")
1408 error = _(".hg/dirstate inconsistent with current parent's manifest")
1409 raise util.Abort(error)
1409 raise util.Abort(error)
1410
1410
1411 @command('debugcommands', [], _('[COMMAND]'))
1411 @command('debugcommands', [], _('[COMMAND]'))
1412 def debugcommands(ui, cmd='', *args):
1412 def debugcommands(ui, cmd='', *args):
1413 """list all available commands and options"""
1413 """list all available commands and options"""
1414 for cmd, vals in sorted(table.iteritems()):
1414 for cmd, vals in sorted(table.iteritems()):
1415 cmd = cmd.split('|')[0].strip('^')
1415 cmd = cmd.split('|')[0].strip('^')
1416 opts = ', '.join([i[1] for i in vals[1]])
1416 opts = ', '.join([i[1] for i in vals[1]])
1417 ui.write('%s: %s\n' % (cmd, opts))
1417 ui.write('%s: %s\n' % (cmd, opts))
1418
1418
1419 @command('debugcomplete',
1419 @command('debugcomplete',
1420 [('o', 'options', None, _('show the command options'))],
1420 [('o', 'options', None, _('show the command options'))],
1421 _('[-o] CMD'))
1421 _('[-o] CMD'))
1422 def debugcomplete(ui, cmd='', **opts):
1422 def debugcomplete(ui, cmd='', **opts):
1423 """returns the completion list associated with the given command"""
1423 """returns the completion list associated with the given command"""
1424
1424
1425 if opts.get('options'):
1425 if opts.get('options'):
1426 options = []
1426 options = []
1427 otables = [globalopts]
1427 otables = [globalopts]
1428 if cmd:
1428 if cmd:
1429 aliases, entry = cmdutil.findcmd(cmd, table, False)
1429 aliases, entry = cmdutil.findcmd(cmd, table, False)
1430 otables.append(entry[1])
1430 otables.append(entry[1])
1431 for t in otables:
1431 for t in otables:
1432 for o in t:
1432 for o in t:
1433 if "(DEPRECATED)" in o[3]:
1433 if "(DEPRECATED)" in o[3]:
1434 continue
1434 continue
1435 if o[0]:
1435 if o[0]:
1436 options.append('-%s' % o[0])
1436 options.append('-%s' % o[0])
1437 options.append('--%s' % o[1])
1437 options.append('--%s' % o[1])
1438 ui.write("%s\n" % "\n".join(options))
1438 ui.write("%s\n" % "\n".join(options))
1439 return
1439 return
1440
1440
1441 cmdlist = cmdutil.findpossible(cmd, table)
1441 cmdlist = cmdutil.findpossible(cmd, table)
1442 if ui.verbose:
1442 if ui.verbose:
1443 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1443 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1444 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1444 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1445
1445
1446 @command('debugdag',
1446 @command('debugdag',
1447 [('t', 'tags', None, _('use tags as labels')),
1447 [('t', 'tags', None, _('use tags as labels')),
1448 ('b', 'branches', None, _('annotate with branch names')),
1448 ('b', 'branches', None, _('annotate with branch names')),
1449 ('', 'dots', None, _('use dots for runs')),
1449 ('', 'dots', None, _('use dots for runs')),
1450 ('s', 'spaces', None, _('separate elements by spaces'))],
1450 ('s', 'spaces', None, _('separate elements by spaces'))],
1451 _('[OPTION]... [FILE [REV]...]'))
1451 _('[OPTION]... [FILE [REV]...]'))
1452 def debugdag(ui, repo, file_=None, *revs, **opts):
1452 def debugdag(ui, repo, file_=None, *revs, **opts):
1453 """format the changelog or an index DAG as a concise textual description
1453 """format the changelog or an index DAG as a concise textual description
1454
1454
1455 If you pass a revlog index, the revlog's DAG is emitted. If you list
1455 If you pass a revlog index, the revlog's DAG is emitted. If you list
1456 revision numbers, they get labelled in the output as rN.
1456 revision numbers, they get labelled in the output as rN.
1457
1457
1458 Otherwise, the changelog DAG of the current repo is emitted.
1458 Otherwise, the changelog DAG of the current repo is emitted.
1459 """
1459 """
1460 spaces = opts.get('spaces')
1460 spaces = opts.get('spaces')
1461 dots = opts.get('dots')
1461 dots = opts.get('dots')
1462 if file_:
1462 if file_:
1463 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1463 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1464 revs = set((int(r) for r in revs))
1464 revs = set((int(r) for r in revs))
1465 def events():
1465 def events():
1466 for r in rlog:
1466 for r in rlog:
1467 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1467 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1468 if r in revs:
1468 if r in revs:
1469 yield 'l', (r, "r%i" % r)
1469 yield 'l', (r, "r%i" % r)
1470 elif repo:
1470 elif repo:
1471 cl = repo.changelog
1471 cl = repo.changelog
1472 tags = opts.get('tags')
1472 tags = opts.get('tags')
1473 branches = opts.get('branches')
1473 branches = opts.get('branches')
1474 if tags:
1474 if tags:
1475 labels = {}
1475 labels = {}
1476 for l, n in repo.tags().items():
1476 for l, n in repo.tags().items():
1477 labels.setdefault(cl.rev(n), []).append(l)
1477 labels.setdefault(cl.rev(n), []).append(l)
1478 def events():
1478 def events():
1479 b = "default"
1479 b = "default"
1480 for r in cl:
1480 for r in cl:
1481 if branches:
1481 if branches:
1482 newb = cl.read(cl.node(r))[5]['branch']
1482 newb = cl.read(cl.node(r))[5]['branch']
1483 if newb != b:
1483 if newb != b:
1484 yield 'a', newb
1484 yield 'a', newb
1485 b = newb
1485 b = newb
1486 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1486 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1487 if tags:
1487 if tags:
1488 ls = labels.get(r)
1488 ls = labels.get(r)
1489 if ls:
1489 if ls:
1490 for l in ls:
1490 for l in ls:
1491 yield 'l', (r, l)
1491 yield 'l', (r, l)
1492 else:
1492 else:
1493 raise util.Abort(_('need repo for changelog dag'))
1493 raise util.Abort(_('need repo for changelog dag'))
1494
1494
1495 for line in dagparser.dagtextlines(events(),
1495 for line in dagparser.dagtextlines(events(),
1496 addspaces=spaces,
1496 addspaces=spaces,
1497 wraplabels=True,
1497 wraplabels=True,
1498 wrapannotations=True,
1498 wrapannotations=True,
1499 wrapnonlinear=dots,
1499 wrapnonlinear=dots,
1500 usedots=dots,
1500 usedots=dots,
1501 maxlinewidth=70):
1501 maxlinewidth=70):
1502 ui.write(line)
1502 ui.write(line)
1503 ui.write("\n")
1503 ui.write("\n")
1504
1504
1505 @command('debugdata', [], _('FILE REV'))
1505 @command('debugdata', [], _('FILE REV'))
1506 def debugdata(ui, repo, file_, rev):
1506 def debugdata(ui, repo, file_, rev):
1507 """dump the contents of a data file revision"""
1507 """dump the contents of a data file revision"""
1508 r = None
1508 r = None
1509 if repo:
1509 if repo:
1510 filelog = repo.file(file_)
1510 filelog = repo.file(file_)
1511 if len(filelog):
1511 if len(filelog):
1512 r = filelog
1512 r = filelog
1513 if not r:
1513 if not r:
1514 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False),
1514 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False),
1515 file_[:-2] + ".i")
1515 file_[:-2] + ".i")
1516 try:
1516 try:
1517 ui.write(r.revision(r.lookup(rev)))
1517 ui.write(r.revision(r.lookup(rev)))
1518 except KeyError:
1518 except KeyError:
1519 raise util.Abort(_('invalid revision identifier %s') % rev)
1519 raise util.Abort(_('invalid revision identifier %s') % rev)
1520
1520
1521 @command('debugdate',
1521 @command('debugdate',
1522 [('e', 'extended', None, _('try extended date formats'))],
1522 [('e', 'extended', None, _('try extended date formats'))],
1523 _('[-e] DATE [RANGE]'))
1523 _('[-e] DATE [RANGE]'))
1524 def debugdate(ui, date, range=None, **opts):
1524 def debugdate(ui, date, range=None, **opts):
1525 """parse and display a date"""
1525 """parse and display a date"""
1526 if opts["extended"]:
1526 if opts["extended"]:
1527 d = util.parsedate(date, util.extendeddateformats)
1527 d = util.parsedate(date, util.extendeddateformats)
1528 else:
1528 else:
1529 d = util.parsedate(date)
1529 d = util.parsedate(date)
1530 ui.write("internal: %s %s\n" % d)
1530 ui.write("internal: %s %s\n" % d)
1531 ui.write("standard: %s\n" % util.datestr(d))
1531 ui.write("standard: %s\n" % util.datestr(d))
1532 if range:
1532 if range:
1533 m = util.matchdate(range)
1533 m = util.matchdate(range)
1534 ui.write("match: %s\n" % m(d[0]))
1534 ui.write("match: %s\n" % m(d[0]))
1535
1535
1536 @command('debugdiscovery',
1536 @command('debugdiscovery',
1537 [('', 'old', None, _('use old-style discovery')),
1537 [('', 'old', None, _('use old-style discovery')),
1538 ('', 'nonheads', None,
1538 ('', 'nonheads', None,
1539 _('use old-style discovery with non-heads included')),
1539 _('use old-style discovery with non-heads included')),
1540 ] + remoteopts,
1540 ] + remoteopts,
1541 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1541 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1542 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1542 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1543 """runs the changeset discovery protocol in isolation"""
1543 """runs the changeset discovery protocol in isolation"""
1544 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1544 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1545 remote = hg.repository(hg.remoteui(repo, opts), remoteurl)
1545 remote = hg.repository(hg.remoteui(repo, opts), remoteurl)
1546 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1546 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1547
1547
1548 # make sure tests are repeatable
1548 # make sure tests are repeatable
1549 random.seed(12323)
1549 random.seed(12323)
1550
1550
1551 def doit(localheads, remoteheads):
1551 def doit(localheads, remoteheads):
1552 if opts.get('old'):
1552 if opts.get('old'):
1553 if localheads:
1553 if localheads:
1554 raise util.Abort('cannot use localheads with old style discovery')
1554 raise util.Abort('cannot use localheads with old style discovery')
1555 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1555 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1556 force=True)
1556 force=True)
1557 common = set(common)
1557 common = set(common)
1558 if not opts.get('nonheads'):
1558 if not opts.get('nonheads'):
1559 ui.write("unpruned common: %s\n" % " ".join([short(n)
1559 ui.write("unpruned common: %s\n" % " ".join([short(n)
1560 for n in common]))
1560 for n in common]))
1561 dag = dagutil.revlogdag(repo.changelog)
1561 dag = dagutil.revlogdag(repo.changelog)
1562 all = dag.ancestorset(dag.internalizeall(common))
1562 all = dag.ancestorset(dag.internalizeall(common))
1563 common = dag.externalizeall(dag.headsetofconnecteds(all))
1563 common = dag.externalizeall(dag.headsetofconnecteds(all))
1564 else:
1564 else:
1565 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1565 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1566 common = set(common)
1566 common = set(common)
1567 rheads = set(hds)
1567 rheads = set(hds)
1568 lheads = set(repo.heads())
1568 lheads = set(repo.heads())
1569 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1569 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1570 if lheads <= common:
1570 if lheads <= common:
1571 ui.write("local is subset\n")
1571 ui.write("local is subset\n")
1572 elif rheads <= common:
1572 elif rheads <= common:
1573 ui.write("remote is subset\n")
1573 ui.write("remote is subset\n")
1574
1574
1575 serverlogs = opts.get('serverlog')
1575 serverlogs = opts.get('serverlog')
1576 if serverlogs:
1576 if serverlogs:
1577 for filename in serverlogs:
1577 for filename in serverlogs:
1578 logfile = open(filename, 'r')
1578 logfile = open(filename, 'r')
1579 try:
1579 try:
1580 line = logfile.readline()
1580 line = logfile.readline()
1581 while line:
1581 while line:
1582 parts = line.strip().split(';')
1582 parts = line.strip().split(';')
1583 op = parts[1]
1583 op = parts[1]
1584 if op == 'cg':
1584 if op == 'cg':
1585 pass
1585 pass
1586 elif op == 'cgss':
1586 elif op == 'cgss':
1587 doit(parts[2].split(' '), parts[3].split(' '))
1587 doit(parts[2].split(' '), parts[3].split(' '))
1588 elif op == 'unb':
1588 elif op == 'unb':
1589 doit(parts[3].split(' '), parts[2].split(' '))
1589 doit(parts[3].split(' '), parts[2].split(' '))
1590 line = logfile.readline()
1590 line = logfile.readline()
1591 finally:
1591 finally:
1592 logfile.close()
1592 logfile.close()
1593
1593
1594 else:
1594 else:
1595 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1595 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1596 opts.get('remote_head'))
1596 opts.get('remote_head'))
1597 localrevs = opts.get('local_head')
1597 localrevs = opts.get('local_head')
1598 doit(localrevs, remoterevs)
1598 doit(localrevs, remoterevs)
1599
1599
1600 @command('debugfsinfo', [], _('[PATH]'))
1600 @command('debugfsinfo', [], _('[PATH]'))
1601 def debugfsinfo(ui, path = "."):
1601 def debugfsinfo(ui, path = "."):
1602 """show information detected about current filesystem"""
1602 """show information detected about current filesystem"""
1603 util.writefile('.debugfsinfo', '')
1603 util.writefile('.debugfsinfo', '')
1604 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1604 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1605 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1605 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1606 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1606 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1607 and 'yes' or 'no'))
1607 and 'yes' or 'no'))
1608 os.unlink('.debugfsinfo')
1608 os.unlink('.debugfsinfo')
1609
1609
1610 @command('debuggetbundle',
1610 @command('debuggetbundle',
1611 [('H', 'head', [], _('id of head node'), _('ID')),
1611 [('H', 'head', [], _('id of head node'), _('ID')),
1612 ('C', 'common', [], _('id of common node'), _('ID')),
1612 ('C', 'common', [], _('id of common node'), _('ID')),
1613 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1613 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1614 _('REPO FILE [-H|-C ID]...'))
1614 _('REPO FILE [-H|-C ID]...'))
1615 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1615 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1616 """retrieves a bundle from a repo
1616 """retrieves a bundle from a repo
1617
1617
1618 Every ID must be a full-length hex node id string. Saves the bundle to the
1618 Every ID must be a full-length hex node id string. Saves the bundle to the
1619 given file.
1619 given file.
1620 """
1620 """
1621 repo = hg.repository(ui, repopath)
1621 repo = hg.repository(ui, repopath)
1622 if not repo.capable('getbundle'):
1622 if not repo.capable('getbundle'):
1623 raise util.Abort("getbundle() not supported by target repository")
1623 raise util.Abort("getbundle() not supported by target repository")
1624 args = {}
1624 args = {}
1625 if common:
1625 if common:
1626 args['common'] = [bin(s) for s in common]
1626 args['common'] = [bin(s) for s in common]
1627 if head:
1627 if head:
1628 args['heads'] = [bin(s) for s in head]
1628 args['heads'] = [bin(s) for s in head]
1629 bundle = repo.getbundle('debug', **args)
1629 bundle = repo.getbundle('debug', **args)
1630
1630
1631 bundletype = opts.get('type', 'bzip2').lower()
1631 bundletype = opts.get('type', 'bzip2').lower()
1632 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1632 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1633 bundletype = btypes.get(bundletype)
1633 bundletype = btypes.get(bundletype)
1634 if bundletype not in changegroup.bundletypes:
1634 if bundletype not in changegroup.bundletypes:
1635 raise util.Abort(_('unknown bundle type specified with --type'))
1635 raise util.Abort(_('unknown bundle type specified with --type'))
1636 changegroup.writebundle(bundle, bundlepath, bundletype)
1636 changegroup.writebundle(bundle, bundlepath, bundletype)
1637
1637
1638 @command('debugignore', [], '')
1638 @command('debugignore', [], '')
1639 def debugignore(ui, repo, *values, **opts):
1639 def debugignore(ui, repo, *values, **opts):
1640 """display the combined ignore pattern"""
1640 """display the combined ignore pattern"""
1641 ignore = repo.dirstate._ignore
1641 ignore = repo.dirstate._ignore
1642 if hasattr(ignore, 'includepat'):
1642 if hasattr(ignore, 'includepat'):
1643 ui.write("%s\n" % ignore.includepat)
1643 ui.write("%s\n" % ignore.includepat)
1644 else:
1644 else:
1645 raise util.Abort(_("no ignore patterns found"))
1645 raise util.Abort(_("no ignore patterns found"))
1646
1646
1647 @command('debugindex',
1647 @command('debugindex',
1648 [('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1648 [('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1649 _('FILE'))
1649 _('FILE'))
1650 def debugindex(ui, repo, file_, **opts):
1650 def debugindex(ui, repo, file_, **opts):
1651 """dump the contents of an index file"""
1651 """dump the contents of an index file"""
1652 r = None
1652 r = None
1653 if repo:
1653 if repo:
1654 filelog = repo.file(file_)
1654 filelog = repo.file(file_)
1655 if len(filelog):
1655 if len(filelog):
1656 r = filelog
1656 r = filelog
1657
1657
1658 format = opts.get('format', 0)
1658 format = opts.get('format', 0)
1659 if format not in (0, 1):
1659 if format not in (0, 1):
1660 raise util.Abort(_("unknown format %d") % format)
1660 raise util.Abort(_("unknown format %d") % format)
1661
1661
1662 if not r:
1662 if not r:
1663 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1663 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1664
1664
1665 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1665 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1666 if generaldelta:
1666 if generaldelta:
1667 basehdr = ' delta'
1667 basehdr = ' delta'
1668 else:
1668 else:
1669 basehdr = ' base'
1669 basehdr = ' base'
1670
1670
1671 if format == 0:
1671 if format == 0:
1672 ui.write(" rev offset length " + basehdr + " linkrev"
1672 ui.write(" rev offset length " + basehdr + " linkrev"
1673 " nodeid p1 p2\n")
1673 " nodeid p1 p2\n")
1674 elif format == 1:
1674 elif format == 1:
1675 ui.write(" rev flag offset length"
1675 ui.write(" rev flag offset length"
1676 " size " + basehdr + " link p1 p2 nodeid\n")
1676 " size " + basehdr + " link p1 p2 nodeid\n")
1677
1677
1678 for i in r:
1678 for i in r:
1679 node = r.node(i)
1679 node = r.node(i)
1680 if generaldelta:
1680 if generaldelta:
1681 base = r.deltaparent(i)
1681 base = r.deltaparent(i)
1682 else:
1682 else:
1683 base = r.chainbase(i)
1683 base = r.chainbase(i)
1684 if format == 0:
1684 if format == 0:
1685 try:
1685 try:
1686 pp = r.parents(node)
1686 pp = r.parents(node)
1687 except:
1687 except:
1688 pp = [nullid, nullid]
1688 pp = [nullid, nullid]
1689 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1689 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1690 i, r.start(i), r.length(i), base, r.linkrev(i),
1690 i, r.start(i), r.length(i), base, r.linkrev(i),
1691 short(node), short(pp[0]), short(pp[1])))
1691 short(node), short(pp[0]), short(pp[1])))
1692 elif format == 1:
1692 elif format == 1:
1693 pr = r.parentrevs(i)
1693 pr = r.parentrevs(i)
1694 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1694 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1695 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1695 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1696 base, r.linkrev(i), pr[0], pr[1], short(node)))
1696 base, r.linkrev(i), pr[0], pr[1], short(node)))
1697
1697
1698 @command('debugindexdot', [], _('FILE'))
1698 @command('debugindexdot', [], _('FILE'))
1699 def debugindexdot(ui, repo, file_):
1699 def debugindexdot(ui, repo, file_):
1700 """dump an index DAG as a graphviz dot file"""
1700 """dump an index DAG as a graphviz dot file"""
1701 r = None
1701 r = None
1702 if repo:
1702 if repo:
1703 filelog = repo.file(file_)
1703 filelog = repo.file(file_)
1704 if len(filelog):
1704 if len(filelog):
1705 r = filelog
1705 r = filelog
1706 if not r:
1706 if not r:
1707 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1707 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1708 ui.write("digraph G {\n")
1708 ui.write("digraph G {\n")
1709 for i in r:
1709 for i in r:
1710 node = r.node(i)
1710 node = r.node(i)
1711 pp = r.parents(node)
1711 pp = r.parents(node)
1712 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1712 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1713 if pp[1] != nullid:
1713 if pp[1] != nullid:
1714 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1714 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1715 ui.write("}\n")
1715 ui.write("}\n")
1716
1716
1717 @command('debuginstall', [], '')
1717 @command('debuginstall', [], '')
1718 def debuginstall(ui):
1718 def debuginstall(ui):
1719 '''test Mercurial installation
1719 '''test Mercurial installation
1720
1720
1721 Returns 0 on success.
1721 Returns 0 on success.
1722 '''
1722 '''
1723
1723
1724 def writetemp(contents):
1724 def writetemp(contents):
1725 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1725 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1726 f = os.fdopen(fd, "wb")
1726 f = os.fdopen(fd, "wb")
1727 f.write(contents)
1727 f.write(contents)
1728 f.close()
1728 f.close()
1729 return name
1729 return name
1730
1730
1731 problems = 0
1731 problems = 0
1732
1732
1733 # encoding
1733 # encoding
1734 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1734 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1735 try:
1735 try:
1736 encoding.fromlocal("test")
1736 encoding.fromlocal("test")
1737 except util.Abort, inst:
1737 except util.Abort, inst:
1738 ui.write(" %s\n" % inst)
1738 ui.write(" %s\n" % inst)
1739 ui.write(_(" (check that your locale is properly set)\n"))
1739 ui.write(_(" (check that your locale is properly set)\n"))
1740 problems += 1
1740 problems += 1
1741
1741
1742 # compiled modules
1742 # compiled modules
1743 ui.status(_("Checking installed modules (%s)...\n")
1743 ui.status(_("Checking installed modules (%s)...\n")
1744 % os.path.dirname(__file__))
1744 % os.path.dirname(__file__))
1745 try:
1745 try:
1746 import bdiff, mpatch, base85, osutil
1746 import bdiff, mpatch, base85, osutil
1747 except Exception, inst:
1747 except Exception, inst:
1748 ui.write(" %s\n" % inst)
1748 ui.write(" %s\n" % inst)
1749 ui.write(_(" One or more extensions could not be found"))
1749 ui.write(_(" One or more extensions could not be found"))
1750 ui.write(_(" (check that you compiled the extensions)\n"))
1750 ui.write(_(" (check that you compiled the extensions)\n"))
1751 problems += 1
1751 problems += 1
1752
1752
1753 # templates
1753 # templates
1754 ui.status(_("Checking templates...\n"))
1754 ui.status(_("Checking templates...\n"))
1755 try:
1755 try:
1756 import templater
1756 import templater
1757 templater.templater(templater.templatepath("map-cmdline.default"))
1757 templater.templater(templater.templatepath("map-cmdline.default"))
1758 except Exception, inst:
1758 except Exception, inst:
1759 ui.write(" %s\n" % inst)
1759 ui.write(" %s\n" % inst)
1760 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1760 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1761 problems += 1
1761 problems += 1
1762
1762
1763 # editor
1763 # editor
1764 ui.status(_("Checking commit editor...\n"))
1764 ui.status(_("Checking commit editor...\n"))
1765 editor = ui.geteditor()
1765 editor = ui.geteditor()
1766 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1766 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1767 if not cmdpath:
1767 if not cmdpath:
1768 if editor == 'vi':
1768 if editor == 'vi':
1769 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1769 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1770 ui.write(_(" (specify a commit editor in your configuration"
1770 ui.write(_(" (specify a commit editor in your configuration"
1771 " file)\n"))
1771 " file)\n"))
1772 else:
1772 else:
1773 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1773 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1774 ui.write(_(" (specify a commit editor in your configuration"
1774 ui.write(_(" (specify a commit editor in your configuration"
1775 " file)\n"))
1775 " file)\n"))
1776 problems += 1
1776 problems += 1
1777
1777
1778 # check username
1778 # check username
1779 ui.status(_("Checking username...\n"))
1779 ui.status(_("Checking username...\n"))
1780 try:
1780 try:
1781 ui.username()
1781 ui.username()
1782 except util.Abort, e:
1782 except util.Abort, e:
1783 ui.write(" %s\n" % e)
1783 ui.write(" %s\n" % e)
1784 ui.write(_(" (specify a username in your configuration file)\n"))
1784 ui.write(_(" (specify a username in your configuration file)\n"))
1785 problems += 1
1785 problems += 1
1786
1786
1787 if not problems:
1787 if not problems:
1788 ui.status(_("No problems detected\n"))
1788 ui.status(_("No problems detected\n"))
1789 else:
1789 else:
1790 ui.write(_("%s problems detected,"
1790 ui.write(_("%s problems detected,"
1791 " please check your install!\n") % problems)
1791 " please check your install!\n") % problems)
1792
1792
1793 return problems
1793 return problems
1794
1794
1795 @command('debugknown', [], _('REPO ID...'))
1795 @command('debugknown', [], _('REPO ID...'))
1796 def debugknown(ui, repopath, *ids, **opts):
1796 def debugknown(ui, repopath, *ids, **opts):
1797 """test whether node ids are known to a repo
1797 """test whether node ids are known to a repo
1798
1798
1799 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1799 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1800 indicating unknown/known.
1800 indicating unknown/known.
1801 """
1801 """
1802 repo = hg.repository(ui, repopath)
1802 repo = hg.repository(ui, repopath)
1803 if not repo.capable('known'):
1803 if not repo.capable('known'):
1804 raise util.Abort("known() not supported by target repository")
1804 raise util.Abort("known() not supported by target repository")
1805 flags = repo.known([bin(s) for s in ids])
1805 flags = repo.known([bin(s) for s in ids])
1806 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1806 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1807
1807
1808 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1808 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1809 def debugpushkey(ui, repopath, namespace, *keyinfo):
1809 def debugpushkey(ui, repopath, namespace, *keyinfo):
1810 '''access the pushkey key/value protocol
1810 '''access the pushkey key/value protocol
1811
1811
1812 With two args, list the keys in the given namespace.
1812 With two args, list the keys in the given namespace.
1813
1813
1814 With five args, set a key to new if it currently is set to old.
1814 With five args, set a key to new if it currently is set to old.
1815 Reports success or failure.
1815 Reports success or failure.
1816 '''
1816 '''
1817
1817
1818 target = hg.repository(ui, repopath)
1818 target = hg.repository(ui, repopath)
1819 if keyinfo:
1819 if keyinfo:
1820 key, old, new = keyinfo
1820 key, old, new = keyinfo
1821 r = target.pushkey(namespace, key, old, new)
1821 r = target.pushkey(namespace, key, old, new)
1822 ui.status(str(r) + '\n')
1822 ui.status(str(r) + '\n')
1823 return not r
1823 return not r
1824 else:
1824 else:
1825 for k, v in target.listkeys(namespace).iteritems():
1825 for k, v in target.listkeys(namespace).iteritems():
1826 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1826 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1827 v.encode('string-escape')))
1827 v.encode('string-escape')))
1828
1828
1829 @command('debugrebuildstate',
1829 @command('debugrebuildstate',
1830 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1830 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1831 _('[-r REV] [REV]'))
1831 _('[-r REV] [REV]'))
1832 def debugrebuildstate(ui, repo, rev="tip"):
1832 def debugrebuildstate(ui, repo, rev="tip"):
1833 """rebuild the dirstate as it would look like for the given revision"""
1833 """rebuild the dirstate as it would look like for the given revision"""
1834 ctx = cmdutil.revsingle(repo, rev)
1834 ctx = cmdutil.revsingle(repo, rev)
1835 wlock = repo.wlock()
1835 wlock = repo.wlock()
1836 try:
1836 try:
1837 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1837 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1838 finally:
1838 finally:
1839 wlock.release()
1839 wlock.release()
1840
1840
1841 @command('debugrename',
1841 @command('debugrename',
1842 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1842 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1843 _('[-r REV] FILE'))
1843 _('[-r REV] FILE'))
1844 def debugrename(ui, repo, file1, *pats, **opts):
1844 def debugrename(ui, repo, file1, *pats, **opts):
1845 """dump rename information"""
1845 """dump rename information"""
1846
1846
1847 ctx = cmdutil.revsingle(repo, opts.get('rev'))
1847 ctx = cmdutil.revsingle(repo, opts.get('rev'))
1848 m = cmdutil.match(repo, (file1,) + pats, opts)
1848 m = cmdutil.match(repo, (file1,) + pats, opts)
1849 for abs in ctx.walk(m):
1849 for abs in ctx.walk(m):
1850 fctx = ctx[abs]
1850 fctx = ctx[abs]
1851 o = fctx.filelog().renamed(fctx.filenode())
1851 o = fctx.filelog().renamed(fctx.filenode())
1852 rel = m.rel(abs)
1852 rel = m.rel(abs)
1853 if o:
1853 if o:
1854 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1854 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1855 else:
1855 else:
1856 ui.write(_("%s not renamed\n") % rel)
1856 ui.write(_("%s not renamed\n") % rel)
1857
1857
1858 @command('debugrevlog', [], _('FILE'))
1858 @command('debugrevlog', [], _('FILE'))
1859 def debugrevlog(ui, repo, file_):
1859 def debugrevlog(ui, repo, file_):
1860 """show data and statistics about a revlog"""
1860 """show data and statistics about a revlog"""
1861 r = None
1861 r = None
1862 if repo:
1862 if repo:
1863 filelog = repo.file(file_)
1863 filelog = repo.file(file_)
1864 if len(filelog):
1864 if len(filelog):
1865 r = filelog
1865 r = filelog
1866 if not r:
1866 if not r:
1867 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1867 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1868
1868
1869 v = r.version
1869 v = r.version
1870 format = v & 0xFFFF
1870 format = v & 0xFFFF
1871 flags = []
1871 flags = []
1872 gdelta = False
1872 gdelta = False
1873 if v & revlog.REVLOGNGINLINEDATA:
1873 if v & revlog.REVLOGNGINLINEDATA:
1874 flags.append('inline')
1874 flags.append('inline')
1875 if v & revlog.REVLOGGENERALDELTA:
1875 if v & revlog.REVLOGGENERALDELTA:
1876 gdelta = True
1876 gdelta = True
1877 flags.append('generaldelta')
1877 flags.append('generaldelta')
1878 if not flags:
1878 if not flags:
1879 flags = ['(none)']
1879 flags = ['(none)']
1880
1880
1881 nummerges = 0
1881 nummerges = 0
1882 numfull = 0
1882 numfull = 0
1883 numprev = 0
1883 numprev = 0
1884 nump1 = 0
1884 nump1 = 0
1885 nump2 = 0
1885 nump2 = 0
1886 numother = 0
1886 numother = 0
1887 nump1prev = 0
1887 nump1prev = 0
1888 nump2prev = 0
1888 nump2prev = 0
1889 chainlengths = []
1889 chainlengths = []
1890
1890
1891 datasize = [None, 0, 0L]
1891 datasize = [None, 0, 0L]
1892 fullsize = [None, 0, 0L]
1892 fullsize = [None, 0, 0L]
1893 deltasize = [None, 0, 0L]
1893 deltasize = [None, 0, 0L]
1894
1894
1895 def addsize(size, l):
1895 def addsize(size, l):
1896 if l[0] is None or size < l[0]:
1896 if l[0] is None or size < l[0]:
1897 l[0] = size
1897 l[0] = size
1898 if size > l[1]:
1898 if size > l[1]:
1899 l[1] = size
1899 l[1] = size
1900 l[2] += size
1900 l[2] += size
1901
1901
1902 numrevs = len(r)
1902 numrevs = len(r)
1903 for rev in xrange(numrevs):
1903 for rev in xrange(numrevs):
1904 p1, p2 = r.parentrevs(rev)
1904 p1, p2 = r.parentrevs(rev)
1905 delta = r.deltaparent(rev)
1905 delta = r.deltaparent(rev)
1906 if format > 0:
1906 if format > 0:
1907 addsize(r.rawsize(rev), datasize)
1907 addsize(r.rawsize(rev), datasize)
1908 if p2 != nullrev:
1908 if p2 != nullrev:
1909 nummerges += 1
1909 nummerges += 1
1910 size = r.length(rev)
1910 size = r.length(rev)
1911 if delta == nullrev:
1911 if delta == nullrev:
1912 chainlengths.append(0)
1912 chainlengths.append(0)
1913 numfull += 1
1913 numfull += 1
1914 addsize(size, fullsize)
1914 addsize(size, fullsize)
1915 else:
1915 else:
1916 chainlengths.append(chainlengths[delta] + 1)
1916 chainlengths.append(chainlengths[delta] + 1)
1917 addsize(size, deltasize)
1917 addsize(size, deltasize)
1918 if delta == rev - 1:
1918 if delta == rev - 1:
1919 numprev += 1
1919 numprev += 1
1920 if delta == p1:
1920 if delta == p1:
1921 nump1prev += 1
1921 nump1prev += 1
1922 elif delta == p2:
1922 elif delta == p2:
1923 nump2prev += 1
1923 nump2prev += 1
1924 elif delta == p1:
1924 elif delta == p1:
1925 nump1 += 1
1925 nump1 += 1
1926 elif delta == p2:
1926 elif delta == p2:
1927 nump2 += 1
1927 nump2 += 1
1928 elif delta != nullrev:
1928 elif delta != nullrev:
1929 numother += 1
1929 numother += 1
1930
1930
1931 numdeltas = numrevs - numfull
1931 numdeltas = numrevs - numfull
1932 numoprev = numprev - nump1prev - nump2prev
1932 numoprev = numprev - nump1prev - nump2prev
1933 totalrawsize = datasize[2]
1933 totalrawsize = datasize[2]
1934 datasize[2] /= numrevs
1934 datasize[2] /= numrevs
1935 fulltotal = fullsize[2]
1935 fulltotal = fullsize[2]
1936 fullsize[2] /= numfull
1936 fullsize[2] /= numfull
1937 deltatotal = deltasize[2]
1937 deltatotal = deltasize[2]
1938 deltasize[2] /= numrevs - numfull
1938 deltasize[2] /= numrevs - numfull
1939 totalsize = fulltotal + deltatotal
1939 totalsize = fulltotal + deltatotal
1940 avgchainlen = sum(chainlengths) / numrevs
1940 avgchainlen = sum(chainlengths) / numrevs
1941 compratio = totalrawsize / totalsize
1941 compratio = totalrawsize / totalsize
1942
1942
1943 basedfmtstr = '%%%dd\n'
1943 basedfmtstr = '%%%dd\n'
1944 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
1944 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
1945
1945
1946 def dfmtstr(max):
1946 def dfmtstr(max):
1947 return basedfmtstr % len(str(max))
1947 return basedfmtstr % len(str(max))
1948 def pcfmtstr(max, padding=0):
1948 def pcfmtstr(max, padding=0):
1949 return basepcfmtstr % (len(str(max)), ' ' * padding)
1949 return basepcfmtstr % (len(str(max)), ' ' * padding)
1950
1950
1951 def pcfmt(value, total):
1951 def pcfmt(value, total):
1952 return (value, 100 * float(value) / total)
1952 return (value, 100 * float(value) / total)
1953
1953
1954 ui.write('format : %d\n' % format)
1954 ui.write('format : %d\n' % format)
1955 ui.write('flags : %s\n' % ', '.join(flags))
1955 ui.write('flags : %s\n' % ', '.join(flags))
1956
1956
1957 ui.write('\n')
1957 ui.write('\n')
1958 fmt = pcfmtstr(totalsize)
1958 fmt = pcfmtstr(totalsize)
1959 fmt2 = dfmtstr(totalsize)
1959 fmt2 = dfmtstr(totalsize)
1960 ui.write('revisions : ' + fmt2 % numrevs)
1960 ui.write('revisions : ' + fmt2 % numrevs)
1961 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
1961 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
1962 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
1962 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
1963 ui.write('revisions : ' + fmt2 % numrevs)
1963 ui.write('revisions : ' + fmt2 % numrevs)
1964 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
1964 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
1965 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
1965 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
1966 ui.write('revision size : ' + fmt2 % totalsize)
1966 ui.write('revision size : ' + fmt2 % totalsize)
1967 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
1967 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
1968 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
1968 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
1969
1969
1970 ui.write('\n')
1970 ui.write('\n')
1971 fmt = dfmtstr(max(avgchainlen, compratio))
1971 fmt = dfmtstr(max(avgchainlen, compratio))
1972 ui.write('avg chain length : ' + fmt % avgchainlen)
1972 ui.write('avg chain length : ' + fmt % avgchainlen)
1973 ui.write('compression ratio : ' + fmt % compratio)
1973 ui.write('compression ratio : ' + fmt % compratio)
1974
1974
1975 if format > 0:
1975 if format > 0:
1976 ui.write('\n')
1976 ui.write('\n')
1977 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
1977 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
1978 % tuple(datasize))
1978 % tuple(datasize))
1979 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
1979 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
1980 % tuple(fullsize))
1980 % tuple(fullsize))
1981 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
1981 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
1982 % tuple(deltasize))
1982 % tuple(deltasize))
1983
1983
1984 if numdeltas > 0:
1984 if numdeltas > 0:
1985 ui.write('\n')
1985 ui.write('\n')
1986 fmt = pcfmtstr(numdeltas)
1986 fmt = pcfmtstr(numdeltas)
1987 fmt2 = pcfmtstr(numdeltas, 4)
1987 fmt2 = pcfmtstr(numdeltas, 4)
1988 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
1988 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
1989 if numprev > 0:
1989 if numprev > 0:
1990 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
1990 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
1991 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
1991 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
1992 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
1992 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
1993 if gdelta:
1993 if gdelta:
1994 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
1994 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
1995 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
1995 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
1996 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
1996 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
1997
1997
1998 @command('debugrevspec', [], ('REVSPEC'))
1998 @command('debugrevspec', [], ('REVSPEC'))
1999 def debugrevspec(ui, repo, expr):
1999 def debugrevspec(ui, repo, expr):
2000 '''parse and apply a revision specification'''
2000 '''parse and apply a revision specification'''
2001 if ui.verbose:
2001 if ui.verbose:
2002 tree = revset.parse(expr)[0]
2002 tree = revset.parse(expr)[0]
2003 ui.note(tree, "\n")
2003 ui.note(tree, "\n")
2004 newtree = revset.findaliases(ui, tree)
2004 newtree = revset.findaliases(ui, tree)
2005 if newtree != tree:
2005 if newtree != tree:
2006 ui.note(newtree, "\n")
2006 ui.note(newtree, "\n")
2007 func = revset.match(ui, expr)
2007 func = revset.match(ui, expr)
2008 for c in func(repo, range(len(repo))):
2008 for c in func(repo, range(len(repo))):
2009 ui.write("%s\n" % c)
2009 ui.write("%s\n" % c)
2010
2010
2011 @command('debugsetparents', [], _('REV1 [REV2]'))
2011 @command('debugsetparents', [], _('REV1 [REV2]'))
2012 def debugsetparents(ui, repo, rev1, rev2=None):
2012 def debugsetparents(ui, repo, rev1, rev2=None):
2013 """manually set the parents of the current working directory
2013 """manually set the parents of the current working directory
2014
2014
2015 This is useful for writing repository conversion tools, but should
2015 This is useful for writing repository conversion tools, but should
2016 be used with care.
2016 be used with care.
2017
2017
2018 Returns 0 on success.
2018 Returns 0 on success.
2019 """
2019 """
2020
2020
2021 r1 = cmdutil.revsingle(repo, rev1).node()
2021 r1 = cmdutil.revsingle(repo, rev1).node()
2022 r2 = cmdutil.revsingle(repo, rev2, 'null').node()
2022 r2 = cmdutil.revsingle(repo, rev2, 'null').node()
2023
2023
2024 wlock = repo.wlock()
2024 wlock = repo.wlock()
2025 try:
2025 try:
2026 repo.dirstate.setparents(r1, r2)
2026 repo.dirstate.setparents(r1, r2)
2027 finally:
2027 finally:
2028 wlock.release()
2028 wlock.release()
2029
2029
2030 @command('debugstate',
2030 @command('debugstate',
2031 [('', 'nodates', None, _('do not display the saved mtime')),
2031 [('', 'nodates', None, _('do not display the saved mtime')),
2032 ('', 'datesort', None, _('sort by saved mtime'))],
2032 ('', 'datesort', None, _('sort by saved mtime'))],
2033 _('[OPTION]...'))
2033 _('[OPTION]...'))
2034 def debugstate(ui, repo, nodates=None, datesort=None):
2034 def debugstate(ui, repo, nodates=None, datesort=None):
2035 """show the contents of the current dirstate"""
2035 """show the contents of the current dirstate"""
2036 timestr = ""
2036 timestr = ""
2037 showdate = not nodates
2037 showdate = not nodates
2038 if datesort:
2038 if datesort:
2039 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2039 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2040 else:
2040 else:
2041 keyfunc = None # sort by filename
2041 keyfunc = None # sort by filename
2042 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2042 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2043 if showdate:
2043 if showdate:
2044 if ent[3] == -1:
2044 if ent[3] == -1:
2045 # Pad or slice to locale representation
2045 # Pad or slice to locale representation
2046 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2046 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2047 time.localtime(0)))
2047 time.localtime(0)))
2048 timestr = 'unset'
2048 timestr = 'unset'
2049 timestr = (timestr[:locale_len] +
2049 timestr = (timestr[:locale_len] +
2050 ' ' * (locale_len - len(timestr)))
2050 ' ' * (locale_len - len(timestr)))
2051 else:
2051 else:
2052 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2052 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2053 time.localtime(ent[3]))
2053 time.localtime(ent[3]))
2054 if ent[1] & 020000:
2054 if ent[1] & 020000:
2055 mode = 'lnk'
2055 mode = 'lnk'
2056 else:
2056 else:
2057 mode = '%3o' % (ent[1] & 0777)
2057 mode = '%3o' % (ent[1] & 0777)
2058 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2058 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2059 for f in repo.dirstate.copies():
2059 for f in repo.dirstate.copies():
2060 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2060 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2061
2061
2062 @command('debugsub',
2062 @command('debugsub',
2063 [('r', 'rev', '',
2063 [('r', 'rev', '',
2064 _('revision to check'), _('REV'))],
2064 _('revision to check'), _('REV'))],
2065 _('[-r REV] [REV]'))
2065 _('[-r REV] [REV]'))
2066 def debugsub(ui, repo, rev=None):
2066 def debugsub(ui, repo, rev=None):
2067 ctx = cmdutil.revsingle(repo, rev, None)
2067 ctx = cmdutil.revsingle(repo, rev, None)
2068 for k, v in sorted(ctx.substate.items()):
2068 for k, v in sorted(ctx.substate.items()):
2069 ui.write('path %s\n' % k)
2069 ui.write('path %s\n' % k)
2070 ui.write(' source %s\n' % v[0])
2070 ui.write(' source %s\n' % v[0])
2071 ui.write(' revision %s\n' % v[1])
2071 ui.write(' revision %s\n' % v[1])
2072
2072
2073 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2073 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2074 def debugwalk(ui, repo, *pats, **opts):
2074 def debugwalk(ui, repo, *pats, **opts):
2075 """show how files match on given patterns"""
2075 """show how files match on given patterns"""
2076 m = cmdutil.match(repo, pats, opts)
2076 m = cmdutil.match(repo, pats, opts)
2077 items = list(repo.walk(m))
2077 items = list(repo.walk(m))
2078 if not items:
2078 if not items:
2079 return
2079 return
2080 fmt = 'f %%-%ds %%-%ds %%s' % (
2080 fmt = 'f %%-%ds %%-%ds %%s' % (
2081 max([len(abs) for abs in items]),
2081 max([len(abs) for abs in items]),
2082 max([len(m.rel(abs)) for abs in items]))
2082 max([len(m.rel(abs)) for abs in items]))
2083 for abs in items:
2083 for abs in items:
2084 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2084 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2085 ui.write("%s\n" % line.rstrip())
2085 ui.write("%s\n" % line.rstrip())
2086
2086
2087 @command('debugwireargs',
2087 @command('debugwireargs',
2088 [('', 'three', '', 'three'),
2088 [('', 'three', '', 'three'),
2089 ('', 'four', '', 'four'),
2089 ('', 'four', '', 'four'),
2090 ('', 'five', '', 'five'),
2090 ('', 'five', '', 'five'),
2091 ] + remoteopts,
2091 ] + remoteopts,
2092 _('REPO [OPTIONS]... [ONE [TWO]]'))
2092 _('REPO [OPTIONS]... [ONE [TWO]]'))
2093 def debugwireargs(ui, repopath, *vals, **opts):
2093 def debugwireargs(ui, repopath, *vals, **opts):
2094 repo = hg.repository(hg.remoteui(ui, opts), repopath)
2094 repo = hg.repository(hg.remoteui(ui, opts), repopath)
2095 for opt in remoteopts:
2095 for opt in remoteopts:
2096 del opts[opt[1]]
2096 del opts[opt[1]]
2097 args = {}
2097 args = {}
2098 for k, v in opts.iteritems():
2098 for k, v in opts.iteritems():
2099 if v:
2099 if v:
2100 args[k] = v
2100 args[k] = v
2101 # run twice to check that we don't mess up the stream for the next command
2101 # run twice to check that we don't mess up the stream for the next command
2102 res1 = repo.debugwireargs(*vals, **args)
2102 res1 = repo.debugwireargs(*vals, **args)
2103 res2 = repo.debugwireargs(*vals, **args)
2103 res2 = repo.debugwireargs(*vals, **args)
2104 ui.write("%s\n" % res1)
2104 ui.write("%s\n" % res1)
2105 if res1 != res2:
2105 if res1 != res2:
2106 ui.warn("%s\n" % res2)
2106 ui.warn("%s\n" % res2)
2107
2107
2108 @command('^diff',
2108 @command('^diff',
2109 [('r', 'rev', [], _('revision'), _('REV')),
2109 [('r', 'rev', [], _('revision'), _('REV')),
2110 ('c', 'change', '', _('change made by revision'), _('REV'))
2110 ('c', 'change', '', _('change made by revision'), _('REV'))
2111 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2111 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2112 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2112 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2113 def diff(ui, repo, *pats, **opts):
2113 def diff(ui, repo, *pats, **opts):
2114 """diff repository (or selected files)
2114 """diff repository (or selected files)
2115
2115
2116 Show differences between revisions for the specified files.
2116 Show differences between revisions for the specified files.
2117
2117
2118 Differences between files are shown using the unified diff format.
2118 Differences between files are shown using the unified diff format.
2119
2119
2120 .. note::
2120 .. note::
2121 diff may generate unexpected results for merges, as it will
2121 diff may generate unexpected results for merges, as it will
2122 default to comparing against the working directory's first
2122 default to comparing against the working directory's first
2123 parent changeset if no revisions are specified.
2123 parent changeset if no revisions are specified.
2124
2124
2125 When two revision arguments are given, then changes are shown
2125 When two revision arguments are given, then changes are shown
2126 between those revisions. If only one revision is specified then
2126 between those revisions. If only one revision is specified then
2127 that revision is compared to the working directory, and, when no
2127 that revision is compared to the working directory, and, when no
2128 revisions are specified, the working directory files are compared
2128 revisions are specified, the working directory files are compared
2129 to its parent.
2129 to its parent.
2130
2130
2131 Alternatively you can specify -c/--change with a revision to see
2131 Alternatively you can specify -c/--change with a revision to see
2132 the changes in that changeset relative to its first parent.
2132 the changes in that changeset relative to its first parent.
2133
2133
2134 Without the -a/--text option, diff will avoid generating diffs of
2134 Without the -a/--text option, diff will avoid generating diffs of
2135 files it detects as binary. With -a, diff will generate a diff
2135 files it detects as binary. With -a, diff will generate a diff
2136 anyway, probably with undesirable results.
2136 anyway, probably with undesirable results.
2137
2137
2138 Use the -g/--git option to generate diffs in the git extended diff
2138 Use the -g/--git option to generate diffs in the git extended diff
2139 format. For more information, read :hg:`help diffs`.
2139 format. For more information, read :hg:`help diffs`.
2140
2140
2141 Returns 0 on success.
2141 Returns 0 on success.
2142 """
2142 """
2143
2143
2144 revs = opts.get('rev')
2144 revs = opts.get('rev')
2145 change = opts.get('change')
2145 change = opts.get('change')
2146 stat = opts.get('stat')
2146 stat = opts.get('stat')
2147 reverse = opts.get('reverse')
2147 reverse = opts.get('reverse')
2148
2148
2149 if revs and change:
2149 if revs and change:
2150 msg = _('cannot specify --rev and --change at the same time')
2150 msg = _('cannot specify --rev and --change at the same time')
2151 raise util.Abort(msg)
2151 raise util.Abort(msg)
2152 elif change:
2152 elif change:
2153 node2 = cmdutil.revsingle(repo, change, None).node()
2153 node2 = cmdutil.revsingle(repo, change, None).node()
2154 node1 = repo[node2].p1().node()
2154 node1 = repo[node2].p1().node()
2155 else:
2155 else:
2156 node1, node2 = cmdutil.revpair(repo, revs)
2156 node1, node2 = cmdutil.revpair(repo, revs)
2157
2157
2158 if reverse:
2158 if reverse:
2159 node1, node2 = node2, node1
2159 node1, node2 = node2, node1
2160
2160
2161 diffopts = patch.diffopts(ui, opts)
2161 diffopts = patch.diffopts(ui, opts)
2162 m = cmdutil.match(repo, pats, opts)
2162 m = cmdutil.match(repo, pats, opts)
2163 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2163 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2164 listsubrepos=opts.get('subrepos'))
2164 listsubrepos=opts.get('subrepos'))
2165
2165
2166 @command('^export',
2166 @command('^export',
2167 [('o', 'output', '',
2167 [('o', 'output', '',
2168 _('print output to file with formatted name'), _('FORMAT')),
2168 _('print output to file with formatted name'), _('FORMAT')),
2169 ('', 'switch-parent', None, _('diff against the second parent')),
2169 ('', 'switch-parent', None, _('diff against the second parent')),
2170 ('r', 'rev', [], _('revisions to export'), _('REV')),
2170 ('r', 'rev', [], _('revisions to export'), _('REV')),
2171 ] + diffopts,
2171 ] + diffopts,
2172 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2172 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2173 def export(ui, repo, *changesets, **opts):
2173 def export(ui, repo, *changesets, **opts):
2174 """dump the header and diffs for one or more changesets
2174 """dump the header and diffs for one or more changesets
2175
2175
2176 Print the changeset header and diffs for one or more revisions.
2176 Print the changeset header and diffs for one or more revisions.
2177
2177
2178 The information shown in the changeset header is: author, date,
2178 The information shown in the changeset header is: author, date,
2179 branch name (if non-default), changeset hash, parent(s) and commit
2179 branch name (if non-default), changeset hash, parent(s) and commit
2180 comment.
2180 comment.
2181
2181
2182 .. note::
2182 .. note::
2183 export may generate unexpected diff output for merge
2183 export may generate unexpected diff output for merge
2184 changesets, as it will compare the merge changeset against its
2184 changesets, as it will compare the merge changeset against its
2185 first parent only.
2185 first parent only.
2186
2186
2187 Output may be to a file, in which case the name of the file is
2187 Output may be to a file, in which case the name of the file is
2188 given using a format string. The formatting rules are as follows:
2188 given using a format string. The formatting rules are as follows:
2189
2189
2190 :``%%``: literal "%" character
2190 :``%%``: literal "%" character
2191 :``%H``: changeset hash (40 hexadecimal digits)
2191 :``%H``: changeset hash (40 hexadecimal digits)
2192 :``%N``: number of patches being generated
2192 :``%N``: number of patches being generated
2193 :``%R``: changeset revision number
2193 :``%R``: changeset revision number
2194 :``%b``: basename of the exporting repository
2194 :``%b``: basename of the exporting repository
2195 :``%h``: short-form changeset hash (12 hexadecimal digits)
2195 :``%h``: short-form changeset hash (12 hexadecimal digits)
2196 :``%n``: zero-padded sequence number, starting at 1
2196 :``%n``: zero-padded sequence number, starting at 1
2197 :``%r``: zero-padded changeset revision number
2197 :``%r``: zero-padded changeset revision number
2198
2198
2199 Without the -a/--text option, export will avoid generating diffs
2199 Without the -a/--text option, export will avoid generating diffs
2200 of files it detects as binary. With -a, export will generate a
2200 of files it detects as binary. With -a, export will generate a
2201 diff anyway, probably with undesirable results.
2201 diff anyway, probably with undesirable results.
2202
2202
2203 Use the -g/--git option to generate diffs in the git extended diff
2203 Use the -g/--git option to generate diffs in the git extended diff
2204 format. See :hg:`help diffs` for more information.
2204 format. See :hg:`help diffs` for more information.
2205
2205
2206 With the --switch-parent option, the diff will be against the
2206 With the --switch-parent option, the diff will be against the
2207 second parent. It can be useful to review a merge.
2207 second parent. It can be useful to review a merge.
2208
2208
2209 Returns 0 on success.
2209 Returns 0 on success.
2210 """
2210 """
2211 changesets += tuple(opts.get('rev', []))
2211 changesets += tuple(opts.get('rev', []))
2212 if not changesets:
2212 if not changesets:
2213 raise util.Abort(_("export requires at least one changeset"))
2213 raise util.Abort(_("export requires at least one changeset"))
2214 revs = cmdutil.revrange(repo, changesets)
2214 revs = cmdutil.revrange(repo, changesets)
2215 if len(revs) > 1:
2215 if len(revs) > 1:
2216 ui.note(_('exporting patches:\n'))
2216 ui.note(_('exporting patches:\n'))
2217 else:
2217 else:
2218 ui.note(_('exporting patch:\n'))
2218 ui.note(_('exporting patch:\n'))
2219 cmdutil.export(repo, revs, template=opts.get('output'),
2219 cmdutil.export(repo, revs, template=opts.get('output'),
2220 switch_parent=opts.get('switch_parent'),
2220 switch_parent=opts.get('switch_parent'),
2221 opts=patch.diffopts(ui, opts))
2221 opts=patch.diffopts(ui, opts))
2222
2222
2223 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2223 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2224 def forget(ui, repo, *pats, **opts):
2224 def forget(ui, repo, *pats, **opts):
2225 """forget the specified files on the next commit
2225 """forget the specified files on the next commit
2226
2226
2227 Mark the specified files so they will no longer be tracked
2227 Mark the specified files so they will no longer be tracked
2228 after the next commit.
2228 after the next commit.
2229
2229
2230 This only removes files from the current branch, not from the
2230 This only removes files from the current branch, not from the
2231 entire project history, and it does not delete them from the
2231 entire project history, and it does not delete them from the
2232 working directory.
2232 working directory.
2233
2233
2234 To undo a forget before the next commit, see :hg:`add`.
2234 To undo a forget before the next commit, see :hg:`add`.
2235
2235
2236 Returns 0 on success.
2236 Returns 0 on success.
2237 """
2237 """
2238
2238
2239 if not pats:
2239 if not pats:
2240 raise util.Abort(_('no files specified'))
2240 raise util.Abort(_('no files specified'))
2241
2241
2242 m = cmdutil.match(repo, pats, opts)
2242 m = cmdutil.match(repo, pats, opts)
2243 s = repo.status(match=m, clean=True)
2243 s = repo.status(match=m, clean=True)
2244 forget = sorted(s[0] + s[1] + s[3] + s[6])
2244 forget = sorted(s[0] + s[1] + s[3] + s[6])
2245 errs = 0
2245 errs = 0
2246
2246
2247 for f in m.files():
2247 for f in m.files():
2248 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2248 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2249 ui.warn(_('not removing %s: file is already untracked\n')
2249 ui.warn(_('not removing %s: file is already untracked\n')
2250 % m.rel(f))
2250 % m.rel(f))
2251 errs = 1
2251 errs = 1
2252
2252
2253 for f in forget:
2253 for f in forget:
2254 if ui.verbose or not m.exact(f):
2254 if ui.verbose or not m.exact(f):
2255 ui.status(_('removing %s\n') % m.rel(f))
2255 ui.status(_('removing %s\n') % m.rel(f))
2256
2256
2257 repo[None].remove(forget, unlink=False)
2257 repo[None].remove(forget, unlink=False)
2258 return errs
2258 return errs
2259
2259
2260 @command('grep',
2260 @command('grep',
2261 [('0', 'print0', None, _('end fields with NUL')),
2261 [('0', 'print0', None, _('end fields with NUL')),
2262 ('', 'all', None, _('print all revisions that match')),
2262 ('', 'all', None, _('print all revisions that match')),
2263 ('a', 'text', None, _('treat all files as text')),
2263 ('a', 'text', None, _('treat all files as text')),
2264 ('f', 'follow', None,
2264 ('f', 'follow', None,
2265 _('follow changeset history,'
2265 _('follow changeset history,'
2266 ' or file history across copies and renames')),
2266 ' or file history across copies and renames')),
2267 ('i', 'ignore-case', None, _('ignore case when matching')),
2267 ('i', 'ignore-case', None, _('ignore case when matching')),
2268 ('l', 'files-with-matches', None,
2268 ('l', 'files-with-matches', None,
2269 _('print only filenames and revisions that match')),
2269 _('print only filenames and revisions that match')),
2270 ('n', 'line-number', None, _('print matching line numbers')),
2270 ('n', 'line-number', None, _('print matching line numbers')),
2271 ('r', 'rev', [],
2271 ('r', 'rev', [],
2272 _('only search files changed within revision range'), _('REV')),
2272 _('only search files changed within revision range'), _('REV')),
2273 ('u', 'user', None, _('list the author (long with -v)')),
2273 ('u', 'user', None, _('list the author (long with -v)')),
2274 ('d', 'date', None, _('list the date (short with -q)')),
2274 ('d', 'date', None, _('list the date (short with -q)')),
2275 ] + walkopts,
2275 ] + walkopts,
2276 _('[OPTION]... PATTERN [FILE]...'))
2276 _('[OPTION]... PATTERN [FILE]...'))
2277 def grep(ui, repo, pattern, *pats, **opts):
2277 def grep(ui, repo, pattern, *pats, **opts):
2278 """search for a pattern in specified files and revisions
2278 """search for a pattern in specified files and revisions
2279
2279
2280 Search revisions of files for a regular expression.
2280 Search revisions of files for a regular expression.
2281
2281
2282 This command behaves differently than Unix grep. It only accepts
2282 This command behaves differently than Unix grep. It only accepts
2283 Python/Perl regexps. It searches repository history, not the
2283 Python/Perl regexps. It searches repository history, not the
2284 working directory. It always prints the revision number in which a
2284 working directory. It always prints the revision number in which a
2285 match appears.
2285 match appears.
2286
2286
2287 By default, grep only prints output for the first revision of a
2287 By default, grep only prints output for the first revision of a
2288 file in which it finds a match. To get it to print every revision
2288 file in which it finds a match. To get it to print every revision
2289 that contains a change in match status ("-" for a match that
2289 that contains a change in match status ("-" for a match that
2290 becomes a non-match, or "+" for a non-match that becomes a match),
2290 becomes a non-match, or "+" for a non-match that becomes a match),
2291 use the --all flag.
2291 use the --all flag.
2292
2292
2293 Returns 0 if a match is found, 1 otherwise.
2293 Returns 0 if a match is found, 1 otherwise.
2294 """
2294 """
2295 reflags = 0
2295 reflags = 0
2296 if opts.get('ignore_case'):
2296 if opts.get('ignore_case'):
2297 reflags |= re.I
2297 reflags |= re.I
2298 try:
2298 try:
2299 regexp = re.compile(pattern, reflags)
2299 regexp = re.compile(pattern, reflags)
2300 except re.error, inst:
2300 except re.error, inst:
2301 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2301 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2302 return 1
2302 return 1
2303 sep, eol = ':', '\n'
2303 sep, eol = ':', '\n'
2304 if opts.get('print0'):
2304 if opts.get('print0'):
2305 sep = eol = '\0'
2305 sep = eol = '\0'
2306
2306
2307 getfile = util.lrucachefunc(repo.file)
2307 getfile = util.lrucachefunc(repo.file)
2308
2308
2309 def matchlines(body):
2309 def matchlines(body):
2310 begin = 0
2310 begin = 0
2311 linenum = 0
2311 linenum = 0
2312 while True:
2312 while True:
2313 match = regexp.search(body, begin)
2313 match = regexp.search(body, begin)
2314 if not match:
2314 if not match:
2315 break
2315 break
2316 mstart, mend = match.span()
2316 mstart, mend = match.span()
2317 linenum += body.count('\n', begin, mstart) + 1
2317 linenum += body.count('\n', begin, mstart) + 1
2318 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2318 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2319 begin = body.find('\n', mend) + 1 or len(body)
2319 begin = body.find('\n', mend) + 1 or len(body)
2320 lend = begin - 1
2320 lend = begin - 1
2321 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2321 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2322
2322
2323 class linestate(object):
2323 class linestate(object):
2324 def __init__(self, line, linenum, colstart, colend):
2324 def __init__(self, line, linenum, colstart, colend):
2325 self.line = line
2325 self.line = line
2326 self.linenum = linenum
2326 self.linenum = linenum
2327 self.colstart = colstart
2327 self.colstart = colstart
2328 self.colend = colend
2328 self.colend = colend
2329
2329
2330 def __hash__(self):
2330 def __hash__(self):
2331 return hash((self.linenum, self.line))
2331 return hash((self.linenum, self.line))
2332
2332
2333 def __eq__(self, other):
2333 def __eq__(self, other):
2334 return self.line == other.line
2334 return self.line == other.line
2335
2335
2336 matches = {}
2336 matches = {}
2337 copies = {}
2337 copies = {}
2338 def grepbody(fn, rev, body):
2338 def grepbody(fn, rev, body):
2339 matches[rev].setdefault(fn, [])
2339 matches[rev].setdefault(fn, [])
2340 m = matches[rev][fn]
2340 m = matches[rev][fn]
2341 for lnum, cstart, cend, line in matchlines(body):
2341 for lnum, cstart, cend, line in matchlines(body):
2342 s = linestate(line, lnum, cstart, cend)
2342 s = linestate(line, lnum, cstart, cend)
2343 m.append(s)
2343 m.append(s)
2344
2344
2345 def difflinestates(a, b):
2345 def difflinestates(a, b):
2346 sm = difflib.SequenceMatcher(None, a, b)
2346 sm = difflib.SequenceMatcher(None, a, b)
2347 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2347 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2348 if tag == 'insert':
2348 if tag == 'insert':
2349 for i in xrange(blo, bhi):
2349 for i in xrange(blo, bhi):
2350 yield ('+', b[i])
2350 yield ('+', b[i])
2351 elif tag == 'delete':
2351 elif tag == 'delete':
2352 for i in xrange(alo, ahi):
2352 for i in xrange(alo, ahi):
2353 yield ('-', a[i])
2353 yield ('-', a[i])
2354 elif tag == 'replace':
2354 elif tag == 'replace':
2355 for i in xrange(alo, ahi):
2355 for i in xrange(alo, ahi):
2356 yield ('-', a[i])
2356 yield ('-', a[i])
2357 for i in xrange(blo, bhi):
2357 for i in xrange(blo, bhi):
2358 yield ('+', b[i])
2358 yield ('+', b[i])
2359
2359
2360 def display(fn, ctx, pstates, states):
2360 def display(fn, ctx, pstates, states):
2361 rev = ctx.rev()
2361 rev = ctx.rev()
2362 datefunc = ui.quiet and util.shortdate or util.datestr
2362 datefunc = ui.quiet and util.shortdate or util.datestr
2363 found = False
2363 found = False
2364 filerevmatches = {}
2364 filerevmatches = {}
2365 def binary():
2365 def binary():
2366 flog = getfile(fn)
2366 flog = getfile(fn)
2367 return util.binary(flog.read(ctx.filenode(fn)))
2367 return util.binary(flog.read(ctx.filenode(fn)))
2368
2368
2369 if opts.get('all'):
2369 if opts.get('all'):
2370 iter = difflinestates(pstates, states)
2370 iter = difflinestates(pstates, states)
2371 else:
2371 else:
2372 iter = [('', l) for l in states]
2372 iter = [('', l) for l in states]
2373 for change, l in iter:
2373 for change, l in iter:
2374 cols = [fn, str(rev)]
2374 cols = [fn, str(rev)]
2375 before, match, after = None, None, None
2375 before, match, after = None, None, None
2376 if opts.get('line_number'):
2376 if opts.get('line_number'):
2377 cols.append(str(l.linenum))
2377 cols.append(str(l.linenum))
2378 if opts.get('all'):
2378 if opts.get('all'):
2379 cols.append(change)
2379 cols.append(change)
2380 if opts.get('user'):
2380 if opts.get('user'):
2381 cols.append(ui.shortuser(ctx.user()))
2381 cols.append(ui.shortuser(ctx.user()))
2382 if opts.get('date'):
2382 if opts.get('date'):
2383 cols.append(datefunc(ctx.date()))
2383 cols.append(datefunc(ctx.date()))
2384 if opts.get('files_with_matches'):
2384 if opts.get('files_with_matches'):
2385 c = (fn, rev)
2385 c = (fn, rev)
2386 if c in filerevmatches:
2386 if c in filerevmatches:
2387 continue
2387 continue
2388 filerevmatches[c] = 1
2388 filerevmatches[c] = 1
2389 else:
2389 else:
2390 before = l.line[:l.colstart]
2390 before = l.line[:l.colstart]
2391 match = l.line[l.colstart:l.colend]
2391 match = l.line[l.colstart:l.colend]
2392 after = l.line[l.colend:]
2392 after = l.line[l.colend:]
2393 ui.write(sep.join(cols))
2393 ui.write(sep.join(cols))
2394 if before is not None:
2394 if before is not None:
2395 if not opts.get('text') and binary():
2395 if not opts.get('text') and binary():
2396 ui.write(sep + " Binary file matches")
2396 ui.write(sep + " Binary file matches")
2397 else:
2397 else:
2398 ui.write(sep + before)
2398 ui.write(sep + before)
2399 ui.write(match, label='grep.match')
2399 ui.write(match, label='grep.match')
2400 ui.write(after)
2400 ui.write(after)
2401 ui.write(eol)
2401 ui.write(eol)
2402 found = True
2402 found = True
2403 return found
2403 return found
2404
2404
2405 skip = {}
2405 skip = {}
2406 revfiles = {}
2406 revfiles = {}
2407 matchfn = cmdutil.match(repo, pats, opts)
2407 matchfn = cmdutil.match(repo, pats, opts)
2408 found = False
2408 found = False
2409 follow = opts.get('follow')
2409 follow = opts.get('follow')
2410
2410
2411 def prep(ctx, fns):
2411 def prep(ctx, fns):
2412 rev = ctx.rev()
2412 rev = ctx.rev()
2413 pctx = ctx.p1()
2413 pctx = ctx.p1()
2414 parent = pctx.rev()
2414 parent = pctx.rev()
2415 matches.setdefault(rev, {})
2415 matches.setdefault(rev, {})
2416 matches.setdefault(parent, {})
2416 matches.setdefault(parent, {})
2417 files = revfiles.setdefault(rev, [])
2417 files = revfiles.setdefault(rev, [])
2418 for fn in fns:
2418 for fn in fns:
2419 flog = getfile(fn)
2419 flog = getfile(fn)
2420 try:
2420 try:
2421 fnode = ctx.filenode(fn)
2421 fnode = ctx.filenode(fn)
2422 except error.LookupError:
2422 except error.LookupError:
2423 continue
2423 continue
2424
2424
2425 copied = flog.renamed(fnode)
2425 copied = flog.renamed(fnode)
2426 copy = follow and copied and copied[0]
2426 copy = follow and copied and copied[0]
2427 if copy:
2427 if copy:
2428 copies.setdefault(rev, {})[fn] = copy
2428 copies.setdefault(rev, {})[fn] = copy
2429 if fn in skip:
2429 if fn in skip:
2430 if copy:
2430 if copy:
2431 skip[copy] = True
2431 skip[copy] = True
2432 continue
2432 continue
2433 files.append(fn)
2433 files.append(fn)
2434
2434
2435 if fn not in matches[rev]:
2435 if fn not in matches[rev]:
2436 grepbody(fn, rev, flog.read(fnode))
2436 grepbody(fn, rev, flog.read(fnode))
2437
2437
2438 pfn = copy or fn
2438 pfn = copy or fn
2439 if pfn not in matches[parent]:
2439 if pfn not in matches[parent]:
2440 try:
2440 try:
2441 fnode = pctx.filenode(pfn)
2441 fnode = pctx.filenode(pfn)
2442 grepbody(pfn, parent, flog.read(fnode))
2442 grepbody(pfn, parent, flog.read(fnode))
2443 except error.LookupError:
2443 except error.LookupError:
2444 pass
2444 pass
2445
2445
2446 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2446 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2447 rev = ctx.rev()
2447 rev = ctx.rev()
2448 parent = ctx.p1().rev()
2448 parent = ctx.p1().rev()
2449 for fn in sorted(revfiles.get(rev, [])):
2449 for fn in sorted(revfiles.get(rev, [])):
2450 states = matches[rev][fn]
2450 states = matches[rev][fn]
2451 copy = copies.get(rev, {}).get(fn)
2451 copy = copies.get(rev, {}).get(fn)
2452 if fn in skip:
2452 if fn in skip:
2453 if copy:
2453 if copy:
2454 skip[copy] = True
2454 skip[copy] = True
2455 continue
2455 continue
2456 pstates = matches.get(parent, {}).get(copy or fn, [])
2456 pstates = matches.get(parent, {}).get(copy or fn, [])
2457 if pstates or states:
2457 if pstates or states:
2458 r = display(fn, ctx, pstates, states)
2458 r = display(fn, ctx, pstates, states)
2459 found = found or r
2459 found = found or r
2460 if r and not opts.get('all'):
2460 if r and not opts.get('all'):
2461 skip[fn] = True
2461 skip[fn] = True
2462 if copy:
2462 if copy:
2463 skip[copy] = True
2463 skip[copy] = True
2464 del matches[rev]
2464 del matches[rev]
2465 del revfiles[rev]
2465 del revfiles[rev]
2466
2466
2467 return not found
2467 return not found
2468
2468
2469 @command('heads',
2469 @command('heads',
2470 [('r', 'rev', '',
2470 [('r', 'rev', '',
2471 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2471 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2472 ('t', 'topo', False, _('show topological heads only')),
2472 ('t', 'topo', False, _('show topological heads only')),
2473 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2473 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2474 ('c', 'closed', False, _('show normal and closed branch heads')),
2474 ('c', 'closed', False, _('show normal and closed branch heads')),
2475 ] + templateopts,
2475 ] + templateopts,
2476 _('[-ac] [-r STARTREV] [REV]...'))
2476 _('[-ac] [-r STARTREV] [REV]...'))
2477 def heads(ui, repo, *branchrevs, **opts):
2477 def heads(ui, repo, *branchrevs, **opts):
2478 """show current repository heads or show branch heads
2478 """show current repository heads or show branch heads
2479
2479
2480 With no arguments, show all repository branch heads.
2480 With no arguments, show all repository branch heads.
2481
2481
2482 Repository "heads" are changesets with no child changesets. They are
2482 Repository "heads" are changesets with no child changesets. They are
2483 where development generally takes place and are the usual targets
2483 where development generally takes place and are the usual targets
2484 for update and merge operations. Branch heads are changesets that have
2484 for update and merge operations. Branch heads are changesets that have
2485 no child changeset on the same branch.
2485 no child changeset on the same branch.
2486
2486
2487 If one or more REVs are given, only branch heads on the branches
2487 If one or more REVs are given, only branch heads on the branches
2488 associated with the specified changesets are shown.
2488 associated with the specified changesets are shown.
2489
2489
2490 If -c/--closed is specified, also show branch heads marked closed
2490 If -c/--closed is specified, also show branch heads marked closed
2491 (see :hg:`commit --close-branch`).
2491 (see :hg:`commit --close-branch`).
2492
2492
2493 If STARTREV is specified, only those heads that are descendants of
2493 If STARTREV is specified, only those heads that are descendants of
2494 STARTREV will be displayed.
2494 STARTREV will be displayed.
2495
2495
2496 If -t/--topo is specified, named branch mechanics will be ignored and only
2496 If -t/--topo is specified, named branch mechanics will be ignored and only
2497 changesets without children will be shown.
2497 changesets without children will be shown.
2498
2498
2499 Returns 0 if matching heads are found, 1 if not.
2499 Returns 0 if matching heads are found, 1 if not.
2500 """
2500 """
2501
2501
2502 start = None
2502 start = None
2503 if 'rev' in opts:
2503 if 'rev' in opts:
2504 start = cmdutil.revsingle(repo, opts['rev'], None).node()
2504 start = cmdutil.revsingle(repo, opts['rev'], None).node()
2505
2505
2506 if opts.get('topo'):
2506 if opts.get('topo'):
2507 heads = [repo[h] for h in repo.heads(start)]
2507 heads = [repo[h] for h in repo.heads(start)]
2508 else:
2508 else:
2509 heads = []
2509 heads = []
2510 for b, ls in repo.branchmap().iteritems():
2510 for b, ls in repo.branchmap().iteritems():
2511 if start is None:
2511 if start is None:
2512 heads += [repo[h] for h in ls]
2512 heads += [repo[h] for h in ls]
2513 continue
2513 continue
2514 startrev = repo.changelog.rev(start)
2514 startrev = repo.changelog.rev(start)
2515 descendants = set(repo.changelog.descendants(startrev))
2515 descendants = set(repo.changelog.descendants(startrev))
2516 descendants.add(startrev)
2516 descendants.add(startrev)
2517 rev = repo.changelog.rev
2517 rev = repo.changelog.rev
2518 heads += [repo[h] for h in ls if rev(h) in descendants]
2518 heads += [repo[h] for h in ls if rev(h) in descendants]
2519
2519
2520 if branchrevs:
2520 if branchrevs:
2521 branches = set(repo[br].branch() for br in branchrevs)
2521 branches = set(repo[br].branch() for br in branchrevs)
2522 heads = [h for h in heads if h.branch() in branches]
2522 heads = [h for h in heads if h.branch() in branches]
2523
2523
2524 if not opts.get('closed'):
2524 if not opts.get('closed'):
2525 heads = [h for h in heads if not h.extra().get('close')]
2525 heads = [h for h in heads if not h.extra().get('close')]
2526
2526
2527 if opts.get('active') and branchrevs:
2527 if opts.get('active') and branchrevs:
2528 dagheads = repo.heads(start)
2528 dagheads = repo.heads(start)
2529 heads = [h for h in heads if h.node() in dagheads]
2529 heads = [h for h in heads if h.node() in dagheads]
2530
2530
2531 if branchrevs:
2531 if branchrevs:
2532 haveheads = set(h.branch() for h in heads)
2532 haveheads = set(h.branch() for h in heads)
2533 if branches - haveheads:
2533 if branches - haveheads:
2534 headless = ', '.join(b for b in branches - haveheads)
2534 headless = ', '.join(b for b in branches - haveheads)
2535 msg = _('no open branch heads found on branches %s')
2535 msg = _('no open branch heads found on branches %s')
2536 if opts.get('rev'):
2536 if opts.get('rev'):
2537 msg += _(' (started at %s)' % opts['rev'])
2537 msg += _(' (started at %s)' % opts['rev'])
2538 ui.warn((msg + '\n') % headless)
2538 ui.warn((msg + '\n') % headless)
2539
2539
2540 if not heads:
2540 if not heads:
2541 return 1
2541 return 1
2542
2542
2543 heads = sorted(heads, key=lambda x: -x.rev())
2543 heads = sorted(heads, key=lambda x: -x.rev())
2544 displayer = cmdutil.show_changeset(ui, repo, opts)
2544 displayer = cmdutil.show_changeset(ui, repo, opts)
2545 for ctx in heads:
2545 for ctx in heads:
2546 displayer.show(ctx)
2546 displayer.show(ctx)
2547 displayer.close()
2547 displayer.close()
2548
2548
2549 @command('help',
2549 @command('help',
2550 [('e', 'extension', None, _('show only help for extensions')),
2550 [('e', 'extension', None, _('show only help for extensions')),
2551 ('c', 'command', None, _('show only help for commands'))],
2551 ('c', 'command', None, _('show only help for commands'))],
2552 _('[-ec] [TOPIC]'))
2552 _('[-ec] [TOPIC]'))
2553 def help_(ui, name=None, with_version=False, unknowncmd=False, full=True, **opts):
2553 def help_(ui, name=None, with_version=False, unknowncmd=False, full=True, **opts):
2554 """show help for a given topic or a help overview
2554 """show help for a given topic or a help overview
2555
2555
2556 With no arguments, print a list of commands with short help messages.
2556 With no arguments, print a list of commands with short help messages.
2557
2557
2558 Given a topic, extension, or command name, print help for that
2558 Given a topic, extension, or command name, print help for that
2559 topic.
2559 topic.
2560
2560
2561 Returns 0 if successful.
2561 Returns 0 if successful.
2562 """
2562 """
2563 option_lists = []
2563 option_lists = []
2564 textwidth = min(ui.termwidth(), 80) - 2
2564 textwidth = min(ui.termwidth(), 80) - 2
2565
2565
2566 def addglobalopts(aliases):
2566 def addglobalopts(aliases):
2567 if ui.verbose:
2567 if ui.verbose:
2568 option_lists.append((_("global options:"), globalopts))
2568 option_lists.append((_("global options:"), globalopts))
2569 if name == 'shortlist':
2569 if name == 'shortlist':
2570 option_lists.append((_('use "hg help" for the full list '
2570 option_lists.append((_('use "hg help" for the full list '
2571 'of commands'), ()))
2571 'of commands'), ()))
2572 else:
2572 else:
2573 if name == 'shortlist':
2573 if name == 'shortlist':
2574 msg = _('use "hg help" for the full list of commands '
2574 msg = _('use "hg help" for the full list of commands '
2575 'or "hg -v" for details')
2575 'or "hg -v" for details')
2576 elif name and not full:
2576 elif name and not full:
2577 msg = _('use "hg help %s" to show the full help text' % name)
2577 msg = _('use "hg help %s" to show the full help text' % name)
2578 elif aliases:
2578 elif aliases:
2579 msg = _('use "hg -v help%s" to show builtin aliases and '
2579 msg = _('use "hg -v help%s" to show builtin aliases and '
2580 'global options') % (name and " " + name or "")
2580 'global options') % (name and " " + name or "")
2581 else:
2581 else:
2582 msg = _('use "hg -v help %s" to show global options') % name
2582 msg = _('use "hg -v help %s" to show global options') % name
2583 option_lists.append((msg, ()))
2583 option_lists.append((msg, ()))
2584
2584
2585 def helpcmd(name):
2585 def helpcmd(name):
2586 if with_version:
2586 if with_version:
2587 version_(ui)
2587 version_(ui)
2588 ui.write('\n')
2588 ui.write('\n')
2589
2589
2590 try:
2590 try:
2591 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
2591 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
2592 except error.AmbiguousCommand, inst:
2592 except error.AmbiguousCommand, inst:
2593 # py3k fix: except vars can't be used outside the scope of the
2593 # py3k fix: except vars can't be used outside the scope of the
2594 # except block, nor can be used inside a lambda. python issue4617
2594 # except block, nor can be used inside a lambda. python issue4617
2595 prefix = inst.args[0]
2595 prefix = inst.args[0]
2596 select = lambda c: c.lstrip('^').startswith(prefix)
2596 select = lambda c: c.lstrip('^').startswith(prefix)
2597 helplist(_('list of commands:\n\n'), select)
2597 helplist(_('list of commands:\n\n'), select)
2598 return
2598 return
2599
2599
2600 # check if it's an invalid alias and display its error if it is
2600 # check if it's an invalid alias and display its error if it is
2601 if getattr(entry[0], 'badalias', False):
2601 if getattr(entry[0], 'badalias', False):
2602 if not unknowncmd:
2602 if not unknowncmd:
2603 entry[0](ui)
2603 entry[0](ui)
2604 return
2604 return
2605
2605
2606 # synopsis
2606 # synopsis
2607 if len(entry) > 2:
2607 if len(entry) > 2:
2608 if entry[2].startswith('hg'):
2608 if entry[2].startswith('hg'):
2609 ui.write("%s\n" % entry[2])
2609 ui.write("%s\n" % entry[2])
2610 else:
2610 else:
2611 ui.write('hg %s %s\n' % (aliases[0], entry[2]))
2611 ui.write('hg %s %s\n' % (aliases[0], entry[2]))
2612 else:
2612 else:
2613 ui.write('hg %s\n' % aliases[0])
2613 ui.write('hg %s\n' % aliases[0])
2614
2614
2615 # aliases
2615 # aliases
2616 if full and not ui.quiet and len(aliases) > 1:
2616 if full and not ui.quiet and len(aliases) > 1:
2617 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
2617 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
2618
2618
2619 # description
2619 # description
2620 doc = gettext(entry[0].__doc__)
2620 doc = gettext(entry[0].__doc__)
2621 if not doc:
2621 if not doc:
2622 doc = _("(no help text available)")
2622 doc = _("(no help text available)")
2623 if hasattr(entry[0], 'definition'): # aliased command
2623 if hasattr(entry[0], 'definition'): # aliased command
2624 if entry[0].definition.startswith('!'): # shell alias
2624 if entry[0].definition.startswith('!'): # shell alias
2625 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
2625 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
2626 else:
2626 else:
2627 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
2627 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
2628 if ui.quiet or not full:
2628 if ui.quiet or not full:
2629 doc = doc.splitlines()[0]
2629 doc = doc.splitlines()[0]
2630 keep = ui.verbose and ['verbose'] or []
2630 keep = ui.verbose and ['verbose'] or []
2631 formatted, pruned = minirst.format(doc, textwidth, keep=keep)
2631 formatted, pruned = minirst.format(doc, textwidth, keep=keep)
2632 ui.write("\n%s\n" % formatted)
2632 ui.write("\n%s\n" % formatted)
2633 if pruned:
2633 if pruned:
2634 ui.write(_('\nuse "hg -v help %s" to show verbose help\n') % name)
2634 ui.write(_('\nuse "hg -v help %s" to show verbose help\n') % name)
2635
2635
2636 if not ui.quiet:
2636 if not ui.quiet:
2637 # options
2637 # options
2638 if entry[1]:
2638 if entry[1]:
2639 option_lists.append((_("options:\n"), entry[1]))
2639 option_lists.append((_("options:\n"), entry[1]))
2640
2640
2641 addglobalopts(False)
2641 addglobalopts(False)
2642
2642
2643 # check if this command shadows a non-trivial (multi-line)
2643 # check if this command shadows a non-trivial (multi-line)
2644 # extension help text
2644 # extension help text
2645 try:
2645 try:
2646 mod = extensions.find(name)
2646 mod = extensions.find(name)
2647 doc = gettext(mod.__doc__) or ''
2647 doc = gettext(mod.__doc__) or ''
2648 if '\n' in doc.strip():
2648 if '\n' in doc.strip():
2649 msg = _('use "hg help -e %s" to show help for '
2649 msg = _('use "hg help -e %s" to show help for '
2650 'the %s extension') % (name, name)
2650 'the %s extension') % (name, name)
2651 ui.write('\n%s\n' % msg)
2651 ui.write('\n%s\n' % msg)
2652 except KeyError:
2652 except KeyError:
2653 pass
2653 pass
2654
2654
2655 def helplist(header, select=None):
2655 def helplist(header, select=None):
2656 h = {}
2656 h = {}
2657 cmds = {}
2657 cmds = {}
2658 for c, e in table.iteritems():
2658 for c, e in table.iteritems():
2659 f = c.split("|", 1)[0]
2659 f = c.split("|", 1)[0]
2660 if select and not select(f):
2660 if select and not select(f):
2661 continue
2661 continue
2662 if (not select and name != 'shortlist' and
2662 if (not select and name != 'shortlist' and
2663 e[0].__module__ != __name__):
2663 e[0].__module__ != __name__):
2664 continue
2664 continue
2665 if name == "shortlist" and not f.startswith("^"):
2665 if name == "shortlist" and not f.startswith("^"):
2666 continue
2666 continue
2667 f = f.lstrip("^")
2667 f = f.lstrip("^")
2668 if not ui.debugflag and f.startswith("debug"):
2668 if not ui.debugflag and f.startswith("debug"):
2669 continue
2669 continue
2670 doc = e[0].__doc__
2670 doc = e[0].__doc__
2671 if doc and 'DEPRECATED' in doc and not ui.verbose:
2671 if doc and 'DEPRECATED' in doc and not ui.verbose:
2672 continue
2672 continue
2673 doc = gettext(doc)
2673 doc = gettext(doc)
2674 if not doc:
2674 if not doc:
2675 doc = _("(no help text available)")
2675 doc = _("(no help text available)")
2676 h[f] = doc.splitlines()[0].rstrip()
2676 h[f] = doc.splitlines()[0].rstrip()
2677 cmds[f] = c.lstrip("^")
2677 cmds[f] = c.lstrip("^")
2678
2678
2679 if not h:
2679 if not h:
2680 ui.status(_('no commands defined\n'))
2680 ui.status(_('no commands defined\n'))
2681 return
2681 return
2682
2682
2683 ui.status(header)
2683 ui.status(header)
2684 fns = sorted(h)
2684 fns = sorted(h)
2685 m = max(map(len, fns))
2685 m = max(map(len, fns))
2686 for f in fns:
2686 for f in fns:
2687 if ui.verbose:
2687 if ui.verbose:
2688 commands = cmds[f].replace("|",", ")
2688 commands = cmds[f].replace("|",", ")
2689 ui.write(" %s:\n %s\n"%(commands, h[f]))
2689 ui.write(" %s:\n %s\n"%(commands, h[f]))
2690 else:
2690 else:
2691 ui.write('%s\n' % (util.wrap(h[f], textwidth,
2691 ui.write('%s\n' % (util.wrap(h[f], textwidth,
2692 initindent=' %-*s ' % (m, f),
2692 initindent=' %-*s ' % (m, f),
2693 hangindent=' ' * (m + 4))))
2693 hangindent=' ' * (m + 4))))
2694
2694
2695 if not ui.quiet:
2695 if not ui.quiet:
2696 addglobalopts(True)
2696 addglobalopts(True)
2697
2697
2698 def helptopic(name):
2698 def helptopic(name):
2699 for names, header, doc in help.helptable:
2699 for names, header, doc in help.helptable:
2700 if name in names:
2700 if name in names:
2701 break
2701 break
2702 else:
2702 else:
2703 raise error.UnknownCommand(name)
2703 raise error.UnknownCommand(name)
2704
2704
2705 # description
2705 # description
2706 if not doc:
2706 if not doc:
2707 doc = _("(no help text available)")
2707 doc = _("(no help text available)")
2708 if hasattr(doc, '__call__'):
2708 if hasattr(doc, '__call__'):
2709 doc = doc()
2709 doc = doc()
2710
2710
2711 ui.write("%s\n\n" % header)
2711 ui.write("%s\n\n" % header)
2712 ui.write("%s\n" % minirst.format(doc, textwidth, indent=4))
2712 ui.write("%s\n" % minirst.format(doc, textwidth, indent=4))
2713 try:
2713 try:
2714 cmdutil.findcmd(name, table)
2714 cmdutil.findcmd(name, table)
2715 ui.write(_('\nuse "hg help -c %s" to see help for '
2715 ui.write(_('\nuse "hg help -c %s" to see help for '
2716 'the %s command\n') % (name, name))
2716 'the %s command\n') % (name, name))
2717 except error.UnknownCommand:
2717 except error.UnknownCommand:
2718 pass
2718 pass
2719
2719
2720 def helpext(name):
2720 def helpext(name):
2721 try:
2721 try:
2722 mod = extensions.find(name)
2722 mod = extensions.find(name)
2723 doc = gettext(mod.__doc__) or _('no help text available')
2723 doc = gettext(mod.__doc__) or _('no help text available')
2724 except KeyError:
2724 except KeyError:
2725 mod = None
2725 mod = None
2726 doc = extensions.disabledext(name)
2726 doc = extensions.disabledext(name)
2727 if not doc:
2727 if not doc:
2728 raise error.UnknownCommand(name)
2728 raise error.UnknownCommand(name)
2729
2729
2730 if '\n' not in doc:
2730 if '\n' not in doc:
2731 head, tail = doc, ""
2731 head, tail = doc, ""
2732 else:
2732 else:
2733 head, tail = doc.split('\n', 1)
2733 head, tail = doc.split('\n', 1)
2734 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
2734 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
2735 if tail:
2735 if tail:
2736 ui.write(minirst.format(tail, textwidth))
2736 ui.write(minirst.format(tail, textwidth))
2737 ui.status('\n\n')
2737 ui.status('\n\n')
2738
2738
2739 if mod:
2739 if mod:
2740 try:
2740 try:
2741 ct = mod.cmdtable
2741 ct = mod.cmdtable
2742 except AttributeError:
2742 except AttributeError:
2743 ct = {}
2743 ct = {}
2744 modcmds = set([c.split('|', 1)[0] for c in ct])
2744 modcmds = set([c.split('|', 1)[0] for c in ct])
2745 helplist(_('list of commands:\n\n'), modcmds.__contains__)
2745 helplist(_('list of commands:\n\n'), modcmds.__contains__)
2746 else:
2746 else:
2747 ui.write(_('use "hg help extensions" for information on enabling '
2747 ui.write(_('use "hg help extensions" for information on enabling '
2748 'extensions\n'))
2748 'extensions\n'))
2749
2749
2750 def helpextcmd(name):
2750 def helpextcmd(name):
2751 cmd, ext, mod = extensions.disabledcmd(ui, name, ui.config('ui', 'strict'))
2751 cmd, ext, mod = extensions.disabledcmd(ui, name, ui.config('ui', 'strict'))
2752 doc = gettext(mod.__doc__).splitlines()[0]
2752 doc = gettext(mod.__doc__).splitlines()[0]
2753
2753
2754 msg = help.listexts(_("'%s' is provided by the following "
2754 msg = help.listexts(_("'%s' is provided by the following "
2755 "extension:") % cmd, {ext: doc}, len(ext),
2755 "extension:") % cmd, {ext: doc}, indent=4)
2756 indent=4)
2757 ui.write(minirst.format(msg, textwidth))
2756 ui.write(minirst.format(msg, textwidth))
2758 ui.write('\n\n')
2757 ui.write('\n\n')
2759 ui.write(_('use "hg help extensions" for information on enabling '
2758 ui.write(_('use "hg help extensions" for information on enabling '
2760 'extensions\n'))
2759 'extensions\n'))
2761
2760
2762 help.addtopichook('revsets', revset.makedoc)
2761 help.addtopichook('revsets', revset.makedoc)
2763 help.addtopichook('templates', templatekw.makedoc)
2762 help.addtopichook('templates', templatekw.makedoc)
2764 help.addtopichook('templates', templatefilters.makedoc)
2763 help.addtopichook('templates', templatefilters.makedoc)
2765
2764
2766 if name and name != 'shortlist':
2765 if name and name != 'shortlist':
2767 i = None
2766 i = None
2768 if unknowncmd:
2767 if unknowncmd:
2769 queries = (helpextcmd,)
2768 queries = (helpextcmd,)
2770 elif opts.get('extension'):
2769 elif opts.get('extension'):
2771 queries = (helpext,)
2770 queries = (helpext,)
2772 elif opts.get('command'):
2771 elif opts.get('command'):
2773 queries = (helpcmd,)
2772 queries = (helpcmd,)
2774 else:
2773 else:
2775 queries = (helptopic, helpcmd, helpext, helpextcmd)
2774 queries = (helptopic, helpcmd, helpext, helpextcmd)
2776 for f in queries:
2775 for f in queries:
2777 try:
2776 try:
2778 f(name)
2777 f(name)
2779 i = None
2778 i = None
2780 break
2779 break
2781 except error.UnknownCommand, inst:
2780 except error.UnknownCommand, inst:
2782 i = inst
2781 i = inst
2783 if i:
2782 if i:
2784 raise i
2783 raise i
2785
2784
2786 else:
2785 else:
2787 # program name
2786 # program name
2788 if ui.verbose or with_version:
2787 if ui.verbose or with_version:
2789 version_(ui)
2788 version_(ui)
2790 else:
2789 else:
2791 ui.status(_("Mercurial Distributed SCM\n"))
2790 ui.status(_("Mercurial Distributed SCM\n"))
2792 ui.status('\n')
2791 ui.status('\n')
2793
2792
2794 # list of commands
2793 # list of commands
2795 if name == "shortlist":
2794 if name == "shortlist":
2796 header = _('basic commands:\n\n')
2795 header = _('basic commands:\n\n')
2797 else:
2796 else:
2798 header = _('list of commands:\n\n')
2797 header = _('list of commands:\n\n')
2799
2798
2800 helplist(header)
2799 helplist(header)
2801 if name != 'shortlist':
2800 if name != 'shortlist':
2802 exts, maxlength = extensions.enabled()
2801 text = help.listexts(_('enabled extensions:'), extensions.enabled())
2803 text = help.listexts(_('enabled extensions:'), exts, maxlength)
2804 if text:
2802 if text:
2805 ui.write("\n%s\n" % minirst.format(text, textwidth))
2803 ui.write("\n%s\n" % minirst.format(text, textwidth))
2806
2804
2807 # list all option lists
2805 # list all option lists
2808 opt_output = []
2806 opt_output = []
2809 multioccur = False
2807 multioccur = False
2810 for title, options in option_lists:
2808 for title, options in option_lists:
2811 opt_output.append(("\n%s" % title, None))
2809 opt_output.append(("\n%s" % title, None))
2812 for option in options:
2810 for option in options:
2813 if len(option) == 5:
2811 if len(option) == 5:
2814 shortopt, longopt, default, desc, optlabel = option
2812 shortopt, longopt, default, desc, optlabel = option
2815 else:
2813 else:
2816 shortopt, longopt, default, desc = option
2814 shortopt, longopt, default, desc = option
2817 optlabel = _("VALUE") # default label
2815 optlabel = _("VALUE") # default label
2818
2816
2819 if _("DEPRECATED") in desc and not ui.verbose:
2817 if _("DEPRECATED") in desc and not ui.verbose:
2820 continue
2818 continue
2821 if isinstance(default, list):
2819 if isinstance(default, list):
2822 numqualifier = " %s [+]" % optlabel
2820 numqualifier = " %s [+]" % optlabel
2823 multioccur = True
2821 multioccur = True
2824 elif (default is not None) and not isinstance(default, bool):
2822 elif (default is not None) and not isinstance(default, bool):
2825 numqualifier = " %s" % optlabel
2823 numqualifier = " %s" % optlabel
2826 else:
2824 else:
2827 numqualifier = ""
2825 numqualifier = ""
2828 opt_output.append(("%2s%s" %
2826 opt_output.append(("%2s%s" %
2829 (shortopt and "-%s" % shortopt,
2827 (shortopt and "-%s" % shortopt,
2830 longopt and " --%s%s" %
2828 longopt and " --%s%s" %
2831 (longopt, numqualifier)),
2829 (longopt, numqualifier)),
2832 "%s%s" % (desc,
2830 "%s%s" % (desc,
2833 default
2831 default
2834 and _(" (default: %s)") % default
2832 and _(" (default: %s)") % default
2835 or "")))
2833 or "")))
2836 if multioccur:
2834 if multioccur:
2837 msg = _("\n[+] marked option can be specified multiple times")
2835 msg = _("\n[+] marked option can be specified multiple times")
2838 if ui.verbose and name != 'shortlist':
2836 if ui.verbose and name != 'shortlist':
2839 opt_output.append((msg, None))
2837 opt_output.append((msg, None))
2840 else:
2838 else:
2841 opt_output.insert(-1, (msg, None))
2839 opt_output.insert(-1, (msg, None))
2842
2840
2843 if not name:
2841 if not name:
2844 ui.write(_("\nadditional help topics:\n\n"))
2842 ui.write(_("\nadditional help topics:\n\n"))
2845 topics = []
2843 topics = []
2846 for names, header, doc in help.helptable:
2844 for names, header, doc in help.helptable:
2847 topics.append((sorted(names, key=len, reverse=True)[0], header))
2845 topics.append((sorted(names, key=len, reverse=True)[0], header))
2848 topics_len = max([len(s[0]) for s in topics])
2846 topics_len = max([len(s[0]) for s in topics])
2849 for t, desc in topics:
2847 for t, desc in topics:
2850 ui.write(" %-*s %s\n" % (topics_len, t, desc))
2848 ui.write(" %-*s %s\n" % (topics_len, t, desc))
2851
2849
2852 if opt_output:
2850 if opt_output:
2853 colwidth = encoding.colwidth
2851 colwidth = encoding.colwidth
2854 # normalize: (opt or message, desc or None, width of opt)
2852 # normalize: (opt or message, desc or None, width of opt)
2855 entries = [desc and (opt, desc, colwidth(opt)) or (opt, None, 0)
2853 entries = [desc and (opt, desc, colwidth(opt)) or (opt, None, 0)
2856 for opt, desc in opt_output]
2854 for opt, desc in opt_output]
2857 hanging = max([e[2] for e in entries])
2855 hanging = max([e[2] for e in entries])
2858 for opt, desc, width in entries:
2856 for opt, desc, width in entries:
2859 if desc:
2857 if desc:
2860 initindent = ' %s%s ' % (opt, ' ' * (hanging - width))
2858 initindent = ' %s%s ' % (opt, ' ' * (hanging - width))
2861 hangindent = ' ' * (hanging + 3)
2859 hangindent = ' ' * (hanging + 3)
2862 ui.write('%s\n' % (util.wrap(desc, textwidth,
2860 ui.write('%s\n' % (util.wrap(desc, textwidth,
2863 initindent=initindent,
2861 initindent=initindent,
2864 hangindent=hangindent)))
2862 hangindent=hangindent)))
2865 else:
2863 else:
2866 ui.write("%s\n" % opt)
2864 ui.write("%s\n" % opt)
2867
2865
2868 @command('identify|id',
2866 @command('identify|id',
2869 [('r', 'rev', '',
2867 [('r', 'rev', '',
2870 _('identify the specified revision'), _('REV')),
2868 _('identify the specified revision'), _('REV')),
2871 ('n', 'num', None, _('show local revision number')),
2869 ('n', 'num', None, _('show local revision number')),
2872 ('i', 'id', None, _('show global revision id')),
2870 ('i', 'id', None, _('show global revision id')),
2873 ('b', 'branch', None, _('show branch')),
2871 ('b', 'branch', None, _('show branch')),
2874 ('t', 'tags', None, _('show tags')),
2872 ('t', 'tags', None, _('show tags')),
2875 ('B', 'bookmarks', None, _('show bookmarks'))],
2873 ('B', 'bookmarks', None, _('show bookmarks'))],
2876 _('[-nibtB] [-r REV] [SOURCE]'))
2874 _('[-nibtB] [-r REV] [SOURCE]'))
2877 def identify(ui, repo, source=None, rev=None,
2875 def identify(ui, repo, source=None, rev=None,
2878 num=None, id=None, branch=None, tags=None, bookmarks=None):
2876 num=None, id=None, branch=None, tags=None, bookmarks=None):
2879 """identify the working copy or specified revision
2877 """identify the working copy or specified revision
2880
2878
2881 Print a summary identifying the repository state at REV using one or
2879 Print a summary identifying the repository state at REV using one or
2882 two parent hash identifiers, followed by a "+" if the working
2880 two parent hash identifiers, followed by a "+" if the working
2883 directory has uncommitted changes, the branch name (if not default),
2881 directory has uncommitted changes, the branch name (if not default),
2884 a list of tags, and a list of bookmarks.
2882 a list of tags, and a list of bookmarks.
2885
2883
2886 When REV is not given, print a summary of the current state of the
2884 When REV is not given, print a summary of the current state of the
2887 repository.
2885 repository.
2888
2886
2889 Specifying a path to a repository root or Mercurial bundle will
2887 Specifying a path to a repository root or Mercurial bundle will
2890 cause lookup to operate on that repository/bundle.
2888 cause lookup to operate on that repository/bundle.
2891
2889
2892 Returns 0 if successful.
2890 Returns 0 if successful.
2893 """
2891 """
2894
2892
2895 if not repo and not source:
2893 if not repo and not source:
2896 raise util.Abort(_("there is no Mercurial repository here "
2894 raise util.Abort(_("there is no Mercurial repository here "
2897 "(.hg not found)"))
2895 "(.hg not found)"))
2898
2896
2899 hexfunc = ui.debugflag and hex or short
2897 hexfunc = ui.debugflag and hex or short
2900 default = not (num or id or branch or tags or bookmarks)
2898 default = not (num or id or branch or tags or bookmarks)
2901 output = []
2899 output = []
2902 revs = []
2900 revs = []
2903
2901
2904 if source:
2902 if source:
2905 source, branches = hg.parseurl(ui.expandpath(source))
2903 source, branches = hg.parseurl(ui.expandpath(source))
2906 repo = hg.repository(ui, source)
2904 repo = hg.repository(ui, source)
2907 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
2905 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
2908
2906
2909 if not repo.local():
2907 if not repo.local():
2910 if num or branch or tags:
2908 if num or branch or tags:
2911 raise util.Abort(
2909 raise util.Abort(
2912 _("can't query remote revision number, branch, or tags"))
2910 _("can't query remote revision number, branch, or tags"))
2913 if not rev and revs:
2911 if not rev and revs:
2914 rev = revs[0]
2912 rev = revs[0]
2915 if not rev:
2913 if not rev:
2916 rev = "tip"
2914 rev = "tip"
2917
2915
2918 remoterev = repo.lookup(rev)
2916 remoterev = repo.lookup(rev)
2919 if default or id:
2917 if default or id:
2920 output = [hexfunc(remoterev)]
2918 output = [hexfunc(remoterev)]
2921
2919
2922 def getbms():
2920 def getbms():
2923 bms = []
2921 bms = []
2924
2922
2925 if 'bookmarks' in repo.listkeys('namespaces'):
2923 if 'bookmarks' in repo.listkeys('namespaces'):
2926 hexremoterev = hex(remoterev)
2924 hexremoterev = hex(remoterev)
2927 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
2925 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
2928 if bmr == hexremoterev]
2926 if bmr == hexremoterev]
2929
2927
2930 return bms
2928 return bms
2931
2929
2932 if bookmarks:
2930 if bookmarks:
2933 output.extend(getbms())
2931 output.extend(getbms())
2934 elif default and not ui.quiet:
2932 elif default and not ui.quiet:
2935 # multiple bookmarks for a single parent separated by '/'
2933 # multiple bookmarks for a single parent separated by '/'
2936 bm = '/'.join(getbms())
2934 bm = '/'.join(getbms())
2937 if bm:
2935 if bm:
2938 output.append(bm)
2936 output.append(bm)
2939 else:
2937 else:
2940 if not rev:
2938 if not rev:
2941 ctx = repo[None]
2939 ctx = repo[None]
2942 parents = ctx.parents()
2940 parents = ctx.parents()
2943 changed = ""
2941 changed = ""
2944 if default or id or num:
2942 if default or id or num:
2945 changed = util.any(repo.status()) and "+" or ""
2943 changed = util.any(repo.status()) and "+" or ""
2946 if default or id:
2944 if default or id:
2947 output = ["%s%s" %
2945 output = ["%s%s" %
2948 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
2946 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
2949 if num:
2947 if num:
2950 output.append("%s%s" %
2948 output.append("%s%s" %
2951 ('+'.join([str(p.rev()) for p in parents]), changed))
2949 ('+'.join([str(p.rev()) for p in parents]), changed))
2952 else:
2950 else:
2953 ctx = cmdutil.revsingle(repo, rev)
2951 ctx = cmdutil.revsingle(repo, rev)
2954 if default or id:
2952 if default or id:
2955 output = [hexfunc(ctx.node())]
2953 output = [hexfunc(ctx.node())]
2956 if num:
2954 if num:
2957 output.append(str(ctx.rev()))
2955 output.append(str(ctx.rev()))
2958
2956
2959 if default and not ui.quiet:
2957 if default and not ui.quiet:
2960 b = ctx.branch()
2958 b = ctx.branch()
2961 if b != 'default':
2959 if b != 'default':
2962 output.append("(%s)" % b)
2960 output.append("(%s)" % b)
2963
2961
2964 # multiple tags for a single parent separated by '/'
2962 # multiple tags for a single parent separated by '/'
2965 t = '/'.join(ctx.tags())
2963 t = '/'.join(ctx.tags())
2966 if t:
2964 if t:
2967 output.append(t)
2965 output.append(t)
2968
2966
2969 # multiple bookmarks for a single parent separated by '/'
2967 # multiple bookmarks for a single parent separated by '/'
2970 bm = '/'.join(ctx.bookmarks())
2968 bm = '/'.join(ctx.bookmarks())
2971 if bm:
2969 if bm:
2972 output.append(bm)
2970 output.append(bm)
2973 else:
2971 else:
2974 if branch:
2972 if branch:
2975 output.append(ctx.branch())
2973 output.append(ctx.branch())
2976
2974
2977 if tags:
2975 if tags:
2978 output.extend(ctx.tags())
2976 output.extend(ctx.tags())
2979
2977
2980 if bookmarks:
2978 if bookmarks:
2981 output.extend(ctx.bookmarks())
2979 output.extend(ctx.bookmarks())
2982
2980
2983 ui.write("%s\n" % ' '.join(output))
2981 ui.write("%s\n" % ' '.join(output))
2984
2982
2985 @command('import|patch',
2983 @command('import|patch',
2986 [('p', 'strip', 1,
2984 [('p', 'strip', 1,
2987 _('directory strip option for patch. This has the same '
2985 _('directory strip option for patch. This has the same '
2988 'meaning as the corresponding patch option'), _('NUM')),
2986 'meaning as the corresponding patch option'), _('NUM')),
2989 ('b', 'base', '', _('base path'), _('PATH')),
2987 ('b', 'base', '', _('base path'), _('PATH')),
2990 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
2988 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
2991 ('', 'no-commit', None,
2989 ('', 'no-commit', None,
2992 _("don't commit, just update the working directory")),
2990 _("don't commit, just update the working directory")),
2993 ('', 'exact', None,
2991 ('', 'exact', None,
2994 _('apply patch to the nodes from which it was generated')),
2992 _('apply patch to the nodes from which it was generated')),
2995 ('', 'import-branch', None,
2993 ('', 'import-branch', None,
2996 _('use any branch information in patch (implied by --exact)'))] +
2994 _('use any branch information in patch (implied by --exact)'))] +
2997 commitopts + commitopts2 + similarityopts,
2995 commitopts + commitopts2 + similarityopts,
2998 _('[OPTION]... PATCH...'))
2996 _('[OPTION]... PATCH...'))
2999 def import_(ui, repo, patch1, *patches, **opts):
2997 def import_(ui, repo, patch1, *patches, **opts):
3000 """import an ordered set of patches
2998 """import an ordered set of patches
3001
2999
3002 Import a list of patches and commit them individually (unless
3000 Import a list of patches and commit them individually (unless
3003 --no-commit is specified).
3001 --no-commit is specified).
3004
3002
3005 If there are outstanding changes in the working directory, import
3003 If there are outstanding changes in the working directory, import
3006 will abort unless given the -f/--force flag.
3004 will abort unless given the -f/--force flag.
3007
3005
3008 You can import a patch straight from a mail message. Even patches
3006 You can import a patch straight from a mail message. Even patches
3009 as attachments work (to use the body part, it must have type
3007 as attachments work (to use the body part, it must have type
3010 text/plain or text/x-patch). From and Subject headers of email
3008 text/plain or text/x-patch). From and Subject headers of email
3011 message are used as default committer and commit message. All
3009 message are used as default committer and commit message. All
3012 text/plain body parts before first diff are added to commit
3010 text/plain body parts before first diff are added to commit
3013 message.
3011 message.
3014
3012
3015 If the imported patch was generated by :hg:`export`, user and
3013 If the imported patch was generated by :hg:`export`, user and
3016 description from patch override values from message headers and
3014 description from patch override values from message headers and
3017 body. Values given on command line with -m/--message and -u/--user
3015 body. Values given on command line with -m/--message and -u/--user
3018 override these.
3016 override these.
3019
3017
3020 If --exact is specified, import will set the working directory to
3018 If --exact is specified, import will set the working directory to
3021 the parent of each patch before applying it, and will abort if the
3019 the parent of each patch before applying it, and will abort if the
3022 resulting changeset has a different ID than the one recorded in
3020 resulting changeset has a different ID than the one recorded in
3023 the patch. This may happen due to character set problems or other
3021 the patch. This may happen due to character set problems or other
3024 deficiencies in the text patch format.
3022 deficiencies in the text patch format.
3025
3023
3026 With -s/--similarity, hg will attempt to discover renames and
3024 With -s/--similarity, hg will attempt to discover renames and
3027 copies in the patch in the same way as 'addremove'.
3025 copies in the patch in the same way as 'addremove'.
3028
3026
3029 To read a patch from standard input, use "-" as the patch name. If
3027 To read a patch from standard input, use "-" as the patch name. If
3030 a URL is specified, the patch will be downloaded from it.
3028 a URL is specified, the patch will be downloaded from it.
3031 See :hg:`help dates` for a list of formats valid for -d/--date.
3029 See :hg:`help dates` for a list of formats valid for -d/--date.
3032
3030
3033 Returns 0 on success.
3031 Returns 0 on success.
3034 """
3032 """
3035 patches = (patch1,) + patches
3033 patches = (patch1,) + patches
3036
3034
3037 date = opts.get('date')
3035 date = opts.get('date')
3038 if date:
3036 if date:
3039 opts['date'] = util.parsedate(date)
3037 opts['date'] = util.parsedate(date)
3040
3038
3041 try:
3039 try:
3042 sim = float(opts.get('similarity') or 0)
3040 sim = float(opts.get('similarity') or 0)
3043 except ValueError:
3041 except ValueError:
3044 raise util.Abort(_('similarity must be a number'))
3042 raise util.Abort(_('similarity must be a number'))
3045 if sim < 0 or sim > 100:
3043 if sim < 0 or sim > 100:
3046 raise util.Abort(_('similarity must be between 0 and 100'))
3044 raise util.Abort(_('similarity must be between 0 and 100'))
3047
3045
3048 if opts.get('exact') or not opts.get('force'):
3046 if opts.get('exact') or not opts.get('force'):
3049 cmdutil.bailifchanged(repo)
3047 cmdutil.bailifchanged(repo)
3050
3048
3051 d = opts["base"]
3049 d = opts["base"]
3052 strip = opts["strip"]
3050 strip = opts["strip"]
3053 wlock = lock = None
3051 wlock = lock = None
3054 msgs = []
3052 msgs = []
3055
3053
3056 def tryone(ui, hunk):
3054 def tryone(ui, hunk):
3057 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3055 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3058 patch.extract(ui, hunk)
3056 patch.extract(ui, hunk)
3059
3057
3060 if not tmpname:
3058 if not tmpname:
3061 return None
3059 return None
3062 commitid = _('to working directory')
3060 commitid = _('to working directory')
3063
3061
3064 try:
3062 try:
3065 cmdline_message = cmdutil.logmessage(opts)
3063 cmdline_message = cmdutil.logmessage(opts)
3066 if cmdline_message:
3064 if cmdline_message:
3067 # pickup the cmdline msg
3065 # pickup the cmdline msg
3068 message = cmdline_message
3066 message = cmdline_message
3069 elif message:
3067 elif message:
3070 # pickup the patch msg
3068 # pickup the patch msg
3071 message = message.strip()
3069 message = message.strip()
3072 else:
3070 else:
3073 # launch the editor
3071 # launch the editor
3074 message = None
3072 message = None
3075 ui.debug('message:\n%s\n' % message)
3073 ui.debug('message:\n%s\n' % message)
3076
3074
3077 wp = repo.parents()
3075 wp = repo.parents()
3078 if opts.get('exact'):
3076 if opts.get('exact'):
3079 if not nodeid or not p1:
3077 if not nodeid or not p1:
3080 raise util.Abort(_('not a Mercurial patch'))
3078 raise util.Abort(_('not a Mercurial patch'))
3081 p1 = repo.lookup(p1)
3079 p1 = repo.lookup(p1)
3082 p2 = repo.lookup(p2 or hex(nullid))
3080 p2 = repo.lookup(p2 or hex(nullid))
3083
3081
3084 if p1 != wp[0].node():
3082 if p1 != wp[0].node():
3085 hg.clean(repo, p1)
3083 hg.clean(repo, p1)
3086 repo.dirstate.setparents(p1, p2)
3084 repo.dirstate.setparents(p1, p2)
3087 elif p2:
3085 elif p2:
3088 try:
3086 try:
3089 p1 = repo.lookup(p1)
3087 p1 = repo.lookup(p1)
3090 p2 = repo.lookup(p2)
3088 p2 = repo.lookup(p2)
3091 if p1 == wp[0].node():
3089 if p1 == wp[0].node():
3092 repo.dirstate.setparents(p1, p2)
3090 repo.dirstate.setparents(p1, p2)
3093 except error.RepoError:
3091 except error.RepoError:
3094 pass
3092 pass
3095 if opts.get('exact') or opts.get('import_branch'):
3093 if opts.get('exact') or opts.get('import_branch'):
3096 repo.dirstate.setbranch(branch or 'default')
3094 repo.dirstate.setbranch(branch or 'default')
3097
3095
3098 files = {}
3096 files = {}
3099 patch.patch(ui, repo, tmpname, strip=strip, cwd=repo.root,
3097 patch.patch(ui, repo, tmpname, strip=strip, cwd=repo.root,
3100 files=files, eolmode=None, similarity=sim / 100.0)
3098 files=files, eolmode=None, similarity=sim / 100.0)
3101 files = list(files)
3099 files = list(files)
3102 if opts.get('no_commit'):
3100 if opts.get('no_commit'):
3103 if message:
3101 if message:
3104 msgs.append(message)
3102 msgs.append(message)
3105 else:
3103 else:
3106 if opts.get('exact'):
3104 if opts.get('exact'):
3107 m = None
3105 m = None
3108 else:
3106 else:
3109 m = cmdutil.matchfiles(repo, files or [])
3107 m = cmdutil.matchfiles(repo, files or [])
3110 n = repo.commit(message, opts.get('user') or user,
3108 n = repo.commit(message, opts.get('user') or user,
3111 opts.get('date') or date, match=m,
3109 opts.get('date') or date, match=m,
3112 editor=cmdutil.commiteditor)
3110 editor=cmdutil.commiteditor)
3113 if opts.get('exact'):
3111 if opts.get('exact'):
3114 if hex(n) != nodeid:
3112 if hex(n) != nodeid:
3115 repo.rollback()
3113 repo.rollback()
3116 raise util.Abort(_('patch is damaged'
3114 raise util.Abort(_('patch is damaged'
3117 ' or loses information'))
3115 ' or loses information'))
3118 # Force a dirstate write so that the next transaction
3116 # Force a dirstate write so that the next transaction
3119 # backups an up-do-date file.
3117 # backups an up-do-date file.
3120 repo.dirstate.write()
3118 repo.dirstate.write()
3121 if n:
3119 if n:
3122 commitid = short(n)
3120 commitid = short(n)
3123
3121
3124 return commitid
3122 return commitid
3125 finally:
3123 finally:
3126 os.unlink(tmpname)
3124 os.unlink(tmpname)
3127
3125
3128 try:
3126 try:
3129 wlock = repo.wlock()
3127 wlock = repo.wlock()
3130 lock = repo.lock()
3128 lock = repo.lock()
3131 lastcommit = None
3129 lastcommit = None
3132 for p in patches:
3130 for p in patches:
3133 pf = os.path.join(d, p)
3131 pf = os.path.join(d, p)
3134
3132
3135 if pf == '-':
3133 if pf == '-':
3136 ui.status(_("applying patch from stdin\n"))
3134 ui.status(_("applying patch from stdin\n"))
3137 pf = sys.stdin
3135 pf = sys.stdin
3138 else:
3136 else:
3139 ui.status(_("applying %s\n") % p)
3137 ui.status(_("applying %s\n") % p)
3140 pf = url.open(ui, pf)
3138 pf = url.open(ui, pf)
3141
3139
3142 haspatch = False
3140 haspatch = False
3143 for hunk in patch.split(pf):
3141 for hunk in patch.split(pf):
3144 commitid = tryone(ui, hunk)
3142 commitid = tryone(ui, hunk)
3145 if commitid:
3143 if commitid:
3146 haspatch = True
3144 haspatch = True
3147 if lastcommit:
3145 if lastcommit:
3148 ui.status(_('applied %s\n') % lastcommit)
3146 ui.status(_('applied %s\n') % lastcommit)
3149 lastcommit = commitid
3147 lastcommit = commitid
3150
3148
3151 if not haspatch:
3149 if not haspatch:
3152 raise util.Abort(_('no diffs found'))
3150 raise util.Abort(_('no diffs found'))
3153
3151
3154 if msgs:
3152 if msgs:
3155 repo.opener.write('last-message.txt', '\n* * *\n'.join(msgs))
3153 repo.opener.write('last-message.txt', '\n* * *\n'.join(msgs))
3156 finally:
3154 finally:
3157 release(lock, wlock)
3155 release(lock, wlock)
3158
3156
3159 @command('incoming|in',
3157 @command('incoming|in',
3160 [('f', 'force', None,
3158 [('f', 'force', None,
3161 _('run even if remote repository is unrelated')),
3159 _('run even if remote repository is unrelated')),
3162 ('n', 'newest-first', None, _('show newest record first')),
3160 ('n', 'newest-first', None, _('show newest record first')),
3163 ('', 'bundle', '',
3161 ('', 'bundle', '',
3164 _('file to store the bundles into'), _('FILE')),
3162 _('file to store the bundles into'), _('FILE')),
3165 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3163 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3166 ('B', 'bookmarks', False, _("compare bookmarks")),
3164 ('B', 'bookmarks', False, _("compare bookmarks")),
3167 ('b', 'branch', [],
3165 ('b', 'branch', [],
3168 _('a specific branch you would like to pull'), _('BRANCH')),
3166 _('a specific branch you would like to pull'), _('BRANCH')),
3169 ] + logopts + remoteopts + subrepoopts,
3167 ] + logopts + remoteopts + subrepoopts,
3170 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3168 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3171 def incoming(ui, repo, source="default", **opts):
3169 def incoming(ui, repo, source="default", **opts):
3172 """show new changesets found in source
3170 """show new changesets found in source
3173
3171
3174 Show new changesets found in the specified path/URL or the default
3172 Show new changesets found in the specified path/URL or the default
3175 pull location. These are the changesets that would have been pulled
3173 pull location. These are the changesets that would have been pulled
3176 if a pull at the time you issued this command.
3174 if a pull at the time you issued this command.
3177
3175
3178 For remote repository, using --bundle avoids downloading the
3176 For remote repository, using --bundle avoids downloading the
3179 changesets twice if the incoming is followed by a pull.
3177 changesets twice if the incoming is followed by a pull.
3180
3178
3181 See pull for valid source format details.
3179 See pull for valid source format details.
3182
3180
3183 Returns 0 if there are incoming changes, 1 otherwise.
3181 Returns 0 if there are incoming changes, 1 otherwise.
3184 """
3182 """
3185 if opts.get('bundle') and opts.get('subrepos'):
3183 if opts.get('bundle') and opts.get('subrepos'):
3186 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3184 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3187
3185
3188 if opts.get('bookmarks'):
3186 if opts.get('bookmarks'):
3189 source, branches = hg.parseurl(ui.expandpath(source),
3187 source, branches = hg.parseurl(ui.expandpath(source),
3190 opts.get('branch'))
3188 opts.get('branch'))
3191 other = hg.repository(hg.remoteui(repo, opts), source)
3189 other = hg.repository(hg.remoteui(repo, opts), source)
3192 if 'bookmarks' not in other.listkeys('namespaces'):
3190 if 'bookmarks' not in other.listkeys('namespaces'):
3193 ui.warn(_("remote doesn't support bookmarks\n"))
3191 ui.warn(_("remote doesn't support bookmarks\n"))
3194 return 0
3192 return 0
3195 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3193 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3196 return bookmarks.diff(ui, repo, other)
3194 return bookmarks.diff(ui, repo, other)
3197
3195
3198 ret = hg.incoming(ui, repo, source, opts)
3196 ret = hg.incoming(ui, repo, source, opts)
3199 return ret
3197 return ret
3200
3198
3201 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3199 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3202 def init(ui, dest=".", **opts):
3200 def init(ui, dest=".", **opts):
3203 """create a new repository in the given directory
3201 """create a new repository in the given directory
3204
3202
3205 Initialize a new repository in the given directory. If the given
3203 Initialize a new repository in the given directory. If the given
3206 directory does not exist, it will be created.
3204 directory does not exist, it will be created.
3207
3205
3208 If no directory is given, the current directory is used.
3206 If no directory is given, the current directory is used.
3209
3207
3210 It is possible to specify an ``ssh://`` URL as the destination.
3208 It is possible to specify an ``ssh://`` URL as the destination.
3211 See :hg:`help urls` for more information.
3209 See :hg:`help urls` for more information.
3212
3210
3213 Returns 0 on success.
3211 Returns 0 on success.
3214 """
3212 """
3215 hg.repository(hg.remoteui(ui, opts), ui.expandpath(dest), create=1)
3213 hg.repository(hg.remoteui(ui, opts), ui.expandpath(dest), create=1)
3216
3214
3217 @command('locate',
3215 @command('locate',
3218 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3216 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3219 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3217 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3220 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3218 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3221 ] + walkopts,
3219 ] + walkopts,
3222 _('[OPTION]... [PATTERN]...'))
3220 _('[OPTION]... [PATTERN]...'))
3223 def locate(ui, repo, *pats, **opts):
3221 def locate(ui, repo, *pats, **opts):
3224 """locate files matching specific patterns
3222 """locate files matching specific patterns
3225
3223
3226 Print files under Mercurial control in the working directory whose
3224 Print files under Mercurial control in the working directory whose
3227 names match the given patterns.
3225 names match the given patterns.
3228
3226
3229 By default, this command searches all directories in the working
3227 By default, this command searches all directories in the working
3230 directory. To search just the current directory and its
3228 directory. To search just the current directory and its
3231 subdirectories, use "--include .".
3229 subdirectories, use "--include .".
3232
3230
3233 If no patterns are given to match, this command prints the names
3231 If no patterns are given to match, this command prints the names
3234 of all files under Mercurial control in the working directory.
3232 of all files under Mercurial control in the working directory.
3235
3233
3236 If you want to feed the output of this command into the "xargs"
3234 If you want to feed the output of this command into the "xargs"
3237 command, use the -0 option to both this command and "xargs". This
3235 command, use the -0 option to both this command and "xargs". This
3238 will avoid the problem of "xargs" treating single filenames that
3236 will avoid the problem of "xargs" treating single filenames that
3239 contain whitespace as multiple filenames.
3237 contain whitespace as multiple filenames.
3240
3238
3241 Returns 0 if a match is found, 1 otherwise.
3239 Returns 0 if a match is found, 1 otherwise.
3242 """
3240 """
3243 end = opts.get('print0') and '\0' or '\n'
3241 end = opts.get('print0') and '\0' or '\n'
3244 rev = cmdutil.revsingle(repo, opts.get('rev'), None).node()
3242 rev = cmdutil.revsingle(repo, opts.get('rev'), None).node()
3245
3243
3246 ret = 1
3244 ret = 1
3247 m = cmdutil.match(repo, pats, opts, default='relglob')
3245 m = cmdutil.match(repo, pats, opts, default='relglob')
3248 m.bad = lambda x, y: False
3246 m.bad = lambda x, y: False
3249 for abs in repo[rev].walk(m):
3247 for abs in repo[rev].walk(m):
3250 if not rev and abs not in repo.dirstate:
3248 if not rev and abs not in repo.dirstate:
3251 continue
3249 continue
3252 if opts.get('fullpath'):
3250 if opts.get('fullpath'):
3253 ui.write(repo.wjoin(abs), end)
3251 ui.write(repo.wjoin(abs), end)
3254 else:
3252 else:
3255 ui.write(((pats and m.rel(abs)) or abs), end)
3253 ui.write(((pats and m.rel(abs)) or abs), end)
3256 ret = 0
3254 ret = 0
3257
3255
3258 return ret
3256 return ret
3259
3257
3260 @command('^log|history',
3258 @command('^log|history',
3261 [('f', 'follow', None,
3259 [('f', 'follow', None,
3262 _('follow changeset history, or file history across copies and renames')),
3260 _('follow changeset history, or file history across copies and renames')),
3263 ('', 'follow-first', None,
3261 ('', 'follow-first', None,
3264 _('only follow the first parent of merge changesets')),
3262 _('only follow the first parent of merge changesets')),
3265 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3263 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3266 ('C', 'copies', None, _('show copied files')),
3264 ('C', 'copies', None, _('show copied files')),
3267 ('k', 'keyword', [],
3265 ('k', 'keyword', [],
3268 _('do case-insensitive search for a given text'), _('TEXT')),
3266 _('do case-insensitive search for a given text'), _('TEXT')),
3269 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3267 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3270 ('', 'removed', None, _('include revisions where files were removed')),
3268 ('', 'removed', None, _('include revisions where files were removed')),
3271 ('m', 'only-merges', None, _('show only merges')),
3269 ('m', 'only-merges', None, _('show only merges')),
3272 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3270 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3273 ('', 'only-branch', [],
3271 ('', 'only-branch', [],
3274 _('show only changesets within the given named branch (DEPRECATED)'),
3272 _('show only changesets within the given named branch (DEPRECATED)'),
3275 _('BRANCH')),
3273 _('BRANCH')),
3276 ('b', 'branch', [],
3274 ('b', 'branch', [],
3277 _('show changesets within the given named branch'), _('BRANCH')),
3275 _('show changesets within the given named branch'), _('BRANCH')),
3278 ('P', 'prune', [],
3276 ('P', 'prune', [],
3279 _('do not display revision or any of its ancestors'), _('REV')),
3277 _('do not display revision or any of its ancestors'), _('REV')),
3280 ] + logopts + walkopts,
3278 ] + logopts + walkopts,
3281 _('[OPTION]... [FILE]'))
3279 _('[OPTION]... [FILE]'))
3282 def log(ui, repo, *pats, **opts):
3280 def log(ui, repo, *pats, **opts):
3283 """show revision history of entire repository or files
3281 """show revision history of entire repository or files
3284
3282
3285 Print the revision history of the specified files or the entire
3283 Print the revision history of the specified files or the entire
3286 project.
3284 project.
3287
3285
3288 File history is shown without following rename or copy history of
3286 File history is shown without following rename or copy history of
3289 files. Use -f/--follow with a filename to follow history across
3287 files. Use -f/--follow with a filename to follow history across
3290 renames and copies. --follow without a filename will only show
3288 renames and copies. --follow without a filename will only show
3291 ancestors or descendants of the starting revision. --follow-first
3289 ancestors or descendants of the starting revision. --follow-first
3292 only follows the first parent of merge revisions.
3290 only follows the first parent of merge revisions.
3293
3291
3294 If no revision range is specified, the default is ``tip:0`` unless
3292 If no revision range is specified, the default is ``tip:0`` unless
3295 --follow is set, in which case the working directory parent is
3293 --follow is set, in which case the working directory parent is
3296 used as the starting revision. You can specify a revision set for
3294 used as the starting revision. You can specify a revision set for
3297 log, see :hg:`help revsets` for more information.
3295 log, see :hg:`help revsets` for more information.
3298
3296
3299 See :hg:`help dates` for a list of formats valid for -d/--date.
3297 See :hg:`help dates` for a list of formats valid for -d/--date.
3300
3298
3301 By default this command prints revision number and changeset id,
3299 By default this command prints revision number and changeset id,
3302 tags, non-trivial parents, user, date and time, and a summary for
3300 tags, non-trivial parents, user, date and time, and a summary for
3303 each commit. When the -v/--verbose switch is used, the list of
3301 each commit. When the -v/--verbose switch is used, the list of
3304 changed files and full commit message are shown.
3302 changed files and full commit message are shown.
3305
3303
3306 .. note::
3304 .. note::
3307 log -p/--patch may generate unexpected diff output for merge
3305 log -p/--patch may generate unexpected diff output for merge
3308 changesets, as it will only compare the merge changeset against
3306 changesets, as it will only compare the merge changeset against
3309 its first parent. Also, only files different from BOTH parents
3307 its first parent. Also, only files different from BOTH parents
3310 will appear in files:.
3308 will appear in files:.
3311
3309
3312 Returns 0 on success.
3310 Returns 0 on success.
3313 """
3311 """
3314
3312
3315 matchfn = cmdutil.match(repo, pats, opts)
3313 matchfn = cmdutil.match(repo, pats, opts)
3316 limit = cmdutil.loglimit(opts)
3314 limit = cmdutil.loglimit(opts)
3317 count = 0
3315 count = 0
3318
3316
3319 endrev = None
3317 endrev = None
3320 if opts.get('copies') and opts.get('rev'):
3318 if opts.get('copies') and opts.get('rev'):
3321 endrev = max(cmdutil.revrange(repo, opts.get('rev'))) + 1
3319 endrev = max(cmdutil.revrange(repo, opts.get('rev'))) + 1
3322
3320
3323 df = False
3321 df = False
3324 if opts["date"]:
3322 if opts["date"]:
3325 df = util.matchdate(opts["date"])
3323 df = util.matchdate(opts["date"])
3326
3324
3327 branches = opts.get('branch', []) + opts.get('only_branch', [])
3325 branches = opts.get('branch', []) + opts.get('only_branch', [])
3328 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3326 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3329
3327
3330 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3328 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3331 def prep(ctx, fns):
3329 def prep(ctx, fns):
3332 rev = ctx.rev()
3330 rev = ctx.rev()
3333 parents = [p for p in repo.changelog.parentrevs(rev)
3331 parents = [p for p in repo.changelog.parentrevs(rev)
3334 if p != nullrev]
3332 if p != nullrev]
3335 if opts.get('no_merges') and len(parents) == 2:
3333 if opts.get('no_merges') and len(parents) == 2:
3336 return
3334 return
3337 if opts.get('only_merges') and len(parents) != 2:
3335 if opts.get('only_merges') and len(parents) != 2:
3338 return
3336 return
3339 if opts.get('branch') and ctx.branch() not in opts['branch']:
3337 if opts.get('branch') and ctx.branch() not in opts['branch']:
3340 return
3338 return
3341 if df and not df(ctx.date()[0]):
3339 if df and not df(ctx.date()[0]):
3342 return
3340 return
3343 if opts['user'] and not [k for k in opts['user']
3341 if opts['user'] and not [k for k in opts['user']
3344 if k.lower() in ctx.user().lower()]:
3342 if k.lower() in ctx.user().lower()]:
3345 return
3343 return
3346 if opts.get('keyword'):
3344 if opts.get('keyword'):
3347 for k in [kw.lower() for kw in opts['keyword']]:
3345 for k in [kw.lower() for kw in opts['keyword']]:
3348 if (k in ctx.user().lower() or
3346 if (k in ctx.user().lower() or
3349 k in ctx.description().lower() or
3347 k in ctx.description().lower() or
3350 k in " ".join(ctx.files()).lower()):
3348 k in " ".join(ctx.files()).lower()):
3351 break
3349 break
3352 else:
3350 else:
3353 return
3351 return
3354
3352
3355 copies = None
3353 copies = None
3356 if opts.get('copies') and rev:
3354 if opts.get('copies') and rev:
3357 copies = []
3355 copies = []
3358 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3356 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3359 for fn in ctx.files():
3357 for fn in ctx.files():
3360 rename = getrenamed(fn, rev)
3358 rename = getrenamed(fn, rev)
3361 if rename:
3359 if rename:
3362 copies.append((fn, rename[0]))
3360 copies.append((fn, rename[0]))
3363
3361
3364 revmatchfn = None
3362 revmatchfn = None
3365 if opts.get('patch') or opts.get('stat'):
3363 if opts.get('patch') or opts.get('stat'):
3366 if opts.get('follow') or opts.get('follow_first'):
3364 if opts.get('follow') or opts.get('follow_first'):
3367 # note: this might be wrong when following through merges
3365 # note: this might be wrong when following through merges
3368 revmatchfn = cmdutil.match(repo, fns, default='path')
3366 revmatchfn = cmdutil.match(repo, fns, default='path')
3369 else:
3367 else:
3370 revmatchfn = matchfn
3368 revmatchfn = matchfn
3371
3369
3372 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3370 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3373
3371
3374 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3372 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3375 if count == limit:
3373 if count == limit:
3376 break
3374 break
3377 if displayer.flush(ctx.rev()):
3375 if displayer.flush(ctx.rev()):
3378 count += 1
3376 count += 1
3379 displayer.close()
3377 displayer.close()
3380
3378
3381 @command('manifest',
3379 @command('manifest',
3382 [('r', 'rev', '', _('revision to display'), _('REV'))],
3380 [('r', 'rev', '', _('revision to display'), _('REV'))],
3383 _('[-r REV]'))
3381 _('[-r REV]'))
3384 def manifest(ui, repo, node=None, rev=None):
3382 def manifest(ui, repo, node=None, rev=None):
3385 """output the current or given revision of the project manifest
3383 """output the current or given revision of the project manifest
3386
3384
3387 Print a list of version controlled files for the given revision.
3385 Print a list of version controlled files for the given revision.
3388 If no revision is given, the first parent of the working directory
3386 If no revision is given, the first parent of the working directory
3389 is used, or the null revision if no revision is checked out.
3387 is used, or the null revision if no revision is checked out.
3390
3388
3391 With -v, print file permissions, symlink and executable bits.
3389 With -v, print file permissions, symlink and executable bits.
3392 With --debug, print file revision hashes.
3390 With --debug, print file revision hashes.
3393
3391
3394 Returns 0 on success.
3392 Returns 0 on success.
3395 """
3393 """
3396
3394
3397 if rev and node:
3395 if rev and node:
3398 raise util.Abort(_("please specify just one revision"))
3396 raise util.Abort(_("please specify just one revision"))
3399
3397
3400 if not node:
3398 if not node:
3401 node = rev
3399 node = rev
3402
3400
3403 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3401 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3404 ctx = cmdutil.revsingle(repo, node)
3402 ctx = cmdutil.revsingle(repo, node)
3405 for f in ctx:
3403 for f in ctx:
3406 if ui.debugflag:
3404 if ui.debugflag:
3407 ui.write("%40s " % hex(ctx.manifest()[f]))
3405 ui.write("%40s " % hex(ctx.manifest()[f]))
3408 if ui.verbose:
3406 if ui.verbose:
3409 ui.write(decor[ctx.flags(f)])
3407 ui.write(decor[ctx.flags(f)])
3410 ui.write("%s\n" % f)
3408 ui.write("%s\n" % f)
3411
3409
3412 @command('^merge',
3410 @command('^merge',
3413 [('f', 'force', None, _('force a merge with outstanding changes')),
3411 [('f', 'force', None, _('force a merge with outstanding changes')),
3414 ('t', 'tool', '', _('specify merge tool')),
3412 ('t', 'tool', '', _('specify merge tool')),
3415 ('r', 'rev', '', _('revision to merge'), _('REV')),
3413 ('r', 'rev', '', _('revision to merge'), _('REV')),
3416 ('P', 'preview', None,
3414 ('P', 'preview', None,
3417 _('review revisions to merge (no merge is performed)'))],
3415 _('review revisions to merge (no merge is performed)'))],
3418 _('[-P] [-f] [[-r] REV]'))
3416 _('[-P] [-f] [[-r] REV]'))
3419 def merge(ui, repo, node=None, **opts):
3417 def merge(ui, repo, node=None, **opts):
3420 """merge working directory with another revision
3418 """merge working directory with another revision
3421
3419
3422 The current working directory is updated with all changes made in
3420 The current working directory is updated with all changes made in
3423 the requested revision since the last common predecessor revision.
3421 the requested revision since the last common predecessor revision.
3424
3422
3425 Files that changed between either parent are marked as changed for
3423 Files that changed between either parent are marked as changed for
3426 the next commit and a commit must be performed before any further
3424 the next commit and a commit must be performed before any further
3427 updates to the repository are allowed. The next commit will have
3425 updates to the repository are allowed. The next commit will have
3428 two parents.
3426 two parents.
3429
3427
3430 ``--tool`` can be used to specify the merge tool used for file
3428 ``--tool`` can be used to specify the merge tool used for file
3431 merges. It overrides the HGMERGE environment variable and your
3429 merges. It overrides the HGMERGE environment variable and your
3432 configuration files. See :hg:`help merge-tools` for options.
3430 configuration files. See :hg:`help merge-tools` for options.
3433
3431
3434 If no revision is specified, the working directory's parent is a
3432 If no revision is specified, the working directory's parent is a
3435 head revision, and the current branch contains exactly one other
3433 head revision, and the current branch contains exactly one other
3436 head, the other head is merged with by default. Otherwise, an
3434 head, the other head is merged with by default. Otherwise, an
3437 explicit revision with which to merge with must be provided.
3435 explicit revision with which to merge with must be provided.
3438
3436
3439 :hg:`resolve` must be used to resolve unresolved files.
3437 :hg:`resolve` must be used to resolve unresolved files.
3440
3438
3441 To undo an uncommitted merge, use :hg:`update --clean .` which
3439 To undo an uncommitted merge, use :hg:`update --clean .` which
3442 will check out a clean copy of the original merge parent, losing
3440 will check out a clean copy of the original merge parent, losing
3443 all changes.
3441 all changes.
3444
3442
3445 Returns 0 on success, 1 if there are unresolved files.
3443 Returns 0 on success, 1 if there are unresolved files.
3446 """
3444 """
3447
3445
3448 if opts.get('rev') and node:
3446 if opts.get('rev') and node:
3449 raise util.Abort(_("please specify just one revision"))
3447 raise util.Abort(_("please specify just one revision"))
3450 if not node:
3448 if not node:
3451 node = opts.get('rev')
3449 node = opts.get('rev')
3452
3450
3453 if not node:
3451 if not node:
3454 branch = repo[None].branch()
3452 branch = repo[None].branch()
3455 bheads = repo.branchheads(branch)
3453 bheads = repo.branchheads(branch)
3456 if len(bheads) > 2:
3454 if len(bheads) > 2:
3457 raise util.Abort(_("branch '%s' has %d heads - "
3455 raise util.Abort(_("branch '%s' has %d heads - "
3458 "please merge with an explicit rev")
3456 "please merge with an explicit rev")
3459 % (branch, len(bheads)),
3457 % (branch, len(bheads)),
3460 hint=_("run 'hg heads .' to see heads"))
3458 hint=_("run 'hg heads .' to see heads"))
3461
3459
3462 parent = repo.dirstate.p1()
3460 parent = repo.dirstate.p1()
3463 if len(bheads) == 1:
3461 if len(bheads) == 1:
3464 if len(repo.heads()) > 1:
3462 if len(repo.heads()) > 1:
3465 raise util.Abort(_("branch '%s' has one head - "
3463 raise util.Abort(_("branch '%s' has one head - "
3466 "please merge with an explicit rev")
3464 "please merge with an explicit rev")
3467 % branch,
3465 % branch,
3468 hint=_("run 'hg heads' to see all heads"))
3466 hint=_("run 'hg heads' to see all heads"))
3469 msg = _('there is nothing to merge')
3467 msg = _('there is nothing to merge')
3470 if parent != repo.lookup(repo[None].branch()):
3468 if parent != repo.lookup(repo[None].branch()):
3471 msg = _('%s - use "hg update" instead') % msg
3469 msg = _('%s - use "hg update" instead') % msg
3472 raise util.Abort(msg)
3470 raise util.Abort(msg)
3473
3471
3474 if parent not in bheads:
3472 if parent not in bheads:
3475 raise util.Abort(_('working directory not at a head revision'),
3473 raise util.Abort(_('working directory not at a head revision'),
3476 hint=_("use 'hg update' or merge with an "
3474 hint=_("use 'hg update' or merge with an "
3477 "explicit revision"))
3475 "explicit revision"))
3478 node = parent == bheads[0] and bheads[-1] or bheads[0]
3476 node = parent == bheads[0] and bheads[-1] or bheads[0]
3479 else:
3477 else:
3480 node = cmdutil.revsingle(repo, node).node()
3478 node = cmdutil.revsingle(repo, node).node()
3481
3479
3482 if opts.get('preview'):
3480 if opts.get('preview'):
3483 # find nodes that are ancestors of p2 but not of p1
3481 # find nodes that are ancestors of p2 but not of p1
3484 p1 = repo.lookup('.')
3482 p1 = repo.lookup('.')
3485 p2 = repo.lookup(node)
3483 p2 = repo.lookup(node)
3486 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3484 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3487
3485
3488 displayer = cmdutil.show_changeset(ui, repo, opts)
3486 displayer = cmdutil.show_changeset(ui, repo, opts)
3489 for node in nodes:
3487 for node in nodes:
3490 displayer.show(repo[node])
3488 displayer.show(repo[node])
3491 displayer.close()
3489 displayer.close()
3492 return 0
3490 return 0
3493
3491
3494 try:
3492 try:
3495 # ui.forcemerge is an internal variable, do not document
3493 # ui.forcemerge is an internal variable, do not document
3496 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
3494 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
3497 return hg.merge(repo, node, force=opts.get('force'))
3495 return hg.merge(repo, node, force=opts.get('force'))
3498 finally:
3496 finally:
3499 ui.setconfig('ui', 'forcemerge', '')
3497 ui.setconfig('ui', 'forcemerge', '')
3500
3498
3501 @command('outgoing|out',
3499 @command('outgoing|out',
3502 [('f', 'force', None, _('run even when the destination is unrelated')),
3500 [('f', 'force', None, _('run even when the destination is unrelated')),
3503 ('r', 'rev', [],
3501 ('r', 'rev', [],
3504 _('a changeset intended to be included in the destination'), _('REV')),
3502 _('a changeset intended to be included in the destination'), _('REV')),
3505 ('n', 'newest-first', None, _('show newest record first')),
3503 ('n', 'newest-first', None, _('show newest record first')),
3506 ('B', 'bookmarks', False, _('compare bookmarks')),
3504 ('B', 'bookmarks', False, _('compare bookmarks')),
3507 ('b', 'branch', [], _('a specific branch you would like to push'),
3505 ('b', 'branch', [], _('a specific branch you would like to push'),
3508 _('BRANCH')),
3506 _('BRANCH')),
3509 ] + logopts + remoteopts + subrepoopts,
3507 ] + logopts + remoteopts + subrepoopts,
3510 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3508 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3511 def outgoing(ui, repo, dest=None, **opts):
3509 def outgoing(ui, repo, dest=None, **opts):
3512 """show changesets not found in the destination
3510 """show changesets not found in the destination
3513
3511
3514 Show changesets not found in the specified destination repository
3512 Show changesets not found in the specified destination repository
3515 or the default push location. These are the changesets that would
3513 or the default push location. These are the changesets that would
3516 be pushed if a push was requested.
3514 be pushed if a push was requested.
3517
3515
3518 See pull for details of valid destination formats.
3516 See pull for details of valid destination formats.
3519
3517
3520 Returns 0 if there are outgoing changes, 1 otherwise.
3518 Returns 0 if there are outgoing changes, 1 otherwise.
3521 """
3519 """
3522
3520
3523 if opts.get('bookmarks'):
3521 if opts.get('bookmarks'):
3524 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3522 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3525 dest, branches = hg.parseurl(dest, opts.get('branch'))
3523 dest, branches = hg.parseurl(dest, opts.get('branch'))
3526 other = hg.repository(hg.remoteui(repo, opts), dest)
3524 other = hg.repository(hg.remoteui(repo, opts), dest)
3527 if 'bookmarks' not in other.listkeys('namespaces'):
3525 if 'bookmarks' not in other.listkeys('namespaces'):
3528 ui.warn(_("remote doesn't support bookmarks\n"))
3526 ui.warn(_("remote doesn't support bookmarks\n"))
3529 return 0
3527 return 0
3530 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3528 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3531 return bookmarks.diff(ui, other, repo)
3529 return bookmarks.diff(ui, other, repo)
3532
3530
3533 ret = hg.outgoing(ui, repo, dest, opts)
3531 ret = hg.outgoing(ui, repo, dest, opts)
3534 return ret
3532 return ret
3535
3533
3536 @command('parents',
3534 @command('parents',
3537 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3535 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3538 ] + templateopts,
3536 ] + templateopts,
3539 _('[-r REV] [FILE]'))
3537 _('[-r REV] [FILE]'))
3540 def parents(ui, repo, file_=None, **opts):
3538 def parents(ui, repo, file_=None, **opts):
3541 """show the parents of the working directory or revision
3539 """show the parents of the working directory or revision
3542
3540
3543 Print the working directory's parent revisions. If a revision is
3541 Print the working directory's parent revisions. If a revision is
3544 given via -r/--rev, the parent of that revision will be printed.
3542 given via -r/--rev, the parent of that revision will be printed.
3545 If a file argument is given, the revision in which the file was
3543 If a file argument is given, the revision in which the file was
3546 last changed (before the working directory revision or the
3544 last changed (before the working directory revision or the
3547 argument to --rev if given) is printed.
3545 argument to --rev if given) is printed.
3548
3546
3549 Returns 0 on success.
3547 Returns 0 on success.
3550 """
3548 """
3551
3549
3552 ctx = cmdutil.revsingle(repo, opts.get('rev'), None)
3550 ctx = cmdutil.revsingle(repo, opts.get('rev'), None)
3553
3551
3554 if file_:
3552 if file_:
3555 m = cmdutil.match(repo, (file_,), opts)
3553 m = cmdutil.match(repo, (file_,), opts)
3556 if m.anypats() or len(m.files()) != 1:
3554 if m.anypats() or len(m.files()) != 1:
3557 raise util.Abort(_('can only specify an explicit filename'))
3555 raise util.Abort(_('can only specify an explicit filename'))
3558 file_ = m.files()[0]
3556 file_ = m.files()[0]
3559 filenodes = []
3557 filenodes = []
3560 for cp in ctx.parents():
3558 for cp in ctx.parents():
3561 if not cp:
3559 if not cp:
3562 continue
3560 continue
3563 try:
3561 try:
3564 filenodes.append(cp.filenode(file_))
3562 filenodes.append(cp.filenode(file_))
3565 except error.LookupError:
3563 except error.LookupError:
3566 pass
3564 pass
3567 if not filenodes:
3565 if not filenodes:
3568 raise util.Abort(_("'%s' not found in manifest!") % file_)
3566 raise util.Abort(_("'%s' not found in manifest!") % file_)
3569 fl = repo.file(file_)
3567 fl = repo.file(file_)
3570 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
3568 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
3571 else:
3569 else:
3572 p = [cp.node() for cp in ctx.parents()]
3570 p = [cp.node() for cp in ctx.parents()]
3573
3571
3574 displayer = cmdutil.show_changeset(ui, repo, opts)
3572 displayer = cmdutil.show_changeset(ui, repo, opts)
3575 for n in p:
3573 for n in p:
3576 if n != nullid:
3574 if n != nullid:
3577 displayer.show(repo[n])
3575 displayer.show(repo[n])
3578 displayer.close()
3576 displayer.close()
3579
3577
3580 @command('paths', [], _('[NAME]'))
3578 @command('paths', [], _('[NAME]'))
3581 def paths(ui, repo, search=None):
3579 def paths(ui, repo, search=None):
3582 """show aliases for remote repositories
3580 """show aliases for remote repositories
3583
3581
3584 Show definition of symbolic path name NAME. If no name is given,
3582 Show definition of symbolic path name NAME. If no name is given,
3585 show definition of all available names.
3583 show definition of all available names.
3586
3584
3587 Path names are defined in the [paths] section of your
3585 Path names are defined in the [paths] section of your
3588 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3586 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3589 repository, ``.hg/hgrc`` is used, too.
3587 repository, ``.hg/hgrc`` is used, too.
3590
3588
3591 The path names ``default`` and ``default-push`` have a special
3589 The path names ``default`` and ``default-push`` have a special
3592 meaning. When performing a push or pull operation, they are used
3590 meaning. When performing a push or pull operation, they are used
3593 as fallbacks if no location is specified on the command-line.
3591 as fallbacks if no location is specified on the command-line.
3594 When ``default-push`` is set, it will be used for push and
3592 When ``default-push`` is set, it will be used for push and
3595 ``default`` will be used for pull; otherwise ``default`` is used
3593 ``default`` will be used for pull; otherwise ``default`` is used
3596 as the fallback for both. When cloning a repository, the clone
3594 as the fallback for both. When cloning a repository, the clone
3597 source is written as ``default`` in ``.hg/hgrc``. Note that
3595 source is written as ``default`` in ``.hg/hgrc``. Note that
3598 ``default`` and ``default-push`` apply to all inbound (e.g.
3596 ``default`` and ``default-push`` apply to all inbound (e.g.
3599 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
3597 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
3600 :hg:`bundle`) operations.
3598 :hg:`bundle`) operations.
3601
3599
3602 See :hg:`help urls` for more information.
3600 See :hg:`help urls` for more information.
3603
3601
3604 Returns 0 on success.
3602 Returns 0 on success.
3605 """
3603 """
3606 if search:
3604 if search:
3607 for name, path in ui.configitems("paths"):
3605 for name, path in ui.configitems("paths"):
3608 if name == search:
3606 if name == search:
3609 ui.write("%s\n" % util.hidepassword(path))
3607 ui.write("%s\n" % util.hidepassword(path))
3610 return
3608 return
3611 ui.warn(_("not found!\n"))
3609 ui.warn(_("not found!\n"))
3612 return 1
3610 return 1
3613 else:
3611 else:
3614 for name, path in ui.configitems("paths"):
3612 for name, path in ui.configitems("paths"):
3615 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
3613 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
3616
3614
3617 def postincoming(ui, repo, modheads, optupdate, checkout):
3615 def postincoming(ui, repo, modheads, optupdate, checkout):
3618 if modheads == 0:
3616 if modheads == 0:
3619 return
3617 return
3620 if optupdate:
3618 if optupdate:
3621 if (modheads <= 1 or len(repo.branchheads()) == 1) or checkout:
3619 if (modheads <= 1 or len(repo.branchheads()) == 1) or checkout:
3622 return hg.update(repo, checkout)
3620 return hg.update(repo, checkout)
3623 else:
3621 else:
3624 ui.status(_("not updating, since new heads added\n"))
3622 ui.status(_("not updating, since new heads added\n"))
3625 if modheads > 1:
3623 if modheads > 1:
3626 currentbranchheads = len(repo.branchheads())
3624 currentbranchheads = len(repo.branchheads())
3627 if currentbranchheads == modheads:
3625 if currentbranchheads == modheads:
3628 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3626 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3629 elif currentbranchheads > 1:
3627 elif currentbranchheads > 1:
3630 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
3628 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
3631 else:
3629 else:
3632 ui.status(_("(run 'hg heads' to see heads)\n"))
3630 ui.status(_("(run 'hg heads' to see heads)\n"))
3633 else:
3631 else:
3634 ui.status(_("(run 'hg update' to get a working copy)\n"))
3632 ui.status(_("(run 'hg update' to get a working copy)\n"))
3635
3633
3636 @command('^pull',
3634 @command('^pull',
3637 [('u', 'update', None,
3635 [('u', 'update', None,
3638 _('update to new branch head if changesets were pulled')),
3636 _('update to new branch head if changesets were pulled')),
3639 ('f', 'force', None, _('run even when remote repository is unrelated')),
3637 ('f', 'force', None, _('run even when remote repository is unrelated')),
3640 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3638 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3641 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3639 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3642 ('b', 'branch', [], _('a specific branch you would like to pull'),
3640 ('b', 'branch', [], _('a specific branch you would like to pull'),
3643 _('BRANCH')),
3641 _('BRANCH')),
3644 ] + remoteopts,
3642 ] + remoteopts,
3645 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3643 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3646 def pull(ui, repo, source="default", **opts):
3644 def pull(ui, repo, source="default", **opts):
3647 """pull changes from the specified source
3645 """pull changes from the specified source
3648
3646
3649 Pull changes from a remote repository to a local one.
3647 Pull changes from a remote repository to a local one.
3650
3648
3651 This finds all changes from the repository at the specified path
3649 This finds all changes from the repository at the specified path
3652 or URL and adds them to a local repository (the current one unless
3650 or URL and adds them to a local repository (the current one unless
3653 -R is specified). By default, this does not update the copy of the
3651 -R is specified). By default, this does not update the copy of the
3654 project in the working directory.
3652 project in the working directory.
3655
3653
3656 Use :hg:`incoming` if you want to see what would have been added
3654 Use :hg:`incoming` if you want to see what would have been added
3657 by a pull at the time you issued this command. If you then decide
3655 by a pull at the time you issued this command. If you then decide
3658 to add those changes to the repository, you should use :hg:`pull
3656 to add those changes to the repository, you should use :hg:`pull
3659 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3657 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3660
3658
3661 If SOURCE is omitted, the 'default' path will be used.
3659 If SOURCE is omitted, the 'default' path will be used.
3662 See :hg:`help urls` for more information.
3660 See :hg:`help urls` for more information.
3663
3661
3664 Returns 0 on success, 1 if an update had unresolved files.
3662 Returns 0 on success, 1 if an update had unresolved files.
3665 """
3663 """
3666 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3664 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3667 other = hg.repository(hg.remoteui(repo, opts), source)
3665 other = hg.repository(hg.remoteui(repo, opts), source)
3668 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3666 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3669 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
3667 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
3670
3668
3671 if opts.get('bookmark'):
3669 if opts.get('bookmark'):
3672 if not revs:
3670 if not revs:
3673 revs = []
3671 revs = []
3674 rb = other.listkeys('bookmarks')
3672 rb = other.listkeys('bookmarks')
3675 for b in opts['bookmark']:
3673 for b in opts['bookmark']:
3676 if b not in rb:
3674 if b not in rb:
3677 raise util.Abort(_('remote bookmark %s not found!') % b)
3675 raise util.Abort(_('remote bookmark %s not found!') % b)
3678 revs.append(rb[b])
3676 revs.append(rb[b])
3679
3677
3680 if revs:
3678 if revs:
3681 try:
3679 try:
3682 revs = [other.lookup(rev) for rev in revs]
3680 revs = [other.lookup(rev) for rev in revs]
3683 except error.CapabilityError:
3681 except error.CapabilityError:
3684 err = _("other repository doesn't support revision lookup, "
3682 err = _("other repository doesn't support revision lookup, "
3685 "so a rev cannot be specified.")
3683 "so a rev cannot be specified.")
3686 raise util.Abort(err)
3684 raise util.Abort(err)
3687
3685
3688 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
3686 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
3689 bookmarks.updatefromremote(ui, repo, other)
3687 bookmarks.updatefromremote(ui, repo, other)
3690 if checkout:
3688 if checkout:
3691 checkout = str(repo.changelog.rev(other.lookup(checkout)))
3689 checkout = str(repo.changelog.rev(other.lookup(checkout)))
3692 repo._subtoppath = source
3690 repo._subtoppath = source
3693 try:
3691 try:
3694 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
3692 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
3695
3693
3696 finally:
3694 finally:
3697 del repo._subtoppath
3695 del repo._subtoppath
3698
3696
3699 # update specified bookmarks
3697 # update specified bookmarks
3700 if opts.get('bookmark'):
3698 if opts.get('bookmark'):
3701 for b in opts['bookmark']:
3699 for b in opts['bookmark']:
3702 # explicit pull overrides local bookmark if any
3700 # explicit pull overrides local bookmark if any
3703 ui.status(_("importing bookmark %s\n") % b)
3701 ui.status(_("importing bookmark %s\n") % b)
3704 repo._bookmarks[b] = repo[rb[b]].node()
3702 repo._bookmarks[b] = repo[rb[b]].node()
3705 bookmarks.write(repo)
3703 bookmarks.write(repo)
3706
3704
3707 return ret
3705 return ret
3708
3706
3709 @command('^push',
3707 @command('^push',
3710 [('f', 'force', None, _('force push')),
3708 [('f', 'force', None, _('force push')),
3711 ('r', 'rev', [],
3709 ('r', 'rev', [],
3712 _('a changeset intended to be included in the destination'),
3710 _('a changeset intended to be included in the destination'),
3713 _('REV')),
3711 _('REV')),
3714 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
3712 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
3715 ('b', 'branch', [],
3713 ('b', 'branch', [],
3716 _('a specific branch you would like to push'), _('BRANCH')),
3714 _('a specific branch you would like to push'), _('BRANCH')),
3717 ('', 'new-branch', False, _('allow pushing a new branch')),
3715 ('', 'new-branch', False, _('allow pushing a new branch')),
3718 ] + remoteopts,
3716 ] + remoteopts,
3719 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
3717 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
3720 def push(ui, repo, dest=None, **opts):
3718 def push(ui, repo, dest=None, **opts):
3721 """push changes to the specified destination
3719 """push changes to the specified destination
3722
3720
3723 Push changesets from the local repository to the specified
3721 Push changesets from the local repository to the specified
3724 destination.
3722 destination.
3725
3723
3726 This operation is symmetrical to pull: it is identical to a pull
3724 This operation is symmetrical to pull: it is identical to a pull
3727 in the destination repository from the current one.
3725 in the destination repository from the current one.
3728
3726
3729 By default, push will not allow creation of new heads at the
3727 By default, push will not allow creation of new heads at the
3730 destination, since multiple heads would make it unclear which head
3728 destination, since multiple heads would make it unclear which head
3731 to use. In this situation, it is recommended to pull and merge
3729 to use. In this situation, it is recommended to pull and merge
3732 before pushing.
3730 before pushing.
3733
3731
3734 Use --new-branch if you want to allow push to create a new named
3732 Use --new-branch if you want to allow push to create a new named
3735 branch that is not present at the destination. This allows you to
3733 branch that is not present at the destination. This allows you to
3736 only create a new branch without forcing other changes.
3734 only create a new branch without forcing other changes.
3737
3735
3738 Use -f/--force to override the default behavior and push all
3736 Use -f/--force to override the default behavior and push all
3739 changesets on all branches.
3737 changesets on all branches.
3740
3738
3741 If -r/--rev is used, the specified revision and all its ancestors
3739 If -r/--rev is used, the specified revision and all its ancestors
3742 will be pushed to the remote repository.
3740 will be pushed to the remote repository.
3743
3741
3744 Please see :hg:`help urls` for important details about ``ssh://``
3742 Please see :hg:`help urls` for important details about ``ssh://``
3745 URLs. If DESTINATION is omitted, a default path will be used.
3743 URLs. If DESTINATION is omitted, a default path will be used.
3746
3744
3747 Returns 0 if push was successful, 1 if nothing to push.
3745 Returns 0 if push was successful, 1 if nothing to push.
3748 """
3746 """
3749
3747
3750 if opts.get('bookmark'):
3748 if opts.get('bookmark'):
3751 for b in opts['bookmark']:
3749 for b in opts['bookmark']:
3752 # translate -B options to -r so changesets get pushed
3750 # translate -B options to -r so changesets get pushed
3753 if b in repo._bookmarks:
3751 if b in repo._bookmarks:
3754 opts.setdefault('rev', []).append(b)
3752 opts.setdefault('rev', []).append(b)
3755 else:
3753 else:
3756 # if we try to push a deleted bookmark, translate it to null
3754 # if we try to push a deleted bookmark, translate it to null
3757 # this lets simultaneous -r, -b options continue working
3755 # this lets simultaneous -r, -b options continue working
3758 opts.setdefault('rev', []).append("null")
3756 opts.setdefault('rev', []).append("null")
3759
3757
3760 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3758 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3761 dest, branches = hg.parseurl(dest, opts.get('branch'))
3759 dest, branches = hg.parseurl(dest, opts.get('branch'))
3762 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
3760 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
3763 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
3761 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
3764 other = hg.repository(hg.remoteui(repo, opts), dest)
3762 other = hg.repository(hg.remoteui(repo, opts), dest)
3765 if revs:
3763 if revs:
3766 revs = [repo.lookup(rev) for rev in revs]
3764 revs = [repo.lookup(rev) for rev in revs]
3767
3765
3768 repo._subtoppath = dest
3766 repo._subtoppath = dest
3769 try:
3767 try:
3770 # push subrepos depth-first for coherent ordering
3768 # push subrepos depth-first for coherent ordering
3771 c = repo['']
3769 c = repo['']
3772 subs = c.substate # only repos that are committed
3770 subs = c.substate # only repos that are committed
3773 for s in sorted(subs):
3771 for s in sorted(subs):
3774 if not c.sub(s).push(opts.get('force')):
3772 if not c.sub(s).push(opts.get('force')):
3775 return False
3773 return False
3776 finally:
3774 finally:
3777 del repo._subtoppath
3775 del repo._subtoppath
3778 result = repo.push(other, opts.get('force'), revs=revs,
3776 result = repo.push(other, opts.get('force'), revs=revs,
3779 newbranch=opts.get('new_branch'))
3777 newbranch=opts.get('new_branch'))
3780
3778
3781 result = (result == 0)
3779 result = (result == 0)
3782
3780
3783 if opts.get('bookmark'):
3781 if opts.get('bookmark'):
3784 rb = other.listkeys('bookmarks')
3782 rb = other.listkeys('bookmarks')
3785 for b in opts['bookmark']:
3783 for b in opts['bookmark']:
3786 # explicit push overrides remote bookmark if any
3784 # explicit push overrides remote bookmark if any
3787 if b in repo._bookmarks:
3785 if b in repo._bookmarks:
3788 ui.status(_("exporting bookmark %s\n") % b)
3786 ui.status(_("exporting bookmark %s\n") % b)
3789 new = repo[b].hex()
3787 new = repo[b].hex()
3790 elif b in rb:
3788 elif b in rb:
3791 ui.status(_("deleting remote bookmark %s\n") % b)
3789 ui.status(_("deleting remote bookmark %s\n") % b)
3792 new = '' # delete
3790 new = '' # delete
3793 else:
3791 else:
3794 ui.warn(_('bookmark %s does not exist on the local '
3792 ui.warn(_('bookmark %s does not exist on the local '
3795 'or remote repository!\n') % b)
3793 'or remote repository!\n') % b)
3796 return 2
3794 return 2
3797 old = rb.get(b, '')
3795 old = rb.get(b, '')
3798 r = other.pushkey('bookmarks', b, old, new)
3796 r = other.pushkey('bookmarks', b, old, new)
3799 if not r:
3797 if not r:
3800 ui.warn(_('updating bookmark %s failed!\n') % b)
3798 ui.warn(_('updating bookmark %s failed!\n') % b)
3801 if not result:
3799 if not result:
3802 result = 2
3800 result = 2
3803
3801
3804 return result
3802 return result
3805
3803
3806 @command('recover', [])
3804 @command('recover', [])
3807 def recover(ui, repo):
3805 def recover(ui, repo):
3808 """roll back an interrupted transaction
3806 """roll back an interrupted transaction
3809
3807
3810 Recover from an interrupted commit or pull.
3808 Recover from an interrupted commit or pull.
3811
3809
3812 This command tries to fix the repository status after an
3810 This command tries to fix the repository status after an
3813 interrupted operation. It should only be necessary when Mercurial
3811 interrupted operation. It should only be necessary when Mercurial
3814 suggests it.
3812 suggests it.
3815
3813
3816 Returns 0 if successful, 1 if nothing to recover or verify fails.
3814 Returns 0 if successful, 1 if nothing to recover or verify fails.
3817 """
3815 """
3818 if repo.recover():
3816 if repo.recover():
3819 return hg.verify(repo)
3817 return hg.verify(repo)
3820 return 1
3818 return 1
3821
3819
3822 @command('^remove|rm',
3820 @command('^remove|rm',
3823 [('A', 'after', None, _('record delete for missing files')),
3821 [('A', 'after', None, _('record delete for missing files')),
3824 ('f', 'force', None,
3822 ('f', 'force', None,
3825 _('remove (and delete) file even if added or modified')),
3823 _('remove (and delete) file even if added or modified')),
3826 ] + walkopts,
3824 ] + walkopts,
3827 _('[OPTION]... FILE...'))
3825 _('[OPTION]... FILE...'))
3828 def remove(ui, repo, *pats, **opts):
3826 def remove(ui, repo, *pats, **opts):
3829 """remove the specified files on the next commit
3827 """remove the specified files on the next commit
3830
3828
3831 Schedule the indicated files for removal from the repository.
3829 Schedule the indicated files for removal from the repository.
3832
3830
3833 This only removes files from the current branch, not from the
3831 This only removes files from the current branch, not from the
3834 entire project history. -A/--after can be used to remove only
3832 entire project history. -A/--after can be used to remove only
3835 files that have already been deleted, -f/--force can be used to
3833 files that have already been deleted, -f/--force can be used to
3836 force deletion, and -Af can be used to remove files from the next
3834 force deletion, and -Af can be used to remove files from the next
3837 revision without deleting them from the working directory.
3835 revision without deleting them from the working directory.
3838
3836
3839 The following table details the behavior of remove for different
3837 The following table details the behavior of remove for different
3840 file states (columns) and option combinations (rows). The file
3838 file states (columns) and option combinations (rows). The file
3841 states are Added [A], Clean [C], Modified [M] and Missing [!] (as
3839 states are Added [A], Clean [C], Modified [M] and Missing [!] (as
3842 reported by :hg:`status`). The actions are Warn, Remove (from
3840 reported by :hg:`status`). The actions are Warn, Remove (from
3843 branch) and Delete (from disk)::
3841 branch) and Delete (from disk)::
3844
3842
3845 A C M !
3843 A C M !
3846 none W RD W R
3844 none W RD W R
3847 -f R RD RD R
3845 -f R RD RD R
3848 -A W W W R
3846 -A W W W R
3849 -Af R R R R
3847 -Af R R R R
3850
3848
3851 This command schedules the files to be removed at the next commit.
3849 This command schedules the files to be removed at the next commit.
3852 To undo a remove before that, see :hg:`revert`.
3850 To undo a remove before that, see :hg:`revert`.
3853
3851
3854 Returns 0 on success, 1 if any warnings encountered.
3852 Returns 0 on success, 1 if any warnings encountered.
3855 """
3853 """
3856
3854
3857 ret = 0
3855 ret = 0
3858 after, force = opts.get('after'), opts.get('force')
3856 after, force = opts.get('after'), opts.get('force')
3859 if not pats and not after:
3857 if not pats and not after:
3860 raise util.Abort(_('no files specified'))
3858 raise util.Abort(_('no files specified'))
3861
3859
3862 m = cmdutil.match(repo, pats, opts)
3860 m = cmdutil.match(repo, pats, opts)
3863 s = repo.status(match=m, clean=True)
3861 s = repo.status(match=m, clean=True)
3864 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
3862 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
3865
3863
3866 for f in m.files():
3864 for f in m.files():
3867 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
3865 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
3868 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
3866 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
3869 ret = 1
3867 ret = 1
3870
3868
3871 if force:
3869 if force:
3872 remove, forget = modified + deleted + clean, added
3870 remove, forget = modified + deleted + clean, added
3873 elif after:
3871 elif after:
3874 remove, forget = deleted, []
3872 remove, forget = deleted, []
3875 for f in modified + added + clean:
3873 for f in modified + added + clean:
3876 ui.warn(_('not removing %s: file still exists (use -f'
3874 ui.warn(_('not removing %s: file still exists (use -f'
3877 ' to force removal)\n') % m.rel(f))
3875 ' to force removal)\n') % m.rel(f))
3878 ret = 1
3876 ret = 1
3879 else:
3877 else:
3880 remove, forget = deleted + clean, []
3878 remove, forget = deleted + clean, []
3881 for f in modified:
3879 for f in modified:
3882 ui.warn(_('not removing %s: file is modified (use -f'
3880 ui.warn(_('not removing %s: file is modified (use -f'
3883 ' to force removal)\n') % m.rel(f))
3881 ' to force removal)\n') % m.rel(f))
3884 ret = 1
3882 ret = 1
3885 for f in added:
3883 for f in added:
3886 ui.warn(_('not removing %s: file has been marked for add (use -f'
3884 ui.warn(_('not removing %s: file has been marked for add (use -f'
3887 ' to force removal)\n') % m.rel(f))
3885 ' to force removal)\n') % m.rel(f))
3888 ret = 1
3886 ret = 1
3889
3887
3890 for f in sorted(remove + forget):
3888 for f in sorted(remove + forget):
3891 if ui.verbose or not m.exact(f):
3889 if ui.verbose or not m.exact(f):
3892 ui.status(_('removing %s\n') % m.rel(f))
3890 ui.status(_('removing %s\n') % m.rel(f))
3893
3891
3894 repo[None].forget(forget)
3892 repo[None].forget(forget)
3895 repo[None].remove(remove, unlink=not after)
3893 repo[None].remove(remove, unlink=not after)
3896 return ret
3894 return ret
3897
3895
3898 @command('rename|move|mv',
3896 @command('rename|move|mv',
3899 [('A', 'after', None, _('record a rename that has already occurred')),
3897 [('A', 'after', None, _('record a rename that has already occurred')),
3900 ('f', 'force', None, _('forcibly copy over an existing managed file')),
3898 ('f', 'force', None, _('forcibly copy over an existing managed file')),
3901 ] + walkopts + dryrunopts,
3899 ] + walkopts + dryrunopts,
3902 _('[OPTION]... SOURCE... DEST'))
3900 _('[OPTION]... SOURCE... DEST'))
3903 def rename(ui, repo, *pats, **opts):
3901 def rename(ui, repo, *pats, **opts):
3904 """rename files; equivalent of copy + remove
3902 """rename files; equivalent of copy + remove
3905
3903
3906 Mark dest as copies of sources; mark sources for deletion. If dest
3904 Mark dest as copies of sources; mark sources for deletion. If dest
3907 is a directory, copies are put in that directory. If dest is a
3905 is a directory, copies are put in that directory. If dest is a
3908 file, there can only be one source.
3906 file, there can only be one source.
3909
3907
3910 By default, this command copies the contents of files as they
3908 By default, this command copies the contents of files as they
3911 exist in the working directory. If invoked with -A/--after, the
3909 exist in the working directory. If invoked with -A/--after, the
3912 operation is recorded, but no copying is performed.
3910 operation is recorded, but no copying is performed.
3913
3911
3914 This command takes effect at the next commit. To undo a rename
3912 This command takes effect at the next commit. To undo a rename
3915 before that, see :hg:`revert`.
3913 before that, see :hg:`revert`.
3916
3914
3917 Returns 0 on success, 1 if errors are encountered.
3915 Returns 0 on success, 1 if errors are encountered.
3918 """
3916 """
3919 wlock = repo.wlock(False)
3917 wlock = repo.wlock(False)
3920 try:
3918 try:
3921 return cmdutil.copy(ui, repo, pats, opts, rename=True)
3919 return cmdutil.copy(ui, repo, pats, opts, rename=True)
3922 finally:
3920 finally:
3923 wlock.release()
3921 wlock.release()
3924
3922
3925 @command('resolve',
3923 @command('resolve',
3926 [('a', 'all', None, _('select all unresolved files')),
3924 [('a', 'all', None, _('select all unresolved files')),
3927 ('l', 'list', None, _('list state of files needing merge')),
3925 ('l', 'list', None, _('list state of files needing merge')),
3928 ('m', 'mark', None, _('mark files as resolved')),
3926 ('m', 'mark', None, _('mark files as resolved')),
3929 ('u', 'unmark', None, _('mark files as unresolved')),
3927 ('u', 'unmark', None, _('mark files as unresolved')),
3930 ('t', 'tool', '', _('specify merge tool')),
3928 ('t', 'tool', '', _('specify merge tool')),
3931 ('n', 'no-status', None, _('hide status prefix'))]
3929 ('n', 'no-status', None, _('hide status prefix'))]
3932 + walkopts,
3930 + walkopts,
3933 _('[OPTION]... [FILE]...'))
3931 _('[OPTION]... [FILE]...'))
3934 def resolve(ui, repo, *pats, **opts):
3932 def resolve(ui, repo, *pats, **opts):
3935 """redo merges or set/view the merge status of files
3933 """redo merges or set/view the merge status of files
3936
3934
3937 Merges with unresolved conflicts are often the result of
3935 Merges with unresolved conflicts are often the result of
3938 non-interactive merging using the ``internal:merge`` configuration
3936 non-interactive merging using the ``internal:merge`` configuration
3939 setting, or a command-line merge tool like ``diff3``. The resolve
3937 setting, or a command-line merge tool like ``diff3``. The resolve
3940 command is used to manage the files involved in a merge, after
3938 command is used to manage the files involved in a merge, after
3941 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
3939 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
3942 working directory must have two parents).
3940 working directory must have two parents).
3943
3941
3944 The resolve command can be used in the following ways:
3942 The resolve command can be used in the following ways:
3945
3943
3946 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
3944 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
3947 files, discarding any previous merge attempts. Re-merging is not
3945 files, discarding any previous merge attempts. Re-merging is not
3948 performed for files already marked as resolved. Use ``--all/-a``
3946 performed for files already marked as resolved. Use ``--all/-a``
3949 to selects all unresolved files. ``--tool`` can be used to specify
3947 to selects all unresolved files. ``--tool`` can be used to specify
3950 the merge tool used for the given files. It overrides the HGMERGE
3948 the merge tool used for the given files. It overrides the HGMERGE
3951 environment variable and your configuration files.
3949 environment variable and your configuration files.
3952
3950
3953 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
3951 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
3954 (e.g. after having manually fixed-up the files). The default is
3952 (e.g. after having manually fixed-up the files). The default is
3955 to mark all unresolved files.
3953 to mark all unresolved files.
3956
3954
3957 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
3955 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
3958 default is to mark all resolved files.
3956 default is to mark all resolved files.
3959
3957
3960 - :hg:`resolve -l`: list files which had or still have conflicts.
3958 - :hg:`resolve -l`: list files which had or still have conflicts.
3961 In the printed list, ``U`` = unresolved and ``R`` = resolved.
3959 In the printed list, ``U`` = unresolved and ``R`` = resolved.
3962
3960
3963 Note that Mercurial will not let you commit files with unresolved
3961 Note that Mercurial will not let you commit files with unresolved
3964 merge conflicts. You must use :hg:`resolve -m ...` before you can
3962 merge conflicts. You must use :hg:`resolve -m ...` before you can
3965 commit after a conflicting merge.
3963 commit after a conflicting merge.
3966
3964
3967 Returns 0 on success, 1 if any files fail a resolve attempt.
3965 Returns 0 on success, 1 if any files fail a resolve attempt.
3968 """
3966 """
3969
3967
3970 all, mark, unmark, show, nostatus = \
3968 all, mark, unmark, show, nostatus = \
3971 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
3969 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
3972
3970
3973 if (show and (mark or unmark)) or (mark and unmark):
3971 if (show and (mark or unmark)) or (mark and unmark):
3974 raise util.Abort(_("too many options specified"))
3972 raise util.Abort(_("too many options specified"))
3975 if pats and all:
3973 if pats and all:
3976 raise util.Abort(_("can't specify --all and patterns"))
3974 raise util.Abort(_("can't specify --all and patterns"))
3977 if not (all or pats or show or mark or unmark):
3975 if not (all or pats or show or mark or unmark):
3978 raise util.Abort(_('no files or directories specified; '
3976 raise util.Abort(_('no files or directories specified; '
3979 'use --all to remerge all files'))
3977 'use --all to remerge all files'))
3980
3978
3981 ms = mergemod.mergestate(repo)
3979 ms = mergemod.mergestate(repo)
3982 m = cmdutil.match(repo, pats, opts)
3980 m = cmdutil.match(repo, pats, opts)
3983 ret = 0
3981 ret = 0
3984
3982
3985 for f in ms:
3983 for f in ms:
3986 if m(f):
3984 if m(f):
3987 if show:
3985 if show:
3988 if nostatus:
3986 if nostatus:
3989 ui.write("%s\n" % f)
3987 ui.write("%s\n" % f)
3990 else:
3988 else:
3991 ui.write("%s %s\n" % (ms[f].upper(), f),
3989 ui.write("%s %s\n" % (ms[f].upper(), f),
3992 label='resolve.' +
3990 label='resolve.' +
3993 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
3991 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
3994 elif mark:
3992 elif mark:
3995 ms.mark(f, "r")
3993 ms.mark(f, "r")
3996 elif unmark:
3994 elif unmark:
3997 ms.mark(f, "u")
3995 ms.mark(f, "u")
3998 else:
3996 else:
3999 wctx = repo[None]
3997 wctx = repo[None]
4000 mctx = wctx.parents()[-1]
3998 mctx = wctx.parents()[-1]
4001
3999
4002 # backup pre-resolve (merge uses .orig for its own purposes)
4000 # backup pre-resolve (merge uses .orig for its own purposes)
4003 a = repo.wjoin(f)
4001 a = repo.wjoin(f)
4004 util.copyfile(a, a + ".resolve")
4002 util.copyfile(a, a + ".resolve")
4005
4003
4006 try:
4004 try:
4007 # resolve file
4005 # resolve file
4008 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4006 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4009 if ms.resolve(f, wctx, mctx):
4007 if ms.resolve(f, wctx, mctx):
4010 ret = 1
4008 ret = 1
4011 finally:
4009 finally:
4012 ui.setconfig('ui', 'forcemerge', '')
4010 ui.setconfig('ui', 'forcemerge', '')
4013
4011
4014 # replace filemerge's .orig file with our resolve file
4012 # replace filemerge's .orig file with our resolve file
4015 util.rename(a + ".resolve", a + ".orig")
4013 util.rename(a + ".resolve", a + ".orig")
4016
4014
4017 ms.commit()
4015 ms.commit()
4018 return ret
4016 return ret
4019
4017
4020 @command('revert',
4018 @command('revert',
4021 [('a', 'all', None, _('revert all changes when no arguments given')),
4019 [('a', 'all', None, _('revert all changes when no arguments given')),
4022 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4020 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4023 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4021 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4024 ('', 'no-backup', None, _('do not save backup copies of files')),
4022 ('', 'no-backup', None, _('do not save backup copies of files')),
4025 ] + walkopts + dryrunopts,
4023 ] + walkopts + dryrunopts,
4026 _('[OPTION]... [-r REV] [NAME]...'))
4024 _('[OPTION]... [-r REV] [NAME]...'))
4027 def revert(ui, repo, *pats, **opts):
4025 def revert(ui, repo, *pats, **opts):
4028 """restore individual files or directories to an earlier state
4026 """restore individual files or directories to an earlier state
4029
4027
4030 .. note::
4028 .. note::
4031 This command is most likely not what you are looking for.
4029 This command is most likely not what you are looking for.
4032 Revert will partially overwrite content in the working
4030 Revert will partially overwrite content in the working
4033 directory without changing the working directory parents. Use
4031 directory without changing the working directory parents. Use
4034 :hg:`update -r rev` to check out earlier revisions, or
4032 :hg:`update -r rev` to check out earlier revisions, or
4035 :hg:`update --clean .` to undo a merge which has added another
4033 :hg:`update --clean .` to undo a merge which has added another
4036 parent.
4034 parent.
4037
4035
4038 With no revision specified, revert the named files or directories
4036 With no revision specified, revert the named files or directories
4039 to the contents they had in the parent of the working directory.
4037 to the contents they had in the parent of the working directory.
4040 This restores the contents of the affected files to an unmodified
4038 This restores the contents of the affected files to an unmodified
4041 state and unschedules adds, removes, copies, and renames. If the
4039 state and unschedules adds, removes, copies, and renames. If the
4042 working directory has two parents, you must explicitly specify a
4040 working directory has two parents, you must explicitly specify a
4043 revision.
4041 revision.
4044
4042
4045 Using the -r/--rev option, revert the given files or directories
4043 Using the -r/--rev option, revert the given files or directories
4046 to their contents as of a specific revision. This can be helpful
4044 to their contents as of a specific revision. This can be helpful
4047 to "roll back" some or all of an earlier change. See :hg:`help
4045 to "roll back" some or all of an earlier change. See :hg:`help
4048 dates` for a list of formats valid for -d/--date.
4046 dates` for a list of formats valid for -d/--date.
4049
4047
4050 Revert modifies the working directory. It does not commit any
4048 Revert modifies the working directory. It does not commit any
4051 changes, or change the parent of the working directory. If you
4049 changes, or change the parent of the working directory. If you
4052 revert to a revision other than the parent of the working
4050 revert to a revision other than the parent of the working
4053 directory, the reverted files will thus appear modified
4051 directory, the reverted files will thus appear modified
4054 afterwards.
4052 afterwards.
4055
4053
4056 If a file has been deleted, it is restored. Files scheduled for
4054 If a file has been deleted, it is restored. Files scheduled for
4057 addition are just unscheduled and left as they are. If the
4055 addition are just unscheduled and left as they are. If the
4058 executable mode of a file was changed, it is reset.
4056 executable mode of a file was changed, it is reset.
4059
4057
4060 If names are given, all files matching the names are reverted.
4058 If names are given, all files matching the names are reverted.
4061 If no arguments are given, no files are reverted.
4059 If no arguments are given, no files are reverted.
4062
4060
4063 Modified files are saved with a .orig suffix before reverting.
4061 Modified files are saved with a .orig suffix before reverting.
4064 To disable these backups, use --no-backup.
4062 To disable these backups, use --no-backup.
4065
4063
4066 Returns 0 on success.
4064 Returns 0 on success.
4067 """
4065 """
4068
4066
4069 if opts.get("date"):
4067 if opts.get("date"):
4070 if opts.get("rev"):
4068 if opts.get("rev"):
4071 raise util.Abort(_("you can't specify a revision and a date"))
4069 raise util.Abort(_("you can't specify a revision and a date"))
4072 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4070 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4073
4071
4074 parent, p2 = repo.dirstate.parents()
4072 parent, p2 = repo.dirstate.parents()
4075 if not opts.get('rev') and p2 != nullid:
4073 if not opts.get('rev') and p2 != nullid:
4076 raise util.Abort(_('uncommitted merge - '
4074 raise util.Abort(_('uncommitted merge - '
4077 'use "hg update", see "hg help revert"'))
4075 'use "hg update", see "hg help revert"'))
4078
4076
4079 if not pats and not opts.get('all'):
4077 if not pats and not opts.get('all'):
4080 raise util.Abort(_('no files or directories specified; '
4078 raise util.Abort(_('no files or directories specified; '
4081 'use --all to revert the whole repo'))
4079 'use --all to revert the whole repo'))
4082
4080
4083 ctx = cmdutil.revsingle(repo, opts.get('rev'))
4081 ctx = cmdutil.revsingle(repo, opts.get('rev'))
4084 node = ctx.node()
4082 node = ctx.node()
4085 mf = ctx.manifest()
4083 mf = ctx.manifest()
4086 if node == parent:
4084 if node == parent:
4087 pmf = mf
4085 pmf = mf
4088 else:
4086 else:
4089 pmf = None
4087 pmf = None
4090
4088
4091 # need all matching names in dirstate and manifest of target rev,
4089 # need all matching names in dirstate and manifest of target rev,
4092 # so have to walk both. do not print errors if files exist in one
4090 # so have to walk both. do not print errors if files exist in one
4093 # but not other.
4091 # but not other.
4094
4092
4095 names = {}
4093 names = {}
4096
4094
4097 wlock = repo.wlock()
4095 wlock = repo.wlock()
4098 try:
4096 try:
4099 # walk dirstate.
4097 # walk dirstate.
4100
4098
4101 m = cmdutil.match(repo, pats, opts)
4099 m = cmdutil.match(repo, pats, opts)
4102 m.bad = lambda x, y: False
4100 m.bad = lambda x, y: False
4103 for abs in repo.walk(m):
4101 for abs in repo.walk(m):
4104 names[abs] = m.rel(abs), m.exact(abs)
4102 names[abs] = m.rel(abs), m.exact(abs)
4105
4103
4106 # walk target manifest.
4104 # walk target manifest.
4107
4105
4108 def badfn(path, msg):
4106 def badfn(path, msg):
4109 if path in names:
4107 if path in names:
4110 return
4108 return
4111 path_ = path + '/'
4109 path_ = path + '/'
4112 for f in names:
4110 for f in names:
4113 if f.startswith(path_):
4111 if f.startswith(path_):
4114 return
4112 return
4115 ui.warn("%s: %s\n" % (m.rel(path), msg))
4113 ui.warn("%s: %s\n" % (m.rel(path), msg))
4116
4114
4117 m = cmdutil.match(repo, pats, opts)
4115 m = cmdutil.match(repo, pats, opts)
4118 m.bad = badfn
4116 m.bad = badfn
4119 for abs in repo[node].walk(m):
4117 for abs in repo[node].walk(m):
4120 if abs not in names:
4118 if abs not in names:
4121 names[abs] = m.rel(abs), m.exact(abs)
4119 names[abs] = m.rel(abs), m.exact(abs)
4122
4120
4123 m = cmdutil.matchfiles(repo, names)
4121 m = cmdutil.matchfiles(repo, names)
4124 changes = repo.status(match=m)[:4]
4122 changes = repo.status(match=m)[:4]
4125 modified, added, removed, deleted = map(set, changes)
4123 modified, added, removed, deleted = map(set, changes)
4126
4124
4127 # if f is a rename, also revert the source
4125 # if f is a rename, also revert the source
4128 cwd = repo.getcwd()
4126 cwd = repo.getcwd()
4129 for f in added:
4127 for f in added:
4130 src = repo.dirstate.copied(f)
4128 src = repo.dirstate.copied(f)
4131 if src and src not in names and repo.dirstate[src] == 'r':
4129 if src and src not in names and repo.dirstate[src] == 'r':
4132 removed.add(src)
4130 removed.add(src)
4133 names[src] = (repo.pathto(src, cwd), True)
4131 names[src] = (repo.pathto(src, cwd), True)
4134
4132
4135 def removeforget(abs):
4133 def removeforget(abs):
4136 if repo.dirstate[abs] == 'a':
4134 if repo.dirstate[abs] == 'a':
4137 return _('forgetting %s\n')
4135 return _('forgetting %s\n')
4138 return _('removing %s\n')
4136 return _('removing %s\n')
4139
4137
4140 revert = ([], _('reverting %s\n'))
4138 revert = ([], _('reverting %s\n'))
4141 add = ([], _('adding %s\n'))
4139 add = ([], _('adding %s\n'))
4142 remove = ([], removeforget)
4140 remove = ([], removeforget)
4143 undelete = ([], _('undeleting %s\n'))
4141 undelete = ([], _('undeleting %s\n'))
4144
4142
4145 disptable = (
4143 disptable = (
4146 # dispatch table:
4144 # dispatch table:
4147 # file state
4145 # file state
4148 # action if in target manifest
4146 # action if in target manifest
4149 # action if not in target manifest
4147 # action if not in target manifest
4150 # make backup if in target manifest
4148 # make backup if in target manifest
4151 # make backup if not in target manifest
4149 # make backup if not in target manifest
4152 (modified, revert, remove, True, True),
4150 (modified, revert, remove, True, True),
4153 (added, revert, remove, True, False),
4151 (added, revert, remove, True, False),
4154 (removed, undelete, None, False, False),
4152 (removed, undelete, None, False, False),
4155 (deleted, revert, remove, False, False),
4153 (deleted, revert, remove, False, False),
4156 )
4154 )
4157
4155
4158 for abs, (rel, exact) in sorted(names.items()):
4156 for abs, (rel, exact) in sorted(names.items()):
4159 mfentry = mf.get(abs)
4157 mfentry = mf.get(abs)
4160 target = repo.wjoin(abs)
4158 target = repo.wjoin(abs)
4161 def handle(xlist, dobackup):
4159 def handle(xlist, dobackup):
4162 xlist[0].append(abs)
4160 xlist[0].append(abs)
4163 if (dobackup and not opts.get('no_backup') and
4161 if (dobackup and not opts.get('no_backup') and
4164 os.path.lexists(target)):
4162 os.path.lexists(target)):
4165 bakname = "%s.orig" % rel
4163 bakname = "%s.orig" % rel
4166 ui.note(_('saving current version of %s as %s\n') %
4164 ui.note(_('saving current version of %s as %s\n') %
4167 (rel, bakname))
4165 (rel, bakname))
4168 if not opts.get('dry_run'):
4166 if not opts.get('dry_run'):
4169 util.rename(target, bakname)
4167 util.rename(target, bakname)
4170 if ui.verbose or not exact:
4168 if ui.verbose or not exact:
4171 msg = xlist[1]
4169 msg = xlist[1]
4172 if not isinstance(msg, basestring):
4170 if not isinstance(msg, basestring):
4173 msg = msg(abs)
4171 msg = msg(abs)
4174 ui.status(msg % rel)
4172 ui.status(msg % rel)
4175 for table, hitlist, misslist, backuphit, backupmiss in disptable:
4173 for table, hitlist, misslist, backuphit, backupmiss in disptable:
4176 if abs not in table:
4174 if abs not in table:
4177 continue
4175 continue
4178 # file has changed in dirstate
4176 # file has changed in dirstate
4179 if mfentry:
4177 if mfentry:
4180 handle(hitlist, backuphit)
4178 handle(hitlist, backuphit)
4181 elif misslist is not None:
4179 elif misslist is not None:
4182 handle(misslist, backupmiss)
4180 handle(misslist, backupmiss)
4183 break
4181 break
4184 else:
4182 else:
4185 if abs not in repo.dirstate:
4183 if abs not in repo.dirstate:
4186 if mfentry:
4184 if mfentry:
4187 handle(add, True)
4185 handle(add, True)
4188 elif exact:
4186 elif exact:
4189 ui.warn(_('file not managed: %s\n') % rel)
4187 ui.warn(_('file not managed: %s\n') % rel)
4190 continue
4188 continue
4191 # file has not changed in dirstate
4189 # file has not changed in dirstate
4192 if node == parent:
4190 if node == parent:
4193 if exact:
4191 if exact:
4194 ui.warn(_('no changes needed to %s\n') % rel)
4192 ui.warn(_('no changes needed to %s\n') % rel)
4195 continue
4193 continue
4196 if pmf is None:
4194 if pmf is None:
4197 # only need parent manifest in this unlikely case,
4195 # only need parent manifest in this unlikely case,
4198 # so do not read by default
4196 # so do not read by default
4199 pmf = repo[parent].manifest()
4197 pmf = repo[parent].manifest()
4200 if abs in pmf:
4198 if abs in pmf:
4201 if mfentry:
4199 if mfentry:
4202 # if version of file is same in parent and target
4200 # if version of file is same in parent and target
4203 # manifests, do nothing
4201 # manifests, do nothing
4204 if (pmf[abs] != mfentry or
4202 if (pmf[abs] != mfentry or
4205 pmf.flags(abs) != mf.flags(abs)):
4203 pmf.flags(abs) != mf.flags(abs)):
4206 handle(revert, False)
4204 handle(revert, False)
4207 else:
4205 else:
4208 handle(remove, False)
4206 handle(remove, False)
4209
4207
4210 if not opts.get('dry_run'):
4208 if not opts.get('dry_run'):
4211 def checkout(f):
4209 def checkout(f):
4212 fc = ctx[f]
4210 fc = ctx[f]
4213 repo.wwrite(f, fc.data(), fc.flags())
4211 repo.wwrite(f, fc.data(), fc.flags())
4214
4212
4215 audit_path = scmutil.pathauditor(repo.root)
4213 audit_path = scmutil.pathauditor(repo.root)
4216 for f in remove[0]:
4214 for f in remove[0]:
4217 if repo.dirstate[f] == 'a':
4215 if repo.dirstate[f] == 'a':
4218 repo.dirstate.forget(f)
4216 repo.dirstate.forget(f)
4219 continue
4217 continue
4220 audit_path(f)
4218 audit_path(f)
4221 try:
4219 try:
4222 util.unlinkpath(repo.wjoin(f))
4220 util.unlinkpath(repo.wjoin(f))
4223 except OSError:
4221 except OSError:
4224 pass
4222 pass
4225 repo.dirstate.remove(f)
4223 repo.dirstate.remove(f)
4226
4224
4227 normal = None
4225 normal = None
4228 if node == parent:
4226 if node == parent:
4229 # We're reverting to our parent. If possible, we'd like status
4227 # We're reverting to our parent. If possible, we'd like status
4230 # to report the file as clean. We have to use normallookup for
4228 # to report the file as clean. We have to use normallookup for
4231 # merges to avoid losing information about merged/dirty files.
4229 # merges to avoid losing information about merged/dirty files.
4232 if p2 != nullid:
4230 if p2 != nullid:
4233 normal = repo.dirstate.normallookup
4231 normal = repo.dirstate.normallookup
4234 else:
4232 else:
4235 normal = repo.dirstate.normal
4233 normal = repo.dirstate.normal
4236 for f in revert[0]:
4234 for f in revert[0]:
4237 checkout(f)
4235 checkout(f)
4238 if normal:
4236 if normal:
4239 normal(f)
4237 normal(f)
4240
4238
4241 for f in add[0]:
4239 for f in add[0]:
4242 checkout(f)
4240 checkout(f)
4243 repo.dirstate.add(f)
4241 repo.dirstate.add(f)
4244
4242
4245 normal = repo.dirstate.normallookup
4243 normal = repo.dirstate.normallookup
4246 if node == parent and p2 == nullid:
4244 if node == parent and p2 == nullid:
4247 normal = repo.dirstate.normal
4245 normal = repo.dirstate.normal
4248 for f in undelete[0]:
4246 for f in undelete[0]:
4249 checkout(f)
4247 checkout(f)
4250 normal(f)
4248 normal(f)
4251
4249
4252 finally:
4250 finally:
4253 wlock.release()
4251 wlock.release()
4254
4252
4255 @command('rollback', dryrunopts)
4253 @command('rollback', dryrunopts)
4256 def rollback(ui, repo, **opts):
4254 def rollback(ui, repo, **opts):
4257 """roll back the last transaction (dangerous)
4255 """roll back the last transaction (dangerous)
4258
4256
4259 This command should be used with care. There is only one level of
4257 This command should be used with care. There is only one level of
4260 rollback, and there is no way to undo a rollback. It will also
4258 rollback, and there is no way to undo a rollback. It will also
4261 restore the dirstate at the time of the last transaction, losing
4259 restore the dirstate at the time of the last transaction, losing
4262 any dirstate changes since that time. This command does not alter
4260 any dirstate changes since that time. This command does not alter
4263 the working directory.
4261 the working directory.
4264
4262
4265 Transactions are used to encapsulate the effects of all commands
4263 Transactions are used to encapsulate the effects of all commands
4266 that create new changesets or propagate existing changesets into a
4264 that create new changesets or propagate existing changesets into a
4267 repository. For example, the following commands are transactional,
4265 repository. For example, the following commands are transactional,
4268 and their effects can be rolled back:
4266 and their effects can be rolled back:
4269
4267
4270 - commit
4268 - commit
4271 - import
4269 - import
4272 - pull
4270 - pull
4273 - push (with this repository as the destination)
4271 - push (with this repository as the destination)
4274 - unbundle
4272 - unbundle
4275
4273
4276 This command is not intended for use on public repositories. Once
4274 This command is not intended for use on public repositories. Once
4277 changes are visible for pull by other users, rolling a transaction
4275 changes are visible for pull by other users, rolling a transaction
4278 back locally is ineffective (someone else may already have pulled
4276 back locally is ineffective (someone else may already have pulled
4279 the changes). Furthermore, a race is possible with readers of the
4277 the changes). Furthermore, a race is possible with readers of the
4280 repository; for example an in-progress pull from the repository
4278 repository; for example an in-progress pull from the repository
4281 may fail if a rollback is performed.
4279 may fail if a rollback is performed.
4282
4280
4283 Returns 0 on success, 1 if no rollback data is available.
4281 Returns 0 on success, 1 if no rollback data is available.
4284 """
4282 """
4285 return repo.rollback(opts.get('dry_run'))
4283 return repo.rollback(opts.get('dry_run'))
4286
4284
4287 @command('root', [])
4285 @command('root', [])
4288 def root(ui, repo):
4286 def root(ui, repo):
4289 """print the root (top) of the current working directory
4287 """print the root (top) of the current working directory
4290
4288
4291 Print the root directory of the current repository.
4289 Print the root directory of the current repository.
4292
4290
4293 Returns 0 on success.
4291 Returns 0 on success.
4294 """
4292 """
4295 ui.write(repo.root + "\n")
4293 ui.write(repo.root + "\n")
4296
4294
4297 @command('^serve',
4295 @command('^serve',
4298 [('A', 'accesslog', '', _('name of access log file to write to'),
4296 [('A', 'accesslog', '', _('name of access log file to write to'),
4299 _('FILE')),
4297 _('FILE')),
4300 ('d', 'daemon', None, _('run server in background')),
4298 ('d', 'daemon', None, _('run server in background')),
4301 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4299 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4302 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4300 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4303 # use string type, then we can check if something was passed
4301 # use string type, then we can check if something was passed
4304 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4302 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4305 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4303 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4306 _('ADDR')),
4304 _('ADDR')),
4307 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4305 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4308 _('PREFIX')),
4306 _('PREFIX')),
4309 ('n', 'name', '',
4307 ('n', 'name', '',
4310 _('name to show in web pages (default: working directory)'), _('NAME')),
4308 _('name to show in web pages (default: working directory)'), _('NAME')),
4311 ('', 'web-conf', '',
4309 ('', 'web-conf', '',
4312 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4310 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4313 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4311 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4314 _('FILE')),
4312 _('FILE')),
4315 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4313 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4316 ('', 'stdio', None, _('for remote clients')),
4314 ('', 'stdio', None, _('for remote clients')),
4317 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4315 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4318 ('', 'style', '', _('template style to use'), _('STYLE')),
4316 ('', 'style', '', _('template style to use'), _('STYLE')),
4319 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4317 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4320 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4318 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4321 _('[OPTION]...'))
4319 _('[OPTION]...'))
4322 def serve(ui, repo, **opts):
4320 def serve(ui, repo, **opts):
4323 """start stand-alone webserver
4321 """start stand-alone webserver
4324
4322
4325 Start a local HTTP repository browser and pull server. You can use
4323 Start a local HTTP repository browser and pull server. You can use
4326 this for ad-hoc sharing and browsing of repositories. It is
4324 this for ad-hoc sharing and browsing of repositories. It is
4327 recommended to use a real web server to serve a repository for
4325 recommended to use a real web server to serve a repository for
4328 longer periods of time.
4326 longer periods of time.
4329
4327
4330 Please note that the server does not implement access control.
4328 Please note that the server does not implement access control.
4331 This means that, by default, anybody can read from the server and
4329 This means that, by default, anybody can read from the server and
4332 nobody can write to it by default. Set the ``web.allow_push``
4330 nobody can write to it by default. Set the ``web.allow_push``
4333 option to ``*`` to allow everybody to push to the server. You
4331 option to ``*`` to allow everybody to push to the server. You
4334 should use a real web server if you need to authenticate users.
4332 should use a real web server if you need to authenticate users.
4335
4333
4336 By default, the server logs accesses to stdout and errors to
4334 By default, the server logs accesses to stdout and errors to
4337 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4335 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4338 files.
4336 files.
4339
4337
4340 To have the server choose a free port number to listen on, specify
4338 To have the server choose a free port number to listen on, specify
4341 a port number of 0; in this case, the server will print the port
4339 a port number of 0; in this case, the server will print the port
4342 number it uses.
4340 number it uses.
4343
4341
4344 Returns 0 on success.
4342 Returns 0 on success.
4345 """
4343 """
4346
4344
4347 if opts["stdio"]:
4345 if opts["stdio"]:
4348 if repo is None:
4346 if repo is None:
4349 raise error.RepoError(_("There is no Mercurial repository here"
4347 raise error.RepoError(_("There is no Mercurial repository here"
4350 " (.hg not found)"))
4348 " (.hg not found)"))
4351 s = sshserver.sshserver(ui, repo)
4349 s = sshserver.sshserver(ui, repo)
4352 s.serve_forever()
4350 s.serve_forever()
4353
4351
4354 # this way we can check if something was given in the command-line
4352 # this way we can check if something was given in the command-line
4355 if opts.get('port'):
4353 if opts.get('port'):
4356 opts['port'] = util.getport(opts.get('port'))
4354 opts['port'] = util.getport(opts.get('port'))
4357
4355
4358 baseui = repo and repo.baseui or ui
4356 baseui = repo and repo.baseui or ui
4359 optlist = ("name templates style address port prefix ipv6"
4357 optlist = ("name templates style address port prefix ipv6"
4360 " accesslog errorlog certificate encoding")
4358 " accesslog errorlog certificate encoding")
4361 for o in optlist.split():
4359 for o in optlist.split():
4362 val = opts.get(o, '')
4360 val = opts.get(o, '')
4363 if val in (None, ''): # should check against default options instead
4361 if val in (None, ''): # should check against default options instead
4364 continue
4362 continue
4365 baseui.setconfig("web", o, val)
4363 baseui.setconfig("web", o, val)
4366 if repo and repo.ui != baseui:
4364 if repo and repo.ui != baseui:
4367 repo.ui.setconfig("web", o, val)
4365 repo.ui.setconfig("web", o, val)
4368
4366
4369 o = opts.get('web_conf') or opts.get('webdir_conf')
4367 o = opts.get('web_conf') or opts.get('webdir_conf')
4370 if not o:
4368 if not o:
4371 if not repo:
4369 if not repo:
4372 raise error.RepoError(_("There is no Mercurial repository"
4370 raise error.RepoError(_("There is no Mercurial repository"
4373 " here (.hg not found)"))
4371 " here (.hg not found)"))
4374 o = repo.root
4372 o = repo.root
4375
4373
4376 app = hgweb.hgweb(o, baseui=ui)
4374 app = hgweb.hgweb(o, baseui=ui)
4377
4375
4378 class service(object):
4376 class service(object):
4379 def init(self):
4377 def init(self):
4380 util.setsignalhandler()
4378 util.setsignalhandler()
4381 self.httpd = hgweb.server.create_server(ui, app)
4379 self.httpd = hgweb.server.create_server(ui, app)
4382
4380
4383 if opts['port'] and not ui.verbose:
4381 if opts['port'] and not ui.verbose:
4384 return
4382 return
4385
4383
4386 if self.httpd.prefix:
4384 if self.httpd.prefix:
4387 prefix = self.httpd.prefix.strip('/') + '/'
4385 prefix = self.httpd.prefix.strip('/') + '/'
4388 else:
4386 else:
4389 prefix = ''
4387 prefix = ''
4390
4388
4391 port = ':%d' % self.httpd.port
4389 port = ':%d' % self.httpd.port
4392 if port == ':80':
4390 if port == ':80':
4393 port = ''
4391 port = ''
4394
4392
4395 bindaddr = self.httpd.addr
4393 bindaddr = self.httpd.addr
4396 if bindaddr == '0.0.0.0':
4394 if bindaddr == '0.0.0.0':
4397 bindaddr = '*'
4395 bindaddr = '*'
4398 elif ':' in bindaddr: # IPv6
4396 elif ':' in bindaddr: # IPv6
4399 bindaddr = '[%s]' % bindaddr
4397 bindaddr = '[%s]' % bindaddr
4400
4398
4401 fqaddr = self.httpd.fqaddr
4399 fqaddr = self.httpd.fqaddr
4402 if ':' in fqaddr:
4400 if ':' in fqaddr:
4403 fqaddr = '[%s]' % fqaddr
4401 fqaddr = '[%s]' % fqaddr
4404 if opts['port']:
4402 if opts['port']:
4405 write = ui.status
4403 write = ui.status
4406 else:
4404 else:
4407 write = ui.write
4405 write = ui.write
4408 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
4406 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
4409 (fqaddr, port, prefix, bindaddr, self.httpd.port))
4407 (fqaddr, port, prefix, bindaddr, self.httpd.port))
4410
4408
4411 def run(self):
4409 def run(self):
4412 self.httpd.serve_forever()
4410 self.httpd.serve_forever()
4413
4411
4414 service = service()
4412 service = service()
4415
4413
4416 cmdutil.service(opts, initfn=service.init, runfn=service.run)
4414 cmdutil.service(opts, initfn=service.init, runfn=service.run)
4417
4415
4418 @command('showconfig|debugconfig',
4416 @command('showconfig|debugconfig',
4419 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4417 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4420 _('[-u] [NAME]...'))
4418 _('[-u] [NAME]...'))
4421 def showconfig(ui, repo, *values, **opts):
4419 def showconfig(ui, repo, *values, **opts):
4422 """show combined config settings from all hgrc files
4420 """show combined config settings from all hgrc files
4423
4421
4424 With no arguments, print names and values of all config items.
4422 With no arguments, print names and values of all config items.
4425
4423
4426 With one argument of the form section.name, print just the value
4424 With one argument of the form section.name, print just the value
4427 of that config item.
4425 of that config item.
4428
4426
4429 With multiple arguments, print names and values of all config
4427 With multiple arguments, print names and values of all config
4430 items with matching section names.
4428 items with matching section names.
4431
4429
4432 With --debug, the source (filename and line number) is printed
4430 With --debug, the source (filename and line number) is printed
4433 for each config item.
4431 for each config item.
4434
4432
4435 Returns 0 on success.
4433 Returns 0 on success.
4436 """
4434 """
4437
4435
4438 for f in scmutil.rcpath():
4436 for f in scmutil.rcpath():
4439 ui.debug(_('read config from: %s\n') % f)
4437 ui.debug(_('read config from: %s\n') % f)
4440 untrusted = bool(opts.get('untrusted'))
4438 untrusted = bool(opts.get('untrusted'))
4441 if values:
4439 if values:
4442 sections = [v for v in values if '.' not in v]
4440 sections = [v for v in values if '.' not in v]
4443 items = [v for v in values if '.' in v]
4441 items = [v for v in values if '.' in v]
4444 if len(items) > 1 or items and sections:
4442 if len(items) > 1 or items and sections:
4445 raise util.Abort(_('only one config item permitted'))
4443 raise util.Abort(_('only one config item permitted'))
4446 for section, name, value in ui.walkconfig(untrusted=untrusted):
4444 for section, name, value in ui.walkconfig(untrusted=untrusted):
4447 value = str(value).replace('\n', '\\n')
4445 value = str(value).replace('\n', '\\n')
4448 sectname = section + '.' + name
4446 sectname = section + '.' + name
4449 if values:
4447 if values:
4450 for v in values:
4448 for v in values:
4451 if v == section:
4449 if v == section:
4452 ui.debug('%s: ' %
4450 ui.debug('%s: ' %
4453 ui.configsource(section, name, untrusted))
4451 ui.configsource(section, name, untrusted))
4454 ui.write('%s=%s\n' % (sectname, value))
4452 ui.write('%s=%s\n' % (sectname, value))
4455 elif v == sectname:
4453 elif v == sectname:
4456 ui.debug('%s: ' %
4454 ui.debug('%s: ' %
4457 ui.configsource(section, name, untrusted))
4455 ui.configsource(section, name, untrusted))
4458 ui.write(value, '\n')
4456 ui.write(value, '\n')
4459 else:
4457 else:
4460 ui.debug('%s: ' %
4458 ui.debug('%s: ' %
4461 ui.configsource(section, name, untrusted))
4459 ui.configsource(section, name, untrusted))
4462 ui.write('%s=%s\n' % (sectname, value))
4460 ui.write('%s=%s\n' % (sectname, value))
4463
4461
4464 @command('^status|st',
4462 @command('^status|st',
4465 [('A', 'all', None, _('show status of all files')),
4463 [('A', 'all', None, _('show status of all files')),
4466 ('m', 'modified', None, _('show only modified files')),
4464 ('m', 'modified', None, _('show only modified files')),
4467 ('a', 'added', None, _('show only added files')),
4465 ('a', 'added', None, _('show only added files')),
4468 ('r', 'removed', None, _('show only removed files')),
4466 ('r', 'removed', None, _('show only removed files')),
4469 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4467 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4470 ('c', 'clean', None, _('show only files without changes')),
4468 ('c', 'clean', None, _('show only files without changes')),
4471 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4469 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4472 ('i', 'ignored', None, _('show only ignored files')),
4470 ('i', 'ignored', None, _('show only ignored files')),
4473 ('n', 'no-status', None, _('hide status prefix')),
4471 ('n', 'no-status', None, _('hide status prefix')),
4474 ('C', 'copies', None, _('show source of copied files')),
4472 ('C', 'copies', None, _('show source of copied files')),
4475 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4473 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4476 ('', 'rev', [], _('show difference from revision'), _('REV')),
4474 ('', 'rev', [], _('show difference from revision'), _('REV')),
4477 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4475 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4478 ] + walkopts + subrepoopts,
4476 ] + walkopts + subrepoopts,
4479 _('[OPTION]... [FILE]...'))
4477 _('[OPTION]... [FILE]...'))
4480 def status(ui, repo, *pats, **opts):
4478 def status(ui, repo, *pats, **opts):
4481 """show changed files in the working directory
4479 """show changed files in the working directory
4482
4480
4483 Show status of files in the repository. If names are given, only
4481 Show status of files in the repository. If names are given, only
4484 files that match are shown. Files that are clean or ignored or
4482 files that match are shown. Files that are clean or ignored or
4485 the source of a copy/move operation, are not listed unless
4483 the source of a copy/move operation, are not listed unless
4486 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4484 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4487 Unless options described with "show only ..." are given, the
4485 Unless options described with "show only ..." are given, the
4488 options -mardu are used.
4486 options -mardu are used.
4489
4487
4490 Option -q/--quiet hides untracked (unknown and ignored) files
4488 Option -q/--quiet hides untracked (unknown and ignored) files
4491 unless explicitly requested with -u/--unknown or -i/--ignored.
4489 unless explicitly requested with -u/--unknown or -i/--ignored.
4492
4490
4493 .. note::
4491 .. note::
4494 status may appear to disagree with diff if permissions have
4492 status may appear to disagree with diff if permissions have
4495 changed or a merge has occurred. The standard diff format does
4493 changed or a merge has occurred. The standard diff format does
4496 not report permission changes and diff only reports changes
4494 not report permission changes and diff only reports changes
4497 relative to one merge parent.
4495 relative to one merge parent.
4498
4496
4499 If one revision is given, it is used as the base revision.
4497 If one revision is given, it is used as the base revision.
4500 If two revisions are given, the differences between them are
4498 If two revisions are given, the differences between them are
4501 shown. The --change option can also be used as a shortcut to list
4499 shown. The --change option can also be used as a shortcut to list
4502 the changed files of a revision from its first parent.
4500 the changed files of a revision from its first parent.
4503
4501
4504 The codes used to show the status of files are::
4502 The codes used to show the status of files are::
4505
4503
4506 M = modified
4504 M = modified
4507 A = added
4505 A = added
4508 R = removed
4506 R = removed
4509 C = clean
4507 C = clean
4510 ! = missing (deleted by non-hg command, but still tracked)
4508 ! = missing (deleted by non-hg command, but still tracked)
4511 ? = not tracked
4509 ? = not tracked
4512 I = ignored
4510 I = ignored
4513 = origin of the previous file listed as A (added)
4511 = origin of the previous file listed as A (added)
4514
4512
4515 Returns 0 on success.
4513 Returns 0 on success.
4516 """
4514 """
4517
4515
4518 revs = opts.get('rev')
4516 revs = opts.get('rev')
4519 change = opts.get('change')
4517 change = opts.get('change')
4520
4518
4521 if revs and change:
4519 if revs and change:
4522 msg = _('cannot specify --rev and --change at the same time')
4520 msg = _('cannot specify --rev and --change at the same time')
4523 raise util.Abort(msg)
4521 raise util.Abort(msg)
4524 elif change:
4522 elif change:
4525 node2 = repo.lookup(change)
4523 node2 = repo.lookup(change)
4526 node1 = repo[node2].p1().node()
4524 node1 = repo[node2].p1().node()
4527 else:
4525 else:
4528 node1, node2 = cmdutil.revpair(repo, revs)
4526 node1, node2 = cmdutil.revpair(repo, revs)
4529
4527
4530 cwd = (pats and repo.getcwd()) or ''
4528 cwd = (pats and repo.getcwd()) or ''
4531 end = opts.get('print0') and '\0' or '\n'
4529 end = opts.get('print0') and '\0' or '\n'
4532 copy = {}
4530 copy = {}
4533 states = 'modified added removed deleted unknown ignored clean'.split()
4531 states = 'modified added removed deleted unknown ignored clean'.split()
4534 show = [k for k in states if opts.get(k)]
4532 show = [k for k in states if opts.get(k)]
4535 if opts.get('all'):
4533 if opts.get('all'):
4536 show += ui.quiet and (states[:4] + ['clean']) or states
4534 show += ui.quiet and (states[:4] + ['clean']) or states
4537 if not show:
4535 if not show:
4538 show = ui.quiet and states[:4] or states[:5]
4536 show = ui.quiet and states[:4] or states[:5]
4539
4537
4540 stat = repo.status(node1, node2, cmdutil.match(repo, pats, opts),
4538 stat = repo.status(node1, node2, cmdutil.match(repo, pats, opts),
4541 'ignored' in show, 'clean' in show, 'unknown' in show,
4539 'ignored' in show, 'clean' in show, 'unknown' in show,
4542 opts.get('subrepos'))
4540 opts.get('subrepos'))
4543 changestates = zip(states, 'MAR!?IC', stat)
4541 changestates = zip(states, 'MAR!?IC', stat)
4544
4542
4545 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
4543 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
4546 ctxn = repo[nullid]
4544 ctxn = repo[nullid]
4547 ctx1 = repo[node1]
4545 ctx1 = repo[node1]
4548 ctx2 = repo[node2]
4546 ctx2 = repo[node2]
4549 added = stat[1]
4547 added = stat[1]
4550 if node2 is None:
4548 if node2 is None:
4551 added = stat[0] + stat[1] # merged?
4549 added = stat[0] + stat[1] # merged?
4552
4550
4553 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
4551 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
4554 if k in added:
4552 if k in added:
4555 copy[k] = v
4553 copy[k] = v
4556 elif v in added:
4554 elif v in added:
4557 copy[v] = k
4555 copy[v] = k
4558
4556
4559 for state, char, files in changestates:
4557 for state, char, files in changestates:
4560 if state in show:
4558 if state in show:
4561 format = "%s %%s%s" % (char, end)
4559 format = "%s %%s%s" % (char, end)
4562 if opts.get('no_status'):
4560 if opts.get('no_status'):
4563 format = "%%s%s" % end
4561 format = "%%s%s" % end
4564
4562
4565 for f in files:
4563 for f in files:
4566 ui.write(format % repo.pathto(f, cwd),
4564 ui.write(format % repo.pathto(f, cwd),
4567 label='status.' + state)
4565 label='status.' + state)
4568 if f in copy:
4566 if f in copy:
4569 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
4567 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
4570 label='status.copied')
4568 label='status.copied')
4571
4569
4572 @command('^summary|sum',
4570 @command('^summary|sum',
4573 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
4571 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
4574 def summary(ui, repo, **opts):
4572 def summary(ui, repo, **opts):
4575 """summarize working directory state
4573 """summarize working directory state
4576
4574
4577 This generates a brief summary of the working directory state,
4575 This generates a brief summary of the working directory state,
4578 including parents, branch, commit status, and available updates.
4576 including parents, branch, commit status, and available updates.
4579
4577
4580 With the --remote option, this will check the default paths for
4578 With the --remote option, this will check the default paths for
4581 incoming and outgoing changes. This can be time-consuming.
4579 incoming and outgoing changes. This can be time-consuming.
4582
4580
4583 Returns 0 on success.
4581 Returns 0 on success.
4584 """
4582 """
4585
4583
4586 ctx = repo[None]
4584 ctx = repo[None]
4587 parents = ctx.parents()
4585 parents = ctx.parents()
4588 pnode = parents[0].node()
4586 pnode = parents[0].node()
4589
4587
4590 for p in parents:
4588 for p in parents:
4591 # label with log.changeset (instead of log.parent) since this
4589 # label with log.changeset (instead of log.parent) since this
4592 # shows a working directory parent *changeset*:
4590 # shows a working directory parent *changeset*:
4593 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
4591 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
4594 label='log.changeset')
4592 label='log.changeset')
4595 ui.write(' '.join(p.tags()), label='log.tag')
4593 ui.write(' '.join(p.tags()), label='log.tag')
4596 if p.bookmarks():
4594 if p.bookmarks():
4597 ui.write(' ' + ' '.join(p.bookmarks()), label='log.bookmark')
4595 ui.write(' ' + ' '.join(p.bookmarks()), label='log.bookmark')
4598 if p.rev() == -1:
4596 if p.rev() == -1:
4599 if not len(repo):
4597 if not len(repo):
4600 ui.write(_(' (empty repository)'))
4598 ui.write(_(' (empty repository)'))
4601 else:
4599 else:
4602 ui.write(_(' (no revision checked out)'))
4600 ui.write(_(' (no revision checked out)'))
4603 ui.write('\n')
4601 ui.write('\n')
4604 if p.description():
4602 if p.description():
4605 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
4603 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
4606 label='log.summary')
4604 label='log.summary')
4607
4605
4608 branch = ctx.branch()
4606 branch = ctx.branch()
4609 bheads = repo.branchheads(branch)
4607 bheads = repo.branchheads(branch)
4610 m = _('branch: %s\n') % branch
4608 m = _('branch: %s\n') % branch
4611 if branch != 'default':
4609 if branch != 'default':
4612 ui.write(m, label='log.branch')
4610 ui.write(m, label='log.branch')
4613 else:
4611 else:
4614 ui.status(m, label='log.branch')
4612 ui.status(m, label='log.branch')
4615
4613
4616 st = list(repo.status(unknown=True))[:6]
4614 st = list(repo.status(unknown=True))[:6]
4617
4615
4618 c = repo.dirstate.copies()
4616 c = repo.dirstate.copies()
4619 copied, renamed = [], []
4617 copied, renamed = [], []
4620 for d, s in c.iteritems():
4618 for d, s in c.iteritems():
4621 if s in st[2]:
4619 if s in st[2]:
4622 st[2].remove(s)
4620 st[2].remove(s)
4623 renamed.append(d)
4621 renamed.append(d)
4624 else:
4622 else:
4625 copied.append(d)
4623 copied.append(d)
4626 if d in st[1]:
4624 if d in st[1]:
4627 st[1].remove(d)
4625 st[1].remove(d)
4628 st.insert(3, renamed)
4626 st.insert(3, renamed)
4629 st.insert(4, copied)
4627 st.insert(4, copied)
4630
4628
4631 ms = mergemod.mergestate(repo)
4629 ms = mergemod.mergestate(repo)
4632 st.append([f for f in ms if ms[f] == 'u'])
4630 st.append([f for f in ms if ms[f] == 'u'])
4633
4631
4634 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
4632 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
4635 st.append(subs)
4633 st.append(subs)
4636
4634
4637 labels = [ui.label(_('%d modified'), 'status.modified'),
4635 labels = [ui.label(_('%d modified'), 'status.modified'),
4638 ui.label(_('%d added'), 'status.added'),
4636 ui.label(_('%d added'), 'status.added'),
4639 ui.label(_('%d removed'), 'status.removed'),
4637 ui.label(_('%d removed'), 'status.removed'),
4640 ui.label(_('%d renamed'), 'status.copied'),
4638 ui.label(_('%d renamed'), 'status.copied'),
4641 ui.label(_('%d copied'), 'status.copied'),
4639 ui.label(_('%d copied'), 'status.copied'),
4642 ui.label(_('%d deleted'), 'status.deleted'),
4640 ui.label(_('%d deleted'), 'status.deleted'),
4643 ui.label(_('%d unknown'), 'status.unknown'),
4641 ui.label(_('%d unknown'), 'status.unknown'),
4644 ui.label(_('%d ignored'), 'status.ignored'),
4642 ui.label(_('%d ignored'), 'status.ignored'),
4645 ui.label(_('%d unresolved'), 'resolve.unresolved'),
4643 ui.label(_('%d unresolved'), 'resolve.unresolved'),
4646 ui.label(_('%d subrepos'), 'status.modified')]
4644 ui.label(_('%d subrepos'), 'status.modified')]
4647 t = []
4645 t = []
4648 for s, l in zip(st, labels):
4646 for s, l in zip(st, labels):
4649 if s:
4647 if s:
4650 t.append(l % len(s))
4648 t.append(l % len(s))
4651
4649
4652 t = ', '.join(t)
4650 t = ', '.join(t)
4653 cleanworkdir = False
4651 cleanworkdir = False
4654
4652
4655 if len(parents) > 1:
4653 if len(parents) > 1:
4656 t += _(' (merge)')
4654 t += _(' (merge)')
4657 elif branch != parents[0].branch():
4655 elif branch != parents[0].branch():
4658 t += _(' (new branch)')
4656 t += _(' (new branch)')
4659 elif (parents[0].extra().get('close') and
4657 elif (parents[0].extra().get('close') and
4660 pnode in repo.branchheads(branch, closed=True)):
4658 pnode in repo.branchheads(branch, closed=True)):
4661 t += _(' (head closed)')
4659 t += _(' (head closed)')
4662 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
4660 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
4663 t += _(' (clean)')
4661 t += _(' (clean)')
4664 cleanworkdir = True
4662 cleanworkdir = True
4665 elif pnode not in bheads:
4663 elif pnode not in bheads:
4666 t += _(' (new branch head)')
4664 t += _(' (new branch head)')
4667
4665
4668 if cleanworkdir:
4666 if cleanworkdir:
4669 ui.status(_('commit: %s\n') % t.strip())
4667 ui.status(_('commit: %s\n') % t.strip())
4670 else:
4668 else:
4671 ui.write(_('commit: %s\n') % t.strip())
4669 ui.write(_('commit: %s\n') % t.strip())
4672
4670
4673 # all ancestors of branch heads - all ancestors of parent = new csets
4671 # all ancestors of branch heads - all ancestors of parent = new csets
4674 new = [0] * len(repo)
4672 new = [0] * len(repo)
4675 cl = repo.changelog
4673 cl = repo.changelog
4676 for a in [cl.rev(n) for n in bheads]:
4674 for a in [cl.rev(n) for n in bheads]:
4677 new[a] = 1
4675 new[a] = 1
4678 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
4676 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
4679 new[a] = 1
4677 new[a] = 1
4680 for a in [p.rev() for p in parents]:
4678 for a in [p.rev() for p in parents]:
4681 if a >= 0:
4679 if a >= 0:
4682 new[a] = 0
4680 new[a] = 0
4683 for a in cl.ancestors(*[p.rev() for p in parents]):
4681 for a in cl.ancestors(*[p.rev() for p in parents]):
4684 new[a] = 0
4682 new[a] = 0
4685 new = sum(new)
4683 new = sum(new)
4686
4684
4687 if new == 0:
4685 if new == 0:
4688 ui.status(_('update: (current)\n'))
4686 ui.status(_('update: (current)\n'))
4689 elif pnode not in bheads:
4687 elif pnode not in bheads:
4690 ui.write(_('update: %d new changesets (update)\n') % new)
4688 ui.write(_('update: %d new changesets (update)\n') % new)
4691 else:
4689 else:
4692 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
4690 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
4693 (new, len(bheads)))
4691 (new, len(bheads)))
4694
4692
4695 if opts.get('remote'):
4693 if opts.get('remote'):
4696 t = []
4694 t = []
4697 source, branches = hg.parseurl(ui.expandpath('default'))
4695 source, branches = hg.parseurl(ui.expandpath('default'))
4698 other = hg.repository(hg.remoteui(repo, {}), source)
4696 other = hg.repository(hg.remoteui(repo, {}), source)
4699 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4697 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4700 ui.debug('comparing with %s\n' % util.hidepassword(source))
4698 ui.debug('comparing with %s\n' % util.hidepassword(source))
4701 repo.ui.pushbuffer()
4699 repo.ui.pushbuffer()
4702 commoninc = discovery.findcommonincoming(repo, other)
4700 commoninc = discovery.findcommonincoming(repo, other)
4703 _common, incoming, _rheads = commoninc
4701 _common, incoming, _rheads = commoninc
4704 repo.ui.popbuffer()
4702 repo.ui.popbuffer()
4705 if incoming:
4703 if incoming:
4706 t.append(_('1 or more incoming'))
4704 t.append(_('1 or more incoming'))
4707
4705
4708 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
4706 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
4709 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
4707 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
4710 if source != dest:
4708 if source != dest:
4711 other = hg.repository(hg.remoteui(repo, {}), dest)
4709 other = hg.repository(hg.remoteui(repo, {}), dest)
4712 commoninc = None
4710 commoninc = None
4713 ui.debug('comparing with %s\n' % util.hidepassword(dest))
4711 ui.debug('comparing with %s\n' % util.hidepassword(dest))
4714 repo.ui.pushbuffer()
4712 repo.ui.pushbuffer()
4715 common, outheads = discovery.findcommonoutgoing(repo, other,
4713 common, outheads = discovery.findcommonoutgoing(repo, other,
4716 commoninc=commoninc)
4714 commoninc=commoninc)
4717 repo.ui.popbuffer()
4715 repo.ui.popbuffer()
4718 o = repo.changelog.findmissing(common=common, heads=outheads)
4716 o = repo.changelog.findmissing(common=common, heads=outheads)
4719 if o:
4717 if o:
4720 t.append(_('%d outgoing') % len(o))
4718 t.append(_('%d outgoing') % len(o))
4721 if 'bookmarks' in other.listkeys('namespaces'):
4719 if 'bookmarks' in other.listkeys('namespaces'):
4722 lmarks = repo.listkeys('bookmarks')
4720 lmarks = repo.listkeys('bookmarks')
4723 rmarks = other.listkeys('bookmarks')
4721 rmarks = other.listkeys('bookmarks')
4724 diff = set(rmarks) - set(lmarks)
4722 diff = set(rmarks) - set(lmarks)
4725 if len(diff) > 0:
4723 if len(diff) > 0:
4726 t.append(_('%d incoming bookmarks') % len(diff))
4724 t.append(_('%d incoming bookmarks') % len(diff))
4727 diff = set(lmarks) - set(rmarks)
4725 diff = set(lmarks) - set(rmarks)
4728 if len(diff) > 0:
4726 if len(diff) > 0:
4729 t.append(_('%d outgoing bookmarks') % len(diff))
4727 t.append(_('%d outgoing bookmarks') % len(diff))
4730
4728
4731 if t:
4729 if t:
4732 ui.write(_('remote: %s\n') % (', '.join(t)))
4730 ui.write(_('remote: %s\n') % (', '.join(t)))
4733 else:
4731 else:
4734 ui.status(_('remote: (synced)\n'))
4732 ui.status(_('remote: (synced)\n'))
4735
4733
4736 @command('tag',
4734 @command('tag',
4737 [('f', 'force', None, _('force tag')),
4735 [('f', 'force', None, _('force tag')),
4738 ('l', 'local', None, _('make the tag local')),
4736 ('l', 'local', None, _('make the tag local')),
4739 ('r', 'rev', '', _('revision to tag'), _('REV')),
4737 ('r', 'rev', '', _('revision to tag'), _('REV')),
4740 ('', 'remove', None, _('remove a tag')),
4738 ('', 'remove', None, _('remove a tag')),
4741 # -l/--local is already there, commitopts cannot be used
4739 # -l/--local is already there, commitopts cannot be used
4742 ('e', 'edit', None, _('edit commit message')),
4740 ('e', 'edit', None, _('edit commit message')),
4743 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
4741 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
4744 ] + commitopts2,
4742 ] + commitopts2,
4745 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
4743 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
4746 def tag(ui, repo, name1, *names, **opts):
4744 def tag(ui, repo, name1, *names, **opts):
4747 """add one or more tags for the current or given revision
4745 """add one or more tags for the current or given revision
4748
4746
4749 Name a particular revision using <name>.
4747 Name a particular revision using <name>.
4750
4748
4751 Tags are used to name particular revisions of the repository and are
4749 Tags are used to name particular revisions of the repository and are
4752 very useful to compare different revisions, to go back to significant
4750 very useful to compare different revisions, to go back to significant
4753 earlier versions or to mark branch points as releases, etc. Changing
4751 earlier versions or to mark branch points as releases, etc. Changing
4754 an existing tag is normally disallowed; use -f/--force to override.
4752 an existing tag is normally disallowed; use -f/--force to override.
4755
4753
4756 If no revision is given, the parent of the working directory is
4754 If no revision is given, the parent of the working directory is
4757 used, or tip if no revision is checked out.
4755 used, or tip if no revision is checked out.
4758
4756
4759 To facilitate version control, distribution, and merging of tags,
4757 To facilitate version control, distribution, and merging of tags,
4760 they are stored as a file named ".hgtags" which is managed similarly
4758 they are stored as a file named ".hgtags" which is managed similarly
4761 to other project files and can be hand-edited if necessary. This
4759 to other project files and can be hand-edited if necessary. This
4762 also means that tagging creates a new commit. The file
4760 also means that tagging creates a new commit. The file
4763 ".hg/localtags" is used for local tags (not shared among
4761 ".hg/localtags" is used for local tags (not shared among
4764 repositories).
4762 repositories).
4765
4763
4766 Tag commits are usually made at the head of a branch. If the parent
4764 Tag commits are usually made at the head of a branch. If the parent
4767 of the working directory is not a branch head, :hg:`tag` aborts; use
4765 of the working directory is not a branch head, :hg:`tag` aborts; use
4768 -f/--force to force the tag commit to be based on a non-head
4766 -f/--force to force the tag commit to be based on a non-head
4769 changeset.
4767 changeset.
4770
4768
4771 See :hg:`help dates` for a list of formats valid for -d/--date.
4769 See :hg:`help dates` for a list of formats valid for -d/--date.
4772
4770
4773 Since tag names have priority over branch names during revision
4771 Since tag names have priority over branch names during revision
4774 lookup, using an existing branch name as a tag name is discouraged.
4772 lookup, using an existing branch name as a tag name is discouraged.
4775
4773
4776 Returns 0 on success.
4774 Returns 0 on success.
4777 """
4775 """
4778
4776
4779 rev_ = "."
4777 rev_ = "."
4780 names = [t.strip() for t in (name1,) + names]
4778 names = [t.strip() for t in (name1,) + names]
4781 if len(names) != len(set(names)):
4779 if len(names) != len(set(names)):
4782 raise util.Abort(_('tag names must be unique'))
4780 raise util.Abort(_('tag names must be unique'))
4783 for n in names:
4781 for n in names:
4784 if n in ['tip', '.', 'null']:
4782 if n in ['tip', '.', 'null']:
4785 raise util.Abort(_("the name '%s' is reserved") % n)
4783 raise util.Abort(_("the name '%s' is reserved") % n)
4786 if not n:
4784 if not n:
4787 raise util.Abort(_('tag names cannot consist entirely of whitespace'))
4785 raise util.Abort(_('tag names cannot consist entirely of whitespace'))
4788 if opts.get('rev') and opts.get('remove'):
4786 if opts.get('rev') and opts.get('remove'):
4789 raise util.Abort(_("--rev and --remove are incompatible"))
4787 raise util.Abort(_("--rev and --remove are incompatible"))
4790 if opts.get('rev'):
4788 if opts.get('rev'):
4791 rev_ = opts['rev']
4789 rev_ = opts['rev']
4792 message = opts.get('message')
4790 message = opts.get('message')
4793 if opts.get('remove'):
4791 if opts.get('remove'):
4794 expectedtype = opts.get('local') and 'local' or 'global'
4792 expectedtype = opts.get('local') and 'local' or 'global'
4795 for n in names:
4793 for n in names:
4796 if not repo.tagtype(n):
4794 if not repo.tagtype(n):
4797 raise util.Abort(_("tag '%s' does not exist") % n)
4795 raise util.Abort(_("tag '%s' does not exist") % n)
4798 if repo.tagtype(n) != expectedtype:
4796 if repo.tagtype(n) != expectedtype:
4799 if expectedtype == 'global':
4797 if expectedtype == 'global':
4800 raise util.Abort(_("tag '%s' is not a global tag") % n)
4798 raise util.Abort(_("tag '%s' is not a global tag") % n)
4801 else:
4799 else:
4802 raise util.Abort(_("tag '%s' is not a local tag") % n)
4800 raise util.Abort(_("tag '%s' is not a local tag") % n)
4803 rev_ = nullid
4801 rev_ = nullid
4804 if not message:
4802 if not message:
4805 # we don't translate commit messages
4803 # we don't translate commit messages
4806 message = 'Removed tag %s' % ', '.join(names)
4804 message = 'Removed tag %s' % ', '.join(names)
4807 elif not opts.get('force'):
4805 elif not opts.get('force'):
4808 for n in names:
4806 for n in names:
4809 if n in repo.tags():
4807 if n in repo.tags():
4810 raise util.Abort(_("tag '%s' already exists "
4808 raise util.Abort(_("tag '%s' already exists "
4811 "(use -f to force)") % n)
4809 "(use -f to force)") % n)
4812 if not opts.get('local'):
4810 if not opts.get('local'):
4813 p1, p2 = repo.dirstate.parents()
4811 p1, p2 = repo.dirstate.parents()
4814 if p2 != nullid:
4812 if p2 != nullid:
4815 raise util.Abort(_('uncommitted merge'))
4813 raise util.Abort(_('uncommitted merge'))
4816 bheads = repo.branchheads()
4814 bheads = repo.branchheads()
4817 if not opts.get('force') and bheads and p1 not in bheads:
4815 if not opts.get('force') and bheads and p1 not in bheads:
4818 raise util.Abort(_('not at a branch head (use -f to force)'))
4816 raise util.Abort(_('not at a branch head (use -f to force)'))
4819 r = cmdutil.revsingle(repo, rev_).node()
4817 r = cmdutil.revsingle(repo, rev_).node()
4820
4818
4821 if not message:
4819 if not message:
4822 # we don't translate commit messages
4820 # we don't translate commit messages
4823 message = ('Added tag %s for changeset %s' %
4821 message = ('Added tag %s for changeset %s' %
4824 (', '.join(names), short(r)))
4822 (', '.join(names), short(r)))
4825
4823
4826 date = opts.get('date')
4824 date = opts.get('date')
4827 if date:
4825 if date:
4828 date = util.parsedate(date)
4826 date = util.parsedate(date)
4829
4827
4830 if opts.get('edit'):
4828 if opts.get('edit'):
4831 message = ui.edit(message, ui.username())
4829 message = ui.edit(message, ui.username())
4832
4830
4833 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
4831 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
4834
4832
4835 @command('tags', [], '')
4833 @command('tags', [], '')
4836 def tags(ui, repo):
4834 def tags(ui, repo):
4837 """list repository tags
4835 """list repository tags
4838
4836
4839 This lists both regular and local tags. When the -v/--verbose
4837 This lists both regular and local tags. When the -v/--verbose
4840 switch is used, a third column "local" is printed for local tags.
4838 switch is used, a third column "local" is printed for local tags.
4841
4839
4842 Returns 0 on success.
4840 Returns 0 on success.
4843 """
4841 """
4844
4842
4845 hexfunc = ui.debugflag and hex or short
4843 hexfunc = ui.debugflag and hex or short
4846 tagtype = ""
4844 tagtype = ""
4847
4845
4848 for t, n in reversed(repo.tagslist()):
4846 for t, n in reversed(repo.tagslist()):
4849 if ui.quiet:
4847 if ui.quiet:
4850 ui.write("%s\n" % t)
4848 ui.write("%s\n" % t)
4851 continue
4849 continue
4852
4850
4853 hn = hexfunc(n)
4851 hn = hexfunc(n)
4854 r = "%5d:%s" % (repo.changelog.rev(n), hn)
4852 r = "%5d:%s" % (repo.changelog.rev(n), hn)
4855 spaces = " " * (30 - encoding.colwidth(t))
4853 spaces = " " * (30 - encoding.colwidth(t))
4856
4854
4857 if ui.verbose:
4855 if ui.verbose:
4858 if repo.tagtype(t) == 'local':
4856 if repo.tagtype(t) == 'local':
4859 tagtype = " local"
4857 tagtype = " local"
4860 else:
4858 else:
4861 tagtype = ""
4859 tagtype = ""
4862 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
4860 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
4863
4861
4864 @command('tip',
4862 @command('tip',
4865 [('p', 'patch', None, _('show patch')),
4863 [('p', 'patch', None, _('show patch')),
4866 ('g', 'git', None, _('use git extended diff format')),
4864 ('g', 'git', None, _('use git extended diff format')),
4867 ] + templateopts,
4865 ] + templateopts,
4868 _('[-p] [-g]'))
4866 _('[-p] [-g]'))
4869 def tip(ui, repo, **opts):
4867 def tip(ui, repo, **opts):
4870 """show the tip revision
4868 """show the tip revision
4871
4869
4872 The tip revision (usually just called the tip) is the changeset
4870 The tip revision (usually just called the tip) is the changeset
4873 most recently added to the repository (and therefore the most
4871 most recently added to the repository (and therefore the most
4874 recently changed head).
4872 recently changed head).
4875
4873
4876 If you have just made a commit, that commit will be the tip. If
4874 If you have just made a commit, that commit will be the tip. If
4877 you have just pulled changes from another repository, the tip of
4875 you have just pulled changes from another repository, the tip of
4878 that repository becomes the current tip. The "tip" tag is special
4876 that repository becomes the current tip. The "tip" tag is special
4879 and cannot be renamed or assigned to a different changeset.
4877 and cannot be renamed or assigned to a different changeset.
4880
4878
4881 Returns 0 on success.
4879 Returns 0 on success.
4882 """
4880 """
4883 displayer = cmdutil.show_changeset(ui, repo, opts)
4881 displayer = cmdutil.show_changeset(ui, repo, opts)
4884 displayer.show(repo[len(repo) - 1])
4882 displayer.show(repo[len(repo) - 1])
4885 displayer.close()
4883 displayer.close()
4886
4884
4887 @command('unbundle',
4885 @command('unbundle',
4888 [('u', 'update', None,
4886 [('u', 'update', None,
4889 _('update to new branch head if changesets were unbundled'))],
4887 _('update to new branch head if changesets were unbundled'))],
4890 _('[-u] FILE...'))
4888 _('[-u] FILE...'))
4891 def unbundle(ui, repo, fname1, *fnames, **opts):
4889 def unbundle(ui, repo, fname1, *fnames, **opts):
4892 """apply one or more changegroup files
4890 """apply one or more changegroup files
4893
4891
4894 Apply one or more compressed changegroup files generated by the
4892 Apply one or more compressed changegroup files generated by the
4895 bundle command.
4893 bundle command.
4896
4894
4897 Returns 0 on success, 1 if an update has unresolved files.
4895 Returns 0 on success, 1 if an update has unresolved files.
4898 """
4896 """
4899 fnames = (fname1,) + fnames
4897 fnames = (fname1,) + fnames
4900
4898
4901 lock = repo.lock()
4899 lock = repo.lock()
4902 wc = repo['.']
4900 wc = repo['.']
4903 try:
4901 try:
4904 for fname in fnames:
4902 for fname in fnames:
4905 f = url.open(ui, fname)
4903 f = url.open(ui, fname)
4906 gen = changegroup.readbundle(f, fname)
4904 gen = changegroup.readbundle(f, fname)
4907 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
4905 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
4908 lock=lock)
4906 lock=lock)
4909 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
4907 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
4910 finally:
4908 finally:
4911 lock.release()
4909 lock.release()
4912 return postincoming(ui, repo, modheads, opts.get('update'), None)
4910 return postincoming(ui, repo, modheads, opts.get('update'), None)
4913
4911
4914 @command('^update|up|checkout|co',
4912 @command('^update|up|checkout|co',
4915 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
4913 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
4916 ('c', 'check', None,
4914 ('c', 'check', None,
4917 _('update across branches if no uncommitted changes')),
4915 _('update across branches if no uncommitted changes')),
4918 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4916 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4919 ('r', 'rev', '', _('revision'), _('REV'))],
4917 ('r', 'rev', '', _('revision'), _('REV'))],
4920 _('[-c] [-C] [-d DATE] [[-r] REV]'))
4918 _('[-c] [-C] [-d DATE] [[-r] REV]'))
4921 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
4919 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
4922 """update working directory (or switch revisions)
4920 """update working directory (or switch revisions)
4923
4921
4924 Update the repository's working directory to the specified
4922 Update the repository's working directory to the specified
4925 changeset. If no changeset is specified, update to the tip of the
4923 changeset. If no changeset is specified, update to the tip of the
4926 current named branch.
4924 current named branch.
4927
4925
4928 If the changeset is not a descendant of the working directory's
4926 If the changeset is not a descendant of the working directory's
4929 parent, the update is aborted. With the -c/--check option, the
4927 parent, the update is aborted. With the -c/--check option, the
4930 working directory is checked for uncommitted changes; if none are
4928 working directory is checked for uncommitted changes; if none are
4931 found, the working directory is updated to the specified
4929 found, the working directory is updated to the specified
4932 changeset.
4930 changeset.
4933
4931
4934 The following rules apply when the working directory contains
4932 The following rules apply when the working directory contains
4935 uncommitted changes:
4933 uncommitted changes:
4936
4934
4937 1. If neither -c/--check nor -C/--clean is specified, and if
4935 1. If neither -c/--check nor -C/--clean is specified, and if
4938 the requested changeset is an ancestor or descendant of
4936 the requested changeset is an ancestor or descendant of
4939 the working directory's parent, the uncommitted changes
4937 the working directory's parent, the uncommitted changes
4940 are merged into the requested changeset and the merged
4938 are merged into the requested changeset and the merged
4941 result is left uncommitted. If the requested changeset is
4939 result is left uncommitted. If the requested changeset is
4942 not an ancestor or descendant (that is, it is on another
4940 not an ancestor or descendant (that is, it is on another
4943 branch), the update is aborted and the uncommitted changes
4941 branch), the update is aborted and the uncommitted changes
4944 are preserved.
4942 are preserved.
4945
4943
4946 2. With the -c/--check option, the update is aborted and the
4944 2. With the -c/--check option, the update is aborted and the
4947 uncommitted changes are preserved.
4945 uncommitted changes are preserved.
4948
4946
4949 3. With the -C/--clean option, uncommitted changes are discarded and
4947 3. With the -C/--clean option, uncommitted changes are discarded and
4950 the working directory is updated to the requested changeset.
4948 the working directory is updated to the requested changeset.
4951
4949
4952 Use null as the changeset to remove the working directory (like
4950 Use null as the changeset to remove the working directory (like
4953 :hg:`clone -U`).
4951 :hg:`clone -U`).
4954
4952
4955 If you want to update just one file to an older changeset, use
4953 If you want to update just one file to an older changeset, use
4956 :hg:`revert`.
4954 :hg:`revert`.
4957
4955
4958 See :hg:`help dates` for a list of formats valid for -d/--date.
4956 See :hg:`help dates` for a list of formats valid for -d/--date.
4959
4957
4960 Returns 0 on success, 1 if there are unresolved files.
4958 Returns 0 on success, 1 if there are unresolved files.
4961 """
4959 """
4962 if rev and node:
4960 if rev and node:
4963 raise util.Abort(_("please specify just one revision"))
4961 raise util.Abort(_("please specify just one revision"))
4964
4962
4965 if rev is None or rev == '':
4963 if rev is None or rev == '':
4966 rev = node
4964 rev = node
4967
4965
4968 # if we defined a bookmark, we have to remember the original bookmark name
4966 # if we defined a bookmark, we have to remember the original bookmark name
4969 brev = rev
4967 brev = rev
4970 rev = cmdutil.revsingle(repo, rev, rev).rev()
4968 rev = cmdutil.revsingle(repo, rev, rev).rev()
4971
4969
4972 if check and clean:
4970 if check and clean:
4973 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
4971 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
4974
4972
4975 if check:
4973 if check:
4976 # we could use dirty() but we can ignore merge and branch trivia
4974 # we could use dirty() but we can ignore merge and branch trivia
4977 c = repo[None]
4975 c = repo[None]
4978 if c.modified() or c.added() or c.removed():
4976 if c.modified() or c.added() or c.removed():
4979 raise util.Abort(_("uncommitted local changes"))
4977 raise util.Abort(_("uncommitted local changes"))
4980
4978
4981 if date:
4979 if date:
4982 if rev is not None:
4980 if rev is not None:
4983 raise util.Abort(_("you can't specify a revision and a date"))
4981 raise util.Abort(_("you can't specify a revision and a date"))
4984 rev = cmdutil.finddate(ui, repo, date)
4982 rev = cmdutil.finddate(ui, repo, date)
4985
4983
4986 if clean or check:
4984 if clean or check:
4987 ret = hg.clean(repo, rev)
4985 ret = hg.clean(repo, rev)
4988 else:
4986 else:
4989 ret = hg.update(repo, rev)
4987 ret = hg.update(repo, rev)
4990
4988
4991 if brev in repo._bookmarks:
4989 if brev in repo._bookmarks:
4992 bookmarks.setcurrent(repo, brev)
4990 bookmarks.setcurrent(repo, brev)
4993
4991
4994 return ret
4992 return ret
4995
4993
4996 @command('verify', [])
4994 @command('verify', [])
4997 def verify(ui, repo):
4995 def verify(ui, repo):
4998 """verify the integrity of the repository
4996 """verify the integrity of the repository
4999
4997
5000 Verify the integrity of the current repository.
4998 Verify the integrity of the current repository.
5001
4999
5002 This will perform an extensive check of the repository's
5000 This will perform an extensive check of the repository's
5003 integrity, validating the hashes and checksums of each entry in
5001 integrity, validating the hashes and checksums of each entry in
5004 the changelog, manifest, and tracked files, as well as the
5002 the changelog, manifest, and tracked files, as well as the
5005 integrity of their crosslinks and indices.
5003 integrity of their crosslinks and indices.
5006
5004
5007 Returns 0 on success, 1 if errors are encountered.
5005 Returns 0 on success, 1 if errors are encountered.
5008 """
5006 """
5009 return hg.verify(repo)
5007 return hg.verify(repo)
5010
5008
5011 @command('version', [])
5009 @command('version', [])
5012 def version_(ui):
5010 def version_(ui):
5013 """output version and copyright information"""
5011 """output version and copyright information"""
5014 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5012 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5015 % util.version())
5013 % util.version())
5016 ui.status(_(
5014 ui.status(_(
5017 "(see http://mercurial.selenic.com for more information)\n"
5015 "(see http://mercurial.selenic.com for more information)\n"
5018 "\nCopyright (C) 2005-2011 Matt Mackall and others\n"
5016 "\nCopyright (C) 2005-2011 Matt Mackall and others\n"
5019 "This is free software; see the source for copying conditions. "
5017 "This is free software; see the source for copying conditions. "
5020 "There is NO\nwarranty; "
5018 "There is NO\nwarranty; "
5021 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5019 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5022 ))
5020 ))
5023
5021
5024 norepo = ("clone init version help debugcommands debugcomplete"
5022 norepo = ("clone init version help debugcommands debugcomplete"
5025 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5023 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5026 " debugknown debuggetbundle debugbundle")
5024 " debugknown debuggetbundle debugbundle")
5027 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5025 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5028 " debugdata debugindex debugindexdot")
5026 " debugdata debugindex debugindexdot")
@@ -1,309 +1,302 b''
1 # extensions.py - extension handling for mercurial
1 # extensions.py - extension handling for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 import imp, os
8 import imp, os
9 import util, cmdutil, help, error
9 import util, cmdutil, help, error
10 from i18n import _, gettext
10 from i18n import _, gettext
11
11
12 _extensions = {}
12 _extensions = {}
13 _order = []
13 _order = []
14 _ignore = ['hbisect', 'bookmarks', 'parentrevspec']
14 _ignore = ['hbisect', 'bookmarks', 'parentrevspec']
15
15
16 def extensions():
16 def extensions():
17 for name in _order:
17 for name in _order:
18 module = _extensions[name]
18 module = _extensions[name]
19 if module:
19 if module:
20 yield name, module
20 yield name, module
21
21
22 def find(name):
22 def find(name):
23 '''return module with given extension name'''
23 '''return module with given extension name'''
24 try:
24 try:
25 return _extensions[name]
25 return _extensions[name]
26 except KeyError:
26 except KeyError:
27 for k, v in _extensions.iteritems():
27 for k, v in _extensions.iteritems():
28 if k.endswith('.' + name) or k.endswith('/' + name):
28 if k.endswith('.' + name) or k.endswith('/' + name):
29 return v
29 return v
30 raise KeyError(name)
30 raise KeyError(name)
31
31
32 def loadpath(path, module_name):
32 def loadpath(path, module_name):
33 module_name = module_name.replace('.', '_')
33 module_name = module_name.replace('.', '_')
34 path = util.expandpath(path)
34 path = util.expandpath(path)
35 if os.path.isdir(path):
35 if os.path.isdir(path):
36 # module/__init__.py style
36 # module/__init__.py style
37 d, f = os.path.split(path.rstrip('/'))
37 d, f = os.path.split(path.rstrip('/'))
38 fd, fpath, desc = imp.find_module(f, [d])
38 fd, fpath, desc = imp.find_module(f, [d])
39 return imp.load_module(module_name, fd, fpath, desc)
39 return imp.load_module(module_name, fd, fpath, desc)
40 else:
40 else:
41 return imp.load_source(module_name, path)
41 return imp.load_source(module_name, path)
42
42
43 def load(ui, name, path):
43 def load(ui, name, path):
44 # unused ui argument kept for backwards compatibility
44 # unused ui argument kept for backwards compatibility
45 if name.startswith('hgext.') or name.startswith('hgext/'):
45 if name.startswith('hgext.') or name.startswith('hgext/'):
46 shortname = name[6:]
46 shortname = name[6:]
47 else:
47 else:
48 shortname = name
48 shortname = name
49 if shortname in _ignore:
49 if shortname in _ignore:
50 return None
50 return None
51 if shortname in _extensions:
51 if shortname in _extensions:
52 return _extensions[shortname]
52 return _extensions[shortname]
53 _extensions[shortname] = None
53 _extensions[shortname] = None
54 if path:
54 if path:
55 # the module will be loaded in sys.modules
55 # the module will be loaded in sys.modules
56 # choose an unique name so that it doesn't
56 # choose an unique name so that it doesn't
57 # conflicts with other modules
57 # conflicts with other modules
58 mod = loadpath(path, 'hgext.%s' % name)
58 mod = loadpath(path, 'hgext.%s' % name)
59 else:
59 else:
60 def importh(name):
60 def importh(name):
61 mod = __import__(name)
61 mod = __import__(name)
62 components = name.split('.')
62 components = name.split('.')
63 for comp in components[1:]:
63 for comp in components[1:]:
64 mod = getattr(mod, comp)
64 mod = getattr(mod, comp)
65 return mod
65 return mod
66 try:
66 try:
67 mod = importh("hgext.%s" % name)
67 mod = importh("hgext.%s" % name)
68 except ImportError:
68 except ImportError:
69 mod = importh(name)
69 mod = importh(name)
70 _extensions[shortname] = mod
70 _extensions[shortname] = mod
71 _order.append(shortname)
71 _order.append(shortname)
72 return mod
72 return mod
73
73
74 def loadall(ui):
74 def loadall(ui):
75 result = ui.configitems("extensions")
75 result = ui.configitems("extensions")
76 newindex = len(_order)
76 newindex = len(_order)
77 for (name, path) in result:
77 for (name, path) in result:
78 if path:
78 if path:
79 if path[0] == '!':
79 if path[0] == '!':
80 continue
80 continue
81 try:
81 try:
82 load(ui, name, path)
82 load(ui, name, path)
83 except KeyboardInterrupt:
83 except KeyboardInterrupt:
84 raise
84 raise
85 except Exception, inst:
85 except Exception, inst:
86 if path:
86 if path:
87 ui.warn(_("*** failed to import extension %s from %s: %s\n")
87 ui.warn(_("*** failed to import extension %s from %s: %s\n")
88 % (name, path, inst))
88 % (name, path, inst))
89 else:
89 else:
90 ui.warn(_("*** failed to import extension %s: %s\n")
90 ui.warn(_("*** failed to import extension %s: %s\n")
91 % (name, inst))
91 % (name, inst))
92 if ui.traceback():
92 if ui.traceback():
93 return 1
93 return 1
94
94
95 for name in _order[newindex:]:
95 for name in _order[newindex:]:
96 uisetup = getattr(_extensions[name], 'uisetup', None)
96 uisetup = getattr(_extensions[name], 'uisetup', None)
97 if uisetup:
97 if uisetup:
98 uisetup(ui)
98 uisetup(ui)
99
99
100 for name in _order[newindex:]:
100 for name in _order[newindex:]:
101 extsetup = getattr(_extensions[name], 'extsetup', None)
101 extsetup = getattr(_extensions[name], 'extsetup', None)
102 if extsetup:
102 if extsetup:
103 try:
103 try:
104 extsetup(ui)
104 extsetup(ui)
105 except TypeError:
105 except TypeError:
106 if extsetup.func_code.co_argcount != 0:
106 if extsetup.func_code.co_argcount != 0:
107 raise
107 raise
108 extsetup() # old extsetup with no ui argument
108 extsetup() # old extsetup with no ui argument
109
109
110 def wrapcommand(table, command, wrapper):
110 def wrapcommand(table, command, wrapper):
111 '''Wrap the command named `command' in table
111 '''Wrap the command named `command' in table
112
112
113 Replace command in the command table with wrapper. The wrapped command will
113 Replace command in the command table with wrapper. The wrapped command will
114 be inserted into the command table specified by the table argument.
114 be inserted into the command table specified by the table argument.
115
115
116 The wrapper will be called like
116 The wrapper will be called like
117
117
118 wrapper(orig, *args, **kwargs)
118 wrapper(orig, *args, **kwargs)
119
119
120 where orig is the original (wrapped) function, and *args, **kwargs
120 where orig is the original (wrapped) function, and *args, **kwargs
121 are the arguments passed to it.
121 are the arguments passed to it.
122 '''
122 '''
123 assert hasattr(wrapper, '__call__')
123 assert hasattr(wrapper, '__call__')
124 aliases, entry = cmdutil.findcmd(command, table)
124 aliases, entry = cmdutil.findcmd(command, table)
125 for alias, e in table.iteritems():
125 for alias, e in table.iteritems():
126 if e is entry:
126 if e is entry:
127 key = alias
127 key = alias
128 break
128 break
129
129
130 origfn = entry[0]
130 origfn = entry[0]
131 def wrap(*args, **kwargs):
131 def wrap(*args, **kwargs):
132 return util.checksignature(wrapper)(
132 return util.checksignature(wrapper)(
133 util.checksignature(origfn), *args, **kwargs)
133 util.checksignature(origfn), *args, **kwargs)
134
134
135 wrap.__doc__ = getattr(origfn, '__doc__')
135 wrap.__doc__ = getattr(origfn, '__doc__')
136 wrap.__module__ = getattr(origfn, '__module__')
136 wrap.__module__ = getattr(origfn, '__module__')
137
137
138 newentry = list(entry)
138 newentry = list(entry)
139 newentry[0] = wrap
139 newentry[0] = wrap
140 table[key] = tuple(newentry)
140 table[key] = tuple(newentry)
141 return entry
141 return entry
142
142
143 def wrapfunction(container, funcname, wrapper):
143 def wrapfunction(container, funcname, wrapper):
144 '''Wrap the function named funcname in container
144 '''Wrap the function named funcname in container
145
145
146 Replace the funcname member in the given container with the specified
146 Replace the funcname member in the given container with the specified
147 wrapper. The container is typically a module, class, or instance.
147 wrapper. The container is typically a module, class, or instance.
148
148
149 The wrapper will be called like
149 The wrapper will be called like
150
150
151 wrapper(orig, *args, **kwargs)
151 wrapper(orig, *args, **kwargs)
152
152
153 where orig is the original (wrapped) function, and *args, **kwargs
153 where orig is the original (wrapped) function, and *args, **kwargs
154 are the arguments passed to it.
154 are the arguments passed to it.
155
155
156 Wrapping methods of the repository object is not recommended since
156 Wrapping methods of the repository object is not recommended since
157 it conflicts with extensions that extend the repository by
157 it conflicts with extensions that extend the repository by
158 subclassing. All extensions that need to extend methods of
158 subclassing. All extensions that need to extend methods of
159 localrepository should use this subclassing trick: namely,
159 localrepository should use this subclassing trick: namely,
160 reposetup() should look like
160 reposetup() should look like
161
161
162 def reposetup(ui, repo):
162 def reposetup(ui, repo):
163 class myrepo(repo.__class__):
163 class myrepo(repo.__class__):
164 def whatever(self, *args, **kwargs):
164 def whatever(self, *args, **kwargs):
165 [...extension stuff...]
165 [...extension stuff...]
166 super(myrepo, self).whatever(*args, **kwargs)
166 super(myrepo, self).whatever(*args, **kwargs)
167 [...extension stuff...]
167 [...extension stuff...]
168
168
169 repo.__class__ = myrepo
169 repo.__class__ = myrepo
170
170
171 In general, combining wrapfunction() with subclassing does not
171 In general, combining wrapfunction() with subclassing does not
172 work. Since you cannot control what other extensions are loaded by
172 work. Since you cannot control what other extensions are loaded by
173 your end users, you should play nicely with others by using the
173 your end users, you should play nicely with others by using the
174 subclass trick.
174 subclass trick.
175 '''
175 '''
176 assert hasattr(wrapper, '__call__')
176 assert hasattr(wrapper, '__call__')
177 def wrap(*args, **kwargs):
177 def wrap(*args, **kwargs):
178 return wrapper(origfn, *args, **kwargs)
178 return wrapper(origfn, *args, **kwargs)
179
179
180 origfn = getattr(container, funcname)
180 origfn = getattr(container, funcname)
181 assert hasattr(origfn, '__call__')
181 assert hasattr(origfn, '__call__')
182 setattr(container, funcname, wrap)
182 setattr(container, funcname, wrap)
183 return origfn
183 return origfn
184
184
185 def _disabledpaths(strip_init=False):
185 def _disabledpaths(strip_init=False):
186 '''find paths of disabled extensions. returns a dict of {name: path}
186 '''find paths of disabled extensions. returns a dict of {name: path}
187 removes /__init__.py from packages if strip_init is True'''
187 removes /__init__.py from packages if strip_init is True'''
188 import hgext
188 import hgext
189 extpath = os.path.dirname(os.path.abspath(hgext.__file__))
189 extpath = os.path.dirname(os.path.abspath(hgext.__file__))
190 try: # might not be a filesystem path
190 try: # might not be a filesystem path
191 files = os.listdir(extpath)
191 files = os.listdir(extpath)
192 except OSError:
192 except OSError:
193 return {}
193 return {}
194
194
195 exts = {}
195 exts = {}
196 for e in files:
196 for e in files:
197 if e.endswith('.py'):
197 if e.endswith('.py'):
198 name = e.rsplit('.', 1)[0]
198 name = e.rsplit('.', 1)[0]
199 path = os.path.join(extpath, e)
199 path = os.path.join(extpath, e)
200 else:
200 else:
201 name = e
201 name = e
202 path = os.path.join(extpath, e, '__init__.py')
202 path = os.path.join(extpath, e, '__init__.py')
203 if not os.path.exists(path):
203 if not os.path.exists(path):
204 continue
204 continue
205 if strip_init:
205 if strip_init:
206 path = os.path.dirname(path)
206 path = os.path.dirname(path)
207 if name in exts or name in _order or name == '__init__':
207 if name in exts or name in _order or name == '__init__':
208 continue
208 continue
209 exts[name] = path
209 exts[name] = path
210 return exts
210 return exts
211
211
212 def _disabledhelp(path):
212 def _disabledhelp(path):
213 '''retrieve help synopsis of a disabled extension (without importing)'''
213 '''retrieve help synopsis of a disabled extension (without importing)'''
214 try:
214 try:
215 file = open(path)
215 file = open(path)
216 except IOError:
216 except IOError:
217 return
217 return
218 else:
218 else:
219 doc = help.moduledoc(file)
219 doc = help.moduledoc(file)
220 file.close()
220 file.close()
221
221
222 if doc: # extracting localized synopsis
222 if doc: # extracting localized synopsis
223 return gettext(doc).splitlines()[0]
223 return gettext(doc).splitlines()[0]
224 else:
224 else:
225 return _('(no help text available)')
225 return _('(no help text available)')
226
226
227 def disabled():
227 def disabled():
228 '''find disabled extensions from hgext
228 '''find disabled extensions from hgext
229 returns a dict of {name: desc}, and the max name length'''
229 returns a dict of {name: desc}, and the max name length'''
230
230
231 paths = _disabledpaths()
231 paths = _disabledpaths()
232 if not paths:
232 if not paths:
233 return None, 0
233 return None
234
234
235 exts = {}
235 exts = {}
236 maxlength = 0
237 for name, path in paths.iteritems():
236 for name, path in paths.iteritems():
238 doc = _disabledhelp(path)
237 doc = _disabledhelp(path)
239 if not doc:
238 if doc:
240 continue
241
242 exts[name] = doc
239 exts[name] = doc
243 if len(name) > maxlength:
244 maxlength = len(name)
245
240
246 return exts, maxlength
241 return exts
247
242
248 def disabledext(name):
243 def disabledext(name):
249 '''find a specific disabled extension from hgext. returns desc'''
244 '''find a specific disabled extension from hgext. returns desc'''
250 paths = _disabledpaths()
245 paths = _disabledpaths()
251 if name in paths:
246 if name in paths:
252 return _disabledhelp(paths[name])
247 return _disabledhelp(paths[name])
253
248
254 def disabledcmd(ui, cmd, strict=False):
249 def disabledcmd(ui, cmd, strict=False):
255 '''import disabled extensions until cmd is found.
250 '''import disabled extensions until cmd is found.
256 returns (cmdname, extname, doc)'''
251 returns (cmdname, extname, doc)'''
257
252
258 paths = _disabledpaths(strip_init=True)
253 paths = _disabledpaths(strip_init=True)
259 if not paths:
254 if not paths:
260 raise error.UnknownCommand(cmd)
255 raise error.UnknownCommand(cmd)
261
256
262 def findcmd(cmd, name, path):
257 def findcmd(cmd, name, path):
263 try:
258 try:
264 mod = loadpath(path, 'hgext.%s' % name)
259 mod = loadpath(path, 'hgext.%s' % name)
265 except Exception:
260 except Exception:
266 return
261 return
267 try:
262 try:
268 aliases, entry = cmdutil.findcmd(cmd,
263 aliases, entry = cmdutil.findcmd(cmd,
269 getattr(mod, 'cmdtable', {}), strict)
264 getattr(mod, 'cmdtable', {}), strict)
270 except (error.AmbiguousCommand, error.UnknownCommand):
265 except (error.AmbiguousCommand, error.UnknownCommand):
271 return
266 return
272 except Exception:
267 except Exception:
273 ui.warn(_('warning: error finding commands in %s\n') % path)
268 ui.warn(_('warning: error finding commands in %s\n') % path)
274 ui.traceback()
269 ui.traceback()
275 return
270 return
276 for c in aliases:
271 for c in aliases:
277 if c.startswith(cmd):
272 if c.startswith(cmd):
278 cmd = c
273 cmd = c
279 break
274 break
280 else:
275 else:
281 cmd = aliases[0]
276 cmd = aliases[0]
282 return (cmd, name, mod)
277 return (cmd, name, mod)
283
278
284 # first, search for an extension with the same name as the command
279 # first, search for an extension with the same name as the command
285 path = paths.pop(cmd, None)
280 path = paths.pop(cmd, None)
286 if path:
281 if path:
287 ext = findcmd(cmd, cmd, path)
282 ext = findcmd(cmd, cmd, path)
288 if ext:
283 if ext:
289 return ext
284 return ext
290
285
291 # otherwise, interrogate each extension until there's a match
286 # otherwise, interrogate each extension until there's a match
292 for name, path in paths.iteritems():
287 for name, path in paths.iteritems():
293 ext = findcmd(cmd, name, path)
288 ext = findcmd(cmd, name, path)
294 if ext:
289 if ext:
295 return ext
290 return ext
296
291
297 raise error.UnknownCommand(cmd)
292 raise error.UnknownCommand(cmd)
298
293
299 def enabled():
294 def enabled():
300 '''return a dict of {name: desc} of extensions, and the max name length'''
295 '''return a dict of {name: desc} of extensions, and the max name length'''
301 exts = {}
296 exts = {}
302 maxlength = 0
303 for ename, ext in extensions():
297 for ename, ext in extensions():
304 doc = (gettext(ext.__doc__) or _('(no help text available)'))
298 doc = (gettext(ext.__doc__) or _('(no help text available)'))
305 ename = ename.split('.')[-1]
299 ename = ename.split('.')[-1]
306 maxlength = max(len(ename), maxlength)
307 exts[ename] = doc.splitlines()[0].strip()
300 exts[ename] = doc.splitlines()[0].strip()
308
301
309 return exts, maxlength
302 return exts
@@ -1,136 +1,132 b''
1 # help.py - help data for mercurial
1 # help.py - help data for mercurial
2 #
2 #
3 # Copyright 2006 Matt Mackall <mpm@selenic.com>
3 # Copyright 2006 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from i18n import gettext, _
8 from i18n import gettext, _
9 import sys, os
9 import sys, os
10 import extensions
10 import extensions
11 import util
11 import util
12
12
13
13
14 def moduledoc(file):
14 def moduledoc(file):
15 '''return the top-level python documentation for the given file
15 '''return the top-level python documentation for the given file
16
16
17 Loosely inspired by pydoc.source_synopsis(), but rewritten to
17 Loosely inspired by pydoc.source_synopsis(), but rewritten to
18 handle triple quotes and to return the whole text instead of just
18 handle triple quotes and to return the whole text instead of just
19 the synopsis'''
19 the synopsis'''
20 result = []
20 result = []
21
21
22 line = file.readline()
22 line = file.readline()
23 while line[:1] == '#' or not line.strip():
23 while line[:1] == '#' or not line.strip():
24 line = file.readline()
24 line = file.readline()
25 if not line:
25 if not line:
26 break
26 break
27
27
28 start = line[:3]
28 start = line[:3]
29 if start == '"""' or start == "'''":
29 if start == '"""' or start == "'''":
30 line = line[3:]
30 line = line[3:]
31 while line:
31 while line:
32 if line.rstrip().endswith(start):
32 if line.rstrip().endswith(start):
33 line = line.split(start)[0]
33 line = line.split(start)[0]
34 if line:
34 if line:
35 result.append(line)
35 result.append(line)
36 break
36 break
37 elif not line:
37 elif not line:
38 return None # unmatched delimiter
38 return None # unmatched delimiter
39 result.append(line)
39 result.append(line)
40 line = file.readline()
40 line = file.readline()
41 else:
41 else:
42 return None
42 return None
43
43
44 return ''.join(result)
44 return ''.join(result)
45
45
46 def listexts(header, exts, maxlength, indent=1):
46 def listexts(header, exts, indent=1):
47 '''return a text listing of the given extensions'''
47 '''return a text listing of the given extensions'''
48 if not exts:
48 if not exts:
49 return ''
49 return ''
50 maxlength = max(len(e) for e in exts)
50 result = '\n%s\n\n' % header
51 result = '\n%s\n\n' % header
51 for name, desc in sorted(exts.iteritems()):
52 for name, desc in sorted(exts.iteritems()):
52 result += '%s%-*s %s\n' % (' ' * indent, maxlength + 2,
53 result += '%s%-*s %s\n' % (' ' * indent, maxlength + 2,
53 ':%s:' % name, desc)
54 ':%s:' % name, desc)
54 return result
55 return result
55
56
56 def extshelp():
57 def extshelp():
57 doc = loaddoc('extensions')()
58 doc = loaddoc('extensions')()
58
59 doc += listexts(_('enabled extensions:'), extensions.enabled())
59 exts, maxlength = extensions.enabled()
60 doc += listexts(_('disabled extensions:'), extensions.disabled())
60 doc += listexts(_('enabled extensions:'), exts, maxlength)
61
62 exts, maxlength = extensions.disabled()
63 doc += listexts(_('disabled extensions:'), exts, maxlength)
64
65 return doc
61 return doc
66
62
67 def loaddoc(topic):
63 def loaddoc(topic):
68 """Return a delayed loader for help/topic.txt."""
64 """Return a delayed loader for help/topic.txt."""
69
65
70 def loader():
66 def loader():
71 if hasattr(sys, 'frozen'):
67 if hasattr(sys, 'frozen'):
72 module = sys.executable
68 module = sys.executable
73 else:
69 else:
74 module = __file__
70 module = __file__
75 base = os.path.dirname(module)
71 base = os.path.dirname(module)
76
72
77 for dir in ('.', '..'):
73 for dir in ('.', '..'):
78 docdir = os.path.join(base, dir, 'help')
74 docdir = os.path.join(base, dir, 'help')
79 if os.path.isdir(docdir):
75 if os.path.isdir(docdir):
80 break
76 break
81
77
82 path = os.path.join(docdir, topic + ".txt")
78 path = os.path.join(docdir, topic + ".txt")
83 doc = gettext(util.readfile(path))
79 doc = gettext(util.readfile(path))
84 for rewriter in helphooks.get(topic, []):
80 for rewriter in helphooks.get(topic, []):
85 doc = rewriter(topic, doc)
81 doc = rewriter(topic, doc)
86 return doc
82 return doc
87
83
88 return loader
84 return loader
89
85
90 helptable = sorted([
86 helptable = sorted([
91 (["config", "hgrc"], _("Configuration Files"), loaddoc('config')),
87 (["config", "hgrc"], _("Configuration Files"), loaddoc('config')),
92 (["dates"], _("Date Formats"), loaddoc('dates')),
88 (["dates"], _("Date Formats"), loaddoc('dates')),
93 (["patterns"], _("File Name Patterns"), loaddoc('patterns')),
89 (["patterns"], _("File Name Patterns"), loaddoc('patterns')),
94 (['environment', 'env'], _('Environment Variables'),
90 (['environment', 'env'], _('Environment Variables'),
95 loaddoc('environment')),
91 loaddoc('environment')),
96 (['revs', 'revisions'], _('Specifying Single Revisions'),
92 (['revs', 'revisions'], _('Specifying Single Revisions'),
97 loaddoc('revisions')),
93 loaddoc('revisions')),
98 (['mrevs', 'multirevs'], _('Specifying Multiple Revisions'),
94 (['mrevs', 'multirevs'], _('Specifying Multiple Revisions'),
99 loaddoc('multirevs')),
95 loaddoc('multirevs')),
100 (['revset', 'revsets'], _("Specifying Revision Sets"), loaddoc('revsets')),
96 (['revset', 'revsets'], _("Specifying Revision Sets"), loaddoc('revsets')),
101 (['diffs'], _('Diff Formats'), loaddoc('diffs')),
97 (['diffs'], _('Diff Formats'), loaddoc('diffs')),
102 (['merge-tools'], _('Merge Tools'), loaddoc('merge-tools')),
98 (['merge-tools'], _('Merge Tools'), loaddoc('merge-tools')),
103 (['templating', 'templates'], _('Template Usage'),
99 (['templating', 'templates'], _('Template Usage'),
104 loaddoc('templates')),
100 loaddoc('templates')),
105 (['urls'], _('URL Paths'), loaddoc('urls')),
101 (['urls'], _('URL Paths'), loaddoc('urls')),
106 (["extensions"], _("Using additional features"), extshelp),
102 (["extensions"], _("Using additional features"), extshelp),
107 (["subrepo", "subrepos"], _("Subrepositories"), loaddoc('subrepos')),
103 (["subrepo", "subrepos"], _("Subrepositories"), loaddoc('subrepos')),
108 (["hgweb"], _("Configuring hgweb"), loaddoc('hgweb')),
104 (["hgweb"], _("Configuring hgweb"), loaddoc('hgweb')),
109 (["glossary"], _("Glossary"), loaddoc('glossary')),
105 (["glossary"], _("Glossary"), loaddoc('glossary')),
110 (["hgignore", "ignore"], _("syntax for Mercurial ignore files"),
106 (["hgignore", "ignore"], _("syntax for Mercurial ignore files"),
111 loaddoc('hgignore')),
107 loaddoc('hgignore')),
112 ])
108 ])
113
109
114 # Map topics to lists of callable taking the current topic help and
110 # Map topics to lists of callable taking the current topic help and
115 # returning the updated version
111 # returning the updated version
116 helphooks = {
112 helphooks = {
117 }
113 }
118
114
119 def addtopichook(topic, rewriter):
115 def addtopichook(topic, rewriter):
120 helphooks.setdefault(topic, []).append(rewriter)
116 helphooks.setdefault(topic, []).append(rewriter)
121
117
122 def makeitemsdoc(topic, doc, marker, items):
118 def makeitemsdoc(topic, doc, marker, items):
123 """Extract docstring from the items key to function mapping, build a
119 """Extract docstring from the items key to function mapping, build a
124 .single documentation block and use it to overwrite the marker in doc
120 .single documentation block and use it to overwrite the marker in doc
125 """
121 """
126 entries = []
122 entries = []
127 for name in sorted(items):
123 for name in sorted(items):
128 text = (items[name].__doc__ or '').rstrip()
124 text = (items[name].__doc__ or '').rstrip()
129 if not text:
125 if not text:
130 continue
126 continue
131 text = gettext(text)
127 text = gettext(text)
132 lines = text.splitlines()
128 lines = text.splitlines()
133 lines[1:] = [(' ' + l.strip()) for l in lines[1:]]
129 lines[1:] = [(' ' + l.strip()) for l in lines[1:]]
134 entries.append('\n'.join(lines))
130 entries.append('\n'.join(lines))
135 entries = '\n\n'.join(entries)
131 entries = '\n\n'.join(entries)
136 return doc.replace(marker, entries)
132 return doc.replace(marker, entries)
@@ -1,1057 +1,1057 b''
1 # subrepo.py - sub-repository handling for Mercurial
1 # subrepo.py - sub-repository handling for Mercurial
2 #
2 #
3 # Copyright 2009-2010 Matt Mackall <mpm@selenic.com>
3 # Copyright 2009-2010 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 import errno, os, re, xml.dom.minidom, shutil, posixpath
8 import errno, os, re, xml.dom.minidom, shutil, posixpath
9 import stat, subprocess, tarfile
9 import stat, subprocess, tarfile
10 from i18n import _
10 from i18n import _
11 import config, scmutil, util, node, error, cmdutil, bookmarks
11 import config, scmutil, util, node, error, cmdutil, bookmarks
12 hg = None
12 hg = None
13 propertycache = util.propertycache
13 propertycache = util.propertycache
14
14
15 nullstate = ('', '', 'empty')
15 nullstate = ('', '', 'empty')
16
16
17 def state(ctx, ui):
17 def state(ctx, ui):
18 """return a state dict, mapping subrepo paths configured in .hgsub
18 """return a state dict, mapping subrepo paths configured in .hgsub
19 to tuple: (source from .hgsub, revision from .hgsubstate, kind
19 to tuple: (source from .hgsub, revision from .hgsubstate, kind
20 (key in types dict))
20 (key in types dict))
21 """
21 """
22 p = config.config()
22 p = config.config()
23 def read(f, sections=None, remap=None):
23 def read(f, sections=None, remap=None):
24 if f in ctx:
24 if f in ctx:
25 try:
25 try:
26 data = ctx[f].data()
26 data = ctx[f].data()
27 except IOError, err:
27 except IOError, err:
28 if err.errno != errno.ENOENT:
28 if err.errno != errno.ENOENT:
29 raise
29 raise
30 # handle missing subrepo spec files as removed
30 # handle missing subrepo spec files as removed
31 ui.warn(_("warning: subrepo spec file %s not found\n") % f)
31 ui.warn(_("warning: subrepo spec file %s not found\n") % f)
32 return
32 return
33 p.parse(f, data, sections, remap, read)
33 p.parse(f, data, sections, remap, read)
34 else:
34 else:
35 raise util.Abort(_("subrepo spec file %s not found") % f)
35 raise util.Abort(_("subrepo spec file %s not found") % f)
36
36
37 if '.hgsub' in ctx:
37 if '.hgsub' in ctx:
38 read('.hgsub')
38 read('.hgsub')
39
39
40 for path, src in ui.configitems('subpaths'):
40 for path, src in ui.configitems('subpaths'):
41 p.set('subpaths', path, src, ui.configsource('subpaths', path))
41 p.set('subpaths', path, src, ui.configsource('subpaths', path))
42
42
43 rev = {}
43 rev = {}
44 if '.hgsubstate' in ctx:
44 if '.hgsubstate' in ctx:
45 try:
45 try:
46 for l in ctx['.hgsubstate'].data().splitlines():
46 for l in ctx['.hgsubstate'].data().splitlines():
47 revision, path = l.split(" ", 1)
47 revision, path = l.split(" ", 1)
48 rev[path] = revision
48 rev[path] = revision
49 except IOError, err:
49 except IOError, err:
50 if err.errno != errno.ENOENT:
50 if err.errno != errno.ENOENT:
51 raise
51 raise
52
52
53 state = {}
53 state = {}
54 for path, src in p[''].items():
54 for path, src in p[''].items():
55 kind = 'hg'
55 kind = 'hg'
56 if src.startswith('['):
56 if src.startswith('['):
57 if ']' not in src:
57 if ']' not in src:
58 raise util.Abort(_('missing ] in subrepo source'))
58 raise util.Abort(_('missing ] in subrepo source'))
59 kind, src = src.split(']', 1)
59 kind, src = src.split(']', 1)
60 kind = kind[1:]
60 kind = kind[1:]
61
61
62 for pattern, repl in p.items('subpaths'):
62 for pattern, repl in p.items('subpaths'):
63 # Turn r'C:\foo\bar' into r'C:\\foo\\bar' since re.sub
63 # Turn r'C:\foo\bar' into r'C:\\foo\\bar' since re.sub
64 # does a string decode.
64 # does a string decode.
65 repl = repl.encode('string-escape')
65 repl = repl.encode('string-escape')
66 # However, we still want to allow back references to go
66 # However, we still want to allow back references to go
67 # through unharmed, so we turn r'\\1' into r'\1'. Again,
67 # through unharmed, so we turn r'\\1' into r'\1'. Again,
68 # extra escapes are needed because re.sub string decodes.
68 # extra escapes are needed because re.sub string decodes.
69 repl = re.sub(r'\\\\([0-9]+)', r'\\\1', repl)
69 repl = re.sub(r'\\\\([0-9]+)', r'\\\1', repl)
70 try:
70 try:
71 src = re.sub(pattern, repl, src, 1)
71 src = re.sub(pattern, repl, src, 1)
72 except re.error, e:
72 except re.error, e:
73 raise util.Abort(_("bad subrepository pattern in %s: %s")
73 raise util.Abort(_("bad subrepository pattern in %s: %s")
74 % (p.source('subpaths', pattern), e))
74 % (p.source('subpaths', pattern), e))
75
75
76 state[path] = (src.strip(), rev.get(path, ''), kind)
76 state[path] = (src.strip(), rev.get(path, ''), kind)
77
77
78 return state
78 return state
79
79
80 def writestate(repo, state):
80 def writestate(repo, state):
81 """rewrite .hgsubstate in (outer) repo with these subrepo states"""
81 """rewrite .hgsubstate in (outer) repo with these subrepo states"""
82 repo.wwrite('.hgsubstate',
82 repo.wwrite('.hgsubstate',
83 ''.join(['%s %s\n' % (state[s][1], s)
83 ''.join(['%s %s\n' % (state[s][1], s)
84 for s in sorted(state)]), '')
84 for s in sorted(state)]), '')
85
85
86 def submerge(repo, wctx, mctx, actx, overwrite):
86 def submerge(repo, wctx, mctx, actx, overwrite):
87 """delegated from merge.applyupdates: merging of .hgsubstate file
87 """delegated from merge.applyupdates: merging of .hgsubstate file
88 in working context, merging context and ancestor context"""
88 in working context, merging context and ancestor context"""
89 if mctx == actx: # backwards?
89 if mctx == actx: # backwards?
90 actx = wctx.p1()
90 actx = wctx.p1()
91 s1 = wctx.substate
91 s1 = wctx.substate
92 s2 = mctx.substate
92 s2 = mctx.substate
93 sa = actx.substate
93 sa = actx.substate
94 sm = {}
94 sm = {}
95
95
96 repo.ui.debug("subrepo merge %s %s %s\n" % (wctx, mctx, actx))
96 repo.ui.debug("subrepo merge %s %s %s\n" % (wctx, mctx, actx))
97
97
98 def debug(s, msg, r=""):
98 def debug(s, msg, r=""):
99 if r:
99 if r:
100 r = "%s:%s:%s" % r
100 r = "%s:%s:%s" % r
101 repo.ui.debug(" subrepo %s: %s %s\n" % (s, msg, r))
101 repo.ui.debug(" subrepo %s: %s %s\n" % (s, msg, r))
102
102
103 for s, l in s1.items():
103 for s, l in s1.items():
104 a = sa.get(s, nullstate)
104 a = sa.get(s, nullstate)
105 ld = l # local state with possible dirty flag for compares
105 ld = l # local state with possible dirty flag for compares
106 if wctx.sub(s).dirty():
106 if wctx.sub(s).dirty():
107 ld = (l[0], l[1] + "+")
107 ld = (l[0], l[1] + "+")
108 if wctx == actx: # overwrite
108 if wctx == actx: # overwrite
109 a = ld
109 a = ld
110
110
111 if s in s2:
111 if s in s2:
112 r = s2[s]
112 r = s2[s]
113 if ld == r or r == a: # no change or local is newer
113 if ld == r or r == a: # no change or local is newer
114 sm[s] = l
114 sm[s] = l
115 continue
115 continue
116 elif ld == a: # other side changed
116 elif ld == a: # other side changed
117 debug(s, "other changed, get", r)
117 debug(s, "other changed, get", r)
118 wctx.sub(s).get(r, overwrite)
118 wctx.sub(s).get(r, overwrite)
119 sm[s] = r
119 sm[s] = r
120 elif ld[0] != r[0]: # sources differ
120 elif ld[0] != r[0]: # sources differ
121 if repo.ui.promptchoice(
121 if repo.ui.promptchoice(
122 _(' subrepository sources for %s differ\n'
122 _(' subrepository sources for %s differ\n'
123 'use (l)ocal source (%s) or (r)emote source (%s)?')
123 'use (l)ocal source (%s) or (r)emote source (%s)?')
124 % (s, l[0], r[0]),
124 % (s, l[0], r[0]),
125 (_('&Local'), _('&Remote')), 0):
125 (_('&Local'), _('&Remote')), 0):
126 debug(s, "prompt changed, get", r)
126 debug(s, "prompt changed, get", r)
127 wctx.sub(s).get(r, overwrite)
127 wctx.sub(s).get(r, overwrite)
128 sm[s] = r
128 sm[s] = r
129 elif ld[1] == a[1]: # local side is unchanged
129 elif ld[1] == a[1]: # local side is unchanged
130 debug(s, "other side changed, get", r)
130 debug(s, "other side changed, get", r)
131 wctx.sub(s).get(r, overwrite)
131 wctx.sub(s).get(r, overwrite)
132 sm[s] = r
132 sm[s] = r
133 else:
133 else:
134 debug(s, "both sides changed, merge with", r)
134 debug(s, "both sides changed, merge with", r)
135 wctx.sub(s).merge(r)
135 wctx.sub(s).merge(r)
136 sm[s] = l
136 sm[s] = l
137 elif ld == a: # remote removed, local unchanged
137 elif ld == a: # remote removed, local unchanged
138 debug(s, "remote removed, remove")
138 debug(s, "remote removed, remove")
139 wctx.sub(s).remove()
139 wctx.sub(s).remove()
140 else:
140 else:
141 if repo.ui.promptchoice(
141 if repo.ui.promptchoice(
142 _(' local changed subrepository %s which remote removed\n'
142 _(' local changed subrepository %s which remote removed\n'
143 'use (c)hanged version or (d)elete?') % s,
143 'use (c)hanged version or (d)elete?') % s,
144 (_('&Changed'), _('&Delete')), 0):
144 (_('&Changed'), _('&Delete')), 0):
145 debug(s, "prompt remove")
145 debug(s, "prompt remove")
146 wctx.sub(s).remove()
146 wctx.sub(s).remove()
147
147
148 for s, r in sorted(s2.items()):
148 for s, r in sorted(s2.items()):
149 if s in s1:
149 if s in s1:
150 continue
150 continue
151 elif s not in sa:
151 elif s not in sa:
152 debug(s, "remote added, get", r)
152 debug(s, "remote added, get", r)
153 mctx.sub(s).get(r)
153 mctx.sub(s).get(r)
154 sm[s] = r
154 sm[s] = r
155 elif r != sa[s]:
155 elif r != sa[s]:
156 if repo.ui.promptchoice(
156 if repo.ui.promptchoice(
157 _(' remote changed subrepository %s which local removed\n'
157 _(' remote changed subrepository %s which local removed\n'
158 'use (c)hanged version or (d)elete?') % s,
158 'use (c)hanged version or (d)elete?') % s,
159 (_('&Changed'), _('&Delete')), 0) == 0:
159 (_('&Changed'), _('&Delete')), 0) == 0:
160 debug(s, "prompt recreate", r)
160 debug(s, "prompt recreate", r)
161 wctx.sub(s).get(r)
161 wctx.sub(s).get(r)
162 sm[s] = r
162 sm[s] = r
163
163
164 # record merged .hgsubstate
164 # record merged .hgsubstate
165 writestate(repo, sm)
165 writestate(repo, sm)
166
166
167 def _updateprompt(ui, sub, dirty, local, remote):
167 def _updateprompt(ui, sub, dirty, local, remote):
168 if dirty:
168 if dirty:
169 msg = (_(' subrepository sources for %s differ\n'
169 msg = (_(' subrepository sources for %s differ\n'
170 'use (l)ocal source (%s) or (r)emote source (%s)?\n')
170 'use (l)ocal source (%s) or (r)emote source (%s)?\n')
171 % (subrelpath(sub), local, remote))
171 % (subrelpath(sub), local, remote))
172 else:
172 else:
173 msg = (_(' subrepository sources for %s differ (in checked out version)\n'
173 msg = (_(' subrepository sources for %s differ (in checked out version)\n'
174 'use (l)ocal source (%s) or (r)emote source (%s)?\n')
174 'use (l)ocal source (%s) or (r)emote source (%s)?\n')
175 % (subrelpath(sub), local, remote))
175 % (subrelpath(sub), local, remote))
176 return ui.promptchoice(msg, (_('&Local'), _('&Remote')), 0)
176 return ui.promptchoice(msg, (_('&Local'), _('&Remote')), 0)
177
177
178 def reporelpath(repo):
178 def reporelpath(repo):
179 """return path to this (sub)repo as seen from outermost repo"""
179 """return path to this (sub)repo as seen from outermost repo"""
180 parent = repo
180 parent = repo
181 while hasattr(parent, '_subparent'):
181 while hasattr(parent, '_subparent'):
182 parent = parent._subparent
182 parent = parent._subparent
183 return repo.root[len(parent.root)+1:]
183 return repo.root[len(parent.root)+1:]
184
184
185 def subrelpath(sub):
185 def subrelpath(sub):
186 """return path to this subrepo as seen from outermost repo"""
186 """return path to this subrepo as seen from outermost repo"""
187 if hasattr(sub, '_relpath'):
187 if hasattr(sub, '_relpath'):
188 return sub._relpath
188 return sub._relpath
189 if not hasattr(sub, '_repo'):
189 if not hasattr(sub, '_repo'):
190 return sub._path
190 return sub._path
191 return reporelpath(sub._repo)
191 return reporelpath(sub._repo)
192
192
193 def _abssource(repo, push=False, abort=True):
193 def _abssource(repo, push=False, abort=True):
194 """return pull/push path of repo - either based on parent repo .hgsub info
194 """return pull/push path of repo - either based on parent repo .hgsub info
195 or on the top repo config. Abort or return None if no source found."""
195 or on the top repo config. Abort or return None if no source found."""
196 if hasattr(repo, '_subparent'):
196 if hasattr(repo, '_subparent'):
197 source = util.url(repo._subsource)
197 source = util.url(repo._subsource)
198 source.path = posixpath.normpath(source.path)
198 source.path = posixpath.normpath(source.path)
199 if posixpath.isabs(source.path) or source.scheme:
199 if posixpath.isabs(source.path) or source.scheme:
200 return str(source)
200 return str(source)
201 parent = _abssource(repo._subparent, push, abort=False)
201 parent = _abssource(repo._subparent, push, abort=False)
202 if parent:
202 if parent:
203 parent = util.url(parent)
203 parent = util.url(parent)
204 parent.path = posixpath.join(parent.path, source.path)
204 parent.path = posixpath.join(parent.path, source.path)
205 parent.path = posixpath.normpath(parent.path)
205 parent.path = posixpath.normpath(parent.path)
206 return str(parent)
206 return str(parent)
207 else: # recursion reached top repo
207 else: # recursion reached top repo
208 if hasattr(repo, '_subtoppath'):
208 if hasattr(repo, '_subtoppath'):
209 return repo._subtoppath
209 return repo._subtoppath
210 if push and repo.ui.config('paths', 'default-push'):
210 if push and repo.ui.config('paths', 'default-push'):
211 return repo.ui.config('paths', 'default-push')
211 return repo.ui.config('paths', 'default-push')
212 if repo.ui.config('paths', 'default'):
212 if repo.ui.config('paths', 'default'):
213 return repo.ui.config('paths', 'default')
213 return repo.ui.config('paths', 'default')
214 if abort:
214 if abort:
215 raise util.Abort(_("default path for subrepository %s not found") %
215 raise util.Abort(_("default path for subrepository %s not found") %
216 reporelpath(repo))
216 reporelpath(repo))
217
217
218 def itersubrepos(ctx1, ctx2):
218 def itersubrepos(ctx1, ctx2):
219 """find subrepos in ctx1 or ctx2"""
219 """find subrepos in ctx1 or ctx2"""
220 # Create a (subpath, ctx) mapping where we prefer subpaths from
220 # Create a (subpath, ctx) mapping where we prefer subpaths from
221 # ctx1. The subpaths from ctx2 are important when the .hgsub file
221 # ctx1. The subpaths from ctx2 are important when the .hgsub file
222 # has been modified (in ctx2) but not yet committed (in ctx1).
222 # has been modified (in ctx2) but not yet committed (in ctx1).
223 subpaths = dict.fromkeys(ctx2.substate, ctx2)
223 subpaths = dict.fromkeys(ctx2.substate, ctx2)
224 subpaths.update(dict.fromkeys(ctx1.substate, ctx1))
224 subpaths.update(dict.fromkeys(ctx1.substate, ctx1))
225 for subpath, ctx in sorted(subpaths.iteritems()):
225 for subpath, ctx in sorted(subpaths.iteritems()):
226 yield subpath, ctx.sub(subpath)
226 yield subpath, ctx.sub(subpath)
227
227
228 def subrepo(ctx, path):
228 def subrepo(ctx, path):
229 """return instance of the right subrepo class for subrepo in path"""
229 """return instance of the right subrepo class for subrepo in path"""
230 # subrepo inherently violates our import layering rules
230 # subrepo inherently violates our import layering rules
231 # because it wants to make repo objects from deep inside the stack
231 # because it wants to make repo objects from deep inside the stack
232 # so we manually delay the circular imports to not break
232 # so we manually delay the circular imports to not break
233 # scripts that don't use our demand-loading
233 # scripts that don't use our demand-loading
234 global hg
234 global hg
235 import hg as h
235 import hg as h
236 hg = h
236 hg = h
237
237
238 scmutil.pathauditor(ctx._repo.root)(path)
238 scmutil.pathauditor(ctx._repo.root)(path)
239 state = ctx.substate.get(path, nullstate)
239 state = ctx.substate.get(path, nullstate)
240 if state[2] not in types:
240 if state[2] not in types:
241 raise util.Abort(_('unknown subrepo type %s') % state[2])
241 raise util.Abort(_('unknown subrepo type %s') % state[2])
242 return types[state[2]](ctx, path, state[:2])
242 return types[state[2]](ctx, path, state[:2])
243
243
244 # subrepo classes need to implement the following abstract class:
244 # subrepo classes need to implement the following abstract class:
245
245
246 class abstractsubrepo(object):
246 class abstractsubrepo(object):
247
247
248 def dirty(self, ignoreupdate=False):
248 def dirty(self, ignoreupdate=False):
249 """returns true if the dirstate of the subrepo is dirty or does not
249 """returns true if the dirstate of the subrepo is dirty or does not
250 match current stored state. If ignoreupdate is true, only check
250 match current stored state. If ignoreupdate is true, only check
251 whether the subrepo has uncommitted changes in its dirstate.
251 whether the subrepo has uncommitted changes in its dirstate.
252 """
252 """
253 raise NotImplementedError
253 raise NotImplementedError
254
254
255 def checknested(self, path):
255 def checknested(self, path):
256 """check if path is a subrepository within this repository"""
256 """check if path is a subrepository within this repository"""
257 return False
257 return False
258
258
259 def commit(self, text, user, date):
259 def commit(self, text, user, date):
260 """commit the current changes to the subrepo with the given
260 """commit the current changes to the subrepo with the given
261 log message. Use given user and date if possible. Return the
261 log message. Use given user and date if possible. Return the
262 new state of the subrepo.
262 new state of the subrepo.
263 """
263 """
264 raise NotImplementedError
264 raise NotImplementedError
265
265
266 def remove(self):
266 def remove(self):
267 """remove the subrepo
267 """remove the subrepo
268
268
269 (should verify the dirstate is not dirty first)
269 (should verify the dirstate is not dirty first)
270 """
270 """
271 raise NotImplementedError
271 raise NotImplementedError
272
272
273 def get(self, state, overwrite=False):
273 def get(self, state, overwrite=False):
274 """run whatever commands are needed to put the subrepo into
274 """run whatever commands are needed to put the subrepo into
275 this state
275 this state
276 """
276 """
277 raise NotImplementedError
277 raise NotImplementedError
278
278
279 def merge(self, state):
279 def merge(self, state):
280 """merge currently-saved state with the new state."""
280 """merge currently-saved state with the new state."""
281 raise NotImplementedError
281 raise NotImplementedError
282
282
283 def push(self, force):
283 def push(self, force):
284 """perform whatever action is analogous to 'hg push'
284 """perform whatever action is analogous to 'hg push'
285
285
286 This may be a no-op on some systems.
286 This may be a no-op on some systems.
287 """
287 """
288 raise NotImplementedError
288 raise NotImplementedError
289
289
290 def add(self, ui, match, dryrun, prefix):
290 def add(self, ui, match, dryrun, prefix):
291 return []
291 return []
292
292
293 def status(self, rev2, **opts):
293 def status(self, rev2, **opts):
294 return [], [], [], [], [], [], []
294 return [], [], [], [], [], [], []
295
295
296 def diff(self, diffopts, node2, match, prefix, **opts):
296 def diff(self, diffopts, node2, match, prefix, **opts):
297 pass
297 pass
298
298
299 def outgoing(self, ui, dest, opts):
299 def outgoing(self, ui, dest, opts):
300 return 1
300 return 1
301
301
302 def incoming(self, ui, source, opts):
302 def incoming(self, ui, source, opts):
303 return 1
303 return 1
304
304
305 def files(self):
305 def files(self):
306 """return filename iterator"""
306 """return filename iterator"""
307 raise NotImplementedError
307 raise NotImplementedError
308
308
309 def filedata(self, name):
309 def filedata(self, name):
310 """return file data"""
310 """return file data"""
311 raise NotImplementedError
311 raise NotImplementedError
312
312
313 def fileflags(self, name):
313 def fileflags(self, name):
314 """return file flags"""
314 """return file flags"""
315 return ''
315 return ''
316
316
317 def archive(self, ui, archiver, prefix):
317 def archive(self, ui, archiver, prefix):
318 files = self.files()
318 files = self.files()
319 total = len(files)
319 total = len(files)
320 relpath = subrelpath(self)
320 relpath = subrelpath(self)
321 ui.progress(_('archiving (%s)') % relpath, 0,
321 ui.progress(_('archiving (%s)') % relpath, 0,
322 unit=_('files'), total=total)
322 unit=_('files'), total=total)
323 for i, name in enumerate(files):
323 for i, name in enumerate(files):
324 flags = self.fileflags(name)
324 flags = self.fileflags(name)
325 mode = 'x' in flags and 0755 or 0644
325 mode = 'x' in flags and 0755 or 0644
326 symlink = 'l' in flags
326 symlink = 'l' in flags
327 archiver.addfile(os.path.join(prefix, self._path, name),
327 archiver.addfile(os.path.join(prefix, self._path, name),
328 mode, symlink, self.filedata(name))
328 mode, symlink, self.filedata(name))
329 ui.progress(_('archiving (%s)') % relpath, i + 1,
329 ui.progress(_('archiving (%s)') % relpath, i + 1,
330 unit=_('files'), total=total)
330 unit=_('files'), total=total)
331 ui.progress(_('archiving (%s)') % relpath, None)
331 ui.progress(_('archiving (%s)') % relpath, None)
332
332
333
333
334 class hgsubrepo(abstractsubrepo):
334 class hgsubrepo(abstractsubrepo):
335 def __init__(self, ctx, path, state):
335 def __init__(self, ctx, path, state):
336 self._path = path
336 self._path = path
337 self._state = state
337 self._state = state
338 r = ctx._repo
338 r = ctx._repo
339 root = r.wjoin(path)
339 root = r.wjoin(path)
340 create = False
340 create = False
341 if not os.path.exists(os.path.join(root, '.hg')):
341 if not os.path.exists(os.path.join(root, '.hg')):
342 create = True
342 create = True
343 util.makedirs(root)
343 util.makedirs(root)
344 self._repo = hg.repository(r.ui, root, create=create)
344 self._repo = hg.repository(r.ui, root, create=create)
345 self._initrepo(r, state[0], create)
345 self._initrepo(r, state[0], create)
346
346
347 def _initrepo(self, parentrepo, source, create):
347 def _initrepo(self, parentrepo, source, create):
348 self._repo._subparent = parentrepo
348 self._repo._subparent = parentrepo
349 self._repo._subsource = source
349 self._repo._subsource = source
350
350
351 if create:
351 if create:
352 fp = self._repo.opener("hgrc", "w", text=True)
352 fp = self._repo.opener("hgrc", "w", text=True)
353 fp.write('[paths]\n')
353 fp.write('[paths]\n')
354
354
355 def addpathconfig(key, value):
355 def addpathconfig(key, value):
356 if value:
356 if value:
357 fp.write('%s = %s\n' % (key, value))
357 fp.write('%s = %s\n' % (key, value))
358 self._repo.ui.setconfig('paths', key, value)
358 self._repo.ui.setconfig('paths', key, value)
359
359
360 defpath = _abssource(self._repo, abort=False)
360 defpath = _abssource(self._repo, abort=False)
361 defpushpath = _abssource(self._repo, True, abort=False)
361 defpushpath = _abssource(self._repo, True, abort=False)
362 addpathconfig('default', defpath)
362 addpathconfig('default', defpath)
363 if defpath != defpushpath:
363 if defpath != defpushpath:
364 addpathconfig('default-push', defpushpath)
364 addpathconfig('default-push', defpushpath)
365 fp.close()
365 fp.close()
366
366
367 def add(self, ui, match, dryrun, prefix):
367 def add(self, ui, match, dryrun, prefix):
368 return cmdutil.add(ui, self._repo, match, dryrun, True,
368 return cmdutil.add(ui, self._repo, match, dryrun, True,
369 os.path.join(prefix, self._path))
369 os.path.join(prefix, self._path))
370
370
371 def status(self, rev2, **opts):
371 def status(self, rev2, **opts):
372 try:
372 try:
373 rev1 = self._state[1]
373 rev1 = self._state[1]
374 ctx1 = self._repo[rev1]
374 ctx1 = self._repo[rev1]
375 ctx2 = self._repo[rev2]
375 ctx2 = self._repo[rev2]
376 return self._repo.status(ctx1, ctx2, **opts)
376 return self._repo.status(ctx1, ctx2, **opts)
377 except error.RepoLookupError, inst:
377 except error.RepoLookupError, inst:
378 self._repo.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
378 self._repo.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
379 % (inst, subrelpath(self)))
379 % (inst, subrelpath(self)))
380 return [], [], [], [], [], [], []
380 return [], [], [], [], [], [], []
381
381
382 def diff(self, diffopts, node2, match, prefix, **opts):
382 def diff(self, diffopts, node2, match, prefix, **opts):
383 try:
383 try:
384 node1 = node.bin(self._state[1])
384 node1 = node.bin(self._state[1])
385 # We currently expect node2 to come from substate and be
385 # We currently expect node2 to come from substate and be
386 # in hex format
386 # in hex format
387 if node2 is not None:
387 if node2 is not None:
388 node2 = node.bin(node2)
388 node2 = node.bin(node2)
389 cmdutil.diffordiffstat(self._repo.ui, self._repo, diffopts,
389 cmdutil.diffordiffstat(self._repo.ui, self._repo, diffopts,
390 node1, node2, match,
390 node1, node2, match,
391 prefix=os.path.join(prefix, self._path),
391 prefix=os.path.join(prefix, self._path),
392 listsubrepos=True, **opts)
392 listsubrepos=True, **opts)
393 except error.RepoLookupError, inst:
393 except error.RepoLookupError, inst:
394 self._repo.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
394 self._repo.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
395 % (inst, subrelpath(self)))
395 % (inst, subrelpath(self)))
396
396
397 def archive(self, ui, archiver, prefix):
397 def archive(self, ui, archiver, prefix):
398 abstractsubrepo.archive(self, ui, archiver, prefix)
398 abstractsubrepo.archive(self, ui, archiver, prefix)
399
399
400 rev = self._state[1]
400 rev = self._state[1]
401 ctx = self._repo[rev]
401 ctx = self._repo[rev]
402 for subpath in ctx.substate:
402 for subpath in ctx.substate:
403 s = subrepo(ctx, subpath)
403 s = subrepo(ctx, subpath)
404 s.archive(ui, archiver, os.path.join(prefix, self._path))
404 s.archive(ui, archiver, os.path.join(prefix, self._path))
405
405
406 def dirty(self, ignoreupdate=False):
406 def dirty(self, ignoreupdate=False):
407 r = self._state[1]
407 r = self._state[1]
408 if r == '' and not ignoreupdate: # no state recorded
408 if r == '' and not ignoreupdate: # no state recorded
409 return True
409 return True
410 w = self._repo[None]
410 w = self._repo[None]
411 if r != w.p1().node() and not ignoreupdate:
411 if r != w.p1().hex() and not ignoreupdate:
412 # different version checked out
412 # different version checked out
413 return True
413 return True
414 return w.dirty() # working directory changed
414 return w.dirty() # working directory changed
415
415
416 def checknested(self, path):
416 def checknested(self, path):
417 return self._repo._checknested(self._repo.wjoin(path))
417 return self._repo._checknested(self._repo.wjoin(path))
418
418
419 def commit(self, text, user, date):
419 def commit(self, text, user, date):
420 self._repo.ui.debug("committing subrepo %s\n" % subrelpath(self))
420 self._repo.ui.debug("committing subrepo %s\n" % subrelpath(self))
421 n = self._repo.commit(text, user, date)
421 n = self._repo.commit(text, user, date)
422 if not n:
422 if not n:
423 return self._repo['.'].hex() # different version checked out
423 return self._repo['.'].hex() # different version checked out
424 return node.hex(n)
424 return node.hex(n)
425
425
426 def remove(self):
426 def remove(self):
427 # we can't fully delete the repository as it may contain
427 # we can't fully delete the repository as it may contain
428 # local-only history
428 # local-only history
429 self._repo.ui.note(_('removing subrepo %s\n') % subrelpath(self))
429 self._repo.ui.note(_('removing subrepo %s\n') % subrelpath(self))
430 hg.clean(self._repo, node.nullid, False)
430 hg.clean(self._repo, node.nullid, False)
431
431
432 def _get(self, state):
432 def _get(self, state):
433 source, revision, kind = state
433 source, revision, kind = state
434 if revision not in self._repo:
434 if revision not in self._repo:
435 self._repo._subsource = source
435 self._repo._subsource = source
436 srcurl = _abssource(self._repo)
436 srcurl = _abssource(self._repo)
437 other = hg.repository(self._repo.ui, srcurl)
437 other = hg.repository(self._repo.ui, srcurl)
438 if len(self._repo) == 0:
438 if len(self._repo) == 0:
439 self._repo.ui.status(_('cloning subrepo %s from %s\n')
439 self._repo.ui.status(_('cloning subrepo %s from %s\n')
440 % (subrelpath(self), srcurl))
440 % (subrelpath(self), srcurl))
441 parentrepo = self._repo._subparent
441 parentrepo = self._repo._subparent
442 shutil.rmtree(self._repo.root)
442 shutil.rmtree(self._repo.root)
443 other, self._repo = hg.clone(self._repo._subparent.ui, other,
443 other, self._repo = hg.clone(self._repo._subparent.ui, other,
444 self._repo.root, update=False)
444 self._repo.root, update=False)
445 self._initrepo(parentrepo, source, create=True)
445 self._initrepo(parentrepo, source, create=True)
446 else:
446 else:
447 self._repo.ui.status(_('pulling subrepo %s from %s\n')
447 self._repo.ui.status(_('pulling subrepo %s from %s\n')
448 % (subrelpath(self), srcurl))
448 % (subrelpath(self), srcurl))
449 self._repo.pull(other)
449 self._repo.pull(other)
450 bookmarks.updatefromremote(self._repo.ui, self._repo, other)
450 bookmarks.updatefromremote(self._repo.ui, self._repo, other)
451
451
452 def get(self, state, overwrite=False):
452 def get(self, state, overwrite=False):
453 self._get(state)
453 self._get(state)
454 source, revision, kind = state
454 source, revision, kind = state
455 self._repo.ui.debug("getting subrepo %s\n" % self._path)
455 self._repo.ui.debug("getting subrepo %s\n" % self._path)
456 hg.clean(self._repo, revision, False)
456 hg.clean(self._repo, revision, False)
457
457
458 def merge(self, state):
458 def merge(self, state):
459 self._get(state)
459 self._get(state)
460 cur = self._repo['.']
460 cur = self._repo['.']
461 dst = self._repo[state[1]]
461 dst = self._repo[state[1]]
462 anc = dst.ancestor(cur)
462 anc = dst.ancestor(cur)
463
463
464 def mergefunc():
464 def mergefunc():
465 if anc == cur:
465 if anc == cur:
466 self._repo.ui.debug("updating subrepo %s\n" % subrelpath(self))
466 self._repo.ui.debug("updating subrepo %s\n" % subrelpath(self))
467 hg.update(self._repo, state[1])
467 hg.update(self._repo, state[1])
468 elif anc == dst:
468 elif anc == dst:
469 self._repo.ui.debug("skipping subrepo %s\n" % subrelpath(self))
469 self._repo.ui.debug("skipping subrepo %s\n" % subrelpath(self))
470 else:
470 else:
471 self._repo.ui.debug("merging subrepo %s\n" % subrelpath(self))
471 self._repo.ui.debug("merging subrepo %s\n" % subrelpath(self))
472 hg.merge(self._repo, state[1], remind=False)
472 hg.merge(self._repo, state[1], remind=False)
473
473
474 wctx = self._repo[None]
474 wctx = self._repo[None]
475 if self.dirty():
475 if self.dirty():
476 if anc != dst:
476 if anc != dst:
477 if _updateprompt(self._repo.ui, self, wctx.dirty(), cur, dst):
477 if _updateprompt(self._repo.ui, self, wctx.dirty(), cur, dst):
478 mergefunc()
478 mergefunc()
479 else:
479 else:
480 mergefunc()
480 mergefunc()
481 else:
481 else:
482 mergefunc()
482 mergefunc()
483
483
484 def push(self, force):
484 def push(self, force):
485 # push subrepos depth-first for coherent ordering
485 # push subrepos depth-first for coherent ordering
486 c = self._repo['']
486 c = self._repo['']
487 subs = c.substate # only repos that are committed
487 subs = c.substate # only repos that are committed
488 for s in sorted(subs):
488 for s in sorted(subs):
489 if not c.sub(s).push(force):
489 if not c.sub(s).push(force):
490 return False
490 return False
491
491
492 dsturl = _abssource(self._repo, True)
492 dsturl = _abssource(self._repo, True)
493 self._repo.ui.status(_('pushing subrepo %s to %s\n') %
493 self._repo.ui.status(_('pushing subrepo %s to %s\n') %
494 (subrelpath(self), dsturl))
494 (subrelpath(self), dsturl))
495 other = hg.repository(self._repo.ui, dsturl)
495 other = hg.repository(self._repo.ui, dsturl)
496 return self._repo.push(other, force)
496 return self._repo.push(other, force)
497
497
498 def outgoing(self, ui, dest, opts):
498 def outgoing(self, ui, dest, opts):
499 return hg.outgoing(ui, self._repo, _abssource(self._repo, True), opts)
499 return hg.outgoing(ui, self._repo, _abssource(self._repo, True), opts)
500
500
501 def incoming(self, ui, source, opts):
501 def incoming(self, ui, source, opts):
502 return hg.incoming(ui, self._repo, _abssource(self._repo, False), opts)
502 return hg.incoming(ui, self._repo, _abssource(self._repo, False), opts)
503
503
504 def files(self):
504 def files(self):
505 rev = self._state[1]
505 rev = self._state[1]
506 ctx = self._repo[rev]
506 ctx = self._repo[rev]
507 return ctx.manifest()
507 return ctx.manifest()
508
508
509 def filedata(self, name):
509 def filedata(self, name):
510 rev = self._state[1]
510 rev = self._state[1]
511 return self._repo[rev][name].data()
511 return self._repo[rev][name].data()
512
512
513 def fileflags(self, name):
513 def fileflags(self, name):
514 rev = self._state[1]
514 rev = self._state[1]
515 ctx = self._repo[rev]
515 ctx = self._repo[rev]
516 return ctx.flags(name)
516 return ctx.flags(name)
517
517
518
518
519 class svnsubrepo(abstractsubrepo):
519 class svnsubrepo(abstractsubrepo):
520 def __init__(self, ctx, path, state):
520 def __init__(self, ctx, path, state):
521 self._path = path
521 self._path = path
522 self._state = state
522 self._state = state
523 self._ctx = ctx
523 self._ctx = ctx
524 self._ui = ctx._repo.ui
524 self._ui = ctx._repo.ui
525
525
526 def _svncommand(self, commands, filename=''):
526 def _svncommand(self, commands, filename=''):
527 cmd = ['svn']
527 cmd = ['svn']
528 # Starting in svn 1.5 --non-interactive is a global flag
528 # Starting in svn 1.5 --non-interactive is a global flag
529 # instead of being per-command, but we need to support 1.4 so
529 # instead of being per-command, but we need to support 1.4 so
530 # we have to be intelligent about what commands take
530 # we have to be intelligent about what commands take
531 # --non-interactive.
531 # --non-interactive.
532 if (not self._ui.interactive() and
532 if (not self._ui.interactive() and
533 commands[0] in ('update', 'checkout', 'commit')):
533 commands[0] in ('update', 'checkout', 'commit')):
534 cmd.append('--non-interactive')
534 cmd.append('--non-interactive')
535 cmd.extend(commands)
535 cmd.extend(commands)
536 if filename is not None:
536 if filename is not None:
537 path = os.path.join(self._ctx._repo.origroot, self._path, filename)
537 path = os.path.join(self._ctx._repo.origroot, self._path, filename)
538 cmd.append(path)
538 cmd.append(path)
539 env = dict(os.environ)
539 env = dict(os.environ)
540 # Avoid localized output, preserve current locale for everything else.
540 # Avoid localized output, preserve current locale for everything else.
541 env['LC_MESSAGES'] = 'C'
541 env['LC_MESSAGES'] = 'C'
542 p = subprocess.Popen(cmd, bufsize=-1, close_fds=util.closefds,
542 p = subprocess.Popen(cmd, bufsize=-1, close_fds=util.closefds,
543 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
543 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
544 universal_newlines=True, env=env)
544 universal_newlines=True, env=env)
545 stdout, stderr = p.communicate()
545 stdout, stderr = p.communicate()
546 stderr = stderr.strip()
546 stderr = stderr.strip()
547 if stderr:
547 if stderr:
548 raise util.Abort(stderr)
548 raise util.Abort(stderr)
549 return stdout
549 return stdout
550
550
551 @propertycache
551 @propertycache
552 def _svnversion(self):
552 def _svnversion(self):
553 output = self._svncommand(['--version'], filename=None)
553 output = self._svncommand(['--version'], filename=None)
554 m = re.search(r'^svn,\s+version\s+(\d+)\.(\d+)', output)
554 m = re.search(r'^svn,\s+version\s+(\d+)\.(\d+)', output)
555 if not m:
555 if not m:
556 raise util.Abort(_('cannot retrieve svn tool version'))
556 raise util.Abort(_('cannot retrieve svn tool version'))
557 return (int(m.group(1)), int(m.group(2)))
557 return (int(m.group(1)), int(m.group(2)))
558
558
559 def _wcrevs(self):
559 def _wcrevs(self):
560 # Get the working directory revision as well as the last
560 # Get the working directory revision as well as the last
561 # commit revision so we can compare the subrepo state with
561 # commit revision so we can compare the subrepo state with
562 # both. We used to store the working directory one.
562 # both. We used to store the working directory one.
563 output = self._svncommand(['info', '--xml'])
563 output = self._svncommand(['info', '--xml'])
564 doc = xml.dom.minidom.parseString(output)
564 doc = xml.dom.minidom.parseString(output)
565 entries = doc.getElementsByTagName('entry')
565 entries = doc.getElementsByTagName('entry')
566 lastrev, rev = '0', '0'
566 lastrev, rev = '0', '0'
567 if entries:
567 if entries:
568 rev = str(entries[0].getAttribute('revision')) or '0'
568 rev = str(entries[0].getAttribute('revision')) or '0'
569 commits = entries[0].getElementsByTagName('commit')
569 commits = entries[0].getElementsByTagName('commit')
570 if commits:
570 if commits:
571 lastrev = str(commits[0].getAttribute('revision')) or '0'
571 lastrev = str(commits[0].getAttribute('revision')) or '0'
572 return (lastrev, rev)
572 return (lastrev, rev)
573
573
574 def _wcrev(self):
574 def _wcrev(self):
575 return self._wcrevs()[0]
575 return self._wcrevs()[0]
576
576
577 def _wcchanged(self):
577 def _wcchanged(self):
578 """Return (changes, extchanges) where changes is True
578 """Return (changes, extchanges) where changes is True
579 if the working directory was changed, and extchanges is
579 if the working directory was changed, and extchanges is
580 True if any of these changes concern an external entry.
580 True if any of these changes concern an external entry.
581 """
581 """
582 output = self._svncommand(['status', '--xml'])
582 output = self._svncommand(['status', '--xml'])
583 externals, changes = [], []
583 externals, changes = [], []
584 doc = xml.dom.minidom.parseString(output)
584 doc = xml.dom.minidom.parseString(output)
585 for e in doc.getElementsByTagName('entry'):
585 for e in doc.getElementsByTagName('entry'):
586 s = e.getElementsByTagName('wc-status')
586 s = e.getElementsByTagName('wc-status')
587 if not s:
587 if not s:
588 continue
588 continue
589 item = s[0].getAttribute('item')
589 item = s[0].getAttribute('item')
590 props = s[0].getAttribute('props')
590 props = s[0].getAttribute('props')
591 path = e.getAttribute('path')
591 path = e.getAttribute('path')
592 if item == 'external':
592 if item == 'external':
593 externals.append(path)
593 externals.append(path)
594 if (item not in ('', 'normal', 'unversioned', 'external')
594 if (item not in ('', 'normal', 'unversioned', 'external')
595 or props not in ('', 'none')):
595 or props not in ('', 'none')):
596 changes.append(path)
596 changes.append(path)
597 for path in changes:
597 for path in changes:
598 for ext in externals:
598 for ext in externals:
599 if path == ext or path.startswith(ext + os.sep):
599 if path == ext or path.startswith(ext + os.sep):
600 return True, True
600 return True, True
601 return bool(changes), False
601 return bool(changes), False
602
602
603 def dirty(self, ignoreupdate=False):
603 def dirty(self, ignoreupdate=False):
604 if not self._wcchanged()[0]:
604 if not self._wcchanged()[0]:
605 if self._state[1] in self._wcrevs() or ignoreupdate:
605 if self._state[1] in self._wcrevs() or ignoreupdate:
606 return False
606 return False
607 return True
607 return True
608
608
609 def commit(self, text, user, date):
609 def commit(self, text, user, date):
610 # user and date are out of our hands since svn is centralized
610 # user and date are out of our hands since svn is centralized
611 changed, extchanged = self._wcchanged()
611 changed, extchanged = self._wcchanged()
612 if not changed:
612 if not changed:
613 return self._wcrev()
613 return self._wcrev()
614 if extchanged:
614 if extchanged:
615 # Do not try to commit externals
615 # Do not try to commit externals
616 raise util.Abort(_('cannot commit svn externals'))
616 raise util.Abort(_('cannot commit svn externals'))
617 commitinfo = self._svncommand(['commit', '-m', text])
617 commitinfo = self._svncommand(['commit', '-m', text])
618 self._ui.status(commitinfo)
618 self._ui.status(commitinfo)
619 newrev = re.search('Committed revision ([0-9]+).', commitinfo)
619 newrev = re.search('Committed revision ([0-9]+).', commitinfo)
620 if not newrev:
620 if not newrev:
621 raise util.Abort(commitinfo.splitlines()[-1])
621 raise util.Abort(commitinfo.splitlines()[-1])
622 newrev = newrev.groups()[0]
622 newrev = newrev.groups()[0]
623 self._ui.status(self._svncommand(['update', '-r', newrev]))
623 self._ui.status(self._svncommand(['update', '-r', newrev]))
624 return newrev
624 return newrev
625
625
626 def remove(self):
626 def remove(self):
627 if self.dirty():
627 if self.dirty():
628 self._ui.warn(_('not removing repo %s because '
628 self._ui.warn(_('not removing repo %s because '
629 'it has changes.\n' % self._path))
629 'it has changes.\n' % self._path))
630 return
630 return
631 self._ui.note(_('removing subrepo %s\n') % self._path)
631 self._ui.note(_('removing subrepo %s\n') % self._path)
632
632
633 def onerror(function, path, excinfo):
633 def onerror(function, path, excinfo):
634 if function is not os.remove:
634 if function is not os.remove:
635 raise
635 raise
636 # read-only files cannot be unlinked under Windows
636 # read-only files cannot be unlinked under Windows
637 s = os.stat(path)
637 s = os.stat(path)
638 if (s.st_mode & stat.S_IWRITE) != 0:
638 if (s.st_mode & stat.S_IWRITE) != 0:
639 raise
639 raise
640 os.chmod(path, stat.S_IMODE(s.st_mode) | stat.S_IWRITE)
640 os.chmod(path, stat.S_IMODE(s.st_mode) | stat.S_IWRITE)
641 os.remove(path)
641 os.remove(path)
642
642
643 path = self._ctx._repo.wjoin(self._path)
643 path = self._ctx._repo.wjoin(self._path)
644 shutil.rmtree(path, onerror=onerror)
644 shutil.rmtree(path, onerror=onerror)
645 try:
645 try:
646 os.removedirs(os.path.dirname(path))
646 os.removedirs(os.path.dirname(path))
647 except OSError:
647 except OSError:
648 pass
648 pass
649
649
650 def get(self, state, overwrite=False):
650 def get(self, state, overwrite=False):
651 if overwrite:
651 if overwrite:
652 self._svncommand(['revert', '--recursive'])
652 self._svncommand(['revert', '--recursive'])
653 args = ['checkout']
653 args = ['checkout']
654 if self._svnversion >= (1, 5):
654 if self._svnversion >= (1, 5):
655 args.append('--force')
655 args.append('--force')
656 args.extend([state[0], '--revision', state[1]])
656 args.extend([state[0], '--revision', state[1]])
657 status = self._svncommand(args)
657 status = self._svncommand(args)
658 if not re.search('Checked out revision [0-9]+.', status):
658 if not re.search('Checked out revision [0-9]+.', status):
659 raise util.Abort(status.splitlines()[-1])
659 raise util.Abort(status.splitlines()[-1])
660 self._ui.status(status)
660 self._ui.status(status)
661
661
662 def merge(self, state):
662 def merge(self, state):
663 old = self._state[1]
663 old = self._state[1]
664 new = state[1]
664 new = state[1]
665 if new != self._wcrev():
665 if new != self._wcrev():
666 dirty = old == self._wcrev() or self._wcchanged()[0]
666 dirty = old == self._wcrev() or self._wcchanged()[0]
667 if _updateprompt(self._ui, self, dirty, self._wcrev(), new):
667 if _updateprompt(self._ui, self, dirty, self._wcrev(), new):
668 self.get(state, False)
668 self.get(state, False)
669
669
670 def push(self, force):
670 def push(self, force):
671 # push is a no-op for SVN
671 # push is a no-op for SVN
672 return True
672 return True
673
673
674 def files(self):
674 def files(self):
675 output = self._svncommand(['list'])
675 output = self._svncommand(['list'])
676 # This works because svn forbids \n in filenames.
676 # This works because svn forbids \n in filenames.
677 return output.splitlines()
677 return output.splitlines()
678
678
679 def filedata(self, name):
679 def filedata(self, name):
680 return self._svncommand(['cat'], name)
680 return self._svncommand(['cat'], name)
681
681
682
682
683 class gitsubrepo(abstractsubrepo):
683 class gitsubrepo(abstractsubrepo):
684 def __init__(self, ctx, path, state):
684 def __init__(self, ctx, path, state):
685 # TODO add git version check.
685 # TODO add git version check.
686 self._state = state
686 self._state = state
687 self._ctx = ctx
687 self._ctx = ctx
688 self._path = path
688 self._path = path
689 self._relpath = os.path.join(reporelpath(ctx._repo), path)
689 self._relpath = os.path.join(reporelpath(ctx._repo), path)
690 self._abspath = ctx._repo.wjoin(path)
690 self._abspath = ctx._repo.wjoin(path)
691 self._subparent = ctx._repo
691 self._subparent = ctx._repo
692 self._ui = ctx._repo.ui
692 self._ui = ctx._repo.ui
693
693
694 def _gitcommand(self, commands, env=None, stream=False):
694 def _gitcommand(self, commands, env=None, stream=False):
695 return self._gitdir(commands, env=env, stream=stream)[0]
695 return self._gitdir(commands, env=env, stream=stream)[0]
696
696
697 def _gitdir(self, commands, env=None, stream=False):
697 def _gitdir(self, commands, env=None, stream=False):
698 return self._gitnodir(commands, env=env, stream=stream,
698 return self._gitnodir(commands, env=env, stream=stream,
699 cwd=self._abspath)
699 cwd=self._abspath)
700
700
701 def _gitnodir(self, commands, env=None, stream=False, cwd=None):
701 def _gitnodir(self, commands, env=None, stream=False, cwd=None):
702 """Calls the git command
702 """Calls the git command
703
703
704 The methods tries to call the git command. versions previor to 1.6.0
704 The methods tries to call the git command. versions previor to 1.6.0
705 are not supported and very probably fail.
705 are not supported and very probably fail.
706 """
706 """
707 self._ui.debug('%s: git %s\n' % (self._relpath, ' '.join(commands)))
707 self._ui.debug('%s: git %s\n' % (self._relpath, ' '.join(commands)))
708 # unless ui.quiet is set, print git's stderr,
708 # unless ui.quiet is set, print git's stderr,
709 # which is mostly progress and useful info
709 # which is mostly progress and useful info
710 errpipe = None
710 errpipe = None
711 if self._ui.quiet:
711 if self._ui.quiet:
712 errpipe = open(os.devnull, 'w')
712 errpipe = open(os.devnull, 'w')
713 p = subprocess.Popen(['git'] + commands, bufsize=-1, cwd=cwd, env=env,
713 p = subprocess.Popen(['git'] + commands, bufsize=-1, cwd=cwd, env=env,
714 close_fds=util.closefds,
714 close_fds=util.closefds,
715 stdout=subprocess.PIPE, stderr=errpipe)
715 stdout=subprocess.PIPE, stderr=errpipe)
716 if stream:
716 if stream:
717 return p.stdout, None
717 return p.stdout, None
718
718
719 retdata = p.stdout.read().strip()
719 retdata = p.stdout.read().strip()
720 # wait for the child to exit to avoid race condition.
720 # wait for the child to exit to avoid race condition.
721 p.wait()
721 p.wait()
722
722
723 if p.returncode != 0 and p.returncode != 1:
723 if p.returncode != 0 and p.returncode != 1:
724 # there are certain error codes that are ok
724 # there are certain error codes that are ok
725 command = commands[0]
725 command = commands[0]
726 if command in ('cat-file', 'symbolic-ref'):
726 if command in ('cat-file', 'symbolic-ref'):
727 return retdata, p.returncode
727 return retdata, p.returncode
728 # for all others, abort
728 # for all others, abort
729 raise util.Abort('git %s error %d in %s' %
729 raise util.Abort('git %s error %d in %s' %
730 (command, p.returncode, self._relpath))
730 (command, p.returncode, self._relpath))
731
731
732 return retdata, p.returncode
732 return retdata, p.returncode
733
733
734 def _gitmissing(self):
734 def _gitmissing(self):
735 return not os.path.exists(os.path.join(self._abspath, '.git'))
735 return not os.path.exists(os.path.join(self._abspath, '.git'))
736
736
737 def _gitstate(self):
737 def _gitstate(self):
738 return self._gitcommand(['rev-parse', 'HEAD'])
738 return self._gitcommand(['rev-parse', 'HEAD'])
739
739
740 def _gitcurrentbranch(self):
740 def _gitcurrentbranch(self):
741 current, err = self._gitdir(['symbolic-ref', 'HEAD', '--quiet'])
741 current, err = self._gitdir(['symbolic-ref', 'HEAD', '--quiet'])
742 if err:
742 if err:
743 current = None
743 current = None
744 return current
744 return current
745
745
746 def _gitremote(self, remote):
746 def _gitremote(self, remote):
747 out = self._gitcommand(['remote', 'show', '-n', remote])
747 out = self._gitcommand(['remote', 'show', '-n', remote])
748 line = out.split('\n')[1]
748 line = out.split('\n')[1]
749 i = line.index('URL: ') + len('URL: ')
749 i = line.index('URL: ') + len('URL: ')
750 return line[i:]
750 return line[i:]
751
751
752 def _githavelocally(self, revision):
752 def _githavelocally(self, revision):
753 out, code = self._gitdir(['cat-file', '-e', revision])
753 out, code = self._gitdir(['cat-file', '-e', revision])
754 return code == 0
754 return code == 0
755
755
756 def _gitisancestor(self, r1, r2):
756 def _gitisancestor(self, r1, r2):
757 base = self._gitcommand(['merge-base', r1, r2])
757 base = self._gitcommand(['merge-base', r1, r2])
758 return base == r1
758 return base == r1
759
759
760 def _gitbranchmap(self):
760 def _gitbranchmap(self):
761 '''returns 2 things:
761 '''returns 2 things:
762 a map from git branch to revision
762 a map from git branch to revision
763 a map from revision to branches'''
763 a map from revision to branches'''
764 branch2rev = {}
764 branch2rev = {}
765 rev2branch = {}
765 rev2branch = {}
766
766
767 out = self._gitcommand(['for-each-ref', '--format',
767 out = self._gitcommand(['for-each-ref', '--format',
768 '%(objectname) %(refname)'])
768 '%(objectname) %(refname)'])
769 for line in out.split('\n'):
769 for line in out.split('\n'):
770 revision, ref = line.split(' ')
770 revision, ref = line.split(' ')
771 if (not ref.startswith('refs/heads/') and
771 if (not ref.startswith('refs/heads/') and
772 not ref.startswith('refs/remotes/')):
772 not ref.startswith('refs/remotes/')):
773 continue
773 continue
774 if ref.startswith('refs/remotes/') and ref.endswith('/HEAD'):
774 if ref.startswith('refs/remotes/') and ref.endswith('/HEAD'):
775 continue # ignore remote/HEAD redirects
775 continue # ignore remote/HEAD redirects
776 branch2rev[ref] = revision
776 branch2rev[ref] = revision
777 rev2branch.setdefault(revision, []).append(ref)
777 rev2branch.setdefault(revision, []).append(ref)
778 return branch2rev, rev2branch
778 return branch2rev, rev2branch
779
779
780 def _gittracking(self, branches):
780 def _gittracking(self, branches):
781 'return map of remote branch to local tracking branch'
781 'return map of remote branch to local tracking branch'
782 # assumes no more than one local tracking branch for each remote
782 # assumes no more than one local tracking branch for each remote
783 tracking = {}
783 tracking = {}
784 for b in branches:
784 for b in branches:
785 if b.startswith('refs/remotes/'):
785 if b.startswith('refs/remotes/'):
786 continue
786 continue
787 remote = self._gitcommand(['config', 'branch.%s.remote' % b])
787 remote = self._gitcommand(['config', 'branch.%s.remote' % b])
788 if remote:
788 if remote:
789 ref = self._gitcommand(['config', 'branch.%s.merge' % b])
789 ref = self._gitcommand(['config', 'branch.%s.merge' % b])
790 tracking['refs/remotes/%s/%s' %
790 tracking['refs/remotes/%s/%s' %
791 (remote, ref.split('/', 2)[2])] = b
791 (remote, ref.split('/', 2)[2])] = b
792 return tracking
792 return tracking
793
793
794 def _abssource(self, source):
794 def _abssource(self, source):
795 if '://' not in source:
795 if '://' not in source:
796 # recognize the scp syntax as an absolute source
796 # recognize the scp syntax as an absolute source
797 colon = source.find(':')
797 colon = source.find(':')
798 if colon != -1 and '/' not in source[:colon]:
798 if colon != -1 and '/' not in source[:colon]:
799 return source
799 return source
800 self._subsource = source
800 self._subsource = source
801 return _abssource(self)
801 return _abssource(self)
802
802
803 def _fetch(self, source, revision):
803 def _fetch(self, source, revision):
804 if self._gitmissing():
804 if self._gitmissing():
805 source = self._abssource(source)
805 source = self._abssource(source)
806 self._ui.status(_('cloning subrepo %s from %s\n') %
806 self._ui.status(_('cloning subrepo %s from %s\n') %
807 (self._relpath, source))
807 (self._relpath, source))
808 self._gitnodir(['clone', source, self._abspath])
808 self._gitnodir(['clone', source, self._abspath])
809 if self._githavelocally(revision):
809 if self._githavelocally(revision):
810 return
810 return
811 self._ui.status(_('pulling subrepo %s from %s\n') %
811 self._ui.status(_('pulling subrepo %s from %s\n') %
812 (self._relpath, self._gitremote('origin')))
812 (self._relpath, self._gitremote('origin')))
813 # try only origin: the originally cloned repo
813 # try only origin: the originally cloned repo
814 self._gitcommand(['fetch'])
814 self._gitcommand(['fetch'])
815 if not self._githavelocally(revision):
815 if not self._githavelocally(revision):
816 raise util.Abort(_("revision %s does not exist in subrepo %s\n") %
816 raise util.Abort(_("revision %s does not exist in subrepo %s\n") %
817 (revision, self._relpath))
817 (revision, self._relpath))
818
818
819 def dirty(self, ignoreupdate=False):
819 def dirty(self, ignoreupdate=False):
820 if self._gitmissing():
820 if self._gitmissing():
821 return True
821 return True
822 if not ignoreupdate and self._state[1] != self._gitstate():
822 if not ignoreupdate and self._state[1] != self._gitstate():
823 # different version checked out
823 # different version checked out
824 return True
824 return True
825 # check for staged changes or modified files; ignore untracked files
825 # check for staged changes or modified files; ignore untracked files
826 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
826 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
827 return code == 1
827 return code == 1
828
828
829 def get(self, state, overwrite=False):
829 def get(self, state, overwrite=False):
830 source, revision, kind = state
830 source, revision, kind = state
831 self._fetch(source, revision)
831 self._fetch(source, revision)
832 # if the repo was set to be bare, unbare it
832 # if the repo was set to be bare, unbare it
833 if self._gitcommand(['config', '--bool', 'core.bare']) == 'true':
833 if self._gitcommand(['config', '--bool', 'core.bare']) == 'true':
834 self._gitcommand(['config', 'core.bare', 'false'])
834 self._gitcommand(['config', 'core.bare', 'false'])
835 if self._gitstate() == revision:
835 if self._gitstate() == revision:
836 self._gitcommand(['reset', '--hard', 'HEAD'])
836 self._gitcommand(['reset', '--hard', 'HEAD'])
837 return
837 return
838 elif self._gitstate() == revision:
838 elif self._gitstate() == revision:
839 if overwrite:
839 if overwrite:
840 # first reset the index to unmark new files for commit, because
840 # first reset the index to unmark new files for commit, because
841 # reset --hard will otherwise throw away files added for commit,
841 # reset --hard will otherwise throw away files added for commit,
842 # not just unmark them.
842 # not just unmark them.
843 self._gitcommand(['reset', 'HEAD'])
843 self._gitcommand(['reset', 'HEAD'])
844 self._gitcommand(['reset', '--hard', 'HEAD'])
844 self._gitcommand(['reset', '--hard', 'HEAD'])
845 return
845 return
846 branch2rev, rev2branch = self._gitbranchmap()
846 branch2rev, rev2branch = self._gitbranchmap()
847
847
848 def checkout(args):
848 def checkout(args):
849 cmd = ['checkout']
849 cmd = ['checkout']
850 if overwrite:
850 if overwrite:
851 # first reset the index to unmark new files for commit, because
851 # first reset the index to unmark new files for commit, because
852 # the -f option will otherwise throw away files added for
852 # the -f option will otherwise throw away files added for
853 # commit, not just unmark them.
853 # commit, not just unmark them.
854 self._gitcommand(['reset', 'HEAD'])
854 self._gitcommand(['reset', 'HEAD'])
855 cmd.append('-f')
855 cmd.append('-f')
856 self._gitcommand(cmd + args)
856 self._gitcommand(cmd + args)
857
857
858 def rawcheckout():
858 def rawcheckout():
859 # no branch to checkout, check it out with no branch
859 # no branch to checkout, check it out with no branch
860 self._ui.warn(_('checking out detached HEAD in subrepo %s\n') %
860 self._ui.warn(_('checking out detached HEAD in subrepo %s\n') %
861 self._relpath)
861 self._relpath)
862 self._ui.warn(_('check out a git branch if you intend '
862 self._ui.warn(_('check out a git branch if you intend '
863 'to make changes\n'))
863 'to make changes\n'))
864 checkout(['-q', revision])
864 checkout(['-q', revision])
865
865
866 if revision not in rev2branch:
866 if revision not in rev2branch:
867 rawcheckout()
867 rawcheckout()
868 return
868 return
869 branches = rev2branch[revision]
869 branches = rev2branch[revision]
870 firstlocalbranch = None
870 firstlocalbranch = None
871 for b in branches:
871 for b in branches:
872 if b == 'refs/heads/master':
872 if b == 'refs/heads/master':
873 # master trumps all other branches
873 # master trumps all other branches
874 checkout(['refs/heads/master'])
874 checkout(['refs/heads/master'])
875 return
875 return
876 if not firstlocalbranch and not b.startswith('refs/remotes/'):
876 if not firstlocalbranch and not b.startswith('refs/remotes/'):
877 firstlocalbranch = b
877 firstlocalbranch = b
878 if firstlocalbranch:
878 if firstlocalbranch:
879 checkout([firstlocalbranch])
879 checkout([firstlocalbranch])
880 return
880 return
881
881
882 tracking = self._gittracking(branch2rev.keys())
882 tracking = self._gittracking(branch2rev.keys())
883 # choose a remote branch already tracked if possible
883 # choose a remote branch already tracked if possible
884 remote = branches[0]
884 remote = branches[0]
885 if remote not in tracking:
885 if remote not in tracking:
886 for b in branches:
886 for b in branches:
887 if b in tracking:
887 if b in tracking:
888 remote = b
888 remote = b
889 break
889 break
890
890
891 if remote not in tracking:
891 if remote not in tracking:
892 # create a new local tracking branch
892 # create a new local tracking branch
893 local = remote.split('/', 2)[2]
893 local = remote.split('/', 2)[2]
894 checkout(['-b', local, remote])
894 checkout(['-b', local, remote])
895 elif self._gitisancestor(branch2rev[tracking[remote]], remote):
895 elif self._gitisancestor(branch2rev[tracking[remote]], remote):
896 # When updating to a tracked remote branch,
896 # When updating to a tracked remote branch,
897 # if the local tracking branch is downstream of it,
897 # if the local tracking branch is downstream of it,
898 # a normal `git pull` would have performed a "fast-forward merge"
898 # a normal `git pull` would have performed a "fast-forward merge"
899 # which is equivalent to updating the local branch to the remote.
899 # which is equivalent to updating the local branch to the remote.
900 # Since we are only looking at branching at update, we need to
900 # Since we are only looking at branching at update, we need to
901 # detect this situation and perform this action lazily.
901 # detect this situation and perform this action lazily.
902 if tracking[remote] != self._gitcurrentbranch():
902 if tracking[remote] != self._gitcurrentbranch():
903 checkout([tracking[remote]])
903 checkout([tracking[remote]])
904 self._gitcommand(['merge', '--ff', remote])
904 self._gitcommand(['merge', '--ff', remote])
905 else:
905 else:
906 # a real merge would be required, just checkout the revision
906 # a real merge would be required, just checkout the revision
907 rawcheckout()
907 rawcheckout()
908
908
909 def commit(self, text, user, date):
909 def commit(self, text, user, date):
910 if self._gitmissing():
910 if self._gitmissing():
911 raise util.Abort(_("subrepo %s is missing") % self._relpath)
911 raise util.Abort(_("subrepo %s is missing") % self._relpath)
912 cmd = ['commit', '-a', '-m', text]
912 cmd = ['commit', '-a', '-m', text]
913 env = os.environ.copy()
913 env = os.environ.copy()
914 if user:
914 if user:
915 cmd += ['--author', user]
915 cmd += ['--author', user]
916 if date:
916 if date:
917 # git's date parser silently ignores when seconds < 1e9
917 # git's date parser silently ignores when seconds < 1e9
918 # convert to ISO8601
918 # convert to ISO8601
919 env['GIT_AUTHOR_DATE'] = util.datestr(date,
919 env['GIT_AUTHOR_DATE'] = util.datestr(date,
920 '%Y-%m-%dT%H:%M:%S %1%2')
920 '%Y-%m-%dT%H:%M:%S %1%2')
921 self._gitcommand(cmd, env=env)
921 self._gitcommand(cmd, env=env)
922 # make sure commit works otherwise HEAD might not exist under certain
922 # make sure commit works otherwise HEAD might not exist under certain
923 # circumstances
923 # circumstances
924 return self._gitstate()
924 return self._gitstate()
925
925
926 def merge(self, state):
926 def merge(self, state):
927 source, revision, kind = state
927 source, revision, kind = state
928 self._fetch(source, revision)
928 self._fetch(source, revision)
929 base = self._gitcommand(['merge-base', revision, self._state[1]])
929 base = self._gitcommand(['merge-base', revision, self._state[1]])
930 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
930 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
931
931
932 def mergefunc():
932 def mergefunc():
933 if base == revision:
933 if base == revision:
934 self.get(state) # fast forward merge
934 self.get(state) # fast forward merge
935 elif base != self._state[1]:
935 elif base != self._state[1]:
936 self._gitcommand(['merge', '--no-commit', revision])
936 self._gitcommand(['merge', '--no-commit', revision])
937
937
938 if self.dirty():
938 if self.dirty():
939 if self._gitstate() != revision:
939 if self._gitstate() != revision:
940 dirty = self._gitstate() == self._state[1] or code != 0
940 dirty = self._gitstate() == self._state[1] or code != 0
941 if _updateprompt(self._ui, self, dirty,
941 if _updateprompt(self._ui, self, dirty,
942 self._state[1][:7], revision[:7]):
942 self._state[1][:7], revision[:7]):
943 mergefunc()
943 mergefunc()
944 else:
944 else:
945 mergefunc()
945 mergefunc()
946
946
947 def push(self, force):
947 def push(self, force):
948 if self._gitmissing():
948 if self._gitmissing():
949 raise util.Abort(_("subrepo %s is missing") % self._relpath)
949 raise util.Abort(_("subrepo %s is missing") % self._relpath)
950 # if a branch in origin contains the revision, nothing to do
950 # if a branch in origin contains the revision, nothing to do
951 branch2rev, rev2branch = self._gitbranchmap()
951 branch2rev, rev2branch = self._gitbranchmap()
952 if self._state[1] in rev2branch:
952 if self._state[1] in rev2branch:
953 for b in rev2branch[self._state[1]]:
953 for b in rev2branch[self._state[1]]:
954 if b.startswith('refs/remotes/origin/'):
954 if b.startswith('refs/remotes/origin/'):
955 return True
955 return True
956 for b, revision in branch2rev.iteritems():
956 for b, revision in branch2rev.iteritems():
957 if b.startswith('refs/remotes/origin/'):
957 if b.startswith('refs/remotes/origin/'):
958 if self._gitisancestor(self._state[1], revision):
958 if self._gitisancestor(self._state[1], revision):
959 return True
959 return True
960 # otherwise, try to push the currently checked out branch
960 # otherwise, try to push the currently checked out branch
961 cmd = ['push']
961 cmd = ['push']
962 if force:
962 if force:
963 cmd.append('--force')
963 cmd.append('--force')
964
964
965 current = self._gitcurrentbranch()
965 current = self._gitcurrentbranch()
966 if current:
966 if current:
967 # determine if the current branch is even useful
967 # determine if the current branch is even useful
968 if not self._gitisancestor(self._state[1], current):
968 if not self._gitisancestor(self._state[1], current):
969 self._ui.warn(_('unrelated git branch checked out '
969 self._ui.warn(_('unrelated git branch checked out '
970 'in subrepo %s\n') % self._relpath)
970 'in subrepo %s\n') % self._relpath)
971 return False
971 return False
972 self._ui.status(_('pushing branch %s of subrepo %s\n') %
972 self._ui.status(_('pushing branch %s of subrepo %s\n') %
973 (current.split('/', 2)[2], self._relpath))
973 (current.split('/', 2)[2], self._relpath))
974 self._gitcommand(cmd + ['origin', current])
974 self._gitcommand(cmd + ['origin', current])
975 return True
975 return True
976 else:
976 else:
977 self._ui.warn(_('no branch checked out in subrepo %s\n'
977 self._ui.warn(_('no branch checked out in subrepo %s\n'
978 'cannot push revision %s') %
978 'cannot push revision %s') %
979 (self._relpath, self._state[1]))
979 (self._relpath, self._state[1]))
980 return False
980 return False
981
981
982 def remove(self):
982 def remove(self):
983 if self._gitmissing():
983 if self._gitmissing():
984 return
984 return
985 if self.dirty():
985 if self.dirty():
986 self._ui.warn(_('not removing repo %s because '
986 self._ui.warn(_('not removing repo %s because '
987 'it has changes.\n') % self._relpath)
987 'it has changes.\n') % self._relpath)
988 return
988 return
989 # we can't fully delete the repository as it may contain
989 # we can't fully delete the repository as it may contain
990 # local-only history
990 # local-only history
991 self._ui.note(_('removing subrepo %s\n') % self._relpath)
991 self._ui.note(_('removing subrepo %s\n') % self._relpath)
992 self._gitcommand(['config', 'core.bare', 'true'])
992 self._gitcommand(['config', 'core.bare', 'true'])
993 for f in os.listdir(self._abspath):
993 for f in os.listdir(self._abspath):
994 if f == '.git':
994 if f == '.git':
995 continue
995 continue
996 path = os.path.join(self._abspath, f)
996 path = os.path.join(self._abspath, f)
997 if os.path.isdir(path) and not os.path.islink(path):
997 if os.path.isdir(path) and not os.path.islink(path):
998 shutil.rmtree(path)
998 shutil.rmtree(path)
999 else:
999 else:
1000 os.remove(path)
1000 os.remove(path)
1001
1001
1002 def archive(self, ui, archiver, prefix):
1002 def archive(self, ui, archiver, prefix):
1003 source, revision = self._state
1003 source, revision = self._state
1004 self._fetch(source, revision)
1004 self._fetch(source, revision)
1005
1005
1006 # Parse git's native archive command.
1006 # Parse git's native archive command.
1007 # This should be much faster than manually traversing the trees
1007 # This should be much faster than manually traversing the trees
1008 # and objects with many subprocess calls.
1008 # and objects with many subprocess calls.
1009 tarstream = self._gitcommand(['archive', revision], stream=True)
1009 tarstream = self._gitcommand(['archive', revision], stream=True)
1010 tar = tarfile.open(fileobj=tarstream, mode='r|')
1010 tar = tarfile.open(fileobj=tarstream, mode='r|')
1011 relpath = subrelpath(self)
1011 relpath = subrelpath(self)
1012 ui.progress(_('archiving (%s)') % relpath, 0, unit=_('files'))
1012 ui.progress(_('archiving (%s)') % relpath, 0, unit=_('files'))
1013 for i, info in enumerate(tar):
1013 for i, info in enumerate(tar):
1014 if info.isdir():
1014 if info.isdir():
1015 continue
1015 continue
1016 if info.issym():
1016 if info.issym():
1017 data = info.linkname
1017 data = info.linkname
1018 else:
1018 else:
1019 data = tar.extractfile(info).read()
1019 data = tar.extractfile(info).read()
1020 archiver.addfile(os.path.join(prefix, self._path, info.name),
1020 archiver.addfile(os.path.join(prefix, self._path, info.name),
1021 info.mode, info.issym(), data)
1021 info.mode, info.issym(), data)
1022 ui.progress(_('archiving (%s)') % relpath, i + 1,
1022 ui.progress(_('archiving (%s)') % relpath, i + 1,
1023 unit=_('files'))
1023 unit=_('files'))
1024 ui.progress(_('archiving (%s)') % relpath, None)
1024 ui.progress(_('archiving (%s)') % relpath, None)
1025
1025
1026
1026
1027 def status(self, rev2, **opts):
1027 def status(self, rev2, **opts):
1028 if self._gitmissing():
1028 if self._gitmissing():
1029 # if the repo is missing, return no results
1029 # if the repo is missing, return no results
1030 return [], [], [], [], [], [], []
1030 return [], [], [], [], [], [], []
1031 rev1 = self._state[1]
1031 rev1 = self._state[1]
1032 modified, added, removed = [], [], []
1032 modified, added, removed = [], [], []
1033 if rev2:
1033 if rev2:
1034 command = ['diff-tree', rev1, rev2]
1034 command = ['diff-tree', rev1, rev2]
1035 else:
1035 else:
1036 command = ['diff-index', rev1]
1036 command = ['diff-index', rev1]
1037 out = self._gitcommand(command)
1037 out = self._gitcommand(command)
1038 for line in out.split('\n'):
1038 for line in out.split('\n'):
1039 tab = line.find('\t')
1039 tab = line.find('\t')
1040 if tab == -1:
1040 if tab == -1:
1041 continue
1041 continue
1042 status, f = line[tab - 1], line[tab + 1:]
1042 status, f = line[tab - 1], line[tab + 1:]
1043 if status == 'M':
1043 if status == 'M':
1044 modified.append(f)
1044 modified.append(f)
1045 elif status == 'A':
1045 elif status == 'A':
1046 added.append(f)
1046 added.append(f)
1047 elif status == 'D':
1047 elif status == 'D':
1048 removed.append(f)
1048 removed.append(f)
1049
1049
1050 deleted = unknown = ignored = clean = []
1050 deleted = unknown = ignored = clean = []
1051 return modified, added, removed, deleted, unknown, ignored, clean
1051 return modified, added, removed, deleted, unknown, ignored, clean
1052
1052
1053 types = {
1053 types = {
1054 'hg': hgsubrepo,
1054 'hg': hgsubrepo,
1055 'svn': svnsubrepo,
1055 'svn': svnsubrepo,
1056 'git': gitsubrepo,
1056 'git': gitsubrepo,
1057 }
1057 }
General Comments 0
You need to be logged in to leave comments. Login now