##// END OF EJS Templates
add prechangegroup and pretxnchangegroup hooks....
Vadim Gelfer -
r1730:0f1d2c75 default
parent child Browse files
Show More
@@ -1,276 +1,288 b''
1 HGRC(5)
1 HGRC(5)
2 =======
2 =======
3 Bryan O'Sullivan <bos@serpentine.com>
3 Bryan O'Sullivan <bos@serpentine.com>
4
4
5 NAME
5 NAME
6 ----
6 ----
7 hgrc - configuration files for Mercurial
7 hgrc - configuration files for Mercurial
8
8
9 SYNOPSIS
9 SYNOPSIS
10 --------
10 --------
11
11
12 The Mercurial system uses a set of configuration files to control
12 The Mercurial system uses a set of configuration files to control
13 aspects of its behaviour.
13 aspects of its behaviour.
14
14
15 FILES
15 FILES
16 -----
16 -----
17
17
18 Mercurial reads configuration data from several files, if they exist.
18 Mercurial reads configuration data from several files, if they exist.
19 The names of these files depend on the system on which Mercurial is
19 The names of these files depend on the system on which Mercurial is
20 installed.
20 installed.
21
21
22 (Unix) <install-root>/etc/mercurial/hgrc.d/*.rc::
22 (Unix) <install-root>/etc/mercurial/hgrc.d/*.rc::
23 (Unix) <install-root>/etc/mercurial/hgrc::
23 (Unix) <install-root>/etc/mercurial/hgrc::
24 Per-installation configuration files, searched for in the
24 Per-installation configuration files, searched for in the
25 directory where Mercurial is installed. For example, if installed
25 directory where Mercurial is installed. For example, if installed
26 in /shared/tools, Mercurial will look in
26 in /shared/tools, Mercurial will look in
27 /shared/tools/etc/mercurial/hgrc. Options in these files apply to
27 /shared/tools/etc/mercurial/hgrc. Options in these files apply to
28 all Mercurial commands executed by any user in any directory.
28 all Mercurial commands executed by any user in any directory.
29
29
30 (Unix) /etc/mercurial/hgrc.d/*.rc::
30 (Unix) /etc/mercurial/hgrc.d/*.rc::
31 (Unix) /etc/mercurial/hgrc::
31 (Unix) /etc/mercurial/hgrc::
32 (Windows) C:\Mercurial\Mercurial.ini::
32 (Windows) C:\Mercurial\Mercurial.ini::
33 Per-system configuration files, for the system on which Mercurial
33 Per-system configuration files, for the system on which Mercurial
34 is running. Options in these files apply to all Mercurial
34 is running. Options in these files apply to all Mercurial
35 commands executed by any user in any directory. Options in these
35 commands executed by any user in any directory. Options in these
36 files override per-installation options.
36 files override per-installation options.
37
37
38 (Unix) $HOME/.hgrc::
38 (Unix) $HOME/.hgrc::
39 (Windows) C:\Documents and Settings\USERNAME\Mercurial.ini
39 (Windows) C:\Documents and Settings\USERNAME\Mercurial.ini
40 Per-user configuration file, for the user running Mercurial.
40 Per-user configuration file, for the user running Mercurial.
41 Options in this file apply to all Mercurial commands executed by
41 Options in this file apply to all Mercurial commands executed by
42 any user in any directory. Options in this file override
42 any user in any directory. Options in this file override
43 per-installation and per-system options.
43 per-installation and per-system options.
44
44
45 (Unix, Windows) <repo>/.hg/hgrc::
45 (Unix, Windows) <repo>/.hg/hgrc::
46 Per-repository configuration options that only apply in a
46 Per-repository configuration options that only apply in a
47 particular repository. This file is not version-controlled, and
47 particular repository. This file is not version-controlled, and
48 will not get transferred during a "clone" operation. Options in
48 will not get transferred during a "clone" operation. Options in
49 this file override options in all other configuration files.
49 this file override options in all other configuration files.
50
50
51 SYNTAX
51 SYNTAX
52 ------
52 ------
53
53
54 A configuration file consists of sections, led by a "[section]" header
54 A configuration file consists of sections, led by a "[section]" header
55 and followed by "name: value" entries; "name=value" is also accepted.
55 and followed by "name: value" entries; "name=value" is also accepted.
56
56
57 [spam]
57 [spam]
58 eggs=ham
58 eggs=ham
59 green=
59 green=
60 eggs
60 eggs
61
61
62 Each line contains one entry. If the lines that follow are indented,
62 Each line contains one entry. If the lines that follow are indented,
63 they are treated as continuations of that entry.
63 they are treated as continuations of that entry.
64
64
65 Leading whitespace is removed from values. Empty lines are skipped.
65 Leading whitespace is removed from values. Empty lines are skipped.
66
66
67 The optional values can contain format strings which refer to other
67 The optional values can contain format strings which refer to other
68 values in the same section, or values in a special DEFAULT section.
68 values in the same section, or values in a special DEFAULT section.
69
69
70 Lines beginning with "#" or ";" are ignored and may be used to provide
70 Lines beginning with "#" or ";" are ignored and may be used to provide
71 comments.
71 comments.
72
72
73 SECTIONS
73 SECTIONS
74 --------
74 --------
75
75
76 This section describes the different sections that may appear in a
76 This section describes the different sections that may appear in a
77 Mercurial "hgrc" file, the purpose of each section, its possible
77 Mercurial "hgrc" file, the purpose of each section, its possible
78 keys, and their possible values.
78 keys, and their possible values.
79
79
80 decode/encode::
80 decode/encode::
81 Filters for transforming files on checkout/checkin. This would
81 Filters for transforming files on checkout/checkin. This would
82 typically be used for newline processing or other
82 typically be used for newline processing or other
83 localization/canonicalization of files.
83 localization/canonicalization of files.
84
84
85 Filters consist of a filter pattern followed by a filter command.
85 Filters consist of a filter pattern followed by a filter command.
86 Filter patterns are globs by default, rooted at the repository
86 Filter patterns are globs by default, rooted at the repository
87 root. For example, to match any file ending in ".txt" in the root
87 root. For example, to match any file ending in ".txt" in the root
88 directory only, use the pattern "*.txt". To match any file ending
88 directory only, use the pattern "*.txt". To match any file ending
89 in ".c" anywhere in the repository, use the pattern "**.c".
89 in ".c" anywhere in the repository, use the pattern "**.c".
90
90
91 The filter command can start with a specifier, either "pipe:" or
91 The filter command can start with a specifier, either "pipe:" or
92 "tempfile:". If no specifier is given, "pipe:" is used by default.
92 "tempfile:". If no specifier is given, "pipe:" is used by default.
93
93
94 A "pipe:" command must accept data on stdin and return the
94 A "pipe:" command must accept data on stdin and return the
95 transformed data on stdout.
95 transformed data on stdout.
96
96
97 Pipe example:
97 Pipe example:
98
98
99 [encode]
99 [encode]
100 # uncompress gzip files on checkin to improve delta compression
100 # uncompress gzip files on checkin to improve delta compression
101 # note: not necessarily a good idea, just an example
101 # note: not necessarily a good idea, just an example
102 *.gz = pipe: gunzip
102 *.gz = pipe: gunzip
103
103
104 [decode]
104 [decode]
105 # recompress gzip files when writing them to the working dir (we
105 # recompress gzip files when writing them to the working dir (we
106 # can safely omit "pipe:", because it's the default)
106 # can safely omit "pipe:", because it's the default)
107 *.gz = gzip
107 *.gz = gzip
108
108
109 A "tempfile:" command is a template. The string INFILE is replaced
109 A "tempfile:" command is a template. The string INFILE is replaced
110 with the name of a temporary file that contains the data to be
110 with the name of a temporary file that contains the data to be
111 filtered by the command. The string OUTFILE is replaced with the
111 filtered by the command. The string OUTFILE is replaced with the
112 name of an empty temporary file, where the filtered data must be
112 name of an empty temporary file, where the filtered data must be
113 written by the command.
113 written by the command.
114
114
115 NOTE: the tempfile mechanism is recommended for Windows systems,
115 NOTE: the tempfile mechanism is recommended for Windows systems,
116 where the standard shell I/O redirection operators often have
116 where the standard shell I/O redirection operators often have
117 strange effects. In particular, if you are doing line ending
117 strange effects. In particular, if you are doing line ending
118 conversion on Windows using the popular dos2unix and unix2dos
118 conversion on Windows using the popular dos2unix and unix2dos
119 programs, you *must* use the tempfile mechanism, as using pipes will
119 programs, you *must* use the tempfile mechanism, as using pipes will
120 corrupt the contents of your files.
120 corrupt the contents of your files.
121
121
122 Tempfile example:
122 Tempfile example:
123
123
124 [encode]
124 [encode]
125 # convert files to unix line ending conventions on checkin
125 # convert files to unix line ending conventions on checkin
126 **.txt = tempfile: dos2unix -n INFILE OUTFILE
126 **.txt = tempfile: dos2unix -n INFILE OUTFILE
127
127
128 [decode]
128 [decode]
129 # convert files to windows line ending conventions when writing
129 # convert files to windows line ending conventions when writing
130 # them to the working dir
130 # them to the working dir
131 **.txt = tempfile: unix2dos -n INFILE OUTFILE
131 **.txt = tempfile: unix2dos -n INFILE OUTFILE
132
132
133 hooks::
133 hooks::
134 Commands that get automatically executed by various actions such as
134 Commands that get automatically executed by various actions such as
135 starting or finishing a commit. Multiple commands can be run for
135 starting or finishing a commit. Multiple commands can be run for
136 the same action by appending a suffix to the action. Overriding a
136 the same action by appending a suffix to the action. Overriding a
137 site-wide hook can be done by changing its value or setting it to
137 site-wide hook can be done by changing its value or setting it to
138 an empty string.
138 an empty string.
139
139
140 Example .hg/hgrc:
140 Example .hg/hgrc:
141
141
142 [hooks]
142 [hooks]
143 # do not use the site-wide hook
143 # do not use the site-wide hook
144 incoming =
144 incoming =
145 incoming.email = /my/email/hook
145 incoming.email = /my/email/hook
146 incoming.autobuild = /my/build/hook
146 incoming.autobuild = /my/build/hook
147
147
148 changegroup;;
148 changegroup;;
149 Run after a changegroup has been added via push or pull. Passed
149 Run after a changegroup has been added via push, pull or
150 the ID of the first new changeset in $NODE.
150 unbundle. Passed the ID of the first new changeset in $NODE.
151 commit;;
151 commit;;
152 Run after a changeset has been created in the local repository.
152 Run after a changeset has been created in the local repository.
153 Passed the ID of the newly created changeset in environment
153 Passed the ID of the newly created changeset in environment
154 variable $NODE. Parent changeset IDs in $P1 and $P2.
154 variable $NODE. Parent changeset IDs in $P1 and $P2.
155 incoming;;
155 incoming;;
156 Run after a changeset has been pulled, pushed, or unbundled into
156 Run after a changeset has been pulled, pushed, or unbundled into
157 the local repository. Passed the ID of the newly arrived
157 the local repository. Passed the ID of the newly arrived
158 changeset in environment variable $NODE.
158 changeset in environment variable $NODE.
159 prechangegroup;;
160 Run before a changegroup is added via push, pull or unbundle.
161 Exit status 0 allows the changegroup to proceed. Non-zero status
162 will cause the push, pull or unbundle to fail.
159 precommit;;
163 precommit;;
160 Run before starting a local commit. Exit status 0 allows the
164 Run before starting a local commit. Exit status 0 allows the
161 commit to proceed. Non-zero status will cause the commit to
165 commit to proceed. Non-zero status will cause the commit to
162 fail. Parent changeset IDs in $P1 and $P2.
166 fail. Parent changeset IDs in $P1 and $P2.
163 pretag;;
167 pretag;;
164 Run before creating a tag. Exit status 0 allows the tag to be
168 Run before creating a tag. Exit status 0 allows the tag to be
165 created. Non-zero status will cause the tag to fail. ID of
169 created. Non-zero status will cause the tag to fail. ID of
166 changeset to tag in $NODE. Name of tag in $TAG. Tag is local if
170 changeset to tag in $NODE. Name of tag in $TAG. Tag is local if
167 $LOCAL=1, in repo if $LOCAL=0.
171 $LOCAL=1, in repo if $LOCAL=0.
172 pretxnchangegroup;;
173 Run after a changegroup has been added via push, pull or unbundle,
174 but before the transaction has been committed. Changegroup is
175 visible to hook program. This lets you validate incoming changes
176 before accepting them. Passed the ID of the first new changeset
177 in $NODE. Exit status 0 allows the transaction to commit.
178 Non-zero status will cause the transaction to be rolled back and
179 the push, pull or unbundle will fail.
168 pretxncommit;;
180 pretxncommit;;
169 Run after a changeset has been created but the transaction not yet
181 Run after a changeset has been created but the transaction not yet
170 committed. Changeset is visible to hook program. This lets you
182 committed. Changeset is visible to hook program. This lets you
171 validate commit message and changes. Exit status 0 allows the
183 validate commit message and changes. Exit status 0 allows the
172 commit to proceed. Non-zero status will cause the transaction to
184 commit to proceed. Non-zero status will cause the transaction to
173 be rolled back. ID of changeset in $NODE. Parent changeset IDs
185 be rolled back. ID of changeset in $NODE. Parent changeset IDs
174 in $P1 and $P2.
186 in $P1 and $P2.
175 tag;;
187 tag;;
176 Run after a tag is created. ID of tagged changeset in $NODE.
188 Run after a tag is created. ID of tagged changeset in $NODE.
177 Name of tag in $TAG. Tag is local if $LOCAL=1, in repo if
189 Name of tag in $TAG. Tag is local if $LOCAL=1, in repo if
178 $LOCAL=0.
190 $LOCAL=0.
179
191
180 http_proxy::
192 http_proxy::
181 Used to access web-based Mercurial repositories through a HTTP
193 Used to access web-based Mercurial repositories through a HTTP
182 proxy.
194 proxy.
183 host;;
195 host;;
184 Host name and (optional) port of the proxy server, for example
196 Host name and (optional) port of the proxy server, for example
185 "myproxy:8000".
197 "myproxy:8000".
186 no;;
198 no;;
187 Optional. Comma-separated list of host names that should bypass
199 Optional. Comma-separated list of host names that should bypass
188 the proxy.
200 the proxy.
189 passwd;;
201 passwd;;
190 Optional. Password to authenticate with at the proxy server.
202 Optional. Password to authenticate with at the proxy server.
191 user;;
203 user;;
192 Optional. User name to authenticate with at the proxy server.
204 Optional. User name to authenticate with at the proxy server.
193
205
194 paths::
206 paths::
195 Assigns symbolic names to repositories. The left side is the
207 Assigns symbolic names to repositories. The left side is the
196 symbolic name, and the right gives the directory or URL that is the
208 symbolic name, and the right gives the directory or URL that is the
197 location of the repository.
209 location of the repository.
198
210
199 ui::
211 ui::
200 User interface controls.
212 User interface controls.
201 debug;;
213 debug;;
202 Print debugging information. True or False. Default is False.
214 Print debugging information. True or False. Default is False.
203 editor;;
215 editor;;
204 The editor to use during a commit. Default is $EDITOR or "vi".
216 The editor to use during a commit. Default is $EDITOR or "vi".
205 interactive;;
217 interactive;;
206 Allow to prompt the user. True or False. Default is True.
218 Allow to prompt the user. True or False. Default is True.
207 merge;;
219 merge;;
208 The conflict resolution program to use during a manual merge.
220 The conflict resolution program to use during a manual merge.
209 Default is "hgmerge".
221 Default is "hgmerge".
210 quiet;;
222 quiet;;
211 Reduce the amount of output printed. True or False. Default is False.
223 Reduce the amount of output printed. True or False. Default is False.
212 remotecmd;;
224 remotecmd;;
213 remote command to use for clone/push/pull operations. Default is 'hg'.
225 remote command to use for clone/push/pull operations. Default is 'hg'.
214 ssh;;
226 ssh;;
215 command to use for SSH connections. Default is 'ssh'.
227 command to use for SSH connections. Default is 'ssh'.
216 username;;
228 username;;
217 The committer of a changeset created when running "commit".
229 The committer of a changeset created when running "commit".
218 Typically a person's name and email address, e.g. "Fred Widget
230 Typically a person's name and email address, e.g. "Fred Widget
219 <fred@example.com>". Default is $EMAIL or username@hostname.
231 <fred@example.com>". Default is $EMAIL or username@hostname.
220 verbose;;
232 verbose;;
221 Increase the amount of output printed. True or False. Default is False.
233 Increase the amount of output printed. True or False. Default is False.
222
234
223
235
224 web::
236 web::
225 Web interface configuration.
237 Web interface configuration.
226 accesslog;;
238 accesslog;;
227 Where to output the access log. Default is stdout.
239 Where to output the access log. Default is stdout.
228 address;;
240 address;;
229 Interface address to bind to. Default is all.
241 Interface address to bind to. Default is all.
230 allowbz2;;
242 allowbz2;;
231 Whether to allow .tar.bz2 downloading of repo revisions. Default is false.
243 Whether to allow .tar.bz2 downloading of repo revisions. Default is false.
232 allowgz;;
244 allowgz;;
233 Whether to allow .tar.gz downloading of repo revisions. Default is false.
245 Whether to allow .tar.gz downloading of repo revisions. Default is false.
234 allowpull;;
246 allowpull;;
235 Whether to allow pulling from the repository. Default is true.
247 Whether to allow pulling from the repository. Default is true.
236 allowzip;;
248 allowzip;;
237 Whether to allow .zip downloading of repo revisions. Default is false.
249 Whether to allow .zip downloading of repo revisions. Default is false.
238 This feature creates temporary files.
250 This feature creates temporary files.
239 description;;
251 description;;
240 Textual description of the repository's purpose or contents.
252 Textual description of the repository's purpose or contents.
241 Default is "unknown".
253 Default is "unknown".
242 errorlog;;
254 errorlog;;
243 Where to output the error log. Default is stderr.
255 Where to output the error log. Default is stderr.
244 ipv6;;
256 ipv6;;
245 Whether to use IPv6. Default is false.
257 Whether to use IPv6. Default is false.
246 name;;
258 name;;
247 Repository name to use in the web interface. Default is current
259 Repository name to use in the web interface. Default is current
248 working directory.
260 working directory.
249 maxchanges;;
261 maxchanges;;
250 Maximum number of changes to list on the changelog. Default is 10.
262 Maximum number of changes to list on the changelog. Default is 10.
251 maxfiles;;
263 maxfiles;;
252 Maximum number of files to list per changeset. Default is 10.
264 Maximum number of files to list per changeset. Default is 10.
253 port;;
265 port;;
254 Port to listen on. Default is 8000.
266 Port to listen on. Default is 8000.
255 style;;
267 style;;
256 Which template map style to use.
268 Which template map style to use.
257 templates;;
269 templates;;
258 Where to find the HTML templates. Default is install path.
270 Where to find the HTML templates. Default is install path.
259
271
260
272
261 AUTHOR
273 AUTHOR
262 ------
274 ------
263 Bryan O'Sullivan <bos@serpentine.com>.
275 Bryan O'Sullivan <bos@serpentine.com>.
264
276
265 Mercurial was written by Matt Mackall <mpm@selenic.com>.
277 Mercurial was written by Matt Mackall <mpm@selenic.com>.
266
278
267 SEE ALSO
279 SEE ALSO
268 --------
280 --------
269 hg(1)
281 hg(1)
270
282
271 COPYING
283 COPYING
272 -------
284 -------
273 This manual page is copyright 2005 Bryan O'Sullivan.
285 This manual page is copyright 2005 Bryan O'Sullivan.
274 Mercurial is copyright 2005 Matt Mackall.
286 Mercurial is copyright 2005 Matt Mackall.
275 Free use of this software is granted under the terms of the GNU General
287 Free use of this software is granted under the terms of the GNU General
276 Public License (GPL).
288 Public License (GPL).
@@ -1,1848 +1,1854 b''
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 #
2 #
3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7
7
8 import struct, os, util
8 import struct, os, util
9 import filelog, manifest, changelog, dirstate, repo
9 import filelog, manifest, changelog, dirstate, repo
10 from node import *
10 from node import *
11 from i18n import gettext as _
11 from i18n import gettext as _
12 from demandload import *
12 from demandload import *
13 demandload(globals(), "re lock transaction tempfile stat mdiff errno")
13 demandload(globals(), "re lock transaction tempfile stat mdiff errno")
14
14
15 class localrepository(object):
15 class localrepository(object):
16 def __init__(self, ui, path=None, create=0):
16 def __init__(self, ui, path=None, create=0):
17 if not path:
17 if not path:
18 p = os.getcwd()
18 p = os.getcwd()
19 while not os.path.isdir(os.path.join(p, ".hg")):
19 while not os.path.isdir(os.path.join(p, ".hg")):
20 oldp = p
20 oldp = p
21 p = os.path.dirname(p)
21 p = os.path.dirname(p)
22 if p == oldp:
22 if p == oldp:
23 raise repo.RepoError(_("no repo found"))
23 raise repo.RepoError(_("no repo found"))
24 path = p
24 path = p
25 self.path = os.path.join(path, ".hg")
25 self.path = os.path.join(path, ".hg")
26
26
27 if not create and not os.path.isdir(self.path):
27 if not create and not os.path.isdir(self.path):
28 raise repo.RepoError(_("repository %s not found") % path)
28 raise repo.RepoError(_("repository %s not found") % path)
29
29
30 self.root = os.path.abspath(path)
30 self.root = os.path.abspath(path)
31 self.ui = ui
31 self.ui = ui
32 self.opener = util.opener(self.path)
32 self.opener = util.opener(self.path)
33 self.wopener = util.opener(self.root)
33 self.wopener = util.opener(self.root)
34 self.manifest = manifest.manifest(self.opener)
34 self.manifest = manifest.manifest(self.opener)
35 self.changelog = changelog.changelog(self.opener)
35 self.changelog = changelog.changelog(self.opener)
36 self.tagscache = None
36 self.tagscache = None
37 self.nodetagscache = None
37 self.nodetagscache = None
38 self.encodepats = None
38 self.encodepats = None
39 self.decodepats = None
39 self.decodepats = None
40
40
41 if create:
41 if create:
42 os.mkdir(self.path)
42 os.mkdir(self.path)
43 os.mkdir(self.join("data"))
43 os.mkdir(self.join("data"))
44
44
45 self.dirstate = dirstate.dirstate(self.opener, ui, self.root)
45 self.dirstate = dirstate.dirstate(self.opener, ui, self.root)
46 try:
46 try:
47 self.ui.readconfig(self.join("hgrc"))
47 self.ui.readconfig(self.join("hgrc"))
48 except IOError:
48 except IOError:
49 pass
49 pass
50
50
51 def hook(self, name, throw=False, **args):
51 def hook(self, name, throw=False, **args):
52 def runhook(name, cmd):
52 def runhook(name, cmd):
53 self.ui.note(_("running hook %s: %s\n") % (name, cmd))
53 self.ui.note(_("running hook %s: %s\n") % (name, cmd))
54 old = {}
54 old = {}
55 for k, v in args.items():
55 for k, v in args.items():
56 k = k.upper()
56 k = k.upper()
57 old[k] = os.environ.get(k, None)
57 old[k] = os.environ.get(k, None)
58 os.environ[k] = str(v)
58 os.environ[k] = str(v)
59
59
60 try:
60 try:
61 # Hooks run in the repository root
61 # Hooks run in the repository root
62 olddir = os.getcwd()
62 olddir = os.getcwd()
63 os.chdir(self.root)
63 os.chdir(self.root)
64 r = os.system(cmd)
64 r = os.system(cmd)
65 finally:
65 finally:
66 for k, v in old.items():
66 for k, v in old.items():
67 if v != None:
67 if v != None:
68 os.environ[k] = v
68 os.environ[k] = v
69 else:
69 else:
70 del os.environ[k]
70 del os.environ[k]
71
71
72 os.chdir(olddir)
72 os.chdir(olddir)
73
73
74 if r:
74 if r:
75 desc, r = util.explain_exit(r)
75 desc, r = util.explain_exit(r)
76 if throw:
76 if throw:
77 raise util.Abort(_('%s hook %s') % (name, desc))
77 raise util.Abort(_('%s hook %s') % (name, desc))
78 self.ui.warn(_('error: %s hook %s\n') % (name, desc))
78 self.ui.warn(_('error: %s hook %s\n') % (name, desc))
79 return False
79 return False
80 return True
80 return True
81
81
82 r = True
82 r = True
83 for hname, cmd in self.ui.configitems("hooks"):
83 for hname, cmd in self.ui.configitems("hooks"):
84 s = hname.split(".")
84 s = hname.split(".")
85 if s[0] == name and cmd:
85 if s[0] == name and cmd:
86 r = runhook(hname, cmd) and r
86 r = runhook(hname, cmd) and r
87 return r
87 return r
88
88
89 def tags(self):
89 def tags(self):
90 '''return a mapping of tag to node'''
90 '''return a mapping of tag to node'''
91 if not self.tagscache:
91 if not self.tagscache:
92 self.tagscache = {}
92 self.tagscache = {}
93 def addtag(self, k, n):
93 def addtag(self, k, n):
94 try:
94 try:
95 bin_n = bin(n)
95 bin_n = bin(n)
96 except TypeError:
96 except TypeError:
97 bin_n = ''
97 bin_n = ''
98 self.tagscache[k.strip()] = bin_n
98 self.tagscache[k.strip()] = bin_n
99
99
100 try:
100 try:
101 # read each head of the tags file, ending with the tip
101 # read each head of the tags file, ending with the tip
102 # and add each tag found to the map, with "newer" ones
102 # and add each tag found to the map, with "newer" ones
103 # taking precedence
103 # taking precedence
104 fl = self.file(".hgtags")
104 fl = self.file(".hgtags")
105 h = fl.heads()
105 h = fl.heads()
106 h.reverse()
106 h.reverse()
107 for r in h:
107 for r in h:
108 for l in fl.read(r).splitlines():
108 for l in fl.read(r).splitlines():
109 if l:
109 if l:
110 n, k = l.split(" ", 1)
110 n, k = l.split(" ", 1)
111 addtag(self, k, n)
111 addtag(self, k, n)
112 except KeyError:
112 except KeyError:
113 pass
113 pass
114
114
115 try:
115 try:
116 f = self.opener("localtags")
116 f = self.opener("localtags")
117 for l in f:
117 for l in f:
118 n, k = l.split(" ", 1)
118 n, k = l.split(" ", 1)
119 addtag(self, k, n)
119 addtag(self, k, n)
120 except IOError:
120 except IOError:
121 pass
121 pass
122
122
123 self.tagscache['tip'] = self.changelog.tip()
123 self.tagscache['tip'] = self.changelog.tip()
124
124
125 return self.tagscache
125 return self.tagscache
126
126
127 def tagslist(self):
127 def tagslist(self):
128 '''return a list of tags ordered by revision'''
128 '''return a list of tags ordered by revision'''
129 l = []
129 l = []
130 for t, n in self.tags().items():
130 for t, n in self.tags().items():
131 try:
131 try:
132 r = self.changelog.rev(n)
132 r = self.changelog.rev(n)
133 except:
133 except:
134 r = -2 # sort to the beginning of the list if unknown
134 r = -2 # sort to the beginning of the list if unknown
135 l.append((r, t, n))
135 l.append((r, t, n))
136 l.sort()
136 l.sort()
137 return [(t, n) for r, t, n in l]
137 return [(t, n) for r, t, n in l]
138
138
139 def nodetags(self, node):
139 def nodetags(self, node):
140 '''return the tags associated with a node'''
140 '''return the tags associated with a node'''
141 if not self.nodetagscache:
141 if not self.nodetagscache:
142 self.nodetagscache = {}
142 self.nodetagscache = {}
143 for t, n in self.tags().items():
143 for t, n in self.tags().items():
144 self.nodetagscache.setdefault(n, []).append(t)
144 self.nodetagscache.setdefault(n, []).append(t)
145 return self.nodetagscache.get(node, [])
145 return self.nodetagscache.get(node, [])
146
146
147 def lookup(self, key):
147 def lookup(self, key):
148 try:
148 try:
149 return self.tags()[key]
149 return self.tags()[key]
150 except KeyError:
150 except KeyError:
151 try:
151 try:
152 return self.changelog.lookup(key)
152 return self.changelog.lookup(key)
153 except:
153 except:
154 raise repo.RepoError(_("unknown revision '%s'") % key)
154 raise repo.RepoError(_("unknown revision '%s'") % key)
155
155
156 def dev(self):
156 def dev(self):
157 return os.stat(self.path).st_dev
157 return os.stat(self.path).st_dev
158
158
159 def local(self):
159 def local(self):
160 return True
160 return True
161
161
162 def join(self, f):
162 def join(self, f):
163 return os.path.join(self.path, f)
163 return os.path.join(self.path, f)
164
164
165 def wjoin(self, f):
165 def wjoin(self, f):
166 return os.path.join(self.root, f)
166 return os.path.join(self.root, f)
167
167
168 def file(self, f):
168 def file(self, f):
169 if f[0] == '/':
169 if f[0] == '/':
170 f = f[1:]
170 f = f[1:]
171 return filelog.filelog(self.opener, f)
171 return filelog.filelog(self.opener, f)
172
172
173 def getcwd(self):
173 def getcwd(self):
174 return self.dirstate.getcwd()
174 return self.dirstate.getcwd()
175
175
176 def wfile(self, f, mode='r'):
176 def wfile(self, f, mode='r'):
177 return self.wopener(f, mode)
177 return self.wopener(f, mode)
178
178
179 def wread(self, filename):
179 def wread(self, filename):
180 if self.encodepats == None:
180 if self.encodepats == None:
181 l = []
181 l = []
182 for pat, cmd in self.ui.configitems("encode"):
182 for pat, cmd in self.ui.configitems("encode"):
183 mf = util.matcher("", "/", [pat], [], [])[1]
183 mf = util.matcher("", "/", [pat], [], [])[1]
184 l.append((mf, cmd))
184 l.append((mf, cmd))
185 self.encodepats = l
185 self.encodepats = l
186
186
187 data = self.wopener(filename, 'r').read()
187 data = self.wopener(filename, 'r').read()
188
188
189 for mf, cmd in self.encodepats:
189 for mf, cmd in self.encodepats:
190 if mf(filename):
190 if mf(filename):
191 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
191 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
192 data = util.filter(data, cmd)
192 data = util.filter(data, cmd)
193 break
193 break
194
194
195 return data
195 return data
196
196
197 def wwrite(self, filename, data, fd=None):
197 def wwrite(self, filename, data, fd=None):
198 if self.decodepats == None:
198 if self.decodepats == None:
199 l = []
199 l = []
200 for pat, cmd in self.ui.configitems("decode"):
200 for pat, cmd in self.ui.configitems("decode"):
201 mf = util.matcher("", "/", [pat], [], [])[1]
201 mf = util.matcher("", "/", [pat], [], [])[1]
202 l.append((mf, cmd))
202 l.append((mf, cmd))
203 self.decodepats = l
203 self.decodepats = l
204
204
205 for mf, cmd in self.decodepats:
205 for mf, cmd in self.decodepats:
206 if mf(filename):
206 if mf(filename):
207 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
207 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
208 data = util.filter(data, cmd)
208 data = util.filter(data, cmd)
209 break
209 break
210
210
211 if fd:
211 if fd:
212 return fd.write(data)
212 return fd.write(data)
213 return self.wopener(filename, 'w').write(data)
213 return self.wopener(filename, 'w').write(data)
214
214
215 def transaction(self):
215 def transaction(self):
216 # save dirstate for undo
216 # save dirstate for undo
217 try:
217 try:
218 ds = self.opener("dirstate").read()
218 ds = self.opener("dirstate").read()
219 except IOError:
219 except IOError:
220 ds = ""
220 ds = ""
221 self.opener("journal.dirstate", "w").write(ds)
221 self.opener("journal.dirstate", "w").write(ds)
222
222
223 def after():
223 def after():
224 util.rename(self.join("journal"), self.join("undo"))
224 util.rename(self.join("journal"), self.join("undo"))
225 util.rename(self.join("journal.dirstate"),
225 util.rename(self.join("journal.dirstate"),
226 self.join("undo.dirstate"))
226 self.join("undo.dirstate"))
227
227
228 return transaction.transaction(self.ui.warn, self.opener,
228 return transaction.transaction(self.ui.warn, self.opener,
229 self.join("journal"), after)
229 self.join("journal"), after)
230
230
231 def recover(self):
231 def recover(self):
232 lock = self.lock()
232 lock = self.lock()
233 if os.path.exists(self.join("journal")):
233 if os.path.exists(self.join("journal")):
234 self.ui.status(_("rolling back interrupted transaction\n"))
234 self.ui.status(_("rolling back interrupted transaction\n"))
235 transaction.rollback(self.opener, self.join("journal"))
235 transaction.rollback(self.opener, self.join("journal"))
236 self.manifest = manifest.manifest(self.opener)
236 self.manifest = manifest.manifest(self.opener)
237 self.changelog = changelog.changelog(self.opener)
237 self.changelog = changelog.changelog(self.opener)
238 return True
238 return True
239 else:
239 else:
240 self.ui.warn(_("no interrupted transaction available\n"))
240 self.ui.warn(_("no interrupted transaction available\n"))
241 return False
241 return False
242
242
243 def undo(self, wlock=None):
243 def undo(self, wlock=None):
244 if not wlock:
244 if not wlock:
245 wlock = self.wlock()
245 wlock = self.wlock()
246 lock = self.lock()
246 lock = self.lock()
247 if os.path.exists(self.join("undo")):
247 if os.path.exists(self.join("undo")):
248 self.ui.status(_("rolling back last transaction\n"))
248 self.ui.status(_("rolling back last transaction\n"))
249 transaction.rollback(self.opener, self.join("undo"))
249 transaction.rollback(self.opener, self.join("undo"))
250 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
250 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
251 self.dirstate.read()
251 self.dirstate.read()
252 else:
252 else:
253 self.ui.warn(_("no undo information available\n"))
253 self.ui.warn(_("no undo information available\n"))
254
254
255 def lock(self, wait=1):
255 def lock(self, wait=1):
256 try:
256 try:
257 return lock.lock(self.join("lock"), 0)
257 return lock.lock(self.join("lock"), 0)
258 except lock.LockHeld, inst:
258 except lock.LockHeld, inst:
259 if wait:
259 if wait:
260 self.ui.warn(_("waiting for lock held by %s\n") % inst.args[0])
260 self.ui.warn(_("waiting for lock held by %s\n") % inst.args[0])
261 return lock.lock(self.join("lock"), wait)
261 return lock.lock(self.join("lock"), wait)
262 raise inst
262 raise inst
263
263
264 def wlock(self, wait=1):
264 def wlock(self, wait=1):
265 try:
265 try:
266 wlock = lock.lock(self.join("wlock"), 0, self.dirstate.write)
266 wlock = lock.lock(self.join("wlock"), 0, self.dirstate.write)
267 except lock.LockHeld, inst:
267 except lock.LockHeld, inst:
268 if not wait:
268 if not wait:
269 raise inst
269 raise inst
270 self.ui.warn(_("waiting for lock held by %s\n") % inst.args[0])
270 self.ui.warn(_("waiting for lock held by %s\n") % inst.args[0])
271 wlock = lock.lock(self.join("wlock"), wait, self.dirstate.write)
271 wlock = lock.lock(self.join("wlock"), wait, self.dirstate.write)
272 self.dirstate.read()
272 self.dirstate.read()
273 return wlock
273 return wlock
274
274
275 def rawcommit(self, files, text, user, date, p1=None, p2=None, wlock=None):
275 def rawcommit(self, files, text, user, date, p1=None, p2=None, wlock=None):
276 orig_parent = self.dirstate.parents()[0] or nullid
276 orig_parent = self.dirstate.parents()[0] or nullid
277 p1 = p1 or self.dirstate.parents()[0] or nullid
277 p1 = p1 or self.dirstate.parents()[0] or nullid
278 p2 = p2 or self.dirstate.parents()[1] or nullid
278 p2 = p2 or self.dirstate.parents()[1] or nullid
279 c1 = self.changelog.read(p1)
279 c1 = self.changelog.read(p1)
280 c2 = self.changelog.read(p2)
280 c2 = self.changelog.read(p2)
281 m1 = self.manifest.read(c1[0])
281 m1 = self.manifest.read(c1[0])
282 mf1 = self.manifest.readflags(c1[0])
282 mf1 = self.manifest.readflags(c1[0])
283 m2 = self.manifest.read(c2[0])
283 m2 = self.manifest.read(c2[0])
284 changed = []
284 changed = []
285
285
286 if orig_parent == p1:
286 if orig_parent == p1:
287 update_dirstate = 1
287 update_dirstate = 1
288 else:
288 else:
289 update_dirstate = 0
289 update_dirstate = 0
290
290
291 if not wlock:
291 if not wlock:
292 wlock = self.wlock()
292 wlock = self.wlock()
293 lock = self.lock()
293 lock = self.lock()
294 tr = self.transaction()
294 tr = self.transaction()
295 mm = m1.copy()
295 mm = m1.copy()
296 mfm = mf1.copy()
296 mfm = mf1.copy()
297 linkrev = self.changelog.count()
297 linkrev = self.changelog.count()
298 for f in files:
298 for f in files:
299 try:
299 try:
300 t = self.wread(f)
300 t = self.wread(f)
301 tm = util.is_exec(self.wjoin(f), mfm.get(f, False))
301 tm = util.is_exec(self.wjoin(f), mfm.get(f, False))
302 r = self.file(f)
302 r = self.file(f)
303 mfm[f] = tm
303 mfm[f] = tm
304
304
305 fp1 = m1.get(f, nullid)
305 fp1 = m1.get(f, nullid)
306 fp2 = m2.get(f, nullid)
306 fp2 = m2.get(f, nullid)
307
307
308 # is the same revision on two branches of a merge?
308 # is the same revision on two branches of a merge?
309 if fp2 == fp1:
309 if fp2 == fp1:
310 fp2 = nullid
310 fp2 = nullid
311
311
312 if fp2 != nullid:
312 if fp2 != nullid:
313 # is one parent an ancestor of the other?
313 # is one parent an ancestor of the other?
314 fpa = r.ancestor(fp1, fp2)
314 fpa = r.ancestor(fp1, fp2)
315 if fpa == fp1:
315 if fpa == fp1:
316 fp1, fp2 = fp2, nullid
316 fp1, fp2 = fp2, nullid
317 elif fpa == fp2:
317 elif fpa == fp2:
318 fp2 = nullid
318 fp2 = nullid
319
319
320 # is the file unmodified from the parent?
320 # is the file unmodified from the parent?
321 if t == r.read(fp1):
321 if t == r.read(fp1):
322 # record the proper existing parent in manifest
322 # record the proper existing parent in manifest
323 # no need to add a revision
323 # no need to add a revision
324 mm[f] = fp1
324 mm[f] = fp1
325 continue
325 continue
326
326
327 mm[f] = r.add(t, {}, tr, linkrev, fp1, fp2)
327 mm[f] = r.add(t, {}, tr, linkrev, fp1, fp2)
328 changed.append(f)
328 changed.append(f)
329 if update_dirstate:
329 if update_dirstate:
330 self.dirstate.update([f], "n")
330 self.dirstate.update([f], "n")
331 except IOError:
331 except IOError:
332 try:
332 try:
333 del mm[f]
333 del mm[f]
334 del mfm[f]
334 del mfm[f]
335 if update_dirstate:
335 if update_dirstate:
336 self.dirstate.forget([f])
336 self.dirstate.forget([f])
337 except:
337 except:
338 # deleted from p2?
338 # deleted from p2?
339 pass
339 pass
340
340
341 mnode = self.manifest.add(mm, mfm, tr, linkrev, c1[0], c2[0])
341 mnode = self.manifest.add(mm, mfm, tr, linkrev, c1[0], c2[0])
342 user = user or self.ui.username()
342 user = user or self.ui.username()
343 n = self.changelog.add(mnode, changed, text, tr, p1, p2, user, date)
343 n = self.changelog.add(mnode, changed, text, tr, p1, p2, user, date)
344 tr.close()
344 tr.close()
345 if update_dirstate:
345 if update_dirstate:
346 self.dirstate.setparents(n, nullid)
346 self.dirstate.setparents(n, nullid)
347
347
348 def commit(self, files=None, text="", user=None, date=None,
348 def commit(self, files=None, text="", user=None, date=None,
349 match=util.always, force=False, wlock=None):
349 match=util.always, force=False, wlock=None):
350 commit = []
350 commit = []
351 remove = []
351 remove = []
352 changed = []
352 changed = []
353
353
354 if files:
354 if files:
355 for f in files:
355 for f in files:
356 s = self.dirstate.state(f)
356 s = self.dirstate.state(f)
357 if s in 'nmai':
357 if s in 'nmai':
358 commit.append(f)
358 commit.append(f)
359 elif s == 'r':
359 elif s == 'r':
360 remove.append(f)
360 remove.append(f)
361 else:
361 else:
362 self.ui.warn(_("%s not tracked!\n") % f)
362 self.ui.warn(_("%s not tracked!\n") % f)
363 else:
363 else:
364 modified, added, removed, deleted, unknown = self.changes(match=match)
364 modified, added, removed, deleted, unknown = self.changes(match=match)
365 commit = modified + added
365 commit = modified + added
366 remove = removed
366 remove = removed
367
367
368 p1, p2 = self.dirstate.parents()
368 p1, p2 = self.dirstate.parents()
369 c1 = self.changelog.read(p1)
369 c1 = self.changelog.read(p1)
370 c2 = self.changelog.read(p2)
370 c2 = self.changelog.read(p2)
371 m1 = self.manifest.read(c1[0])
371 m1 = self.manifest.read(c1[0])
372 mf1 = self.manifest.readflags(c1[0])
372 mf1 = self.manifest.readflags(c1[0])
373 m2 = self.manifest.read(c2[0])
373 m2 = self.manifest.read(c2[0])
374
374
375 if not commit and not remove and not force and p2 == nullid:
375 if not commit and not remove and not force and p2 == nullid:
376 self.ui.status(_("nothing changed\n"))
376 self.ui.status(_("nothing changed\n"))
377 return None
377 return None
378
378
379 xp1 = hex(p1)
379 xp1 = hex(p1)
380 if p2 == nullid: xp2 = ''
380 if p2 == nullid: xp2 = ''
381 else: xp2 = hex(p2)
381 else: xp2 = hex(p2)
382
382
383 self.hook("precommit", throw=True, p1=xp1, p2=xp2)
383 self.hook("precommit", throw=True, p1=xp1, p2=xp2)
384
384
385 if not wlock:
385 if not wlock:
386 wlock = self.wlock()
386 wlock = self.wlock()
387 lock = self.lock()
387 lock = self.lock()
388 tr = self.transaction()
388 tr = self.transaction()
389
389
390 # check in files
390 # check in files
391 new = {}
391 new = {}
392 linkrev = self.changelog.count()
392 linkrev = self.changelog.count()
393 commit.sort()
393 commit.sort()
394 for f in commit:
394 for f in commit:
395 self.ui.note(f + "\n")
395 self.ui.note(f + "\n")
396 try:
396 try:
397 mf1[f] = util.is_exec(self.wjoin(f), mf1.get(f, False))
397 mf1[f] = util.is_exec(self.wjoin(f), mf1.get(f, False))
398 t = self.wread(f)
398 t = self.wread(f)
399 except IOError:
399 except IOError:
400 self.ui.warn(_("trouble committing %s!\n") % f)
400 self.ui.warn(_("trouble committing %s!\n") % f)
401 raise
401 raise
402
402
403 r = self.file(f)
403 r = self.file(f)
404
404
405 meta = {}
405 meta = {}
406 cp = self.dirstate.copied(f)
406 cp = self.dirstate.copied(f)
407 if cp:
407 if cp:
408 meta["copy"] = cp
408 meta["copy"] = cp
409 meta["copyrev"] = hex(m1.get(cp, m2.get(cp, nullid)))
409 meta["copyrev"] = hex(m1.get(cp, m2.get(cp, nullid)))
410 self.ui.debug(_(" %s: copy %s:%s\n") % (f, cp, meta["copyrev"]))
410 self.ui.debug(_(" %s: copy %s:%s\n") % (f, cp, meta["copyrev"]))
411 fp1, fp2 = nullid, nullid
411 fp1, fp2 = nullid, nullid
412 else:
412 else:
413 fp1 = m1.get(f, nullid)
413 fp1 = m1.get(f, nullid)
414 fp2 = m2.get(f, nullid)
414 fp2 = m2.get(f, nullid)
415
415
416 if fp2 != nullid:
416 if fp2 != nullid:
417 # is one parent an ancestor of the other?
417 # is one parent an ancestor of the other?
418 fpa = r.ancestor(fp1, fp2)
418 fpa = r.ancestor(fp1, fp2)
419 if fpa == fp1:
419 if fpa == fp1:
420 fp1, fp2 = fp2, nullid
420 fp1, fp2 = fp2, nullid
421 elif fpa == fp2:
421 elif fpa == fp2:
422 fp2 = nullid
422 fp2 = nullid
423
423
424 # is the file unmodified from the parent?
424 # is the file unmodified from the parent?
425 if not meta and t == r.read(fp1) and fp2 == nullid:
425 if not meta and t == r.read(fp1) and fp2 == nullid:
426 # record the proper existing parent in manifest
426 # record the proper existing parent in manifest
427 # no need to add a revision
427 # no need to add a revision
428 new[f] = fp1
428 new[f] = fp1
429 continue
429 continue
430
430
431 new[f] = r.add(t, meta, tr, linkrev, fp1, fp2)
431 new[f] = r.add(t, meta, tr, linkrev, fp1, fp2)
432 # remember what we've added so that we can later calculate
432 # remember what we've added so that we can later calculate
433 # the files to pull from a set of changesets
433 # the files to pull from a set of changesets
434 changed.append(f)
434 changed.append(f)
435
435
436 # update manifest
436 # update manifest
437 m1 = m1.copy()
437 m1 = m1.copy()
438 m1.update(new)
438 m1.update(new)
439 for f in remove:
439 for f in remove:
440 if f in m1:
440 if f in m1:
441 del m1[f]
441 del m1[f]
442 mn = self.manifest.add(m1, mf1, tr, linkrev, c1[0], c2[0],
442 mn = self.manifest.add(m1, mf1, tr, linkrev, c1[0], c2[0],
443 (new, remove))
443 (new, remove))
444
444
445 # add changeset
445 # add changeset
446 new = new.keys()
446 new = new.keys()
447 new.sort()
447 new.sort()
448
448
449 if not text:
449 if not text:
450 edittext = [""]
450 edittext = [""]
451 if p2 != nullid:
451 if p2 != nullid:
452 edittext.append("HG: branch merge")
452 edittext.append("HG: branch merge")
453 edittext.extend(["HG: changed %s" % f for f in changed])
453 edittext.extend(["HG: changed %s" % f for f in changed])
454 edittext.extend(["HG: removed %s" % f for f in remove])
454 edittext.extend(["HG: removed %s" % f for f in remove])
455 if not changed and not remove:
455 if not changed and not remove:
456 edittext.append("HG: no files changed")
456 edittext.append("HG: no files changed")
457 edittext.append("")
457 edittext.append("")
458 # run editor in the repository root
458 # run editor in the repository root
459 olddir = os.getcwd()
459 olddir = os.getcwd()
460 os.chdir(self.root)
460 os.chdir(self.root)
461 edittext = self.ui.edit("\n".join(edittext))
461 edittext = self.ui.edit("\n".join(edittext))
462 os.chdir(olddir)
462 os.chdir(olddir)
463 if not edittext.rstrip():
463 if not edittext.rstrip():
464 return None
464 return None
465 text = edittext
465 text = edittext
466
466
467 user = user or self.ui.username()
467 user = user or self.ui.username()
468 n = self.changelog.add(mn, changed + remove, text, tr, p1, p2, user, date)
468 n = self.changelog.add(mn, changed + remove, text, tr, p1, p2, user, date)
469 self.hook('pretxncommit', throw=True, node=hex(n), p1=xp1, p2=xp2)
469 self.hook('pretxncommit', throw=True, node=hex(n), p1=xp1, p2=xp2)
470 tr.close()
470 tr.close()
471
471
472 self.dirstate.setparents(n)
472 self.dirstate.setparents(n)
473 self.dirstate.update(new, "n")
473 self.dirstate.update(new, "n")
474 self.dirstate.forget(remove)
474 self.dirstate.forget(remove)
475
475
476 self.hook("commit", node=hex(n), p1=xp1, p2=xp2)
476 self.hook("commit", node=hex(n), p1=xp1, p2=xp2)
477 return n
477 return n
478
478
479 def walk(self, node=None, files=[], match=util.always):
479 def walk(self, node=None, files=[], match=util.always):
480 if node:
480 if node:
481 fdict = dict.fromkeys(files)
481 fdict = dict.fromkeys(files)
482 for fn in self.manifest.read(self.changelog.read(node)[0]):
482 for fn in self.manifest.read(self.changelog.read(node)[0]):
483 fdict.pop(fn, None)
483 fdict.pop(fn, None)
484 if match(fn):
484 if match(fn):
485 yield 'm', fn
485 yield 'm', fn
486 for fn in fdict:
486 for fn in fdict:
487 self.ui.warn(_('%s: No such file in rev %s\n') % (
487 self.ui.warn(_('%s: No such file in rev %s\n') % (
488 util.pathto(self.getcwd(), fn), short(node)))
488 util.pathto(self.getcwd(), fn), short(node)))
489 else:
489 else:
490 for src, fn in self.dirstate.walk(files, match):
490 for src, fn in self.dirstate.walk(files, match):
491 yield src, fn
491 yield src, fn
492
492
493 def changes(self, node1=None, node2=None, files=[], match=util.always,
493 def changes(self, node1=None, node2=None, files=[], match=util.always,
494 wlock=None):
494 wlock=None):
495 """return changes between two nodes or node and working directory
495 """return changes between two nodes or node and working directory
496
496
497 If node1 is None, use the first dirstate parent instead.
497 If node1 is None, use the first dirstate parent instead.
498 If node2 is None, compare node1 with working directory.
498 If node2 is None, compare node1 with working directory.
499 """
499 """
500
500
501 def fcmp(fn, mf):
501 def fcmp(fn, mf):
502 t1 = self.wread(fn)
502 t1 = self.wread(fn)
503 t2 = self.file(fn).read(mf.get(fn, nullid))
503 t2 = self.file(fn).read(mf.get(fn, nullid))
504 return cmp(t1, t2)
504 return cmp(t1, t2)
505
505
506 def mfmatches(node):
506 def mfmatches(node):
507 change = self.changelog.read(node)
507 change = self.changelog.read(node)
508 mf = dict(self.manifest.read(change[0]))
508 mf = dict(self.manifest.read(change[0]))
509 for fn in mf.keys():
509 for fn in mf.keys():
510 if not match(fn):
510 if not match(fn):
511 del mf[fn]
511 del mf[fn]
512 return mf
512 return mf
513
513
514 # are we comparing the working directory?
514 # are we comparing the working directory?
515 if not node2:
515 if not node2:
516 if not wlock:
516 if not wlock:
517 try:
517 try:
518 wlock = self.wlock(wait=0)
518 wlock = self.wlock(wait=0)
519 except lock.LockHeld:
519 except lock.LockHeld:
520 wlock = None
520 wlock = None
521 lookup, modified, added, removed, deleted, unknown = (
521 lookup, modified, added, removed, deleted, unknown = (
522 self.dirstate.changes(files, match))
522 self.dirstate.changes(files, match))
523
523
524 # are we comparing working dir against its parent?
524 # are we comparing working dir against its parent?
525 if not node1:
525 if not node1:
526 if lookup:
526 if lookup:
527 # do a full compare of any files that might have changed
527 # do a full compare of any files that might have changed
528 mf2 = mfmatches(self.dirstate.parents()[0])
528 mf2 = mfmatches(self.dirstate.parents()[0])
529 for f in lookup:
529 for f in lookup:
530 if fcmp(f, mf2):
530 if fcmp(f, mf2):
531 modified.append(f)
531 modified.append(f)
532 elif wlock is not None:
532 elif wlock is not None:
533 self.dirstate.update([f], "n")
533 self.dirstate.update([f], "n")
534 else:
534 else:
535 # we are comparing working dir against non-parent
535 # we are comparing working dir against non-parent
536 # generate a pseudo-manifest for the working dir
536 # generate a pseudo-manifest for the working dir
537 mf2 = mfmatches(self.dirstate.parents()[0])
537 mf2 = mfmatches(self.dirstate.parents()[0])
538 for f in lookup + modified + added:
538 for f in lookup + modified + added:
539 mf2[f] = ""
539 mf2[f] = ""
540 for f in removed:
540 for f in removed:
541 if f in mf2:
541 if f in mf2:
542 del mf2[f]
542 del mf2[f]
543 else:
543 else:
544 # we are comparing two revisions
544 # we are comparing two revisions
545 deleted, unknown = [], []
545 deleted, unknown = [], []
546 mf2 = mfmatches(node2)
546 mf2 = mfmatches(node2)
547
547
548 if node1:
548 if node1:
549 # flush lists from dirstate before comparing manifests
549 # flush lists from dirstate before comparing manifests
550 modified, added = [], []
550 modified, added = [], []
551
551
552 mf1 = mfmatches(node1)
552 mf1 = mfmatches(node1)
553
553
554 for fn in mf2:
554 for fn in mf2:
555 if mf1.has_key(fn):
555 if mf1.has_key(fn):
556 if mf1[fn] != mf2[fn] and (mf2[fn] != "" or fcmp(fn, mf1)):
556 if mf1[fn] != mf2[fn] and (mf2[fn] != "" or fcmp(fn, mf1)):
557 modified.append(fn)
557 modified.append(fn)
558 del mf1[fn]
558 del mf1[fn]
559 else:
559 else:
560 added.append(fn)
560 added.append(fn)
561
561
562 removed = mf1.keys()
562 removed = mf1.keys()
563
563
564 # sort and return results:
564 # sort and return results:
565 for l in modified, added, removed, deleted, unknown:
565 for l in modified, added, removed, deleted, unknown:
566 l.sort()
566 l.sort()
567 return (modified, added, removed, deleted, unknown)
567 return (modified, added, removed, deleted, unknown)
568
568
569 def add(self, list, wlock=None):
569 def add(self, list, wlock=None):
570 if not wlock:
570 if not wlock:
571 wlock = self.wlock()
571 wlock = self.wlock()
572 for f in list:
572 for f in list:
573 p = self.wjoin(f)
573 p = self.wjoin(f)
574 if not os.path.exists(p):
574 if not os.path.exists(p):
575 self.ui.warn(_("%s does not exist!\n") % f)
575 self.ui.warn(_("%s does not exist!\n") % f)
576 elif not os.path.isfile(p):
576 elif not os.path.isfile(p):
577 self.ui.warn(_("%s not added: only files supported currently\n")
577 self.ui.warn(_("%s not added: only files supported currently\n")
578 % f)
578 % f)
579 elif self.dirstate.state(f) in 'an':
579 elif self.dirstate.state(f) in 'an':
580 self.ui.warn(_("%s already tracked!\n") % f)
580 self.ui.warn(_("%s already tracked!\n") % f)
581 else:
581 else:
582 self.dirstate.update([f], "a")
582 self.dirstate.update([f], "a")
583
583
584 def forget(self, list, wlock=None):
584 def forget(self, list, wlock=None):
585 if not wlock:
585 if not wlock:
586 wlock = self.wlock()
586 wlock = self.wlock()
587 for f in list:
587 for f in list:
588 if self.dirstate.state(f) not in 'ai':
588 if self.dirstate.state(f) not in 'ai':
589 self.ui.warn(_("%s not added!\n") % f)
589 self.ui.warn(_("%s not added!\n") % f)
590 else:
590 else:
591 self.dirstate.forget([f])
591 self.dirstate.forget([f])
592
592
593 def remove(self, list, unlink=False, wlock=None):
593 def remove(self, list, unlink=False, wlock=None):
594 if unlink:
594 if unlink:
595 for f in list:
595 for f in list:
596 try:
596 try:
597 util.unlink(self.wjoin(f))
597 util.unlink(self.wjoin(f))
598 except OSError, inst:
598 except OSError, inst:
599 if inst.errno != errno.ENOENT:
599 if inst.errno != errno.ENOENT:
600 raise
600 raise
601 if not wlock:
601 if not wlock:
602 wlock = self.wlock()
602 wlock = self.wlock()
603 for f in list:
603 for f in list:
604 p = self.wjoin(f)
604 p = self.wjoin(f)
605 if os.path.exists(p):
605 if os.path.exists(p):
606 self.ui.warn(_("%s still exists!\n") % f)
606 self.ui.warn(_("%s still exists!\n") % f)
607 elif self.dirstate.state(f) == 'a':
607 elif self.dirstate.state(f) == 'a':
608 self.ui.warn(_("%s never committed!\n") % f)
608 self.ui.warn(_("%s never committed!\n") % f)
609 self.dirstate.forget([f])
609 self.dirstate.forget([f])
610 elif f not in self.dirstate:
610 elif f not in self.dirstate:
611 self.ui.warn(_("%s not tracked!\n") % f)
611 self.ui.warn(_("%s not tracked!\n") % f)
612 else:
612 else:
613 self.dirstate.update([f], "r")
613 self.dirstate.update([f], "r")
614
614
615 def undelete(self, list, wlock=None):
615 def undelete(self, list, wlock=None):
616 p = self.dirstate.parents()[0]
616 p = self.dirstate.parents()[0]
617 mn = self.changelog.read(p)[0]
617 mn = self.changelog.read(p)[0]
618 mf = self.manifest.readflags(mn)
618 mf = self.manifest.readflags(mn)
619 m = self.manifest.read(mn)
619 m = self.manifest.read(mn)
620 if not wlock:
620 if not wlock:
621 wlock = self.wlock()
621 wlock = self.wlock()
622 for f in list:
622 for f in list:
623 if self.dirstate.state(f) not in "r":
623 if self.dirstate.state(f) not in "r":
624 self.ui.warn("%s not removed!\n" % f)
624 self.ui.warn("%s not removed!\n" % f)
625 else:
625 else:
626 t = self.file(f).read(m[f])
626 t = self.file(f).read(m[f])
627 self.wwrite(f, t)
627 self.wwrite(f, t)
628 util.set_exec(self.wjoin(f), mf[f])
628 util.set_exec(self.wjoin(f), mf[f])
629 self.dirstate.update([f], "n")
629 self.dirstate.update([f], "n")
630
630
631 def copy(self, source, dest, wlock=None):
631 def copy(self, source, dest, wlock=None):
632 p = self.wjoin(dest)
632 p = self.wjoin(dest)
633 if not os.path.exists(p):
633 if not os.path.exists(p):
634 self.ui.warn(_("%s does not exist!\n") % dest)
634 self.ui.warn(_("%s does not exist!\n") % dest)
635 elif not os.path.isfile(p):
635 elif not os.path.isfile(p):
636 self.ui.warn(_("copy failed: %s is not a file\n") % dest)
636 self.ui.warn(_("copy failed: %s is not a file\n") % dest)
637 else:
637 else:
638 if not wlock:
638 if not wlock:
639 wlock = self.wlock()
639 wlock = self.wlock()
640 if self.dirstate.state(dest) == '?':
640 if self.dirstate.state(dest) == '?':
641 self.dirstate.update([dest], "a")
641 self.dirstate.update([dest], "a")
642 self.dirstate.copy(source, dest)
642 self.dirstate.copy(source, dest)
643
643
644 def heads(self, start=None):
644 def heads(self, start=None):
645 heads = self.changelog.heads(start)
645 heads = self.changelog.heads(start)
646 # sort the output in rev descending order
646 # sort the output in rev descending order
647 heads = [(-self.changelog.rev(h), h) for h in heads]
647 heads = [(-self.changelog.rev(h), h) for h in heads]
648 heads.sort()
648 heads.sort()
649 return [n for (r, n) in heads]
649 return [n for (r, n) in heads]
650
650
651 # branchlookup returns a dict giving a list of branches for
651 # branchlookup returns a dict giving a list of branches for
652 # each head. A branch is defined as the tag of a node or
652 # each head. A branch is defined as the tag of a node or
653 # the branch of the node's parents. If a node has multiple
653 # the branch of the node's parents. If a node has multiple
654 # branch tags, tags are eliminated if they are visible from other
654 # branch tags, tags are eliminated if they are visible from other
655 # branch tags.
655 # branch tags.
656 #
656 #
657 # So, for this graph: a->b->c->d->e
657 # So, for this graph: a->b->c->d->e
658 # \ /
658 # \ /
659 # aa -----/
659 # aa -----/
660 # a has tag 2.6.12
660 # a has tag 2.6.12
661 # d has tag 2.6.13
661 # d has tag 2.6.13
662 # e would have branch tags for 2.6.12 and 2.6.13. Because the node
662 # e would have branch tags for 2.6.12 and 2.6.13. Because the node
663 # for 2.6.12 can be reached from the node 2.6.13, that is eliminated
663 # for 2.6.12 can be reached from the node 2.6.13, that is eliminated
664 # from the list.
664 # from the list.
665 #
665 #
666 # It is possible that more than one head will have the same branch tag.
666 # It is possible that more than one head will have the same branch tag.
667 # callers need to check the result for multiple heads under the same
667 # callers need to check the result for multiple heads under the same
668 # branch tag if that is a problem for them (ie checkout of a specific
668 # branch tag if that is a problem for them (ie checkout of a specific
669 # branch).
669 # branch).
670 #
670 #
671 # passing in a specific branch will limit the depth of the search
671 # passing in a specific branch will limit the depth of the search
672 # through the parents. It won't limit the branches returned in the
672 # through the parents. It won't limit the branches returned in the
673 # result though.
673 # result though.
674 def branchlookup(self, heads=None, branch=None):
674 def branchlookup(self, heads=None, branch=None):
675 if not heads:
675 if not heads:
676 heads = self.heads()
676 heads = self.heads()
677 headt = [ h for h in heads ]
677 headt = [ h for h in heads ]
678 chlog = self.changelog
678 chlog = self.changelog
679 branches = {}
679 branches = {}
680 merges = []
680 merges = []
681 seenmerge = {}
681 seenmerge = {}
682
682
683 # traverse the tree once for each head, recording in the branches
683 # traverse the tree once for each head, recording in the branches
684 # dict which tags are visible from this head. The branches
684 # dict which tags are visible from this head. The branches
685 # dict also records which tags are visible from each tag
685 # dict also records which tags are visible from each tag
686 # while we traverse.
686 # while we traverse.
687 while headt or merges:
687 while headt or merges:
688 if merges:
688 if merges:
689 n, found = merges.pop()
689 n, found = merges.pop()
690 visit = [n]
690 visit = [n]
691 else:
691 else:
692 h = headt.pop()
692 h = headt.pop()
693 visit = [h]
693 visit = [h]
694 found = [h]
694 found = [h]
695 seen = {}
695 seen = {}
696 while visit:
696 while visit:
697 n = visit.pop()
697 n = visit.pop()
698 if n in seen:
698 if n in seen:
699 continue
699 continue
700 pp = chlog.parents(n)
700 pp = chlog.parents(n)
701 tags = self.nodetags(n)
701 tags = self.nodetags(n)
702 if tags:
702 if tags:
703 for x in tags:
703 for x in tags:
704 if x == 'tip':
704 if x == 'tip':
705 continue
705 continue
706 for f in found:
706 for f in found:
707 branches.setdefault(f, {})[n] = 1
707 branches.setdefault(f, {})[n] = 1
708 branches.setdefault(n, {})[n] = 1
708 branches.setdefault(n, {})[n] = 1
709 break
709 break
710 if n not in found:
710 if n not in found:
711 found.append(n)
711 found.append(n)
712 if branch in tags:
712 if branch in tags:
713 continue
713 continue
714 seen[n] = 1
714 seen[n] = 1
715 if pp[1] != nullid and n not in seenmerge:
715 if pp[1] != nullid and n not in seenmerge:
716 merges.append((pp[1], [x for x in found]))
716 merges.append((pp[1], [x for x in found]))
717 seenmerge[n] = 1
717 seenmerge[n] = 1
718 if pp[0] != nullid:
718 if pp[0] != nullid:
719 visit.append(pp[0])
719 visit.append(pp[0])
720 # traverse the branches dict, eliminating branch tags from each
720 # traverse the branches dict, eliminating branch tags from each
721 # head that are visible from another branch tag for that head.
721 # head that are visible from another branch tag for that head.
722 out = {}
722 out = {}
723 viscache = {}
723 viscache = {}
724 for h in heads:
724 for h in heads:
725 def visible(node):
725 def visible(node):
726 if node in viscache:
726 if node in viscache:
727 return viscache[node]
727 return viscache[node]
728 ret = {}
728 ret = {}
729 visit = [node]
729 visit = [node]
730 while visit:
730 while visit:
731 x = visit.pop()
731 x = visit.pop()
732 if x in viscache:
732 if x in viscache:
733 ret.update(viscache[x])
733 ret.update(viscache[x])
734 elif x not in ret:
734 elif x not in ret:
735 ret[x] = 1
735 ret[x] = 1
736 if x in branches:
736 if x in branches:
737 visit[len(visit):] = branches[x].keys()
737 visit[len(visit):] = branches[x].keys()
738 viscache[node] = ret
738 viscache[node] = ret
739 return ret
739 return ret
740 if h not in branches:
740 if h not in branches:
741 continue
741 continue
742 # O(n^2), but somewhat limited. This only searches the
742 # O(n^2), but somewhat limited. This only searches the
743 # tags visible from a specific head, not all the tags in the
743 # tags visible from a specific head, not all the tags in the
744 # whole repo.
744 # whole repo.
745 for b in branches[h]:
745 for b in branches[h]:
746 vis = False
746 vis = False
747 for bb in branches[h].keys():
747 for bb in branches[h].keys():
748 if b != bb:
748 if b != bb:
749 if b in visible(bb):
749 if b in visible(bb):
750 vis = True
750 vis = True
751 break
751 break
752 if not vis:
752 if not vis:
753 l = out.setdefault(h, [])
753 l = out.setdefault(h, [])
754 l[len(l):] = self.nodetags(b)
754 l[len(l):] = self.nodetags(b)
755 return out
755 return out
756
756
757 def branches(self, nodes):
757 def branches(self, nodes):
758 if not nodes:
758 if not nodes:
759 nodes = [self.changelog.tip()]
759 nodes = [self.changelog.tip()]
760 b = []
760 b = []
761 for n in nodes:
761 for n in nodes:
762 t = n
762 t = n
763 while n:
763 while n:
764 p = self.changelog.parents(n)
764 p = self.changelog.parents(n)
765 if p[1] != nullid or p[0] == nullid:
765 if p[1] != nullid or p[0] == nullid:
766 b.append((t, n, p[0], p[1]))
766 b.append((t, n, p[0], p[1]))
767 break
767 break
768 n = p[0]
768 n = p[0]
769 return b
769 return b
770
770
771 def between(self, pairs):
771 def between(self, pairs):
772 r = []
772 r = []
773
773
774 for top, bottom in pairs:
774 for top, bottom in pairs:
775 n, l, i = top, [], 0
775 n, l, i = top, [], 0
776 f = 1
776 f = 1
777
777
778 while n != bottom:
778 while n != bottom:
779 p = self.changelog.parents(n)[0]
779 p = self.changelog.parents(n)[0]
780 if i == f:
780 if i == f:
781 l.append(n)
781 l.append(n)
782 f = f * 2
782 f = f * 2
783 n = p
783 n = p
784 i += 1
784 i += 1
785
785
786 r.append(l)
786 r.append(l)
787
787
788 return r
788 return r
789
789
790 def findincoming(self, remote, base=None, heads=None):
790 def findincoming(self, remote, base=None, heads=None):
791 m = self.changelog.nodemap
791 m = self.changelog.nodemap
792 search = []
792 search = []
793 fetch = {}
793 fetch = {}
794 seen = {}
794 seen = {}
795 seenbranch = {}
795 seenbranch = {}
796 if base == None:
796 if base == None:
797 base = {}
797 base = {}
798
798
799 # assume we're closer to the tip than the root
799 # assume we're closer to the tip than the root
800 # and start by examining the heads
800 # and start by examining the heads
801 self.ui.status(_("searching for changes\n"))
801 self.ui.status(_("searching for changes\n"))
802
802
803 if not heads:
803 if not heads:
804 heads = remote.heads()
804 heads = remote.heads()
805
805
806 unknown = []
806 unknown = []
807 for h in heads:
807 for h in heads:
808 if h not in m:
808 if h not in m:
809 unknown.append(h)
809 unknown.append(h)
810 else:
810 else:
811 base[h] = 1
811 base[h] = 1
812
812
813 if not unknown:
813 if not unknown:
814 return None
814 return None
815
815
816 rep = {}
816 rep = {}
817 reqcnt = 0
817 reqcnt = 0
818
818
819 # search through remote branches
819 # search through remote branches
820 # a 'branch' here is a linear segment of history, with four parts:
820 # a 'branch' here is a linear segment of history, with four parts:
821 # head, root, first parent, second parent
821 # head, root, first parent, second parent
822 # (a branch always has two parents (or none) by definition)
822 # (a branch always has two parents (or none) by definition)
823 unknown = remote.branches(unknown)
823 unknown = remote.branches(unknown)
824 while unknown:
824 while unknown:
825 r = []
825 r = []
826 while unknown:
826 while unknown:
827 n = unknown.pop(0)
827 n = unknown.pop(0)
828 if n[0] in seen:
828 if n[0] in seen:
829 continue
829 continue
830
830
831 self.ui.debug(_("examining %s:%s\n")
831 self.ui.debug(_("examining %s:%s\n")
832 % (short(n[0]), short(n[1])))
832 % (short(n[0]), short(n[1])))
833 if n[0] == nullid:
833 if n[0] == nullid:
834 break
834 break
835 if n in seenbranch:
835 if n in seenbranch:
836 self.ui.debug(_("branch already found\n"))
836 self.ui.debug(_("branch already found\n"))
837 continue
837 continue
838 if n[1] and n[1] in m: # do we know the base?
838 if n[1] and n[1] in m: # do we know the base?
839 self.ui.debug(_("found incomplete branch %s:%s\n")
839 self.ui.debug(_("found incomplete branch %s:%s\n")
840 % (short(n[0]), short(n[1])))
840 % (short(n[0]), short(n[1])))
841 search.append(n) # schedule branch range for scanning
841 search.append(n) # schedule branch range for scanning
842 seenbranch[n] = 1
842 seenbranch[n] = 1
843 else:
843 else:
844 if n[1] not in seen and n[1] not in fetch:
844 if n[1] not in seen and n[1] not in fetch:
845 if n[2] in m and n[3] in m:
845 if n[2] in m and n[3] in m:
846 self.ui.debug(_("found new changeset %s\n") %
846 self.ui.debug(_("found new changeset %s\n") %
847 short(n[1]))
847 short(n[1]))
848 fetch[n[1]] = 1 # earliest unknown
848 fetch[n[1]] = 1 # earliest unknown
849 base[n[2]] = 1 # latest known
849 base[n[2]] = 1 # latest known
850 continue
850 continue
851
851
852 for a in n[2:4]:
852 for a in n[2:4]:
853 if a not in rep:
853 if a not in rep:
854 r.append(a)
854 r.append(a)
855 rep[a] = 1
855 rep[a] = 1
856
856
857 seen[n[0]] = 1
857 seen[n[0]] = 1
858
858
859 if r:
859 if r:
860 reqcnt += 1
860 reqcnt += 1
861 self.ui.debug(_("request %d: %s\n") %
861 self.ui.debug(_("request %d: %s\n") %
862 (reqcnt, " ".join(map(short, r))))
862 (reqcnt, " ".join(map(short, r))))
863 for p in range(0, len(r), 10):
863 for p in range(0, len(r), 10):
864 for b in remote.branches(r[p:p+10]):
864 for b in remote.branches(r[p:p+10]):
865 self.ui.debug(_("received %s:%s\n") %
865 self.ui.debug(_("received %s:%s\n") %
866 (short(b[0]), short(b[1])))
866 (short(b[0]), short(b[1])))
867 if b[0] in m:
867 if b[0] in m:
868 self.ui.debug(_("found base node %s\n")
868 self.ui.debug(_("found base node %s\n")
869 % short(b[0]))
869 % short(b[0]))
870 base[b[0]] = 1
870 base[b[0]] = 1
871 elif b[0] not in seen:
871 elif b[0] not in seen:
872 unknown.append(b)
872 unknown.append(b)
873
873
874 # do binary search on the branches we found
874 # do binary search on the branches we found
875 while search:
875 while search:
876 n = search.pop(0)
876 n = search.pop(0)
877 reqcnt += 1
877 reqcnt += 1
878 l = remote.between([(n[0], n[1])])[0]
878 l = remote.between([(n[0], n[1])])[0]
879 l.append(n[1])
879 l.append(n[1])
880 p = n[0]
880 p = n[0]
881 f = 1
881 f = 1
882 for i in l:
882 for i in l:
883 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
883 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
884 if i in m:
884 if i in m:
885 if f <= 2:
885 if f <= 2:
886 self.ui.debug(_("found new branch changeset %s\n") %
886 self.ui.debug(_("found new branch changeset %s\n") %
887 short(p))
887 short(p))
888 fetch[p] = 1
888 fetch[p] = 1
889 base[i] = 1
889 base[i] = 1
890 else:
890 else:
891 self.ui.debug(_("narrowed branch search to %s:%s\n")
891 self.ui.debug(_("narrowed branch search to %s:%s\n")
892 % (short(p), short(i)))
892 % (short(p), short(i)))
893 search.append((p, i))
893 search.append((p, i))
894 break
894 break
895 p, f = i, f * 2
895 p, f = i, f * 2
896
896
897 # sanity check our fetch list
897 # sanity check our fetch list
898 for f in fetch.keys():
898 for f in fetch.keys():
899 if f in m:
899 if f in m:
900 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
900 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
901
901
902 if base.keys() == [nullid]:
902 if base.keys() == [nullid]:
903 self.ui.warn(_("warning: pulling from an unrelated repository!\n"))
903 self.ui.warn(_("warning: pulling from an unrelated repository!\n"))
904
904
905 self.ui.note(_("found new changesets starting at ") +
905 self.ui.note(_("found new changesets starting at ") +
906 " ".join([short(f) for f in fetch]) + "\n")
906 " ".join([short(f) for f in fetch]) + "\n")
907
907
908 self.ui.debug(_("%d total queries\n") % reqcnt)
908 self.ui.debug(_("%d total queries\n") % reqcnt)
909
909
910 return fetch.keys()
910 return fetch.keys()
911
911
912 def findoutgoing(self, remote, base=None, heads=None):
912 def findoutgoing(self, remote, base=None, heads=None):
913 if base == None:
913 if base == None:
914 base = {}
914 base = {}
915 self.findincoming(remote, base, heads)
915 self.findincoming(remote, base, heads)
916
916
917 self.ui.debug(_("common changesets up to ")
917 self.ui.debug(_("common changesets up to ")
918 + " ".join(map(short, base.keys())) + "\n")
918 + " ".join(map(short, base.keys())) + "\n")
919
919
920 remain = dict.fromkeys(self.changelog.nodemap)
920 remain = dict.fromkeys(self.changelog.nodemap)
921
921
922 # prune everything remote has from the tree
922 # prune everything remote has from the tree
923 del remain[nullid]
923 del remain[nullid]
924 remove = base.keys()
924 remove = base.keys()
925 while remove:
925 while remove:
926 n = remove.pop(0)
926 n = remove.pop(0)
927 if n in remain:
927 if n in remain:
928 del remain[n]
928 del remain[n]
929 for p in self.changelog.parents(n):
929 for p in self.changelog.parents(n):
930 remove.append(p)
930 remove.append(p)
931
931
932 # find every node whose parents have been pruned
932 # find every node whose parents have been pruned
933 subset = []
933 subset = []
934 for n in remain:
934 for n in remain:
935 p1, p2 = self.changelog.parents(n)
935 p1, p2 = self.changelog.parents(n)
936 if p1 not in remain and p2 not in remain:
936 if p1 not in remain and p2 not in remain:
937 subset.append(n)
937 subset.append(n)
938
938
939 # this is the set of all roots we have to push
939 # this is the set of all roots we have to push
940 return subset
940 return subset
941
941
942 def pull(self, remote, heads=None):
942 def pull(self, remote, heads=None):
943 lock = self.lock()
943 lock = self.lock()
944
944
945 # if we have an empty repo, fetch everything
945 # if we have an empty repo, fetch everything
946 if self.changelog.tip() == nullid:
946 if self.changelog.tip() == nullid:
947 self.ui.status(_("requesting all changes\n"))
947 self.ui.status(_("requesting all changes\n"))
948 fetch = [nullid]
948 fetch = [nullid]
949 else:
949 else:
950 fetch = self.findincoming(remote)
950 fetch = self.findincoming(remote)
951
951
952 if not fetch:
952 if not fetch:
953 self.ui.status(_("no changes found\n"))
953 self.ui.status(_("no changes found\n"))
954 return 1
954 return 1
955
955
956 if heads is None:
956 if heads is None:
957 cg = remote.changegroup(fetch)
957 cg = remote.changegroup(fetch)
958 else:
958 else:
959 cg = remote.changegroupsubset(fetch, heads)
959 cg = remote.changegroupsubset(fetch, heads)
960 return self.addchangegroup(cg)
960 return self.addchangegroup(cg)
961
961
962 def push(self, remote, force=False):
962 def push(self, remote, force=False):
963 lock = remote.lock()
963 lock = remote.lock()
964
964
965 base = {}
965 base = {}
966 heads = remote.heads()
966 heads = remote.heads()
967 inc = self.findincoming(remote, base, heads)
967 inc = self.findincoming(remote, base, heads)
968 if not force and inc:
968 if not force and inc:
969 self.ui.warn(_("abort: unsynced remote changes!\n"))
969 self.ui.warn(_("abort: unsynced remote changes!\n"))
970 self.ui.status(_("(did you forget to sync? use push -f to force)\n"))
970 self.ui.status(_("(did you forget to sync? use push -f to force)\n"))
971 return 1
971 return 1
972
972
973 update = self.findoutgoing(remote, base)
973 update = self.findoutgoing(remote, base)
974 if not update:
974 if not update:
975 self.ui.status(_("no changes found\n"))
975 self.ui.status(_("no changes found\n"))
976 return 1
976 return 1
977 elif not force:
977 elif not force:
978 if len(heads) < len(self.changelog.heads()):
978 if len(heads) < len(self.changelog.heads()):
979 self.ui.warn(_("abort: push creates new remote branches!\n"))
979 self.ui.warn(_("abort: push creates new remote branches!\n"))
980 self.ui.status(_("(did you forget to merge?"
980 self.ui.status(_("(did you forget to merge?"
981 " use push -f to force)\n"))
981 " use push -f to force)\n"))
982 return 1
982 return 1
983
983
984 cg = self.changegroup(update)
984 cg = self.changegroup(update)
985 return remote.addchangegroup(cg)
985 return remote.addchangegroup(cg)
986
986
987 def changegroupsubset(self, bases, heads):
987 def changegroupsubset(self, bases, heads):
988 """This function generates a changegroup consisting of all the nodes
988 """This function generates a changegroup consisting of all the nodes
989 that are descendents of any of the bases, and ancestors of any of
989 that are descendents of any of the bases, and ancestors of any of
990 the heads.
990 the heads.
991
991
992 It is fairly complex as determining which filenodes and which
992 It is fairly complex as determining which filenodes and which
993 manifest nodes need to be included for the changeset to be complete
993 manifest nodes need to be included for the changeset to be complete
994 is non-trivial.
994 is non-trivial.
995
995
996 Another wrinkle is doing the reverse, figuring out which changeset in
996 Another wrinkle is doing the reverse, figuring out which changeset in
997 the changegroup a particular filenode or manifestnode belongs to."""
997 the changegroup a particular filenode or manifestnode belongs to."""
998
998
999 # Set up some initial variables
999 # Set up some initial variables
1000 # Make it easy to refer to self.changelog
1000 # Make it easy to refer to self.changelog
1001 cl = self.changelog
1001 cl = self.changelog
1002 # msng is short for missing - compute the list of changesets in this
1002 # msng is short for missing - compute the list of changesets in this
1003 # changegroup.
1003 # changegroup.
1004 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1004 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1005 # Some bases may turn out to be superfluous, and some heads may be
1005 # Some bases may turn out to be superfluous, and some heads may be
1006 # too. nodesbetween will return the minimal set of bases and heads
1006 # too. nodesbetween will return the minimal set of bases and heads
1007 # necessary to re-create the changegroup.
1007 # necessary to re-create the changegroup.
1008
1008
1009 # Known heads are the list of heads that it is assumed the recipient
1009 # Known heads are the list of heads that it is assumed the recipient
1010 # of this changegroup will know about.
1010 # of this changegroup will know about.
1011 knownheads = {}
1011 knownheads = {}
1012 # We assume that all parents of bases are known heads.
1012 # We assume that all parents of bases are known heads.
1013 for n in bases:
1013 for n in bases:
1014 for p in cl.parents(n):
1014 for p in cl.parents(n):
1015 if p != nullid:
1015 if p != nullid:
1016 knownheads[p] = 1
1016 knownheads[p] = 1
1017 knownheads = knownheads.keys()
1017 knownheads = knownheads.keys()
1018 if knownheads:
1018 if knownheads:
1019 # Now that we know what heads are known, we can compute which
1019 # Now that we know what heads are known, we can compute which
1020 # changesets are known. The recipient must know about all
1020 # changesets are known. The recipient must know about all
1021 # changesets required to reach the known heads from the null
1021 # changesets required to reach the known heads from the null
1022 # changeset.
1022 # changeset.
1023 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1023 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1024 junk = None
1024 junk = None
1025 # Transform the list into an ersatz set.
1025 # Transform the list into an ersatz set.
1026 has_cl_set = dict.fromkeys(has_cl_set)
1026 has_cl_set = dict.fromkeys(has_cl_set)
1027 else:
1027 else:
1028 # If there were no known heads, the recipient cannot be assumed to
1028 # If there were no known heads, the recipient cannot be assumed to
1029 # know about any changesets.
1029 # know about any changesets.
1030 has_cl_set = {}
1030 has_cl_set = {}
1031
1031
1032 # Make it easy to refer to self.manifest
1032 # Make it easy to refer to self.manifest
1033 mnfst = self.manifest
1033 mnfst = self.manifest
1034 # We don't know which manifests are missing yet
1034 # We don't know which manifests are missing yet
1035 msng_mnfst_set = {}
1035 msng_mnfst_set = {}
1036 # Nor do we know which filenodes are missing.
1036 # Nor do we know which filenodes are missing.
1037 msng_filenode_set = {}
1037 msng_filenode_set = {}
1038
1038
1039 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1039 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1040 junk = None
1040 junk = None
1041
1041
1042 # A changeset always belongs to itself, so the changenode lookup
1042 # A changeset always belongs to itself, so the changenode lookup
1043 # function for a changenode is identity.
1043 # function for a changenode is identity.
1044 def identity(x):
1044 def identity(x):
1045 return x
1045 return x
1046
1046
1047 # A function generating function. Sets up an environment for the
1047 # A function generating function. Sets up an environment for the
1048 # inner function.
1048 # inner function.
1049 def cmp_by_rev_func(revlog):
1049 def cmp_by_rev_func(revlog):
1050 # Compare two nodes by their revision number in the environment's
1050 # Compare two nodes by their revision number in the environment's
1051 # revision history. Since the revision number both represents the
1051 # revision history. Since the revision number both represents the
1052 # most efficient order to read the nodes in, and represents a
1052 # most efficient order to read the nodes in, and represents a
1053 # topological sorting of the nodes, this function is often useful.
1053 # topological sorting of the nodes, this function is often useful.
1054 def cmp_by_rev(a, b):
1054 def cmp_by_rev(a, b):
1055 return cmp(revlog.rev(a), revlog.rev(b))
1055 return cmp(revlog.rev(a), revlog.rev(b))
1056 return cmp_by_rev
1056 return cmp_by_rev
1057
1057
1058 # If we determine that a particular file or manifest node must be a
1058 # If we determine that a particular file or manifest node must be a
1059 # node that the recipient of the changegroup will already have, we can
1059 # node that the recipient of the changegroup will already have, we can
1060 # also assume the recipient will have all the parents. This function
1060 # also assume the recipient will have all the parents. This function
1061 # prunes them from the set of missing nodes.
1061 # prunes them from the set of missing nodes.
1062 def prune_parents(revlog, hasset, msngset):
1062 def prune_parents(revlog, hasset, msngset):
1063 haslst = hasset.keys()
1063 haslst = hasset.keys()
1064 haslst.sort(cmp_by_rev_func(revlog))
1064 haslst.sort(cmp_by_rev_func(revlog))
1065 for node in haslst:
1065 for node in haslst:
1066 parentlst = [p for p in revlog.parents(node) if p != nullid]
1066 parentlst = [p for p in revlog.parents(node) if p != nullid]
1067 while parentlst:
1067 while parentlst:
1068 n = parentlst.pop()
1068 n = parentlst.pop()
1069 if n not in hasset:
1069 if n not in hasset:
1070 hasset[n] = 1
1070 hasset[n] = 1
1071 p = [p for p in revlog.parents(n) if p != nullid]
1071 p = [p for p in revlog.parents(n) if p != nullid]
1072 parentlst.extend(p)
1072 parentlst.extend(p)
1073 for n in hasset:
1073 for n in hasset:
1074 msngset.pop(n, None)
1074 msngset.pop(n, None)
1075
1075
1076 # This is a function generating function used to set up an environment
1076 # This is a function generating function used to set up an environment
1077 # for the inner function to execute in.
1077 # for the inner function to execute in.
1078 def manifest_and_file_collector(changedfileset):
1078 def manifest_and_file_collector(changedfileset):
1079 # This is an information gathering function that gathers
1079 # This is an information gathering function that gathers
1080 # information from each changeset node that goes out as part of
1080 # information from each changeset node that goes out as part of
1081 # the changegroup. The information gathered is a list of which
1081 # the changegroup. The information gathered is a list of which
1082 # manifest nodes are potentially required (the recipient may
1082 # manifest nodes are potentially required (the recipient may
1083 # already have them) and total list of all files which were
1083 # already have them) and total list of all files which were
1084 # changed in any changeset in the changegroup.
1084 # changed in any changeset in the changegroup.
1085 #
1085 #
1086 # We also remember the first changenode we saw any manifest
1086 # We also remember the first changenode we saw any manifest
1087 # referenced by so we can later determine which changenode 'owns'
1087 # referenced by so we can later determine which changenode 'owns'
1088 # the manifest.
1088 # the manifest.
1089 def collect_manifests_and_files(clnode):
1089 def collect_manifests_and_files(clnode):
1090 c = cl.read(clnode)
1090 c = cl.read(clnode)
1091 for f in c[3]:
1091 for f in c[3]:
1092 # This is to make sure we only have one instance of each
1092 # This is to make sure we only have one instance of each
1093 # filename string for each filename.
1093 # filename string for each filename.
1094 changedfileset.setdefault(f, f)
1094 changedfileset.setdefault(f, f)
1095 msng_mnfst_set.setdefault(c[0], clnode)
1095 msng_mnfst_set.setdefault(c[0], clnode)
1096 return collect_manifests_and_files
1096 return collect_manifests_and_files
1097
1097
1098 # Figure out which manifest nodes (of the ones we think might be part
1098 # Figure out which manifest nodes (of the ones we think might be part
1099 # of the changegroup) the recipient must know about and remove them
1099 # of the changegroup) the recipient must know about and remove them
1100 # from the changegroup.
1100 # from the changegroup.
1101 def prune_manifests():
1101 def prune_manifests():
1102 has_mnfst_set = {}
1102 has_mnfst_set = {}
1103 for n in msng_mnfst_set:
1103 for n in msng_mnfst_set:
1104 # If a 'missing' manifest thinks it belongs to a changenode
1104 # If a 'missing' manifest thinks it belongs to a changenode
1105 # the recipient is assumed to have, obviously the recipient
1105 # the recipient is assumed to have, obviously the recipient
1106 # must have that manifest.
1106 # must have that manifest.
1107 linknode = cl.node(mnfst.linkrev(n))
1107 linknode = cl.node(mnfst.linkrev(n))
1108 if linknode in has_cl_set:
1108 if linknode in has_cl_set:
1109 has_mnfst_set[n] = 1
1109 has_mnfst_set[n] = 1
1110 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1110 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1111
1111
1112 # Use the information collected in collect_manifests_and_files to say
1112 # Use the information collected in collect_manifests_and_files to say
1113 # which changenode any manifestnode belongs to.
1113 # which changenode any manifestnode belongs to.
1114 def lookup_manifest_link(mnfstnode):
1114 def lookup_manifest_link(mnfstnode):
1115 return msng_mnfst_set[mnfstnode]
1115 return msng_mnfst_set[mnfstnode]
1116
1116
1117 # A function generating function that sets up the initial environment
1117 # A function generating function that sets up the initial environment
1118 # the inner function.
1118 # the inner function.
1119 def filenode_collector(changedfiles):
1119 def filenode_collector(changedfiles):
1120 next_rev = [0]
1120 next_rev = [0]
1121 # This gathers information from each manifestnode included in the
1121 # This gathers information from each manifestnode included in the
1122 # changegroup about which filenodes the manifest node references
1122 # changegroup about which filenodes the manifest node references
1123 # so we can include those in the changegroup too.
1123 # so we can include those in the changegroup too.
1124 #
1124 #
1125 # It also remembers which changenode each filenode belongs to. It
1125 # It also remembers which changenode each filenode belongs to. It
1126 # does this by assuming the a filenode belongs to the changenode
1126 # does this by assuming the a filenode belongs to the changenode
1127 # the first manifest that references it belongs to.
1127 # the first manifest that references it belongs to.
1128 def collect_msng_filenodes(mnfstnode):
1128 def collect_msng_filenodes(mnfstnode):
1129 r = mnfst.rev(mnfstnode)
1129 r = mnfst.rev(mnfstnode)
1130 if r == next_rev[0]:
1130 if r == next_rev[0]:
1131 # If the last rev we looked at was the one just previous,
1131 # If the last rev we looked at was the one just previous,
1132 # we only need to see a diff.
1132 # we only need to see a diff.
1133 delta = mdiff.patchtext(mnfst.delta(mnfstnode))
1133 delta = mdiff.patchtext(mnfst.delta(mnfstnode))
1134 # For each line in the delta
1134 # For each line in the delta
1135 for dline in delta.splitlines():
1135 for dline in delta.splitlines():
1136 # get the filename and filenode for that line
1136 # get the filename and filenode for that line
1137 f, fnode = dline.split('\0')
1137 f, fnode = dline.split('\0')
1138 fnode = bin(fnode[:40])
1138 fnode = bin(fnode[:40])
1139 f = changedfiles.get(f, None)
1139 f = changedfiles.get(f, None)
1140 # And if the file is in the list of files we care
1140 # And if the file is in the list of files we care
1141 # about.
1141 # about.
1142 if f is not None:
1142 if f is not None:
1143 # Get the changenode this manifest belongs to
1143 # Get the changenode this manifest belongs to
1144 clnode = msng_mnfst_set[mnfstnode]
1144 clnode = msng_mnfst_set[mnfstnode]
1145 # Create the set of filenodes for the file if
1145 # Create the set of filenodes for the file if
1146 # there isn't one already.
1146 # there isn't one already.
1147 ndset = msng_filenode_set.setdefault(f, {})
1147 ndset = msng_filenode_set.setdefault(f, {})
1148 # And set the filenode's changelog node to the
1148 # And set the filenode's changelog node to the
1149 # manifest's if it hasn't been set already.
1149 # manifest's if it hasn't been set already.
1150 ndset.setdefault(fnode, clnode)
1150 ndset.setdefault(fnode, clnode)
1151 else:
1151 else:
1152 # Otherwise we need a full manifest.
1152 # Otherwise we need a full manifest.
1153 m = mnfst.read(mnfstnode)
1153 m = mnfst.read(mnfstnode)
1154 # For every file in we care about.
1154 # For every file in we care about.
1155 for f in changedfiles:
1155 for f in changedfiles:
1156 fnode = m.get(f, None)
1156 fnode = m.get(f, None)
1157 # If it's in the manifest
1157 # If it's in the manifest
1158 if fnode is not None:
1158 if fnode is not None:
1159 # See comments above.
1159 # See comments above.
1160 clnode = msng_mnfst_set[mnfstnode]
1160 clnode = msng_mnfst_set[mnfstnode]
1161 ndset = msng_filenode_set.setdefault(f, {})
1161 ndset = msng_filenode_set.setdefault(f, {})
1162 ndset.setdefault(fnode, clnode)
1162 ndset.setdefault(fnode, clnode)
1163 # Remember the revision we hope to see next.
1163 # Remember the revision we hope to see next.
1164 next_rev[0] = r + 1
1164 next_rev[0] = r + 1
1165 return collect_msng_filenodes
1165 return collect_msng_filenodes
1166
1166
1167 # We have a list of filenodes we think we need for a file, lets remove
1167 # We have a list of filenodes we think we need for a file, lets remove
1168 # all those we now the recipient must have.
1168 # all those we now the recipient must have.
1169 def prune_filenodes(f, filerevlog):
1169 def prune_filenodes(f, filerevlog):
1170 msngset = msng_filenode_set[f]
1170 msngset = msng_filenode_set[f]
1171 hasset = {}
1171 hasset = {}
1172 # If a 'missing' filenode thinks it belongs to a changenode we
1172 # If a 'missing' filenode thinks it belongs to a changenode we
1173 # assume the recipient must have, then the recipient must have
1173 # assume the recipient must have, then the recipient must have
1174 # that filenode.
1174 # that filenode.
1175 for n in msngset:
1175 for n in msngset:
1176 clnode = cl.node(filerevlog.linkrev(n))
1176 clnode = cl.node(filerevlog.linkrev(n))
1177 if clnode in has_cl_set:
1177 if clnode in has_cl_set:
1178 hasset[n] = 1
1178 hasset[n] = 1
1179 prune_parents(filerevlog, hasset, msngset)
1179 prune_parents(filerevlog, hasset, msngset)
1180
1180
1181 # A function generator function that sets up the a context for the
1181 # A function generator function that sets up the a context for the
1182 # inner function.
1182 # inner function.
1183 def lookup_filenode_link_func(fname):
1183 def lookup_filenode_link_func(fname):
1184 msngset = msng_filenode_set[fname]
1184 msngset = msng_filenode_set[fname]
1185 # Lookup the changenode the filenode belongs to.
1185 # Lookup the changenode the filenode belongs to.
1186 def lookup_filenode_link(fnode):
1186 def lookup_filenode_link(fnode):
1187 return msngset[fnode]
1187 return msngset[fnode]
1188 return lookup_filenode_link
1188 return lookup_filenode_link
1189
1189
1190 # Now that we have all theses utility functions to help out and
1190 # Now that we have all theses utility functions to help out and
1191 # logically divide up the task, generate the group.
1191 # logically divide up the task, generate the group.
1192 def gengroup():
1192 def gengroup():
1193 # The set of changed files starts empty.
1193 # The set of changed files starts empty.
1194 changedfiles = {}
1194 changedfiles = {}
1195 # Create a changenode group generator that will call our functions
1195 # Create a changenode group generator that will call our functions
1196 # back to lookup the owning changenode and collect information.
1196 # back to lookup the owning changenode and collect information.
1197 group = cl.group(msng_cl_lst, identity,
1197 group = cl.group(msng_cl_lst, identity,
1198 manifest_and_file_collector(changedfiles))
1198 manifest_and_file_collector(changedfiles))
1199 for chnk in group:
1199 for chnk in group:
1200 yield chnk
1200 yield chnk
1201
1201
1202 # The list of manifests has been collected by the generator
1202 # The list of manifests has been collected by the generator
1203 # calling our functions back.
1203 # calling our functions back.
1204 prune_manifests()
1204 prune_manifests()
1205 msng_mnfst_lst = msng_mnfst_set.keys()
1205 msng_mnfst_lst = msng_mnfst_set.keys()
1206 # Sort the manifestnodes by revision number.
1206 # Sort the manifestnodes by revision number.
1207 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1207 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1208 # Create a generator for the manifestnodes that calls our lookup
1208 # Create a generator for the manifestnodes that calls our lookup
1209 # and data collection functions back.
1209 # and data collection functions back.
1210 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1210 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1211 filenode_collector(changedfiles))
1211 filenode_collector(changedfiles))
1212 for chnk in group:
1212 for chnk in group:
1213 yield chnk
1213 yield chnk
1214
1214
1215 # These are no longer needed, dereference and toss the memory for
1215 # These are no longer needed, dereference and toss the memory for
1216 # them.
1216 # them.
1217 msng_mnfst_lst = None
1217 msng_mnfst_lst = None
1218 msng_mnfst_set.clear()
1218 msng_mnfst_set.clear()
1219
1219
1220 changedfiles = changedfiles.keys()
1220 changedfiles = changedfiles.keys()
1221 changedfiles.sort()
1221 changedfiles.sort()
1222 # Go through all our files in order sorted by name.
1222 # Go through all our files in order sorted by name.
1223 for fname in changedfiles:
1223 for fname in changedfiles:
1224 filerevlog = self.file(fname)
1224 filerevlog = self.file(fname)
1225 # Toss out the filenodes that the recipient isn't really
1225 # Toss out the filenodes that the recipient isn't really
1226 # missing.
1226 # missing.
1227 if msng_filenode_set.has_key(fname):
1227 if msng_filenode_set.has_key(fname):
1228 prune_filenodes(fname, filerevlog)
1228 prune_filenodes(fname, filerevlog)
1229 msng_filenode_lst = msng_filenode_set[fname].keys()
1229 msng_filenode_lst = msng_filenode_set[fname].keys()
1230 else:
1230 else:
1231 msng_filenode_lst = []
1231 msng_filenode_lst = []
1232 # If any filenodes are left, generate the group for them,
1232 # If any filenodes are left, generate the group for them,
1233 # otherwise don't bother.
1233 # otherwise don't bother.
1234 if len(msng_filenode_lst) > 0:
1234 if len(msng_filenode_lst) > 0:
1235 yield struct.pack(">l", len(fname) + 4) + fname
1235 yield struct.pack(">l", len(fname) + 4) + fname
1236 # Sort the filenodes by their revision #
1236 # Sort the filenodes by their revision #
1237 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1237 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1238 # Create a group generator and only pass in a changenode
1238 # Create a group generator and only pass in a changenode
1239 # lookup function as we need to collect no information
1239 # lookup function as we need to collect no information
1240 # from filenodes.
1240 # from filenodes.
1241 group = filerevlog.group(msng_filenode_lst,
1241 group = filerevlog.group(msng_filenode_lst,
1242 lookup_filenode_link_func(fname))
1242 lookup_filenode_link_func(fname))
1243 for chnk in group:
1243 for chnk in group:
1244 yield chnk
1244 yield chnk
1245 if msng_filenode_set.has_key(fname):
1245 if msng_filenode_set.has_key(fname):
1246 # Don't need this anymore, toss it to free memory.
1246 # Don't need this anymore, toss it to free memory.
1247 del msng_filenode_set[fname]
1247 del msng_filenode_set[fname]
1248 # Signal that no more groups are left.
1248 # Signal that no more groups are left.
1249 yield struct.pack(">l", 0)
1249 yield struct.pack(">l", 0)
1250
1250
1251 return util.chunkbuffer(gengroup())
1251 return util.chunkbuffer(gengroup())
1252
1252
1253 def changegroup(self, basenodes):
1253 def changegroup(self, basenodes):
1254 """Generate a changegroup of all nodes that we have that a recipient
1254 """Generate a changegroup of all nodes that we have that a recipient
1255 doesn't.
1255 doesn't.
1256
1256
1257 This is much easier than the previous function as we can assume that
1257 This is much easier than the previous function as we can assume that
1258 the recipient has any changenode we aren't sending them."""
1258 the recipient has any changenode we aren't sending them."""
1259 cl = self.changelog
1259 cl = self.changelog
1260 nodes = cl.nodesbetween(basenodes, None)[0]
1260 nodes = cl.nodesbetween(basenodes, None)[0]
1261 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1261 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1262
1262
1263 def identity(x):
1263 def identity(x):
1264 return x
1264 return x
1265
1265
1266 def gennodelst(revlog):
1266 def gennodelst(revlog):
1267 for r in xrange(0, revlog.count()):
1267 for r in xrange(0, revlog.count()):
1268 n = revlog.node(r)
1268 n = revlog.node(r)
1269 if revlog.linkrev(n) in revset:
1269 if revlog.linkrev(n) in revset:
1270 yield n
1270 yield n
1271
1271
1272 def changed_file_collector(changedfileset):
1272 def changed_file_collector(changedfileset):
1273 def collect_changed_files(clnode):
1273 def collect_changed_files(clnode):
1274 c = cl.read(clnode)
1274 c = cl.read(clnode)
1275 for fname in c[3]:
1275 for fname in c[3]:
1276 changedfileset[fname] = 1
1276 changedfileset[fname] = 1
1277 return collect_changed_files
1277 return collect_changed_files
1278
1278
1279 def lookuprevlink_func(revlog):
1279 def lookuprevlink_func(revlog):
1280 def lookuprevlink(n):
1280 def lookuprevlink(n):
1281 return cl.node(revlog.linkrev(n))
1281 return cl.node(revlog.linkrev(n))
1282 return lookuprevlink
1282 return lookuprevlink
1283
1283
1284 def gengroup():
1284 def gengroup():
1285 # construct a list of all changed files
1285 # construct a list of all changed files
1286 changedfiles = {}
1286 changedfiles = {}
1287
1287
1288 for chnk in cl.group(nodes, identity,
1288 for chnk in cl.group(nodes, identity,
1289 changed_file_collector(changedfiles)):
1289 changed_file_collector(changedfiles)):
1290 yield chnk
1290 yield chnk
1291 changedfiles = changedfiles.keys()
1291 changedfiles = changedfiles.keys()
1292 changedfiles.sort()
1292 changedfiles.sort()
1293
1293
1294 mnfst = self.manifest
1294 mnfst = self.manifest
1295 nodeiter = gennodelst(mnfst)
1295 nodeiter = gennodelst(mnfst)
1296 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1296 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1297 yield chnk
1297 yield chnk
1298
1298
1299 for fname in changedfiles:
1299 for fname in changedfiles:
1300 filerevlog = self.file(fname)
1300 filerevlog = self.file(fname)
1301 nodeiter = gennodelst(filerevlog)
1301 nodeiter = gennodelst(filerevlog)
1302 nodeiter = list(nodeiter)
1302 nodeiter = list(nodeiter)
1303 if nodeiter:
1303 if nodeiter:
1304 yield struct.pack(">l", len(fname) + 4) + fname
1304 yield struct.pack(">l", len(fname) + 4) + fname
1305 lookup = lookuprevlink_func(filerevlog)
1305 lookup = lookuprevlink_func(filerevlog)
1306 for chnk in filerevlog.group(nodeiter, lookup):
1306 for chnk in filerevlog.group(nodeiter, lookup):
1307 yield chnk
1307 yield chnk
1308
1308
1309 yield struct.pack(">l", 0)
1309 yield struct.pack(">l", 0)
1310
1310
1311 return util.chunkbuffer(gengroup())
1311 return util.chunkbuffer(gengroup())
1312
1312
1313 def addchangegroup(self, source):
1313 def addchangegroup(self, source):
1314
1314
1315 def getchunk():
1315 def getchunk():
1316 d = source.read(4)
1316 d = source.read(4)
1317 if not d:
1317 if not d:
1318 return ""
1318 return ""
1319 l = struct.unpack(">l", d)[0]
1319 l = struct.unpack(">l", d)[0]
1320 if l <= 4:
1320 if l <= 4:
1321 return ""
1321 return ""
1322 d = source.read(l - 4)
1322 d = source.read(l - 4)
1323 if len(d) < l - 4:
1323 if len(d) < l - 4:
1324 raise repo.RepoError(_("premature EOF reading chunk"
1324 raise repo.RepoError(_("premature EOF reading chunk"
1325 " (got %d bytes, expected %d)")
1325 " (got %d bytes, expected %d)")
1326 % (len(d), l - 4))
1326 % (len(d), l - 4))
1327 return d
1327 return d
1328
1328
1329 def getgroup():
1329 def getgroup():
1330 while 1:
1330 while 1:
1331 c = getchunk()
1331 c = getchunk()
1332 if not c:
1332 if not c:
1333 break
1333 break
1334 yield c
1334 yield c
1335
1335
1336 def csmap(x):
1336 def csmap(x):
1337 self.ui.debug(_("add changeset %s\n") % short(x))
1337 self.ui.debug(_("add changeset %s\n") % short(x))
1338 return self.changelog.count()
1338 return self.changelog.count()
1339
1339
1340 def revmap(x):
1340 def revmap(x):
1341 return self.changelog.rev(x)
1341 return self.changelog.rev(x)
1342
1342
1343 if not source:
1343 if not source:
1344 return
1344 return
1345
1346 self.hook('prechangegroup', throw=True)
1347
1345 changesets = files = revisions = 0
1348 changesets = files = revisions = 0
1346
1349
1347 tr = self.transaction()
1350 tr = self.transaction()
1348
1351
1349 oldheads = len(self.changelog.heads())
1352 oldheads = len(self.changelog.heads())
1350
1353
1351 # pull off the changeset group
1354 # pull off the changeset group
1352 self.ui.status(_("adding changesets\n"))
1355 self.ui.status(_("adding changesets\n"))
1353 co = self.changelog.tip()
1356 co = self.changelog.tip()
1354 cn = self.changelog.addgroup(getgroup(), csmap, tr, 1) # unique
1357 cn = self.changelog.addgroup(getgroup(), csmap, tr, 1) # unique
1355 cnr, cor = map(self.changelog.rev, (cn, co))
1358 cnr, cor = map(self.changelog.rev, (cn, co))
1356 if cn == nullid:
1359 if cn == nullid:
1357 cnr = cor
1360 cnr = cor
1358 changesets = cnr - cor
1361 changesets = cnr - cor
1359
1362
1360 # pull off the manifest group
1363 # pull off the manifest group
1361 self.ui.status(_("adding manifests\n"))
1364 self.ui.status(_("adding manifests\n"))
1362 mm = self.manifest.tip()
1365 mm = self.manifest.tip()
1363 mo = self.manifest.addgroup(getgroup(), revmap, tr)
1366 mo = self.manifest.addgroup(getgroup(), revmap, tr)
1364
1367
1365 # process the files
1368 # process the files
1366 self.ui.status(_("adding file changes\n"))
1369 self.ui.status(_("adding file changes\n"))
1367 while 1:
1370 while 1:
1368 f = getchunk()
1371 f = getchunk()
1369 if not f:
1372 if not f:
1370 break
1373 break
1371 self.ui.debug(_("adding %s revisions\n") % f)
1374 self.ui.debug(_("adding %s revisions\n") % f)
1372 fl = self.file(f)
1375 fl = self.file(f)
1373 o = fl.count()
1376 o = fl.count()
1374 n = fl.addgroup(getgroup(), revmap, tr)
1377 n = fl.addgroup(getgroup(), revmap, tr)
1375 revisions += fl.count() - o
1378 revisions += fl.count() - o
1376 files += 1
1379 files += 1
1377
1380
1378 newheads = len(self.changelog.heads())
1381 newheads = len(self.changelog.heads())
1379 heads = ""
1382 heads = ""
1380 if oldheads and newheads > oldheads:
1383 if oldheads and newheads > oldheads:
1381 heads = _(" (+%d heads)") % (newheads - oldheads)
1384 heads = _(" (+%d heads)") % (newheads - oldheads)
1382
1385
1383 self.ui.status(_("added %d changesets"
1386 self.ui.status(_("added %d changesets"
1384 " with %d changes to %d files%s\n")
1387 " with %d changes to %d files%s\n")
1385 % (changesets, revisions, files, heads))
1388 % (changesets, revisions, files, heads))
1386
1389
1390 self.hook('pretxnchangegroup', throw=True,
1391 node=hex(self.changelog.node(cor+1)))
1392
1387 tr.close()
1393 tr.close()
1388
1394
1389 if changesets > 0:
1395 if changesets > 0:
1390 self.hook("changegroup", node=hex(self.changelog.node(cor+1)))
1396 self.hook("changegroup", node=hex(self.changelog.node(cor+1)))
1391
1397
1392 for i in range(cor + 1, cnr + 1):
1398 for i in range(cor + 1, cnr + 1):
1393 self.hook("incoming", node=hex(self.changelog.node(i)))
1399 self.hook("incoming", node=hex(self.changelog.node(i)))
1394
1400
1395 def update(self, node, allow=False, force=False, choose=None,
1401 def update(self, node, allow=False, force=False, choose=None,
1396 moddirstate=True, forcemerge=False, wlock=None):
1402 moddirstate=True, forcemerge=False, wlock=None):
1397 pl = self.dirstate.parents()
1403 pl = self.dirstate.parents()
1398 if not force and pl[1] != nullid:
1404 if not force and pl[1] != nullid:
1399 self.ui.warn(_("aborting: outstanding uncommitted merges\n"))
1405 self.ui.warn(_("aborting: outstanding uncommitted merges\n"))
1400 return 1
1406 return 1
1401
1407
1402 err = False
1408 err = False
1403
1409
1404 p1, p2 = pl[0], node
1410 p1, p2 = pl[0], node
1405 pa = self.changelog.ancestor(p1, p2)
1411 pa = self.changelog.ancestor(p1, p2)
1406 m1n = self.changelog.read(p1)[0]
1412 m1n = self.changelog.read(p1)[0]
1407 m2n = self.changelog.read(p2)[0]
1413 m2n = self.changelog.read(p2)[0]
1408 man = self.manifest.ancestor(m1n, m2n)
1414 man = self.manifest.ancestor(m1n, m2n)
1409 m1 = self.manifest.read(m1n)
1415 m1 = self.manifest.read(m1n)
1410 mf1 = self.manifest.readflags(m1n)
1416 mf1 = self.manifest.readflags(m1n)
1411 m2 = self.manifest.read(m2n).copy()
1417 m2 = self.manifest.read(m2n).copy()
1412 mf2 = self.manifest.readflags(m2n)
1418 mf2 = self.manifest.readflags(m2n)
1413 ma = self.manifest.read(man)
1419 ma = self.manifest.read(man)
1414 mfa = self.manifest.readflags(man)
1420 mfa = self.manifest.readflags(man)
1415
1421
1416 modified, added, removed, deleted, unknown = self.changes()
1422 modified, added, removed, deleted, unknown = self.changes()
1417
1423
1418 # is this a jump, or a merge? i.e. is there a linear path
1424 # is this a jump, or a merge? i.e. is there a linear path
1419 # from p1 to p2?
1425 # from p1 to p2?
1420 linear_path = (pa == p1 or pa == p2)
1426 linear_path = (pa == p1 or pa == p2)
1421
1427
1422 if allow and linear_path:
1428 if allow and linear_path:
1423 raise util.Abort(_("there is nothing to merge, "
1429 raise util.Abort(_("there is nothing to merge, "
1424 "just use 'hg update'"))
1430 "just use 'hg update'"))
1425 if allow and not forcemerge:
1431 if allow and not forcemerge:
1426 if modified or added or removed:
1432 if modified or added or removed:
1427 raise util.Abort(_("outstanding uncommited changes"))
1433 raise util.Abort(_("outstanding uncommited changes"))
1428 if not forcemerge and not force:
1434 if not forcemerge and not force:
1429 for f in unknown:
1435 for f in unknown:
1430 if f in m2:
1436 if f in m2:
1431 t1 = self.wread(f)
1437 t1 = self.wread(f)
1432 t2 = self.file(f).read(m2[f])
1438 t2 = self.file(f).read(m2[f])
1433 if cmp(t1, t2) != 0:
1439 if cmp(t1, t2) != 0:
1434 raise util.Abort(_("'%s' already exists in the working"
1440 raise util.Abort(_("'%s' already exists in the working"
1435 " dir and differs from remote") % f)
1441 " dir and differs from remote") % f)
1436
1442
1437 # resolve the manifest to determine which files
1443 # resolve the manifest to determine which files
1438 # we care about merging
1444 # we care about merging
1439 self.ui.note(_("resolving manifests\n"))
1445 self.ui.note(_("resolving manifests\n"))
1440 self.ui.debug(_(" force %s allow %s moddirstate %s linear %s\n") %
1446 self.ui.debug(_(" force %s allow %s moddirstate %s linear %s\n") %
1441 (force, allow, moddirstate, linear_path))
1447 (force, allow, moddirstate, linear_path))
1442 self.ui.debug(_(" ancestor %s local %s remote %s\n") %
1448 self.ui.debug(_(" ancestor %s local %s remote %s\n") %
1443 (short(man), short(m1n), short(m2n)))
1449 (short(man), short(m1n), short(m2n)))
1444
1450
1445 merge = {}
1451 merge = {}
1446 get = {}
1452 get = {}
1447 remove = []
1453 remove = []
1448
1454
1449 # construct a working dir manifest
1455 # construct a working dir manifest
1450 mw = m1.copy()
1456 mw = m1.copy()
1451 mfw = mf1.copy()
1457 mfw = mf1.copy()
1452 umap = dict.fromkeys(unknown)
1458 umap = dict.fromkeys(unknown)
1453
1459
1454 for f in added + modified + unknown:
1460 for f in added + modified + unknown:
1455 mw[f] = ""
1461 mw[f] = ""
1456 mfw[f] = util.is_exec(self.wjoin(f), mfw.get(f, False))
1462 mfw[f] = util.is_exec(self.wjoin(f), mfw.get(f, False))
1457
1463
1458 if moddirstate and not wlock:
1464 if moddirstate and not wlock:
1459 wlock = self.wlock()
1465 wlock = self.wlock()
1460
1466
1461 for f in deleted + removed:
1467 for f in deleted + removed:
1462 if f in mw:
1468 if f in mw:
1463 del mw[f]
1469 del mw[f]
1464
1470
1465 # If we're jumping between revisions (as opposed to merging),
1471 # If we're jumping between revisions (as opposed to merging),
1466 # and if neither the working directory nor the target rev has
1472 # and if neither the working directory nor the target rev has
1467 # the file, then we need to remove it from the dirstate, to
1473 # the file, then we need to remove it from the dirstate, to
1468 # prevent the dirstate from listing the file when it is no
1474 # prevent the dirstate from listing the file when it is no
1469 # longer in the manifest.
1475 # longer in the manifest.
1470 if moddirstate and linear_path and f not in m2:
1476 if moddirstate and linear_path and f not in m2:
1471 self.dirstate.forget((f,))
1477 self.dirstate.forget((f,))
1472
1478
1473 # Compare manifests
1479 # Compare manifests
1474 for f, n in mw.iteritems():
1480 for f, n in mw.iteritems():
1475 if choose and not choose(f):
1481 if choose and not choose(f):
1476 continue
1482 continue
1477 if f in m2:
1483 if f in m2:
1478 s = 0
1484 s = 0
1479
1485
1480 # is the wfile new since m1, and match m2?
1486 # is the wfile new since m1, and match m2?
1481 if f not in m1:
1487 if f not in m1:
1482 t1 = self.wread(f)
1488 t1 = self.wread(f)
1483 t2 = self.file(f).read(m2[f])
1489 t2 = self.file(f).read(m2[f])
1484 if cmp(t1, t2) == 0:
1490 if cmp(t1, t2) == 0:
1485 n = m2[f]
1491 n = m2[f]
1486 del t1, t2
1492 del t1, t2
1487
1493
1488 # are files different?
1494 # are files different?
1489 if n != m2[f]:
1495 if n != m2[f]:
1490 a = ma.get(f, nullid)
1496 a = ma.get(f, nullid)
1491 # are both different from the ancestor?
1497 # are both different from the ancestor?
1492 if n != a and m2[f] != a:
1498 if n != a and m2[f] != a:
1493 self.ui.debug(_(" %s versions differ, resolve\n") % f)
1499 self.ui.debug(_(" %s versions differ, resolve\n") % f)
1494 # merge executable bits
1500 # merge executable bits
1495 # "if we changed or they changed, change in merge"
1501 # "if we changed or they changed, change in merge"
1496 a, b, c = mfa.get(f, 0), mfw[f], mf2[f]
1502 a, b, c = mfa.get(f, 0), mfw[f], mf2[f]
1497 mode = ((a^b) | (a^c)) ^ a
1503 mode = ((a^b) | (a^c)) ^ a
1498 merge[f] = (m1.get(f, nullid), m2[f], mode)
1504 merge[f] = (m1.get(f, nullid), m2[f], mode)
1499 s = 1
1505 s = 1
1500 # are we clobbering?
1506 # are we clobbering?
1501 # is remote's version newer?
1507 # is remote's version newer?
1502 # or are we going back in time?
1508 # or are we going back in time?
1503 elif force or m2[f] != a or (p2 == pa and mw[f] == m1[f]):
1509 elif force or m2[f] != a or (p2 == pa and mw[f] == m1[f]):
1504 self.ui.debug(_(" remote %s is newer, get\n") % f)
1510 self.ui.debug(_(" remote %s is newer, get\n") % f)
1505 get[f] = m2[f]
1511 get[f] = m2[f]
1506 s = 1
1512 s = 1
1507 elif f in umap:
1513 elif f in umap:
1508 # this unknown file is the same as the checkout
1514 # this unknown file is the same as the checkout
1509 get[f] = m2[f]
1515 get[f] = m2[f]
1510
1516
1511 if not s and mfw[f] != mf2[f]:
1517 if not s and mfw[f] != mf2[f]:
1512 if force:
1518 if force:
1513 self.ui.debug(_(" updating permissions for %s\n") % f)
1519 self.ui.debug(_(" updating permissions for %s\n") % f)
1514 util.set_exec(self.wjoin(f), mf2[f])
1520 util.set_exec(self.wjoin(f), mf2[f])
1515 else:
1521 else:
1516 a, b, c = mfa.get(f, 0), mfw[f], mf2[f]
1522 a, b, c = mfa.get(f, 0), mfw[f], mf2[f]
1517 mode = ((a^b) | (a^c)) ^ a
1523 mode = ((a^b) | (a^c)) ^ a
1518 if mode != b:
1524 if mode != b:
1519 self.ui.debug(_(" updating permissions for %s\n")
1525 self.ui.debug(_(" updating permissions for %s\n")
1520 % f)
1526 % f)
1521 util.set_exec(self.wjoin(f), mode)
1527 util.set_exec(self.wjoin(f), mode)
1522 del m2[f]
1528 del m2[f]
1523 elif f in ma:
1529 elif f in ma:
1524 if n != ma[f]:
1530 if n != ma[f]:
1525 r = _("d")
1531 r = _("d")
1526 if not force and (linear_path or allow):
1532 if not force and (linear_path or allow):
1527 r = self.ui.prompt(
1533 r = self.ui.prompt(
1528 (_(" local changed %s which remote deleted\n") % f) +
1534 (_(" local changed %s which remote deleted\n") % f) +
1529 _("(k)eep or (d)elete?"), _("[kd]"), _("k"))
1535 _("(k)eep or (d)elete?"), _("[kd]"), _("k"))
1530 if r == _("d"):
1536 if r == _("d"):
1531 remove.append(f)
1537 remove.append(f)
1532 else:
1538 else:
1533 self.ui.debug(_("other deleted %s\n") % f)
1539 self.ui.debug(_("other deleted %s\n") % f)
1534 remove.append(f) # other deleted it
1540 remove.append(f) # other deleted it
1535 else:
1541 else:
1536 # file is created on branch or in working directory
1542 # file is created on branch or in working directory
1537 if force and f not in umap:
1543 if force and f not in umap:
1538 self.ui.debug(_("remote deleted %s, clobbering\n") % f)
1544 self.ui.debug(_("remote deleted %s, clobbering\n") % f)
1539 remove.append(f)
1545 remove.append(f)
1540 elif n == m1.get(f, nullid): # same as parent
1546 elif n == m1.get(f, nullid): # same as parent
1541 if p2 == pa: # going backwards?
1547 if p2 == pa: # going backwards?
1542 self.ui.debug(_("remote deleted %s\n") % f)
1548 self.ui.debug(_("remote deleted %s\n") % f)
1543 remove.append(f)
1549 remove.append(f)
1544 else:
1550 else:
1545 self.ui.debug(_("local modified %s, keeping\n") % f)
1551 self.ui.debug(_("local modified %s, keeping\n") % f)
1546 else:
1552 else:
1547 self.ui.debug(_("working dir created %s, keeping\n") % f)
1553 self.ui.debug(_("working dir created %s, keeping\n") % f)
1548
1554
1549 for f, n in m2.iteritems():
1555 for f, n in m2.iteritems():
1550 if choose and not choose(f):
1556 if choose and not choose(f):
1551 continue
1557 continue
1552 if f[0] == "/":
1558 if f[0] == "/":
1553 continue
1559 continue
1554 if f in ma and n != ma[f]:
1560 if f in ma and n != ma[f]:
1555 r = _("k")
1561 r = _("k")
1556 if not force and (linear_path or allow):
1562 if not force and (linear_path or allow):
1557 r = self.ui.prompt(
1563 r = self.ui.prompt(
1558 (_("remote changed %s which local deleted\n") % f) +
1564 (_("remote changed %s which local deleted\n") % f) +
1559 _("(k)eep or (d)elete?"), _("[kd]"), _("k"))
1565 _("(k)eep or (d)elete?"), _("[kd]"), _("k"))
1560 if r == _("k"):
1566 if r == _("k"):
1561 get[f] = n
1567 get[f] = n
1562 elif f not in ma:
1568 elif f not in ma:
1563 self.ui.debug(_("remote created %s\n") % f)
1569 self.ui.debug(_("remote created %s\n") % f)
1564 get[f] = n
1570 get[f] = n
1565 else:
1571 else:
1566 if force or p2 == pa: # going backwards?
1572 if force or p2 == pa: # going backwards?
1567 self.ui.debug(_("local deleted %s, recreating\n") % f)
1573 self.ui.debug(_("local deleted %s, recreating\n") % f)
1568 get[f] = n
1574 get[f] = n
1569 else:
1575 else:
1570 self.ui.debug(_("local deleted %s\n") % f)
1576 self.ui.debug(_("local deleted %s\n") % f)
1571
1577
1572 del mw, m1, m2, ma
1578 del mw, m1, m2, ma
1573
1579
1574 if force:
1580 if force:
1575 for f in merge:
1581 for f in merge:
1576 get[f] = merge[f][1]
1582 get[f] = merge[f][1]
1577 merge = {}
1583 merge = {}
1578
1584
1579 if linear_path or force:
1585 if linear_path or force:
1580 # we don't need to do any magic, just jump to the new rev
1586 # we don't need to do any magic, just jump to the new rev
1581 branch_merge = False
1587 branch_merge = False
1582 p1, p2 = p2, nullid
1588 p1, p2 = p2, nullid
1583 else:
1589 else:
1584 if not allow:
1590 if not allow:
1585 self.ui.status(_("this update spans a branch"
1591 self.ui.status(_("this update spans a branch"
1586 " affecting the following files:\n"))
1592 " affecting the following files:\n"))
1587 fl = merge.keys() + get.keys()
1593 fl = merge.keys() + get.keys()
1588 fl.sort()
1594 fl.sort()
1589 for f in fl:
1595 for f in fl:
1590 cf = ""
1596 cf = ""
1591 if f in merge:
1597 if f in merge:
1592 cf = _(" (resolve)")
1598 cf = _(" (resolve)")
1593 self.ui.status(" %s%s\n" % (f, cf))
1599 self.ui.status(" %s%s\n" % (f, cf))
1594 self.ui.warn(_("aborting update spanning branches!\n"))
1600 self.ui.warn(_("aborting update spanning branches!\n"))
1595 self.ui.status(_("(use update -m to merge across branches"
1601 self.ui.status(_("(use update -m to merge across branches"
1596 " or -C to lose changes)\n"))
1602 " or -C to lose changes)\n"))
1597 return 1
1603 return 1
1598 branch_merge = True
1604 branch_merge = True
1599
1605
1600 # get the files we don't need to change
1606 # get the files we don't need to change
1601 files = get.keys()
1607 files = get.keys()
1602 files.sort()
1608 files.sort()
1603 for f in files:
1609 for f in files:
1604 if f[0] == "/":
1610 if f[0] == "/":
1605 continue
1611 continue
1606 self.ui.note(_("getting %s\n") % f)
1612 self.ui.note(_("getting %s\n") % f)
1607 t = self.file(f).read(get[f])
1613 t = self.file(f).read(get[f])
1608 self.wwrite(f, t)
1614 self.wwrite(f, t)
1609 util.set_exec(self.wjoin(f), mf2[f])
1615 util.set_exec(self.wjoin(f), mf2[f])
1610 if moddirstate:
1616 if moddirstate:
1611 if branch_merge:
1617 if branch_merge:
1612 self.dirstate.update([f], 'n', st_mtime=-1)
1618 self.dirstate.update([f], 'n', st_mtime=-1)
1613 else:
1619 else:
1614 self.dirstate.update([f], 'n')
1620 self.dirstate.update([f], 'n')
1615
1621
1616 # merge the tricky bits
1622 # merge the tricky bits
1617 files = merge.keys()
1623 files = merge.keys()
1618 files.sort()
1624 files.sort()
1619 for f in files:
1625 for f in files:
1620 self.ui.status(_("merging %s\n") % f)
1626 self.ui.status(_("merging %s\n") % f)
1621 my, other, flag = merge[f]
1627 my, other, flag = merge[f]
1622 ret = self.merge3(f, my, other)
1628 ret = self.merge3(f, my, other)
1623 if ret:
1629 if ret:
1624 err = True
1630 err = True
1625 util.set_exec(self.wjoin(f), flag)
1631 util.set_exec(self.wjoin(f), flag)
1626 if moddirstate:
1632 if moddirstate:
1627 if branch_merge:
1633 if branch_merge:
1628 # We've done a branch merge, mark this file as merged
1634 # We've done a branch merge, mark this file as merged
1629 # so that we properly record the merger later
1635 # so that we properly record the merger later
1630 self.dirstate.update([f], 'm')
1636 self.dirstate.update([f], 'm')
1631 else:
1637 else:
1632 # We've update-merged a locally modified file, so
1638 # We've update-merged a locally modified file, so
1633 # we set the dirstate to emulate a normal checkout
1639 # we set the dirstate to emulate a normal checkout
1634 # of that file some time in the past. Thus our
1640 # of that file some time in the past. Thus our
1635 # merge will appear as a normal local file
1641 # merge will appear as a normal local file
1636 # modification.
1642 # modification.
1637 f_len = len(self.file(f).read(other))
1643 f_len = len(self.file(f).read(other))
1638 self.dirstate.update([f], 'n', st_size=f_len, st_mtime=-1)
1644 self.dirstate.update([f], 'n', st_size=f_len, st_mtime=-1)
1639
1645
1640 remove.sort()
1646 remove.sort()
1641 for f in remove:
1647 for f in remove:
1642 self.ui.note(_("removing %s\n") % f)
1648 self.ui.note(_("removing %s\n") % f)
1643 try:
1649 try:
1644 util.unlink(self.wjoin(f))
1650 util.unlink(self.wjoin(f))
1645 except OSError, inst:
1651 except OSError, inst:
1646 if inst.errno != errno.ENOENT:
1652 if inst.errno != errno.ENOENT:
1647 self.ui.warn(_("update failed to remove %s: %s!\n") %
1653 self.ui.warn(_("update failed to remove %s: %s!\n") %
1648 (f, inst.strerror))
1654 (f, inst.strerror))
1649 if moddirstate:
1655 if moddirstate:
1650 if branch_merge:
1656 if branch_merge:
1651 self.dirstate.update(remove, 'r')
1657 self.dirstate.update(remove, 'r')
1652 else:
1658 else:
1653 self.dirstate.forget(remove)
1659 self.dirstate.forget(remove)
1654
1660
1655 if moddirstate:
1661 if moddirstate:
1656 self.dirstate.setparents(p1, p2)
1662 self.dirstate.setparents(p1, p2)
1657 return err
1663 return err
1658
1664
1659 def merge3(self, fn, my, other):
1665 def merge3(self, fn, my, other):
1660 """perform a 3-way merge in the working directory"""
1666 """perform a 3-way merge in the working directory"""
1661
1667
1662 def temp(prefix, node):
1668 def temp(prefix, node):
1663 pre = "%s~%s." % (os.path.basename(fn), prefix)
1669 pre = "%s~%s." % (os.path.basename(fn), prefix)
1664 (fd, name) = tempfile.mkstemp("", pre)
1670 (fd, name) = tempfile.mkstemp("", pre)
1665 f = os.fdopen(fd, "wb")
1671 f = os.fdopen(fd, "wb")
1666 self.wwrite(fn, fl.read(node), f)
1672 self.wwrite(fn, fl.read(node), f)
1667 f.close()
1673 f.close()
1668 return name
1674 return name
1669
1675
1670 fl = self.file(fn)
1676 fl = self.file(fn)
1671 base = fl.ancestor(my, other)
1677 base = fl.ancestor(my, other)
1672 a = self.wjoin(fn)
1678 a = self.wjoin(fn)
1673 b = temp("base", base)
1679 b = temp("base", base)
1674 c = temp("other", other)
1680 c = temp("other", other)
1675
1681
1676 self.ui.note(_("resolving %s\n") % fn)
1682 self.ui.note(_("resolving %s\n") % fn)
1677 self.ui.debug(_("file %s: my %s other %s ancestor %s\n") %
1683 self.ui.debug(_("file %s: my %s other %s ancestor %s\n") %
1678 (fn, short(my), short(other), short(base)))
1684 (fn, short(my), short(other), short(base)))
1679
1685
1680 cmd = (os.environ.get("HGMERGE") or self.ui.config("ui", "merge")
1686 cmd = (os.environ.get("HGMERGE") or self.ui.config("ui", "merge")
1681 or "hgmerge")
1687 or "hgmerge")
1682 r = os.system('%s "%s" "%s" "%s"' % (cmd, a, b, c))
1688 r = os.system('%s "%s" "%s" "%s"' % (cmd, a, b, c))
1683 if r:
1689 if r:
1684 self.ui.warn(_("merging %s failed!\n") % fn)
1690 self.ui.warn(_("merging %s failed!\n") % fn)
1685
1691
1686 os.unlink(b)
1692 os.unlink(b)
1687 os.unlink(c)
1693 os.unlink(c)
1688 return r
1694 return r
1689
1695
1690 def verify(self):
1696 def verify(self):
1691 filelinkrevs = {}
1697 filelinkrevs = {}
1692 filenodes = {}
1698 filenodes = {}
1693 changesets = revisions = files = 0
1699 changesets = revisions = files = 0
1694 errors = [0]
1700 errors = [0]
1695 neededmanifests = {}
1701 neededmanifests = {}
1696
1702
1697 def err(msg):
1703 def err(msg):
1698 self.ui.warn(msg + "\n")
1704 self.ui.warn(msg + "\n")
1699 errors[0] += 1
1705 errors[0] += 1
1700
1706
1701 def checksize(obj, name):
1707 def checksize(obj, name):
1702 d = obj.checksize()
1708 d = obj.checksize()
1703 if d[0]:
1709 if d[0]:
1704 err(_("%s data length off by %d bytes") % (name, d[0]))
1710 err(_("%s data length off by %d bytes") % (name, d[0]))
1705 if d[1]:
1711 if d[1]:
1706 err(_("%s index contains %d extra bytes") % (name, d[1]))
1712 err(_("%s index contains %d extra bytes") % (name, d[1]))
1707
1713
1708 seen = {}
1714 seen = {}
1709 self.ui.status(_("checking changesets\n"))
1715 self.ui.status(_("checking changesets\n"))
1710 checksize(self.changelog, "changelog")
1716 checksize(self.changelog, "changelog")
1711
1717
1712 for i in range(self.changelog.count()):
1718 for i in range(self.changelog.count()):
1713 changesets += 1
1719 changesets += 1
1714 n = self.changelog.node(i)
1720 n = self.changelog.node(i)
1715 l = self.changelog.linkrev(n)
1721 l = self.changelog.linkrev(n)
1716 if l != i:
1722 if l != i:
1717 err(_("incorrect link (%d) for changeset revision %d") %(l, i))
1723 err(_("incorrect link (%d) for changeset revision %d") %(l, i))
1718 if n in seen:
1724 if n in seen:
1719 err(_("duplicate changeset at revision %d") % i)
1725 err(_("duplicate changeset at revision %d") % i)
1720 seen[n] = 1
1726 seen[n] = 1
1721
1727
1722 for p in self.changelog.parents(n):
1728 for p in self.changelog.parents(n):
1723 if p not in self.changelog.nodemap:
1729 if p not in self.changelog.nodemap:
1724 err(_("changeset %s has unknown parent %s") %
1730 err(_("changeset %s has unknown parent %s") %
1725 (short(n), short(p)))
1731 (short(n), short(p)))
1726 try:
1732 try:
1727 changes = self.changelog.read(n)
1733 changes = self.changelog.read(n)
1728 except KeyboardInterrupt:
1734 except KeyboardInterrupt:
1729 self.ui.warn(_("interrupted"))
1735 self.ui.warn(_("interrupted"))
1730 raise
1736 raise
1731 except Exception, inst:
1737 except Exception, inst:
1732 err(_("unpacking changeset %s: %s") % (short(n), inst))
1738 err(_("unpacking changeset %s: %s") % (short(n), inst))
1733
1739
1734 neededmanifests[changes[0]] = n
1740 neededmanifests[changes[0]] = n
1735
1741
1736 for f in changes[3]:
1742 for f in changes[3]:
1737 filelinkrevs.setdefault(f, []).append(i)
1743 filelinkrevs.setdefault(f, []).append(i)
1738
1744
1739 seen = {}
1745 seen = {}
1740 self.ui.status(_("checking manifests\n"))
1746 self.ui.status(_("checking manifests\n"))
1741 checksize(self.manifest, "manifest")
1747 checksize(self.manifest, "manifest")
1742
1748
1743 for i in range(self.manifest.count()):
1749 for i in range(self.manifest.count()):
1744 n = self.manifest.node(i)
1750 n = self.manifest.node(i)
1745 l = self.manifest.linkrev(n)
1751 l = self.manifest.linkrev(n)
1746
1752
1747 if l < 0 or l >= self.changelog.count():
1753 if l < 0 or l >= self.changelog.count():
1748 err(_("bad manifest link (%d) at revision %d") % (l, i))
1754 err(_("bad manifest link (%d) at revision %d") % (l, i))
1749
1755
1750 if n in neededmanifests:
1756 if n in neededmanifests:
1751 del neededmanifests[n]
1757 del neededmanifests[n]
1752
1758
1753 if n in seen:
1759 if n in seen:
1754 err(_("duplicate manifest at revision %d") % i)
1760 err(_("duplicate manifest at revision %d") % i)
1755
1761
1756 seen[n] = 1
1762 seen[n] = 1
1757
1763
1758 for p in self.manifest.parents(n):
1764 for p in self.manifest.parents(n):
1759 if p not in self.manifest.nodemap:
1765 if p not in self.manifest.nodemap:
1760 err(_("manifest %s has unknown parent %s") %
1766 err(_("manifest %s has unknown parent %s") %
1761 (short(n), short(p)))
1767 (short(n), short(p)))
1762
1768
1763 try:
1769 try:
1764 delta = mdiff.patchtext(self.manifest.delta(n))
1770 delta = mdiff.patchtext(self.manifest.delta(n))
1765 except KeyboardInterrupt:
1771 except KeyboardInterrupt:
1766 self.ui.warn(_("interrupted"))
1772 self.ui.warn(_("interrupted"))
1767 raise
1773 raise
1768 except Exception, inst:
1774 except Exception, inst:
1769 err(_("unpacking manifest %s: %s") % (short(n), inst))
1775 err(_("unpacking manifest %s: %s") % (short(n), inst))
1770
1776
1771 ff = [ l.split('\0') for l in delta.splitlines() ]
1777 ff = [ l.split('\0') for l in delta.splitlines() ]
1772 for f, fn in ff:
1778 for f, fn in ff:
1773 filenodes.setdefault(f, {})[bin(fn[:40])] = 1
1779 filenodes.setdefault(f, {})[bin(fn[:40])] = 1
1774
1780
1775 self.ui.status(_("crosschecking files in changesets and manifests\n"))
1781 self.ui.status(_("crosschecking files in changesets and manifests\n"))
1776
1782
1777 for m, c in neededmanifests.items():
1783 for m, c in neededmanifests.items():
1778 err(_("Changeset %s refers to unknown manifest %s") %
1784 err(_("Changeset %s refers to unknown manifest %s") %
1779 (short(m), short(c)))
1785 (short(m), short(c)))
1780 del neededmanifests
1786 del neededmanifests
1781
1787
1782 for f in filenodes:
1788 for f in filenodes:
1783 if f not in filelinkrevs:
1789 if f not in filelinkrevs:
1784 err(_("file %s in manifest but not in changesets") % f)
1790 err(_("file %s in manifest but not in changesets") % f)
1785
1791
1786 for f in filelinkrevs:
1792 for f in filelinkrevs:
1787 if f not in filenodes:
1793 if f not in filenodes:
1788 err(_("file %s in changeset but not in manifest") % f)
1794 err(_("file %s in changeset but not in manifest") % f)
1789
1795
1790 self.ui.status(_("checking files\n"))
1796 self.ui.status(_("checking files\n"))
1791 ff = filenodes.keys()
1797 ff = filenodes.keys()
1792 ff.sort()
1798 ff.sort()
1793 for f in ff:
1799 for f in ff:
1794 if f == "/dev/null":
1800 if f == "/dev/null":
1795 continue
1801 continue
1796 files += 1
1802 files += 1
1797 fl = self.file(f)
1803 fl = self.file(f)
1798 checksize(fl, f)
1804 checksize(fl, f)
1799
1805
1800 nodes = {nullid: 1}
1806 nodes = {nullid: 1}
1801 seen = {}
1807 seen = {}
1802 for i in range(fl.count()):
1808 for i in range(fl.count()):
1803 revisions += 1
1809 revisions += 1
1804 n = fl.node(i)
1810 n = fl.node(i)
1805
1811
1806 if n in seen:
1812 if n in seen:
1807 err(_("%s: duplicate revision %d") % (f, i))
1813 err(_("%s: duplicate revision %d") % (f, i))
1808 if n not in filenodes[f]:
1814 if n not in filenodes[f]:
1809 err(_("%s: %d:%s not in manifests") % (f, i, short(n)))
1815 err(_("%s: %d:%s not in manifests") % (f, i, short(n)))
1810 else:
1816 else:
1811 del filenodes[f][n]
1817 del filenodes[f][n]
1812
1818
1813 flr = fl.linkrev(n)
1819 flr = fl.linkrev(n)
1814 if flr not in filelinkrevs[f]:
1820 if flr not in filelinkrevs[f]:
1815 err(_("%s:%s points to unexpected changeset %d")
1821 err(_("%s:%s points to unexpected changeset %d")
1816 % (f, short(n), flr))
1822 % (f, short(n), flr))
1817 else:
1823 else:
1818 filelinkrevs[f].remove(flr)
1824 filelinkrevs[f].remove(flr)
1819
1825
1820 # verify contents
1826 # verify contents
1821 try:
1827 try:
1822 t = fl.read(n)
1828 t = fl.read(n)
1823 except KeyboardInterrupt:
1829 except KeyboardInterrupt:
1824 self.ui.warn(_("interrupted"))
1830 self.ui.warn(_("interrupted"))
1825 raise
1831 raise
1826 except Exception, inst:
1832 except Exception, inst:
1827 err(_("unpacking file %s %s: %s") % (f, short(n), inst))
1833 err(_("unpacking file %s %s: %s") % (f, short(n), inst))
1828
1834
1829 # verify parents
1835 # verify parents
1830 (p1, p2) = fl.parents(n)
1836 (p1, p2) = fl.parents(n)
1831 if p1 not in nodes:
1837 if p1 not in nodes:
1832 err(_("file %s:%s unknown parent 1 %s") %
1838 err(_("file %s:%s unknown parent 1 %s") %
1833 (f, short(n), short(p1)))
1839 (f, short(n), short(p1)))
1834 if p2 not in nodes:
1840 if p2 not in nodes:
1835 err(_("file %s:%s unknown parent 2 %s") %
1841 err(_("file %s:%s unknown parent 2 %s") %
1836 (f, short(n), short(p1)))
1842 (f, short(n), short(p1)))
1837 nodes[n] = 1
1843 nodes[n] = 1
1838
1844
1839 # cross-check
1845 # cross-check
1840 for node in filenodes[f]:
1846 for node in filenodes[f]:
1841 err(_("node %s in manifests not in %s") % (hex(node), f))
1847 err(_("node %s in manifests not in %s") % (hex(node), f))
1842
1848
1843 self.ui.status(_("%d files, %d changesets, %d total revisions\n") %
1849 self.ui.status(_("%d files, %d changesets, %d total revisions\n") %
1844 (files, changesets, revisions))
1850 (files, changesets, revisions))
1845
1851
1846 if errors[0]:
1852 if errors[0]:
1847 self.ui.warn(_("%d integrity errors encountered!\n") % errors[0])
1853 self.ui.warn(_("%d integrity errors encountered!\n") % errors[0])
1848 return 1
1854 return 1
General Comments 0
You need to be logged in to leave comments. Login now