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