##// END OF EJS Templates
replace filehandle version of wwrite with wwritedata
Matt Mackall -
r4005:656e06ee default
parent child Browse files
Show More
@@ -1,186 +1,187 b''
1 1 # extdiff.py - external diff program support for mercurial
2 2 #
3 3 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7 #
8 8 # The `extdiff' Mercurial extension allows you to use external programs
9 9 # to compare revisions, or revision with working dir. The external diff
10 10 # programs are called with a configurable set of options and two
11 11 # non-option arguments: paths to directories containing snapshots of
12 12 # files to compare.
13 13 #
14 14 # To enable this extension:
15 15 #
16 16 # [extensions]
17 17 # hgext.extdiff =
18 18 #
19 19 # The `extdiff' extension also allows to configure new diff commands, so
20 20 # you do not need to type "hg extdiff -p kdiff3" always.
21 21 #
22 22 # [extdiff]
23 23 # # add new command that runs GNU diff(1) in 'context diff' mode
24 24 # cmd.cdiff = gdiff
25 25 # opts.cdiff = -Nprc5
26 26
27 27 # # add new command called vdiff, runs kdiff3
28 28 # cmd.vdiff = kdiff3
29 29
30 30 # # add new command called meld, runs meld (no need to name twice)
31 31 # cmd.meld =
32 32
33 33 # # add new command called vimdiff, runs gvimdiff with DirDiff plugin
34 34 # #(see http://www.vim.org/scripts/script.php?script_id=102)
35 35 # # Non english user, be sure to put "let g:DirDiffDynamicDiffText = 1" in
36 36 # # your .vimrc
37 37 # cmd.vimdiff = gvim
38 38 # opts.vimdiff = -f '+next' '+execute "DirDiff" argv(0) argv(1)'
39 39 #
40 40 # Each custom diff commands can have two parts: a `cmd' and an `opts'
41 41 # part. The cmd.xxx option defines the name of an executable program
42 42 # that will be run, and opts.xxx defines a set of command-line options
43 43 # which will be inserted to the command between the program name and
44 44 # the files/directories to diff (i.e. the cdiff example above).
45 45 #
46 46 # You can use -I/-X and list of file or directory names like normal
47 47 # "hg diff" command. The `extdiff' extension makes snapshots of only
48 48 # needed files, so running the external diff program will actually be
49 49 # pretty fast (at least faster than having to compare the entire tree).
50 50
51 51 from mercurial.i18n import _
52 52 from mercurial.node import *
53 53 from mercurial import cmdutil, util
54 54 import os, shutil, tempfile
55 55
56 56 def dodiff(ui, repo, diffcmd, diffopts, pats, opts):
57 57 def snapshot_node(files, node):
58 58 '''snapshot files as of some revision'''
59 59 mf = repo.changectx(node).manifest()
60 60 dirname = '%s.%s' % (os.path.basename(repo.root), short(node))
61 61 base = os.path.join(tmproot, dirname)
62 62 os.mkdir(base)
63 63 if not ui.quiet:
64 64 ui.write_err(_('making snapshot of %d files from rev %s\n') %
65 65 (len(files), short(node)))
66 66 for fn in files:
67 67 if not fn in mf:
68 68 # skipping new file after a merge ?
69 69 continue
70 70 wfn = util.pconvert(fn)
71 71 ui.note(' %s\n' % wfn)
72 72 dest = os.path.join(base, wfn)
73 73 destdir = os.path.dirname(dest)
74 74 if not os.path.isdir(destdir):
75 75 os.makedirs(destdir)
76 repo.wwrite(wfn, repo.file(fn).read(mf[fn]), open(dest, 'w'))
76 data = repo.wwritedata(wfn, repo.file(wfn).read(mf[wfn]))
77 open(dest, 'w').write(data)
77 78 return dirname
78 79
79 80 def snapshot_wdir(files):
80 81 '''snapshot files from working directory.
81 82 if not using snapshot, -I/-X does not work and recursive diff
82 83 in tools like kdiff3 and meld displays too many files.'''
83 84 dirname = os.path.basename(repo.root)
84 85 base = os.path.join(tmproot, dirname)
85 86 os.mkdir(base)
86 87 if not ui.quiet:
87 88 ui.write_err(_('making snapshot of %d files from working dir\n') %
88 89 (len(files)))
89 90 for fn in files:
90 91 wfn = util.pconvert(fn)
91 92 ui.note(' %s\n' % wfn)
92 93 dest = os.path.join(base, wfn)
93 94 destdir = os.path.dirname(dest)
94 95 if not os.path.isdir(destdir):
95 96 os.makedirs(destdir)
96 97 fp = open(dest, 'w')
97 98 for chunk in util.filechunkiter(repo.wopener(wfn)):
98 99 fp.write(chunk)
99 100 return dirname
100 101
101 102 node1, node2 = cmdutil.revpair(repo, opts['rev'])
102 103 files, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
103 104 modified, added, removed, deleted, unknown = repo.status(
104 105 node1, node2, files, match=matchfn)[:5]
105 106 if not (modified or added or removed):
106 107 return 0
107 108
108 109 tmproot = tempfile.mkdtemp(prefix='extdiff.')
109 110 try:
110 111 dir1 = snapshot_node(modified + removed, node1)
111 112 if node2:
112 113 dir2 = snapshot_node(modified + added, node2)
113 114 else:
114 115 dir2 = snapshot_wdir(modified + added)
115 116 cmdline = ('%s %s %s %s' %
116 117 (util.shellquote(diffcmd), ' '.join(diffopts),
117 118 util.shellquote(dir1), util.shellquote(dir2)))
118 119 ui.debug('running %r in %s\n' % (cmdline, tmproot))
119 120 util.system(cmdline, cwd=tmproot)
120 121 return 1
121 122 finally:
122 123 ui.note(_('cleaning up temp directory\n'))
123 124 shutil.rmtree(tmproot)
124 125
125 126 def extdiff(ui, repo, *pats, **opts):
126 127 '''use external program to diff repository (or selected files)
127 128
128 129 Show differences between revisions for the specified files, using
129 130 an external program. The default program used is diff, with
130 131 default options "-Npru".
131 132
132 133 To select a different program, use the -p option. The program
133 134 will be passed the names of two directories to compare. To pass
134 135 additional options to the program, use the -o option. These will
135 136 be passed before the names of the directories to compare.
136 137
137 138 When two revision arguments are given, then changes are
138 139 shown between those revisions. If only one revision is
139 140 specified then that revision is compared to the working
140 141 directory, and, when no revisions are specified, the
141 142 working directory files are compared to its parent.'''
142 143 program = opts['program'] or 'diff'
143 144 if opts['program']:
144 145 option = opts['option']
145 146 else:
146 147 option = opts['option'] or ['-Npru']
147 148 return dodiff(ui, repo, program, option, pats, opts)
148 149
149 150 cmdtable = {
150 151 "extdiff":
151 152 (extdiff,
152 153 [('p', 'program', '', _('comparison program to run')),
153 154 ('o', 'option', [], _('pass option to comparison program')),
154 155 ('r', 'rev', [], _('revision')),
155 156 ('I', 'include', [], _('include names matching the given patterns')),
156 157 ('X', 'exclude', [], _('exclude names matching the given patterns'))],
157 158 _('hg extdiff [OPT]... [FILE]...')),
158 159 }
159 160
160 161 def uisetup(ui):
161 162 for cmd, path in ui.configitems('extdiff'):
162 163 if not cmd.startswith('cmd.'): continue
163 164 cmd = cmd[4:]
164 165 if not path: path = cmd
165 166 diffopts = ui.config('extdiff', 'opts.' + cmd, '')
166 167 diffopts = diffopts and [diffopts] or []
167 168 def save(cmd, path, diffopts):
168 169 '''use closure to save diff command to use'''
169 170 def mydiff(ui, repo, *pats, **opts):
170 171 return dodiff(ui, repo, path, diffopts, pats, opts)
171 172 mydiff.__doc__ = '''use %(path)r to diff repository (or selected files)
172 173
173 174 Show differences between revisions for the specified
174 175 files, using the %(path)r program.
175 176
176 177 When two revision arguments are given, then changes are
177 178 shown between those revisions. If only one revision is
178 179 specified then that revision is compared to the working
179 180 directory, and, when no revisions are specified, the
180 181 working directory files are compared to its parent.''' % {
181 182 'path': path,
182 183 }
183 184 return mydiff
184 185 cmdtable[cmd] = (save(cmd, path, diffopts),
185 186 cmdtable['extdiff'][1][1:],
186 187 _('hg %s [OPT]... [FILE]...') % cmd)
@@ -1,172 +1,170 b''
1 1 # archival.py - revision archival for mercurial
2 2 #
3 3 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of
6 6 # the GNU General Public License, incorporated herein by reference.
7 7
8 8 from i18n import _
9 9 from node import *
10 10 import cStringIO, os, stat, tarfile, time, util, zipfile
11 11
12 12 def tidyprefix(dest, prefix, suffixes):
13 13 '''choose prefix to use for names in archive. make sure prefix is
14 14 safe for consumers.'''
15 15
16 16 if prefix:
17 17 prefix = prefix.replace('\\', '/')
18 18 else:
19 19 if not isinstance(dest, str):
20 20 raise ValueError('dest must be string if no prefix')
21 21 prefix = os.path.basename(dest)
22 22 lower = prefix.lower()
23 23 for sfx in suffixes:
24 24 if lower.endswith(sfx):
25 25 prefix = prefix[:-len(sfx)]
26 26 break
27 27 lpfx = os.path.normpath(util.localpath(prefix))
28 28 prefix = util.pconvert(lpfx)
29 29 if not prefix.endswith('/'):
30 30 prefix += '/'
31 31 if prefix.startswith('../') or os.path.isabs(lpfx) or '/../' in prefix:
32 32 raise util.Abort(_('archive prefix contains illegal components'))
33 33 return prefix
34 34
35 35 class tarit:
36 36 '''write archive to tar file or stream. can write uncompressed,
37 37 or compress with gzip or bzip2.'''
38 38
39 39 def __init__(self, dest, prefix, mtime, kind=''):
40 40 self.prefix = tidyprefix(dest, prefix, ['.tar', '.tar.bz2', '.tar.gz',
41 41 '.tgz', '.tbz2'])
42 42 self.mtime = mtime
43 43 if isinstance(dest, str):
44 44 self.z = tarfile.open(dest, mode='w:'+kind)
45 45 else:
46 46 self.z = tarfile.open(mode='w|'+kind, fileobj=dest)
47 47
48 48 def addfile(self, name, mode, data):
49 49 i = tarfile.TarInfo(self.prefix + name)
50 50 i.mtime = self.mtime
51 51 i.size = len(data)
52 52 i.mode = mode
53 53 self.z.addfile(i, cStringIO.StringIO(data))
54 54
55 55 def done(self):
56 56 self.z.close()
57 57
58 58 class tellable:
59 59 '''provide tell method for zipfile.ZipFile when writing to http
60 60 response file object.'''
61 61
62 62 def __init__(self, fp):
63 63 self.fp = fp
64 64 self.offset = 0
65 65
66 66 def __getattr__(self, key):
67 67 return getattr(self.fp, key)
68 68
69 69 def write(self, s):
70 70 self.fp.write(s)
71 71 self.offset += len(s)
72 72
73 73 def tell(self):
74 74 return self.offset
75 75
76 76 class zipit:
77 77 '''write archive to zip file or stream. can write uncompressed,
78 78 or compressed with deflate.'''
79 79
80 80 def __init__(self, dest, prefix, mtime, compress=True):
81 81 self.prefix = tidyprefix(dest, prefix, ('.zip',))
82 82 if not isinstance(dest, str):
83 83 try:
84 84 dest.tell()
85 85 except (AttributeError, IOError):
86 86 dest = tellable(dest)
87 87 self.z = zipfile.ZipFile(dest, 'w',
88 88 compress and zipfile.ZIP_DEFLATED or
89 89 zipfile.ZIP_STORED)
90 90 self.date_time = time.gmtime(mtime)[:6]
91 91
92 92 def addfile(self, name, mode, data):
93 93 i = zipfile.ZipInfo(self.prefix + name, self.date_time)
94 94 i.compress_type = self.z.compression
95 95 i.flag_bits = 0x08
96 96 # unzip will not honor unix file modes unless file creator is
97 97 # set to unix (id 3).
98 98 i.create_system = 3
99 99 i.external_attr = (mode | stat.S_IFREG) << 16L
100 100 self.z.writestr(i, data)
101 101
102 102 def done(self):
103 103 self.z.close()
104 104
105 105 class fileit:
106 106 '''write archive as files in directory.'''
107 107
108 108 def __init__(self, name, prefix, mtime):
109 109 if prefix:
110 110 raise util.Abort(_('cannot give prefix when archiving to files'))
111 111 self.basedir = name
112 112 self.dirs = {}
113 113 self.oflags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY |
114 114 getattr(os, 'O_BINARY', 0) |
115 115 getattr(os, 'O_NOFOLLOW', 0))
116 116
117 117 def addfile(self, name, mode, data):
118 118 destfile = os.path.join(self.basedir, name)
119 119 destdir = os.path.dirname(destfile)
120 120 if destdir not in self.dirs:
121 121 if not os.path.isdir(destdir):
122 122 os.makedirs(destdir)
123 123 self.dirs[destdir] = 1
124 124 os.fdopen(os.open(destfile, self.oflags, mode), 'wb').write(data)
125 125
126 126 def done(self):
127 127 pass
128 128
129 129 archivers = {
130 130 'files': fileit,
131 131 'tar': tarit,
132 132 'tbz2': lambda name, prefix, mtime: tarit(name, prefix, mtime, 'bz2'),
133 133 'tgz': lambda name, prefix, mtime: tarit(name, prefix, mtime, 'gz'),
134 134 'uzip': lambda name, prefix, mtime: zipit(name, prefix, mtime, False),
135 135 'zip': zipit,
136 136 }
137 137
138 138 def archive(repo, dest, node, kind, decode=True, matchfn=None,
139 139 prefix=None, mtime=None):
140 140 '''create archive of repo as it was at node.
141 141
142 142 dest can be name of directory, name of archive file, or file
143 143 object to write archive to.
144 144
145 145 kind is type of archive to create.
146 146
147 147 decode tells whether to put files through decode filters from
148 148 hgrc.
149 149
150 150 matchfn is function to filter names of files to write to archive.
151 151
152 152 prefix is name of path to put before every archive member.'''
153 153
154 154 def write(name, mode, data):
155 155 if matchfn and not matchfn(name): return
156 156 if decode:
157 fp = cStringIO.StringIO()
158 repo.wwrite(name, data, fp)
159 data = fp.getvalue()
157 data = repo.wwritedata(name, data)
160 158 archiver.addfile(name, mode, data)
161 159
162 160 ctx = repo.changectx(node)
163 161 archiver = archivers[kind](dest, prefix, mtime or ctx.date()[0])
164 162 m = ctx.manifest()
165 163 items = m.items()
166 164 items.sort()
167 165 write('.hg_archival.txt', 0644,
168 166 'repo: %s\nnode: %s\n' % (hex(repo.changelog.node(0)), hex(node)))
169 167 for filename, filenode in items:
170 168 write(filename, m.execf(filename) and 0755 or 0644,
171 169 repo.file(filename).read(filenode))
172 170 archiver.done()
@@ -1,1866 +1,1867 b''
1 1 # localrepo.py - read/write repository class for mercurial
2 2 #
3 3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7
8 8 from node import *
9 9 from i18n import _
10 10 import repo, appendfile, changegroup
11 11 import changelog, dirstate, filelog, manifest, context
12 12 import re, lock, transaction, tempfile, stat, mdiff, errno, ui
13 13 import os, revlog, time, util
14 14
15 15 class localrepository(repo.repository):
16 16 capabilities = ('lookup', 'changegroupsubset')
17 17 supported = ('revlogv1', 'store')
18 18
19 19 def __del__(self):
20 20 self.transhandle = None
21 21 def __init__(self, parentui, path=None, create=0):
22 22 repo.repository.__init__(self)
23 23 if not path:
24 24 p = os.getcwd()
25 25 while not os.path.isdir(os.path.join(p, ".hg")):
26 26 oldp = p
27 27 p = os.path.dirname(p)
28 28 if p == oldp:
29 29 raise repo.RepoError(_("There is no Mercurial repository"
30 30 " here (.hg not found)"))
31 31 path = p
32 32
33 33 self.path = os.path.join(path, ".hg")
34 34 self.root = os.path.realpath(path)
35 35 self.origroot = path
36 36 self.opener = util.opener(self.path)
37 37 self.wopener = util.opener(self.root)
38 38
39 39 if not os.path.isdir(self.path):
40 40 if create:
41 41 if not os.path.exists(path):
42 42 os.mkdir(path)
43 43 os.mkdir(self.path)
44 44 os.mkdir(os.path.join(self.path, "store"))
45 45 requirements = ("revlogv1", "store")
46 46 reqfile = self.opener("requires", "w")
47 47 for r in requirements:
48 48 reqfile.write("%s\n" % r)
49 49 reqfile.close()
50 50 # create an invalid changelog
51 51 self.opener("00changelog.i", "a").write(
52 52 '\0\0\0\2' # represents revlogv2
53 53 ' dummy changelog to prevent using the old repo layout'
54 54 )
55 55 else:
56 56 raise repo.RepoError(_("repository %s not found") % path)
57 57 elif create:
58 58 raise repo.RepoError(_("repository %s already exists") % path)
59 59 else:
60 60 # find requirements
61 61 try:
62 62 requirements = self.opener("requires").read().splitlines()
63 63 except IOError, inst:
64 64 if inst.errno != errno.ENOENT:
65 65 raise
66 66 requirements = []
67 67 # check them
68 68 for r in requirements:
69 69 if r not in self.supported:
70 70 raise repo.RepoError(_("requirement '%s' not supported") % r)
71 71
72 72 # setup store
73 73 if "store" in requirements:
74 74 self.encodefn = util.encodefilename
75 75 self.decodefn = util.decodefilename
76 76 self.spath = os.path.join(self.path, "store")
77 77 else:
78 78 self.encodefn = lambda x: x
79 79 self.decodefn = lambda x: x
80 80 self.spath = self.path
81 81 self.sopener = util.encodedopener(util.opener(self.spath), self.encodefn)
82 82
83 83 self.ui = ui.ui(parentui=parentui)
84 84 try:
85 85 self.ui.readconfig(self.join("hgrc"), self.root)
86 86 except IOError:
87 87 pass
88 88
89 89 v = self.ui.configrevlog()
90 90 self.revlogversion = int(v.get('format', revlog.REVLOG_DEFAULT_FORMAT))
91 91 self.revlogv1 = self.revlogversion != revlog.REVLOGV0
92 92 fl = v.get('flags', None)
93 93 flags = 0
94 94 if fl != None:
95 95 for x in fl.split():
96 96 flags |= revlog.flagstr(x)
97 97 elif self.revlogv1:
98 98 flags = revlog.REVLOG_DEFAULT_FLAGS
99 99
100 100 v = self.revlogversion | flags
101 101 self.manifest = manifest.manifest(self.sopener, v)
102 102 self.changelog = changelog.changelog(self.sopener, v)
103 103
104 104 fallback = self.ui.config('ui', 'fallbackencoding')
105 105 if fallback:
106 106 util._fallbackencoding = fallback
107 107
108 108 # the changelog might not have the inline index flag
109 109 # on. If the format of the changelog is the same as found in
110 110 # .hgrc, apply any flags found in the .hgrc as well.
111 111 # Otherwise, just version from the changelog
112 112 v = self.changelog.version
113 113 if v == self.revlogversion:
114 114 v |= flags
115 115 self.revlogversion = v
116 116
117 117 self.tagscache = None
118 118 self.branchcache = None
119 119 self.nodetagscache = None
120 120 self.filterpats = {}
121 121 self.transhandle = None
122 122
123 123 self._link = lambda x: False
124 124 if util.checklink(self.root):
125 125 r = self.root # avoid circular reference in lambda
126 126 self._link = lambda x: util.is_link(os.path.join(r, x))
127 127
128 128 self.dirstate = dirstate.dirstate(self.opener, self.ui, self.root)
129 129
130 130 def url(self):
131 131 return 'file:' + self.root
132 132
133 133 def hook(self, name, throw=False, **args):
134 134 def callhook(hname, funcname):
135 135 '''call python hook. hook is callable object, looked up as
136 136 name in python module. if callable returns "true", hook
137 137 fails, else passes. if hook raises exception, treated as
138 138 hook failure. exception propagates if throw is "true".
139 139
140 140 reason for "true" meaning "hook failed" is so that
141 141 unmodified commands (e.g. mercurial.commands.update) can
142 142 be run as hooks without wrappers to convert return values.'''
143 143
144 144 self.ui.note(_("calling hook %s: %s\n") % (hname, funcname))
145 145 d = funcname.rfind('.')
146 146 if d == -1:
147 147 raise util.Abort(_('%s hook is invalid ("%s" not in a module)')
148 148 % (hname, funcname))
149 149 modname = funcname[:d]
150 150 try:
151 151 obj = __import__(modname)
152 152 except ImportError:
153 153 try:
154 154 # extensions are loaded with hgext_ prefix
155 155 obj = __import__("hgext_%s" % modname)
156 156 except ImportError:
157 157 raise util.Abort(_('%s hook is invalid '
158 158 '(import of "%s" failed)') %
159 159 (hname, modname))
160 160 try:
161 161 for p in funcname.split('.')[1:]:
162 162 obj = getattr(obj, p)
163 163 except AttributeError, err:
164 164 raise util.Abort(_('%s hook is invalid '
165 165 '("%s" is not defined)') %
166 166 (hname, funcname))
167 167 if not callable(obj):
168 168 raise util.Abort(_('%s hook is invalid '
169 169 '("%s" is not callable)') %
170 170 (hname, funcname))
171 171 try:
172 172 r = obj(ui=self.ui, repo=self, hooktype=name, **args)
173 173 except (KeyboardInterrupt, util.SignalInterrupt):
174 174 raise
175 175 except Exception, exc:
176 176 if isinstance(exc, util.Abort):
177 177 self.ui.warn(_('error: %s hook failed: %s\n') %
178 178 (hname, exc.args[0]))
179 179 else:
180 180 self.ui.warn(_('error: %s hook raised an exception: '
181 181 '%s\n') % (hname, exc))
182 182 if throw:
183 183 raise
184 184 self.ui.print_exc()
185 185 return True
186 186 if r:
187 187 if throw:
188 188 raise util.Abort(_('%s hook failed') % hname)
189 189 self.ui.warn(_('warning: %s hook failed\n') % hname)
190 190 return r
191 191
192 192 def runhook(name, cmd):
193 193 self.ui.note(_("running hook %s: %s\n") % (name, cmd))
194 194 env = dict([('HG_' + k.upper(), v) for k, v in args.iteritems()])
195 195 r = util.system(cmd, environ=env, cwd=self.root)
196 196 if r:
197 197 desc, r = util.explain_exit(r)
198 198 if throw:
199 199 raise util.Abort(_('%s hook %s') % (name, desc))
200 200 self.ui.warn(_('warning: %s hook %s\n') % (name, desc))
201 201 return r
202 202
203 203 r = False
204 204 hooks = [(hname, cmd) for hname, cmd in self.ui.configitems("hooks")
205 205 if hname.split(".", 1)[0] == name and cmd]
206 206 hooks.sort()
207 207 for hname, cmd in hooks:
208 208 if cmd.startswith('python:'):
209 209 r = callhook(hname, cmd[7:].strip()) or r
210 210 else:
211 211 r = runhook(hname, cmd) or r
212 212 return r
213 213
214 214 tag_disallowed = ':\r\n'
215 215
216 216 def tag(self, name, node, message, local, user, date):
217 217 '''tag a revision with a symbolic name.
218 218
219 219 if local is True, the tag is stored in a per-repository file.
220 220 otherwise, it is stored in the .hgtags file, and a new
221 221 changeset is committed with the change.
222 222
223 223 keyword arguments:
224 224
225 225 local: whether to store tag in non-version-controlled file
226 226 (default False)
227 227
228 228 message: commit message to use if committing
229 229
230 230 user: name of user to use if committing
231 231
232 232 date: date tuple to use if committing'''
233 233
234 234 for c in self.tag_disallowed:
235 235 if c in name:
236 236 raise util.Abort(_('%r cannot be used in a tag name') % c)
237 237
238 238 self.hook('pretag', throw=True, node=hex(node), tag=name, local=local)
239 239
240 240 if local:
241 241 # local tags are stored in the current charset
242 242 self.opener('localtags', 'a').write('%s %s\n' % (hex(node), name))
243 243 self.hook('tag', node=hex(node), tag=name, local=local)
244 244 return
245 245
246 246 for x in self.status()[:5]:
247 247 if '.hgtags' in x:
248 248 raise util.Abort(_('working copy of .hgtags is changed '
249 249 '(please commit .hgtags manually)'))
250 250
251 251 # committed tags are stored in UTF-8
252 252 line = '%s %s\n' % (hex(node), util.fromlocal(name))
253 253 self.wfile('.hgtags', 'ab').write(line)
254 254 if self.dirstate.state('.hgtags') == '?':
255 255 self.add(['.hgtags'])
256 256
257 257 self.commit(['.hgtags'], message, user, date)
258 258 self.hook('tag', node=hex(node), tag=name, local=local)
259 259
260 260 def tags(self):
261 261 '''return a mapping of tag to node'''
262 262 if not self.tagscache:
263 263 self.tagscache = {}
264 264
265 265 def parsetag(line, context):
266 266 if not line:
267 267 return
268 268 s = l.split(" ", 1)
269 269 if len(s) != 2:
270 270 self.ui.warn(_("%s: cannot parse entry\n") % context)
271 271 return
272 272 node, key = s
273 273 key = util.tolocal(key.strip()) # stored in UTF-8
274 274 try:
275 275 bin_n = bin(node)
276 276 except TypeError:
277 277 self.ui.warn(_("%s: node '%s' is not well formed\n") %
278 278 (context, node))
279 279 return
280 280 if bin_n not in self.changelog.nodemap:
281 281 self.ui.warn(_("%s: tag '%s' refers to unknown node\n") %
282 282 (context, key))
283 283 return
284 284 self.tagscache[key] = bin_n
285 285
286 286 # read the tags file from each head, ending with the tip,
287 287 # and add each tag found to the map, with "newer" ones
288 288 # taking precedence
289 289 f = None
290 290 for rev, node, fnode in self._hgtagsnodes():
291 291 f = (f and f.filectx(fnode) or
292 292 self.filectx('.hgtags', fileid=fnode))
293 293 count = 0
294 294 for l in f.data().splitlines():
295 295 count += 1
296 296 parsetag(l, _("%s, line %d") % (str(f), count))
297 297
298 298 try:
299 299 f = self.opener("localtags")
300 300 count = 0
301 301 for l in f:
302 302 # localtags are stored in the local character set
303 303 # while the internal tag table is stored in UTF-8
304 304 l = util.fromlocal(l)
305 305 count += 1
306 306 parsetag(l, _("localtags, line %d") % count)
307 307 except IOError:
308 308 pass
309 309
310 310 self.tagscache['tip'] = self.changelog.tip()
311 311
312 312 return self.tagscache
313 313
314 314 def _hgtagsnodes(self):
315 315 heads = self.heads()
316 316 heads.reverse()
317 317 last = {}
318 318 ret = []
319 319 for node in heads:
320 320 c = self.changectx(node)
321 321 rev = c.rev()
322 322 try:
323 323 fnode = c.filenode('.hgtags')
324 324 except revlog.LookupError:
325 325 continue
326 326 ret.append((rev, node, fnode))
327 327 if fnode in last:
328 328 ret[last[fnode]] = None
329 329 last[fnode] = len(ret) - 1
330 330 return [item for item in ret if item]
331 331
332 332 def tagslist(self):
333 333 '''return a list of tags ordered by revision'''
334 334 l = []
335 335 for t, n in self.tags().items():
336 336 try:
337 337 r = self.changelog.rev(n)
338 338 except:
339 339 r = -2 # sort to the beginning of the list if unknown
340 340 l.append((r, t, n))
341 341 l.sort()
342 342 return [(t, n) for r, t, n in l]
343 343
344 344 def nodetags(self, node):
345 345 '''return the tags associated with a node'''
346 346 if not self.nodetagscache:
347 347 self.nodetagscache = {}
348 348 for t, n in self.tags().items():
349 349 self.nodetagscache.setdefault(n, []).append(t)
350 350 return self.nodetagscache.get(node, [])
351 351
352 352 def _branchtags(self):
353 353 partial, last, lrev = self._readbranchcache()
354 354
355 355 tiprev = self.changelog.count() - 1
356 356 if lrev != tiprev:
357 357 self._updatebranchcache(partial, lrev+1, tiprev+1)
358 358 self._writebranchcache(partial, self.changelog.tip(), tiprev)
359 359
360 360 return partial
361 361
362 362 def branchtags(self):
363 363 if self.branchcache is not None:
364 364 return self.branchcache
365 365
366 366 self.branchcache = {} # avoid recursion in changectx
367 367 partial = self._branchtags()
368 368
369 369 # the branch cache is stored on disk as UTF-8, but in the local
370 370 # charset internally
371 371 for k, v in partial.items():
372 372 self.branchcache[util.tolocal(k)] = v
373 373 return self.branchcache
374 374
375 375 def _readbranchcache(self):
376 376 partial = {}
377 377 try:
378 378 f = self.opener("branches.cache")
379 379 lines = f.read().split('\n')
380 380 f.close()
381 381 last, lrev = lines.pop(0).rstrip().split(" ", 1)
382 382 last, lrev = bin(last), int(lrev)
383 383 if not (lrev < self.changelog.count() and
384 384 self.changelog.node(lrev) == last): # sanity check
385 385 # invalidate the cache
386 386 raise ValueError('Invalid branch cache: unknown tip')
387 387 for l in lines:
388 388 if not l: continue
389 389 node, label = l.rstrip().split(" ", 1)
390 390 partial[label] = bin(node)
391 391 except (KeyboardInterrupt, util.SignalInterrupt):
392 392 raise
393 393 except Exception, inst:
394 394 if self.ui.debugflag:
395 395 self.ui.warn(str(inst), '\n')
396 396 partial, last, lrev = {}, nullid, nullrev
397 397 return partial, last, lrev
398 398
399 399 def _writebranchcache(self, branches, tip, tiprev):
400 400 try:
401 401 f = self.opener("branches.cache", "w")
402 402 f.write("%s %s\n" % (hex(tip), tiprev))
403 403 for label, node in branches.iteritems():
404 404 f.write("%s %s\n" % (hex(node), label))
405 405 except IOError:
406 406 pass
407 407
408 408 def _updatebranchcache(self, partial, start, end):
409 409 for r in xrange(start, end):
410 410 c = self.changectx(r)
411 411 b = c.branch()
412 412 if b:
413 413 partial[b] = c.node()
414 414
415 415 def lookup(self, key):
416 416 if key == '.':
417 417 key = self.dirstate.parents()[0]
418 418 if key == nullid:
419 419 raise repo.RepoError(_("no revision checked out"))
420 420 elif key == 'null':
421 421 return nullid
422 422 n = self.changelog._match(key)
423 423 if n:
424 424 return n
425 425 if key in self.tags():
426 426 return self.tags()[key]
427 427 if key in self.branchtags():
428 428 return self.branchtags()[key]
429 429 n = self.changelog._partialmatch(key)
430 430 if n:
431 431 return n
432 432 raise repo.RepoError(_("unknown revision '%s'") % key)
433 433
434 434 def dev(self):
435 435 return os.lstat(self.path).st_dev
436 436
437 437 def local(self):
438 438 return True
439 439
440 440 def join(self, f):
441 441 return os.path.join(self.path, f)
442 442
443 443 def sjoin(self, f):
444 444 f = self.encodefn(f)
445 445 return os.path.join(self.spath, f)
446 446
447 447 def wjoin(self, f):
448 448 return os.path.join(self.root, f)
449 449
450 450 def file(self, f):
451 451 if f[0] == '/':
452 452 f = f[1:]
453 453 return filelog.filelog(self.sopener, f, self.revlogversion)
454 454
455 455 def changectx(self, changeid=None):
456 456 return context.changectx(self, changeid)
457 457
458 458 def workingctx(self):
459 459 return context.workingctx(self)
460 460
461 461 def parents(self, changeid=None):
462 462 '''
463 463 get list of changectxs for parents of changeid or working directory
464 464 '''
465 465 if changeid is None:
466 466 pl = self.dirstate.parents()
467 467 else:
468 468 n = self.changelog.lookup(changeid)
469 469 pl = self.changelog.parents(n)
470 470 if pl[1] == nullid:
471 471 return [self.changectx(pl[0])]
472 472 return [self.changectx(pl[0]), self.changectx(pl[1])]
473 473
474 474 def filectx(self, path, changeid=None, fileid=None):
475 475 """changeid can be a changeset revision, node, or tag.
476 476 fileid can be a file revision or node."""
477 477 return context.filectx(self, path, changeid, fileid)
478 478
479 479 def getcwd(self):
480 480 return self.dirstate.getcwd()
481 481
482 482 def wfile(self, f, mode='r'):
483 483 return self.wopener(f, mode)
484 484
485 485 def _filter(self, filter, filename, data):
486 486 if filter not in self.filterpats:
487 487 l = []
488 488 for pat, cmd in self.ui.configitems(filter):
489 489 mf = util.matcher(self.root, "", [pat], [], [])[1]
490 490 l.append((mf, cmd))
491 491 self.filterpats[filter] = l
492 492
493 493 for mf, cmd in self.filterpats[filter]:
494 494 if mf(filename):
495 495 self.ui.debug(_("filtering %s through %s\n") % (filename, cmd))
496 496 data = util.filter(data, cmd)
497 497 break
498 498
499 499 return data
500 500
501 501 def wread(self, filename):
502 502 if self._link(filename):
503 503 data = os.readlink(self.wjoin(filename))
504 504 else:
505 505 data = self.wopener(filename, 'r').read()
506 506 return self._filter("encode", filename, data)
507 507
508 def wwrite(self, filename, data, fd=None):
508 def wwrite(self, filename, data):
509 509 data = self._filter("decode", filename, data)
510 if fd:
511 return fd.write(data)
512 510 return self.wopener(filename, 'w').write(data)
513 511
512 def wwritedata(self, filename, data):
513 return self._filter("decode", filename, data)
514
514 515 def transaction(self):
515 516 tr = self.transhandle
516 517 if tr != None and tr.running():
517 518 return tr.nest()
518 519
519 520 # save dirstate for rollback
520 521 try:
521 522 ds = self.opener("dirstate").read()
522 523 except IOError:
523 524 ds = ""
524 525 self.opener("journal.dirstate", "w").write(ds)
525 526
526 527 renames = [(self.sjoin("journal"), self.sjoin("undo")),
527 528 (self.join("journal.dirstate"), self.join("undo.dirstate"))]
528 529 tr = transaction.transaction(self.ui.warn, self.sopener,
529 530 self.sjoin("journal"),
530 531 aftertrans(renames))
531 532 self.transhandle = tr
532 533 return tr
533 534
534 535 def recover(self):
535 536 l = self.lock()
536 537 if os.path.exists(self.sjoin("journal")):
537 538 self.ui.status(_("rolling back interrupted transaction\n"))
538 539 transaction.rollback(self.sopener, self.sjoin("journal"))
539 540 self.reload()
540 541 return True
541 542 else:
542 543 self.ui.warn(_("no interrupted transaction available\n"))
543 544 return False
544 545
545 546 def rollback(self, wlock=None):
546 547 if not wlock:
547 548 wlock = self.wlock()
548 549 l = self.lock()
549 550 if os.path.exists(self.sjoin("undo")):
550 551 self.ui.status(_("rolling back last transaction\n"))
551 552 transaction.rollback(self.sopener, self.sjoin("undo"))
552 553 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
553 554 self.reload()
554 555 self.wreload()
555 556 else:
556 557 self.ui.warn(_("no rollback information available\n"))
557 558
558 559 def wreload(self):
559 560 self.dirstate.read()
560 561
561 562 def reload(self):
562 563 self.changelog.load()
563 564 self.manifest.load()
564 565 self.tagscache = None
565 566 self.nodetagscache = None
566 567
567 568 def do_lock(self, lockname, wait, releasefn=None, acquirefn=None,
568 569 desc=None):
569 570 try:
570 571 l = lock.lock(lockname, 0, releasefn, desc=desc)
571 572 except lock.LockHeld, inst:
572 573 if not wait:
573 574 raise
574 575 self.ui.warn(_("waiting for lock on %s held by %r\n") %
575 576 (desc, inst.locker))
576 577 # default to 600 seconds timeout
577 578 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
578 579 releasefn, desc=desc)
579 580 if acquirefn:
580 581 acquirefn()
581 582 return l
582 583
583 584 def lock(self, wait=1):
584 585 return self.do_lock(self.sjoin("lock"), wait, acquirefn=self.reload,
585 586 desc=_('repository %s') % self.origroot)
586 587
587 588 def wlock(self, wait=1):
588 589 return self.do_lock(self.join("wlock"), wait, self.dirstate.write,
589 590 self.wreload,
590 591 desc=_('working directory of %s') % self.origroot)
591 592
592 593 def filecommit(self, fn, manifest1, manifest2, linkrev, transaction, changelist):
593 594 """
594 595 commit an individual file as part of a larger transaction
595 596 """
596 597
597 598 t = self.wread(fn)
598 599 fl = self.file(fn)
599 600 fp1 = manifest1.get(fn, nullid)
600 601 fp2 = manifest2.get(fn, nullid)
601 602
602 603 meta = {}
603 604 cp = self.dirstate.copied(fn)
604 605 if cp:
605 606 meta["copy"] = cp
606 607 if not manifest2: # not a branch merge
607 608 meta["copyrev"] = hex(manifest1.get(cp, nullid))
608 609 fp2 = nullid
609 610 elif fp2 != nullid: # copied on remote side
610 611 meta["copyrev"] = hex(manifest1.get(cp, nullid))
611 612 elif fp1 != nullid: # copied on local side, reversed
612 613 meta["copyrev"] = hex(manifest2.get(cp))
613 614 fp2 = nullid
614 615 else: # directory rename
615 616 meta["copyrev"] = hex(manifest1.get(cp, nullid))
616 617 self.ui.debug(_(" %s: copy %s:%s\n") %
617 618 (fn, cp, meta["copyrev"]))
618 619 fp1 = nullid
619 620 elif fp2 != nullid:
620 621 # is one parent an ancestor of the other?
621 622 fpa = fl.ancestor(fp1, fp2)
622 623 if fpa == fp1:
623 624 fp1, fp2 = fp2, nullid
624 625 elif fpa == fp2:
625 626 fp2 = nullid
626 627
627 628 # is the file unmodified from the parent? report existing entry
628 629 if fp2 == nullid and not fl.cmp(fp1, t):
629 630 return fp1
630 631
631 632 changelist.append(fn)
632 633 return fl.add(t, meta, transaction, linkrev, fp1, fp2)
633 634
634 635 def rawcommit(self, files, text, user, date, p1=None, p2=None, wlock=None, extra={}):
635 636 if p1 is None:
636 637 p1, p2 = self.dirstate.parents()
637 638 return self.commit(files=files, text=text, user=user, date=date,
638 639 p1=p1, p2=p2, wlock=wlock, extra=extra)
639 640
640 641 def commit(self, files=None, text="", user=None, date=None,
641 642 match=util.always, force=False, lock=None, wlock=None,
642 643 force_editor=False, p1=None, p2=None, extra={}):
643 644
644 645 commit = []
645 646 remove = []
646 647 changed = []
647 648 use_dirstate = (p1 is None) # not rawcommit
648 649 extra = extra.copy()
649 650
650 651 if use_dirstate:
651 652 if files:
652 653 for f in files:
653 654 s = self.dirstate.state(f)
654 655 if s in 'nmai':
655 656 commit.append(f)
656 657 elif s == 'r':
657 658 remove.append(f)
658 659 else:
659 660 self.ui.warn(_("%s not tracked!\n") % f)
660 661 else:
661 662 changes = self.status(match=match)[:5]
662 663 modified, added, removed, deleted, unknown = changes
663 664 commit = modified + added
664 665 remove = removed
665 666 else:
666 667 commit = files
667 668
668 669 if use_dirstate:
669 670 p1, p2 = self.dirstate.parents()
670 671 update_dirstate = True
671 672 else:
672 673 p1, p2 = p1, p2 or nullid
673 674 update_dirstate = (self.dirstate.parents()[0] == p1)
674 675
675 676 c1 = self.changelog.read(p1)
676 677 c2 = self.changelog.read(p2)
677 678 m1 = self.manifest.read(c1[0]).copy()
678 679 m2 = self.manifest.read(c2[0])
679 680
680 681 if use_dirstate:
681 682 branchname = self.workingctx().branch()
682 683 try:
683 684 branchname = branchname.decode('UTF-8').encode('UTF-8')
684 685 except UnicodeDecodeError:
685 686 raise util.Abort(_('branch name not in UTF-8!'))
686 687 else:
687 688 branchname = ""
688 689
689 690 if use_dirstate:
690 691 oldname = c1[5].get("branch", "") # stored in UTF-8
691 692 if not commit and not remove and not force and p2 == nullid and \
692 693 branchname == oldname:
693 694 self.ui.status(_("nothing changed\n"))
694 695 return None
695 696
696 697 xp1 = hex(p1)
697 698 if p2 == nullid: xp2 = ''
698 699 else: xp2 = hex(p2)
699 700
700 701 self.hook("precommit", throw=True, parent1=xp1, parent2=xp2)
701 702
702 703 if not wlock:
703 704 wlock = self.wlock()
704 705 if not lock:
705 706 lock = self.lock()
706 707 tr = self.transaction()
707 708
708 709 # check in files
709 710 new = {}
710 711 linkrev = self.changelog.count()
711 712 commit.sort()
712 713 is_exec = util.execfunc(self.root, m1.execf)
713 714 is_link = util.linkfunc(self.root, m1.linkf)
714 715 for f in commit:
715 716 self.ui.note(f + "\n")
716 717 try:
717 718 new[f] = self.filecommit(f, m1, m2, linkrev, tr, changed)
718 719 m1.set(f, is_exec(f), is_link(f))
719 720 except OSError:
720 721 if use_dirstate:
721 722 self.ui.warn(_("trouble committing %s!\n") % f)
722 723 raise
723 724 else:
724 725 remove.append(f)
725 726
726 727 # update manifest
727 728 m1.update(new)
728 729 remove.sort()
729 730 removed = []
730 731
731 732 for f in remove:
732 733 if f in m1:
733 734 del m1[f]
734 735 removed.append(f)
735 736 mn = self.manifest.add(m1, tr, linkrev, c1[0], c2[0], (new, removed))
736 737
737 738 # add changeset
738 739 new = new.keys()
739 740 new.sort()
740 741
741 742 user = user or self.ui.username()
742 743 if not text or force_editor:
743 744 edittext = []
744 745 if text:
745 746 edittext.append(text)
746 747 edittext.append("")
747 748 edittext.append("HG: user: %s" % user)
748 749 if p2 != nullid:
749 750 edittext.append("HG: branch merge")
750 751 edittext.extend(["HG: changed %s" % f for f in changed])
751 752 edittext.extend(["HG: removed %s" % f for f in removed])
752 753 if not changed and not remove:
753 754 edittext.append("HG: no files changed")
754 755 edittext.append("")
755 756 # run editor in the repository root
756 757 olddir = os.getcwd()
757 758 os.chdir(self.root)
758 759 text = self.ui.edit("\n".join(edittext), user)
759 760 os.chdir(olddir)
760 761
761 762 lines = [line.rstrip() for line in text.rstrip().splitlines()]
762 763 while lines and not lines[0]:
763 764 del lines[0]
764 765 if not lines:
765 766 return None
766 767 text = '\n'.join(lines)
767 768 if branchname:
768 769 extra["branch"] = branchname
769 770 n = self.changelog.add(mn, changed + removed, text, tr, p1, p2,
770 771 user, date, extra)
771 772 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
772 773 parent2=xp2)
773 774 tr.close()
774 775
775 776 if use_dirstate or update_dirstate:
776 777 self.dirstate.setparents(n)
777 778 if use_dirstate:
778 779 self.dirstate.update(new, "n")
779 780 self.dirstate.forget(removed)
780 781
781 782 self.hook("commit", node=hex(n), parent1=xp1, parent2=xp2)
782 783 return n
783 784
784 785 def walk(self, node=None, files=[], match=util.always, badmatch=None):
785 786 '''
786 787 walk recursively through the directory tree or a given
787 788 changeset, finding all files matched by the match
788 789 function
789 790
790 791 results are yielded in a tuple (src, filename), where src
791 792 is one of:
792 793 'f' the file was found in the directory tree
793 794 'm' the file was only in the dirstate and not in the tree
794 795 'b' file was not found and matched badmatch
795 796 '''
796 797
797 798 if node:
798 799 fdict = dict.fromkeys(files)
799 800 for fn in self.manifest.read(self.changelog.read(node)[0]):
800 801 for ffn in fdict:
801 802 # match if the file is the exact name or a directory
802 803 if ffn == fn or fn.startswith("%s/" % ffn):
803 804 del fdict[ffn]
804 805 break
805 806 if match(fn):
806 807 yield 'm', fn
807 808 for fn in fdict:
808 809 if badmatch and badmatch(fn):
809 810 if match(fn):
810 811 yield 'b', fn
811 812 else:
812 813 self.ui.warn(_('%s: No such file in rev %s\n') % (
813 814 util.pathto(self.getcwd(), fn), short(node)))
814 815 else:
815 816 for src, fn in self.dirstate.walk(files, match, badmatch=badmatch):
816 817 yield src, fn
817 818
818 819 def status(self, node1=None, node2=None, files=[], match=util.always,
819 820 wlock=None, list_ignored=False, list_clean=False):
820 821 """return status of files between two nodes or node and working directory
821 822
822 823 If node1 is None, use the first dirstate parent instead.
823 824 If node2 is None, compare node1 with working directory.
824 825 """
825 826
826 827 def fcmp(fn, mf):
827 828 t1 = self.wread(fn)
828 829 return self.file(fn).cmp(mf.get(fn, nullid), t1)
829 830
830 831 def mfmatches(node):
831 832 change = self.changelog.read(node)
832 833 mf = self.manifest.read(change[0]).copy()
833 834 for fn in mf.keys():
834 835 if not match(fn):
835 836 del mf[fn]
836 837 return mf
837 838
838 839 modified, added, removed, deleted, unknown = [], [], [], [], []
839 840 ignored, clean = [], []
840 841
841 842 compareworking = False
842 843 if not node1 or (not node2 and node1 == self.dirstate.parents()[0]):
843 844 compareworking = True
844 845
845 846 if not compareworking:
846 847 # read the manifest from node1 before the manifest from node2,
847 848 # so that we'll hit the manifest cache if we're going through
848 849 # all the revisions in parent->child order.
849 850 mf1 = mfmatches(node1)
850 851
851 852 # are we comparing the working directory?
852 853 if not node2:
853 854 if not wlock:
854 855 try:
855 856 wlock = self.wlock(wait=0)
856 857 except lock.LockException:
857 858 wlock = None
858 859 (lookup, modified, added, removed, deleted, unknown,
859 860 ignored, clean) = self.dirstate.status(files, match,
860 861 list_ignored, list_clean)
861 862
862 863 # are we comparing working dir against its parent?
863 864 if compareworking:
864 865 if lookup:
865 866 # do a full compare of any files that might have changed
866 867 mf2 = mfmatches(self.dirstate.parents()[0])
867 868 for f in lookup:
868 869 if fcmp(f, mf2):
869 870 modified.append(f)
870 871 else:
871 872 clean.append(f)
872 873 if wlock is not None:
873 874 self.dirstate.update([f], "n")
874 875 else:
875 876 # we are comparing working dir against non-parent
876 877 # generate a pseudo-manifest for the working dir
877 878 # XXX: create it in dirstate.py ?
878 879 mf2 = mfmatches(self.dirstate.parents()[0])
879 880 is_exec = util.execfunc(self.root, mf2.execf)
880 881 is_link = util.linkfunc(self.root, mf2.linkf)
881 882 for f in lookup + modified + added:
882 883 mf2[f] = ""
883 884 mf2.set(f, is_exec(f), is_link(f))
884 885 for f in removed:
885 886 if f in mf2:
886 887 del mf2[f]
887 888 else:
888 889 # we are comparing two revisions
889 890 mf2 = mfmatches(node2)
890 891
891 892 if not compareworking:
892 893 # flush lists from dirstate before comparing manifests
893 894 modified, added, clean = [], [], []
894 895
895 896 # make sure to sort the files so we talk to the disk in a
896 897 # reasonable order
897 898 mf2keys = mf2.keys()
898 899 mf2keys.sort()
899 900 for fn in mf2keys:
900 901 if mf1.has_key(fn):
901 902 if mf1.flags(fn) != mf2.flags(fn) or \
902 903 (mf1[fn] != mf2[fn] and (mf2[fn] != "" or fcmp(fn, mf1))):
903 904 modified.append(fn)
904 905 elif list_clean:
905 906 clean.append(fn)
906 907 del mf1[fn]
907 908 else:
908 909 added.append(fn)
909 910
910 911 removed = mf1.keys()
911 912
912 913 # sort and return results:
913 914 for l in modified, added, removed, deleted, unknown, ignored, clean:
914 915 l.sort()
915 916 return (modified, added, removed, deleted, unknown, ignored, clean)
916 917
917 918 def add(self, list, wlock=None):
918 919 if not wlock:
919 920 wlock = self.wlock()
920 921 for f in list:
921 922 p = self.wjoin(f)
922 923 if not os.path.exists(p):
923 924 self.ui.warn(_("%s does not exist!\n") % f)
924 925 elif not os.path.isfile(p):
925 926 self.ui.warn(_("%s not added: only files supported currently\n")
926 927 % f)
927 928 elif self.dirstate.state(f) in 'an':
928 929 self.ui.warn(_("%s already tracked!\n") % f)
929 930 else:
930 931 self.dirstate.update([f], "a")
931 932
932 933 def forget(self, list, wlock=None):
933 934 if not wlock:
934 935 wlock = self.wlock()
935 936 for f in list:
936 937 if self.dirstate.state(f) not in 'ai':
937 938 self.ui.warn(_("%s not added!\n") % f)
938 939 else:
939 940 self.dirstate.forget([f])
940 941
941 942 def remove(self, list, unlink=False, wlock=None):
942 943 if unlink:
943 944 for f in list:
944 945 try:
945 946 util.unlink(self.wjoin(f))
946 947 except OSError, inst:
947 948 if inst.errno != errno.ENOENT:
948 949 raise
949 950 if not wlock:
950 951 wlock = self.wlock()
951 952 for f in list:
952 953 p = self.wjoin(f)
953 954 if os.path.exists(p):
954 955 self.ui.warn(_("%s still exists!\n") % f)
955 956 elif self.dirstate.state(f) == 'a':
956 957 self.dirstate.forget([f])
957 958 elif f not in self.dirstate:
958 959 self.ui.warn(_("%s not tracked!\n") % f)
959 960 else:
960 961 self.dirstate.update([f], "r")
961 962
962 963 def undelete(self, list, wlock=None):
963 964 p = self.dirstate.parents()[0]
964 965 mn = self.changelog.read(p)[0]
965 966 m = self.manifest.read(mn)
966 967 if not wlock:
967 968 wlock = self.wlock()
968 969 for f in list:
969 970 if self.dirstate.state(f) not in "r":
970 971 self.ui.warn("%s not removed!\n" % f)
971 972 else:
972 973 t = self.file(f).read(m[f])
973 974 self.wwrite(f, t)
974 975 util.set_exec(self.wjoin(f), m.execf(f))
975 976 self.dirstate.update([f], "n")
976 977
977 978 def copy(self, source, dest, wlock=None):
978 979 p = self.wjoin(dest)
979 980 if not os.path.exists(p):
980 981 self.ui.warn(_("%s does not exist!\n") % dest)
981 982 elif not os.path.isfile(p):
982 983 self.ui.warn(_("copy failed: %s is not a file\n") % dest)
983 984 else:
984 985 if not wlock:
985 986 wlock = self.wlock()
986 987 if self.dirstate.state(dest) == '?':
987 988 self.dirstate.update([dest], "a")
988 989 self.dirstate.copy(source, dest)
989 990
990 991 def heads(self, start=None):
991 992 heads = self.changelog.heads(start)
992 993 # sort the output in rev descending order
993 994 heads = [(-self.changelog.rev(h), h) for h in heads]
994 995 heads.sort()
995 996 return [n for (r, n) in heads]
996 997
997 998 def branches(self, nodes):
998 999 if not nodes:
999 1000 nodes = [self.changelog.tip()]
1000 1001 b = []
1001 1002 for n in nodes:
1002 1003 t = n
1003 1004 while 1:
1004 1005 p = self.changelog.parents(n)
1005 1006 if p[1] != nullid or p[0] == nullid:
1006 1007 b.append((t, n, p[0], p[1]))
1007 1008 break
1008 1009 n = p[0]
1009 1010 return b
1010 1011
1011 1012 def between(self, pairs):
1012 1013 r = []
1013 1014
1014 1015 for top, bottom in pairs:
1015 1016 n, l, i = top, [], 0
1016 1017 f = 1
1017 1018
1018 1019 while n != bottom:
1019 1020 p = self.changelog.parents(n)[0]
1020 1021 if i == f:
1021 1022 l.append(n)
1022 1023 f = f * 2
1023 1024 n = p
1024 1025 i += 1
1025 1026
1026 1027 r.append(l)
1027 1028
1028 1029 return r
1029 1030
1030 1031 def findincoming(self, remote, base=None, heads=None, force=False):
1031 1032 """Return list of roots of the subsets of missing nodes from remote
1032 1033
1033 1034 If base dict is specified, assume that these nodes and their parents
1034 1035 exist on the remote side and that no child of a node of base exists
1035 1036 in both remote and self.
1036 1037 Furthermore base will be updated to include the nodes that exists
1037 1038 in self and remote but no children exists in self and remote.
1038 1039 If a list of heads is specified, return only nodes which are heads
1039 1040 or ancestors of these heads.
1040 1041
1041 1042 All the ancestors of base are in self and in remote.
1042 1043 All the descendants of the list returned are missing in self.
1043 1044 (and so we know that the rest of the nodes are missing in remote, see
1044 1045 outgoing)
1045 1046 """
1046 1047 m = self.changelog.nodemap
1047 1048 search = []
1048 1049 fetch = {}
1049 1050 seen = {}
1050 1051 seenbranch = {}
1051 1052 if base == None:
1052 1053 base = {}
1053 1054
1054 1055 if not heads:
1055 1056 heads = remote.heads()
1056 1057
1057 1058 if self.changelog.tip() == nullid:
1058 1059 base[nullid] = 1
1059 1060 if heads != [nullid]:
1060 1061 return [nullid]
1061 1062 return []
1062 1063
1063 1064 # assume we're closer to the tip than the root
1064 1065 # and start by examining the heads
1065 1066 self.ui.status(_("searching for changes\n"))
1066 1067
1067 1068 unknown = []
1068 1069 for h in heads:
1069 1070 if h not in m:
1070 1071 unknown.append(h)
1071 1072 else:
1072 1073 base[h] = 1
1073 1074
1074 1075 if not unknown:
1075 1076 return []
1076 1077
1077 1078 req = dict.fromkeys(unknown)
1078 1079 reqcnt = 0
1079 1080
1080 1081 # search through remote branches
1081 1082 # a 'branch' here is a linear segment of history, with four parts:
1082 1083 # head, root, first parent, second parent
1083 1084 # (a branch always has two parents (or none) by definition)
1084 1085 unknown = remote.branches(unknown)
1085 1086 while unknown:
1086 1087 r = []
1087 1088 while unknown:
1088 1089 n = unknown.pop(0)
1089 1090 if n[0] in seen:
1090 1091 continue
1091 1092
1092 1093 self.ui.debug(_("examining %s:%s\n")
1093 1094 % (short(n[0]), short(n[1])))
1094 1095 if n[0] == nullid: # found the end of the branch
1095 1096 pass
1096 1097 elif n in seenbranch:
1097 1098 self.ui.debug(_("branch already found\n"))
1098 1099 continue
1099 1100 elif n[1] and n[1] in m: # do we know the base?
1100 1101 self.ui.debug(_("found incomplete branch %s:%s\n")
1101 1102 % (short(n[0]), short(n[1])))
1102 1103 search.append(n) # schedule branch range for scanning
1103 1104 seenbranch[n] = 1
1104 1105 else:
1105 1106 if n[1] not in seen and n[1] not in fetch:
1106 1107 if n[2] in m and n[3] in m:
1107 1108 self.ui.debug(_("found new changeset %s\n") %
1108 1109 short(n[1]))
1109 1110 fetch[n[1]] = 1 # earliest unknown
1110 1111 for p in n[2:4]:
1111 1112 if p in m:
1112 1113 base[p] = 1 # latest known
1113 1114
1114 1115 for p in n[2:4]:
1115 1116 if p not in req and p not in m:
1116 1117 r.append(p)
1117 1118 req[p] = 1
1118 1119 seen[n[0]] = 1
1119 1120
1120 1121 if r:
1121 1122 reqcnt += 1
1122 1123 self.ui.debug(_("request %d: %s\n") %
1123 1124 (reqcnt, " ".join(map(short, r))))
1124 1125 for p in xrange(0, len(r), 10):
1125 1126 for b in remote.branches(r[p:p+10]):
1126 1127 self.ui.debug(_("received %s:%s\n") %
1127 1128 (short(b[0]), short(b[1])))
1128 1129 unknown.append(b)
1129 1130
1130 1131 # do binary search on the branches we found
1131 1132 while search:
1132 1133 n = search.pop(0)
1133 1134 reqcnt += 1
1134 1135 l = remote.between([(n[0], n[1])])[0]
1135 1136 l.append(n[1])
1136 1137 p = n[0]
1137 1138 f = 1
1138 1139 for i in l:
1139 1140 self.ui.debug(_("narrowing %d:%d %s\n") % (f, len(l), short(i)))
1140 1141 if i in m:
1141 1142 if f <= 2:
1142 1143 self.ui.debug(_("found new branch changeset %s\n") %
1143 1144 short(p))
1144 1145 fetch[p] = 1
1145 1146 base[i] = 1
1146 1147 else:
1147 1148 self.ui.debug(_("narrowed branch search to %s:%s\n")
1148 1149 % (short(p), short(i)))
1149 1150 search.append((p, i))
1150 1151 break
1151 1152 p, f = i, f * 2
1152 1153
1153 1154 # sanity check our fetch list
1154 1155 for f in fetch.keys():
1155 1156 if f in m:
1156 1157 raise repo.RepoError(_("already have changeset ") + short(f[:4]))
1157 1158
1158 1159 if base.keys() == [nullid]:
1159 1160 if force:
1160 1161 self.ui.warn(_("warning: repository is unrelated\n"))
1161 1162 else:
1162 1163 raise util.Abort(_("repository is unrelated"))
1163 1164
1164 1165 self.ui.debug(_("found new changesets starting at ") +
1165 1166 " ".join([short(f) for f in fetch]) + "\n")
1166 1167
1167 1168 self.ui.debug(_("%d total queries\n") % reqcnt)
1168 1169
1169 1170 return fetch.keys()
1170 1171
1171 1172 def findoutgoing(self, remote, base=None, heads=None, force=False):
1172 1173 """Return list of nodes that are roots of subsets not in remote
1173 1174
1174 1175 If base dict is specified, assume that these nodes and their parents
1175 1176 exist on the remote side.
1176 1177 If a list of heads is specified, return only nodes which are heads
1177 1178 or ancestors of these heads, and return a second element which
1178 1179 contains all remote heads which get new children.
1179 1180 """
1180 1181 if base == None:
1181 1182 base = {}
1182 1183 self.findincoming(remote, base, heads, force=force)
1183 1184
1184 1185 self.ui.debug(_("common changesets up to ")
1185 1186 + " ".join(map(short, base.keys())) + "\n")
1186 1187
1187 1188 remain = dict.fromkeys(self.changelog.nodemap)
1188 1189
1189 1190 # prune everything remote has from the tree
1190 1191 del remain[nullid]
1191 1192 remove = base.keys()
1192 1193 while remove:
1193 1194 n = remove.pop(0)
1194 1195 if n in remain:
1195 1196 del remain[n]
1196 1197 for p in self.changelog.parents(n):
1197 1198 remove.append(p)
1198 1199
1199 1200 # find every node whose parents have been pruned
1200 1201 subset = []
1201 1202 # find every remote head that will get new children
1202 1203 updated_heads = {}
1203 1204 for n in remain:
1204 1205 p1, p2 = self.changelog.parents(n)
1205 1206 if p1 not in remain and p2 not in remain:
1206 1207 subset.append(n)
1207 1208 if heads:
1208 1209 if p1 in heads:
1209 1210 updated_heads[p1] = True
1210 1211 if p2 in heads:
1211 1212 updated_heads[p2] = True
1212 1213
1213 1214 # this is the set of all roots we have to push
1214 1215 if heads:
1215 1216 return subset, updated_heads.keys()
1216 1217 else:
1217 1218 return subset
1218 1219
1219 1220 def pull(self, remote, heads=None, force=False, lock=None):
1220 1221 mylock = False
1221 1222 if not lock:
1222 1223 lock = self.lock()
1223 1224 mylock = True
1224 1225
1225 1226 try:
1226 1227 fetch = self.findincoming(remote, force=force)
1227 1228 if fetch == [nullid]:
1228 1229 self.ui.status(_("requesting all changes\n"))
1229 1230
1230 1231 if not fetch:
1231 1232 self.ui.status(_("no changes found\n"))
1232 1233 return 0
1233 1234
1234 1235 if heads is None:
1235 1236 cg = remote.changegroup(fetch, 'pull')
1236 1237 else:
1237 1238 if 'changegroupsubset' not in remote.capabilities:
1238 1239 raise util.Abort(_("Partial pull cannot be done because other repository doesn't support changegroupsubset."))
1239 1240 cg = remote.changegroupsubset(fetch, heads, 'pull')
1240 1241 return self.addchangegroup(cg, 'pull', remote.url())
1241 1242 finally:
1242 1243 if mylock:
1243 1244 lock.release()
1244 1245
1245 1246 def push(self, remote, force=False, revs=None):
1246 1247 # there are two ways to push to remote repo:
1247 1248 #
1248 1249 # addchangegroup assumes local user can lock remote
1249 1250 # repo (local filesystem, old ssh servers).
1250 1251 #
1251 1252 # unbundle assumes local user cannot lock remote repo (new ssh
1252 1253 # servers, http servers).
1253 1254
1254 1255 if remote.capable('unbundle'):
1255 1256 return self.push_unbundle(remote, force, revs)
1256 1257 return self.push_addchangegroup(remote, force, revs)
1257 1258
1258 1259 def prepush(self, remote, force, revs):
1259 1260 base = {}
1260 1261 remote_heads = remote.heads()
1261 1262 inc = self.findincoming(remote, base, remote_heads, force=force)
1262 1263
1263 1264 update, updated_heads = self.findoutgoing(remote, base, remote_heads)
1264 1265 if revs is not None:
1265 1266 msng_cl, bases, heads = self.changelog.nodesbetween(update, revs)
1266 1267 else:
1267 1268 bases, heads = update, self.changelog.heads()
1268 1269
1269 1270 if not bases:
1270 1271 self.ui.status(_("no changes found\n"))
1271 1272 return None, 1
1272 1273 elif not force:
1273 1274 # check if we're creating new remote heads
1274 1275 # to be a remote head after push, node must be either
1275 1276 # - unknown locally
1276 1277 # - a local outgoing head descended from update
1277 1278 # - a remote head that's known locally and not
1278 1279 # ancestral to an outgoing head
1279 1280
1280 1281 warn = 0
1281 1282
1282 1283 if remote_heads == [nullid]:
1283 1284 warn = 0
1284 1285 elif not revs and len(heads) > len(remote_heads):
1285 1286 warn = 1
1286 1287 else:
1287 1288 newheads = list(heads)
1288 1289 for r in remote_heads:
1289 1290 if r in self.changelog.nodemap:
1290 1291 desc = self.changelog.heads(r, heads)
1291 1292 l = [h for h in heads if h in desc]
1292 1293 if not l:
1293 1294 newheads.append(r)
1294 1295 else:
1295 1296 newheads.append(r)
1296 1297 if len(newheads) > len(remote_heads):
1297 1298 warn = 1
1298 1299
1299 1300 if warn:
1300 1301 self.ui.warn(_("abort: push creates new remote branches!\n"))
1301 1302 self.ui.status(_("(did you forget to merge?"
1302 1303 " use push -f to force)\n"))
1303 1304 return None, 1
1304 1305 elif inc:
1305 1306 self.ui.warn(_("note: unsynced remote changes!\n"))
1306 1307
1307 1308
1308 1309 if revs is None:
1309 1310 cg = self.changegroup(update, 'push')
1310 1311 else:
1311 1312 cg = self.changegroupsubset(update, revs, 'push')
1312 1313 return cg, remote_heads
1313 1314
1314 1315 def push_addchangegroup(self, remote, force, revs):
1315 1316 lock = remote.lock()
1316 1317
1317 1318 ret = self.prepush(remote, force, revs)
1318 1319 if ret[0] is not None:
1319 1320 cg, remote_heads = ret
1320 1321 return remote.addchangegroup(cg, 'push', self.url())
1321 1322 return ret[1]
1322 1323
1323 1324 def push_unbundle(self, remote, force, revs):
1324 1325 # local repo finds heads on server, finds out what revs it
1325 1326 # must push. once revs transferred, if server finds it has
1326 1327 # different heads (someone else won commit/push race), server
1327 1328 # aborts.
1328 1329
1329 1330 ret = self.prepush(remote, force, revs)
1330 1331 if ret[0] is not None:
1331 1332 cg, remote_heads = ret
1332 1333 if force: remote_heads = ['force']
1333 1334 return remote.unbundle(cg, remote_heads, 'push')
1334 1335 return ret[1]
1335 1336
1336 1337 def changegroupinfo(self, nodes):
1337 1338 self.ui.note(_("%d changesets found\n") % len(nodes))
1338 1339 if self.ui.debugflag:
1339 1340 self.ui.debug(_("List of changesets:\n"))
1340 1341 for node in nodes:
1341 1342 self.ui.debug("%s\n" % hex(node))
1342 1343
1343 1344 def changegroupsubset(self, bases, heads, source):
1344 1345 """This function generates a changegroup consisting of all the nodes
1345 1346 that are descendents of any of the bases, and ancestors of any of
1346 1347 the heads.
1347 1348
1348 1349 It is fairly complex as determining which filenodes and which
1349 1350 manifest nodes need to be included for the changeset to be complete
1350 1351 is non-trivial.
1351 1352
1352 1353 Another wrinkle is doing the reverse, figuring out which changeset in
1353 1354 the changegroup a particular filenode or manifestnode belongs to."""
1354 1355
1355 1356 self.hook('preoutgoing', throw=True, source=source)
1356 1357
1357 1358 # Set up some initial variables
1358 1359 # Make it easy to refer to self.changelog
1359 1360 cl = self.changelog
1360 1361 # msng is short for missing - compute the list of changesets in this
1361 1362 # changegroup.
1362 1363 msng_cl_lst, bases, heads = cl.nodesbetween(bases, heads)
1363 1364 self.changegroupinfo(msng_cl_lst)
1364 1365 # Some bases may turn out to be superfluous, and some heads may be
1365 1366 # too. nodesbetween will return the minimal set of bases and heads
1366 1367 # necessary to re-create the changegroup.
1367 1368
1368 1369 # Known heads are the list of heads that it is assumed the recipient
1369 1370 # of this changegroup will know about.
1370 1371 knownheads = {}
1371 1372 # We assume that all parents of bases are known heads.
1372 1373 for n in bases:
1373 1374 for p in cl.parents(n):
1374 1375 if p != nullid:
1375 1376 knownheads[p] = 1
1376 1377 knownheads = knownheads.keys()
1377 1378 if knownheads:
1378 1379 # Now that we know what heads are known, we can compute which
1379 1380 # changesets are known. The recipient must know about all
1380 1381 # changesets required to reach the known heads from the null
1381 1382 # changeset.
1382 1383 has_cl_set, junk, junk = cl.nodesbetween(None, knownheads)
1383 1384 junk = None
1384 1385 # Transform the list into an ersatz set.
1385 1386 has_cl_set = dict.fromkeys(has_cl_set)
1386 1387 else:
1387 1388 # If there were no known heads, the recipient cannot be assumed to
1388 1389 # know about any changesets.
1389 1390 has_cl_set = {}
1390 1391
1391 1392 # Make it easy to refer to self.manifest
1392 1393 mnfst = self.manifest
1393 1394 # We don't know which manifests are missing yet
1394 1395 msng_mnfst_set = {}
1395 1396 # Nor do we know which filenodes are missing.
1396 1397 msng_filenode_set = {}
1397 1398
1398 1399 junk = mnfst.index[mnfst.count() - 1] # Get around a bug in lazyindex
1399 1400 junk = None
1400 1401
1401 1402 # A changeset always belongs to itself, so the changenode lookup
1402 1403 # function for a changenode is identity.
1403 1404 def identity(x):
1404 1405 return x
1405 1406
1406 1407 # A function generating function. Sets up an environment for the
1407 1408 # inner function.
1408 1409 def cmp_by_rev_func(revlog):
1409 1410 # Compare two nodes by their revision number in the environment's
1410 1411 # revision history. Since the revision number both represents the
1411 1412 # most efficient order to read the nodes in, and represents a
1412 1413 # topological sorting of the nodes, this function is often useful.
1413 1414 def cmp_by_rev(a, b):
1414 1415 return cmp(revlog.rev(a), revlog.rev(b))
1415 1416 return cmp_by_rev
1416 1417
1417 1418 # If we determine that a particular file or manifest node must be a
1418 1419 # node that the recipient of the changegroup will already have, we can
1419 1420 # also assume the recipient will have all the parents. This function
1420 1421 # prunes them from the set of missing nodes.
1421 1422 def prune_parents(revlog, hasset, msngset):
1422 1423 haslst = hasset.keys()
1423 1424 haslst.sort(cmp_by_rev_func(revlog))
1424 1425 for node in haslst:
1425 1426 parentlst = [p for p in revlog.parents(node) if p != nullid]
1426 1427 while parentlst:
1427 1428 n = parentlst.pop()
1428 1429 if n not in hasset:
1429 1430 hasset[n] = 1
1430 1431 p = [p for p in revlog.parents(n) if p != nullid]
1431 1432 parentlst.extend(p)
1432 1433 for n in hasset:
1433 1434 msngset.pop(n, None)
1434 1435
1435 1436 # This is a function generating function used to set up an environment
1436 1437 # for the inner function to execute in.
1437 1438 def manifest_and_file_collector(changedfileset):
1438 1439 # This is an information gathering function that gathers
1439 1440 # information from each changeset node that goes out as part of
1440 1441 # the changegroup. The information gathered is a list of which
1441 1442 # manifest nodes are potentially required (the recipient may
1442 1443 # already have them) and total list of all files which were
1443 1444 # changed in any changeset in the changegroup.
1444 1445 #
1445 1446 # We also remember the first changenode we saw any manifest
1446 1447 # referenced by so we can later determine which changenode 'owns'
1447 1448 # the manifest.
1448 1449 def collect_manifests_and_files(clnode):
1449 1450 c = cl.read(clnode)
1450 1451 for f in c[3]:
1451 1452 # This is to make sure we only have one instance of each
1452 1453 # filename string for each filename.
1453 1454 changedfileset.setdefault(f, f)
1454 1455 msng_mnfst_set.setdefault(c[0], clnode)
1455 1456 return collect_manifests_and_files
1456 1457
1457 1458 # Figure out which manifest nodes (of the ones we think might be part
1458 1459 # of the changegroup) the recipient must know about and remove them
1459 1460 # from the changegroup.
1460 1461 def prune_manifests():
1461 1462 has_mnfst_set = {}
1462 1463 for n in msng_mnfst_set:
1463 1464 # If a 'missing' manifest thinks it belongs to a changenode
1464 1465 # the recipient is assumed to have, obviously the recipient
1465 1466 # must have that manifest.
1466 1467 linknode = cl.node(mnfst.linkrev(n))
1467 1468 if linknode in has_cl_set:
1468 1469 has_mnfst_set[n] = 1
1469 1470 prune_parents(mnfst, has_mnfst_set, msng_mnfst_set)
1470 1471
1471 1472 # Use the information collected in collect_manifests_and_files to say
1472 1473 # which changenode any manifestnode belongs to.
1473 1474 def lookup_manifest_link(mnfstnode):
1474 1475 return msng_mnfst_set[mnfstnode]
1475 1476
1476 1477 # A function generating function that sets up the initial environment
1477 1478 # the inner function.
1478 1479 def filenode_collector(changedfiles):
1479 1480 next_rev = [0]
1480 1481 # This gathers information from each manifestnode included in the
1481 1482 # changegroup about which filenodes the manifest node references
1482 1483 # so we can include those in the changegroup too.
1483 1484 #
1484 1485 # It also remembers which changenode each filenode belongs to. It
1485 1486 # does this by assuming the a filenode belongs to the changenode
1486 1487 # the first manifest that references it belongs to.
1487 1488 def collect_msng_filenodes(mnfstnode):
1488 1489 r = mnfst.rev(mnfstnode)
1489 1490 if r == next_rev[0]:
1490 1491 # If the last rev we looked at was the one just previous,
1491 1492 # we only need to see a diff.
1492 1493 delta = mdiff.patchtext(mnfst.delta(mnfstnode))
1493 1494 # For each line in the delta
1494 1495 for dline in delta.splitlines():
1495 1496 # get the filename and filenode for that line
1496 1497 f, fnode = dline.split('\0')
1497 1498 fnode = bin(fnode[:40])
1498 1499 f = changedfiles.get(f, None)
1499 1500 # And if the file is in the list of files we care
1500 1501 # about.
1501 1502 if f is not None:
1502 1503 # Get the changenode this manifest belongs to
1503 1504 clnode = msng_mnfst_set[mnfstnode]
1504 1505 # Create the set of filenodes for the file if
1505 1506 # there isn't one already.
1506 1507 ndset = msng_filenode_set.setdefault(f, {})
1507 1508 # And set the filenode's changelog node to the
1508 1509 # manifest's if it hasn't been set already.
1509 1510 ndset.setdefault(fnode, clnode)
1510 1511 else:
1511 1512 # Otherwise we need a full manifest.
1512 1513 m = mnfst.read(mnfstnode)
1513 1514 # For every file in we care about.
1514 1515 for f in changedfiles:
1515 1516 fnode = m.get(f, None)
1516 1517 # If it's in the manifest
1517 1518 if fnode is not None:
1518 1519 # See comments above.
1519 1520 clnode = msng_mnfst_set[mnfstnode]
1520 1521 ndset = msng_filenode_set.setdefault(f, {})
1521 1522 ndset.setdefault(fnode, clnode)
1522 1523 # Remember the revision we hope to see next.
1523 1524 next_rev[0] = r + 1
1524 1525 return collect_msng_filenodes
1525 1526
1526 1527 # We have a list of filenodes we think we need for a file, lets remove
1527 1528 # all those we now the recipient must have.
1528 1529 def prune_filenodes(f, filerevlog):
1529 1530 msngset = msng_filenode_set[f]
1530 1531 hasset = {}
1531 1532 # If a 'missing' filenode thinks it belongs to a changenode we
1532 1533 # assume the recipient must have, then the recipient must have
1533 1534 # that filenode.
1534 1535 for n in msngset:
1535 1536 clnode = cl.node(filerevlog.linkrev(n))
1536 1537 if clnode in has_cl_set:
1537 1538 hasset[n] = 1
1538 1539 prune_parents(filerevlog, hasset, msngset)
1539 1540
1540 1541 # A function generator function that sets up the a context for the
1541 1542 # inner function.
1542 1543 def lookup_filenode_link_func(fname):
1543 1544 msngset = msng_filenode_set[fname]
1544 1545 # Lookup the changenode the filenode belongs to.
1545 1546 def lookup_filenode_link(fnode):
1546 1547 return msngset[fnode]
1547 1548 return lookup_filenode_link
1548 1549
1549 1550 # Now that we have all theses utility functions to help out and
1550 1551 # logically divide up the task, generate the group.
1551 1552 def gengroup():
1552 1553 # The set of changed files starts empty.
1553 1554 changedfiles = {}
1554 1555 # Create a changenode group generator that will call our functions
1555 1556 # back to lookup the owning changenode and collect information.
1556 1557 group = cl.group(msng_cl_lst, identity,
1557 1558 manifest_and_file_collector(changedfiles))
1558 1559 for chnk in group:
1559 1560 yield chnk
1560 1561
1561 1562 # The list of manifests has been collected by the generator
1562 1563 # calling our functions back.
1563 1564 prune_manifests()
1564 1565 msng_mnfst_lst = msng_mnfst_set.keys()
1565 1566 # Sort the manifestnodes by revision number.
1566 1567 msng_mnfst_lst.sort(cmp_by_rev_func(mnfst))
1567 1568 # Create a generator for the manifestnodes that calls our lookup
1568 1569 # and data collection functions back.
1569 1570 group = mnfst.group(msng_mnfst_lst, lookup_manifest_link,
1570 1571 filenode_collector(changedfiles))
1571 1572 for chnk in group:
1572 1573 yield chnk
1573 1574
1574 1575 # These are no longer needed, dereference and toss the memory for
1575 1576 # them.
1576 1577 msng_mnfst_lst = None
1577 1578 msng_mnfst_set.clear()
1578 1579
1579 1580 changedfiles = changedfiles.keys()
1580 1581 changedfiles.sort()
1581 1582 # Go through all our files in order sorted by name.
1582 1583 for fname in changedfiles:
1583 1584 filerevlog = self.file(fname)
1584 1585 # Toss out the filenodes that the recipient isn't really
1585 1586 # missing.
1586 1587 if msng_filenode_set.has_key(fname):
1587 1588 prune_filenodes(fname, filerevlog)
1588 1589 msng_filenode_lst = msng_filenode_set[fname].keys()
1589 1590 else:
1590 1591 msng_filenode_lst = []
1591 1592 # If any filenodes are left, generate the group for them,
1592 1593 # otherwise don't bother.
1593 1594 if len(msng_filenode_lst) > 0:
1594 1595 yield changegroup.genchunk(fname)
1595 1596 # Sort the filenodes by their revision #
1596 1597 msng_filenode_lst.sort(cmp_by_rev_func(filerevlog))
1597 1598 # Create a group generator and only pass in a changenode
1598 1599 # lookup function as we need to collect no information
1599 1600 # from filenodes.
1600 1601 group = filerevlog.group(msng_filenode_lst,
1601 1602 lookup_filenode_link_func(fname))
1602 1603 for chnk in group:
1603 1604 yield chnk
1604 1605 if msng_filenode_set.has_key(fname):
1605 1606 # Don't need this anymore, toss it to free memory.
1606 1607 del msng_filenode_set[fname]
1607 1608 # Signal that no more groups are left.
1608 1609 yield changegroup.closechunk()
1609 1610
1610 1611 if msng_cl_lst:
1611 1612 self.hook('outgoing', node=hex(msng_cl_lst[0]), source=source)
1612 1613
1613 1614 return util.chunkbuffer(gengroup())
1614 1615
1615 1616 def changegroup(self, basenodes, source):
1616 1617 """Generate a changegroup of all nodes that we have that a recipient
1617 1618 doesn't.
1618 1619
1619 1620 This is much easier than the previous function as we can assume that
1620 1621 the recipient has any changenode we aren't sending them."""
1621 1622
1622 1623 self.hook('preoutgoing', throw=True, source=source)
1623 1624
1624 1625 cl = self.changelog
1625 1626 nodes = cl.nodesbetween(basenodes, None)[0]
1626 1627 revset = dict.fromkeys([cl.rev(n) for n in nodes])
1627 1628 self.changegroupinfo(nodes)
1628 1629
1629 1630 def identity(x):
1630 1631 return x
1631 1632
1632 1633 def gennodelst(revlog):
1633 1634 for r in xrange(0, revlog.count()):
1634 1635 n = revlog.node(r)
1635 1636 if revlog.linkrev(n) in revset:
1636 1637 yield n
1637 1638
1638 1639 def changed_file_collector(changedfileset):
1639 1640 def collect_changed_files(clnode):
1640 1641 c = cl.read(clnode)
1641 1642 for fname in c[3]:
1642 1643 changedfileset[fname] = 1
1643 1644 return collect_changed_files
1644 1645
1645 1646 def lookuprevlink_func(revlog):
1646 1647 def lookuprevlink(n):
1647 1648 return cl.node(revlog.linkrev(n))
1648 1649 return lookuprevlink
1649 1650
1650 1651 def gengroup():
1651 1652 # construct a list of all changed files
1652 1653 changedfiles = {}
1653 1654
1654 1655 for chnk in cl.group(nodes, identity,
1655 1656 changed_file_collector(changedfiles)):
1656 1657 yield chnk
1657 1658 changedfiles = changedfiles.keys()
1658 1659 changedfiles.sort()
1659 1660
1660 1661 mnfst = self.manifest
1661 1662 nodeiter = gennodelst(mnfst)
1662 1663 for chnk in mnfst.group(nodeiter, lookuprevlink_func(mnfst)):
1663 1664 yield chnk
1664 1665
1665 1666 for fname in changedfiles:
1666 1667 filerevlog = self.file(fname)
1667 1668 nodeiter = gennodelst(filerevlog)
1668 1669 nodeiter = list(nodeiter)
1669 1670 if nodeiter:
1670 1671 yield changegroup.genchunk(fname)
1671 1672 lookup = lookuprevlink_func(filerevlog)
1672 1673 for chnk in filerevlog.group(nodeiter, lookup):
1673 1674 yield chnk
1674 1675
1675 1676 yield changegroup.closechunk()
1676 1677
1677 1678 if nodes:
1678 1679 self.hook('outgoing', node=hex(nodes[0]), source=source)
1679 1680
1680 1681 return util.chunkbuffer(gengroup())
1681 1682
1682 1683 def addchangegroup(self, source, srctype, url):
1683 1684 """add changegroup to repo.
1684 1685
1685 1686 return values:
1686 1687 - nothing changed or no source: 0
1687 1688 - more heads than before: 1+added heads (2..n)
1688 1689 - less heads than before: -1-removed heads (-2..-n)
1689 1690 - number of heads stays the same: 1
1690 1691 """
1691 1692 def csmap(x):
1692 1693 self.ui.debug(_("add changeset %s\n") % short(x))
1693 1694 return cl.count()
1694 1695
1695 1696 def revmap(x):
1696 1697 return cl.rev(x)
1697 1698
1698 1699 if not source:
1699 1700 return 0
1700 1701
1701 1702 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1702 1703
1703 1704 changesets = files = revisions = 0
1704 1705
1705 1706 tr = self.transaction()
1706 1707
1707 1708 # write changelog data to temp files so concurrent readers will not see
1708 1709 # inconsistent view
1709 1710 cl = None
1710 1711 try:
1711 1712 cl = appendfile.appendchangelog(self.sopener,
1712 1713 self.changelog.version)
1713 1714
1714 1715 oldheads = len(cl.heads())
1715 1716
1716 1717 # pull off the changeset group
1717 1718 self.ui.status(_("adding changesets\n"))
1718 1719 cor = cl.count() - 1
1719 1720 chunkiter = changegroup.chunkiter(source)
1720 1721 if cl.addgroup(chunkiter, csmap, tr, 1) is None:
1721 1722 raise util.Abort(_("received changelog group is empty"))
1722 1723 cnr = cl.count() - 1
1723 1724 changesets = cnr - cor
1724 1725
1725 1726 # pull off the manifest group
1726 1727 self.ui.status(_("adding manifests\n"))
1727 1728 chunkiter = changegroup.chunkiter(source)
1728 1729 # no need to check for empty manifest group here:
1729 1730 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1730 1731 # no new manifest will be created and the manifest group will
1731 1732 # be empty during the pull
1732 1733 self.manifest.addgroup(chunkiter, revmap, tr)
1733 1734
1734 1735 # process the files
1735 1736 self.ui.status(_("adding file changes\n"))
1736 1737 while 1:
1737 1738 f = changegroup.getchunk(source)
1738 1739 if not f:
1739 1740 break
1740 1741 self.ui.debug(_("adding %s revisions\n") % f)
1741 1742 fl = self.file(f)
1742 1743 o = fl.count()
1743 1744 chunkiter = changegroup.chunkiter(source)
1744 1745 if fl.addgroup(chunkiter, revmap, tr) is None:
1745 1746 raise util.Abort(_("received file revlog group is empty"))
1746 1747 revisions += fl.count() - o
1747 1748 files += 1
1748 1749
1749 1750 cl.writedata()
1750 1751 finally:
1751 1752 if cl:
1752 1753 cl.cleanup()
1753 1754
1754 1755 # make changelog see real files again
1755 1756 self.changelog = changelog.changelog(self.sopener,
1756 1757 self.changelog.version)
1757 1758 self.changelog.checkinlinesize(tr)
1758 1759
1759 1760 newheads = len(self.changelog.heads())
1760 1761 heads = ""
1761 1762 if oldheads and newheads != oldheads:
1762 1763 heads = _(" (%+d heads)") % (newheads - oldheads)
1763 1764
1764 1765 self.ui.status(_("added %d changesets"
1765 1766 " with %d changes to %d files%s\n")
1766 1767 % (changesets, revisions, files, heads))
1767 1768
1768 1769 if changesets > 0:
1769 1770 self.hook('pretxnchangegroup', throw=True,
1770 1771 node=hex(self.changelog.node(cor+1)), source=srctype,
1771 1772 url=url)
1772 1773
1773 1774 tr.close()
1774 1775
1775 1776 if changesets > 0:
1776 1777 self.hook("changegroup", node=hex(self.changelog.node(cor+1)),
1777 1778 source=srctype, url=url)
1778 1779
1779 1780 for i in xrange(cor + 1, cnr + 1):
1780 1781 self.hook("incoming", node=hex(self.changelog.node(i)),
1781 1782 source=srctype, url=url)
1782 1783
1783 1784 # never return 0 here:
1784 1785 if newheads < oldheads:
1785 1786 return newheads - oldheads - 1
1786 1787 else:
1787 1788 return newheads - oldheads + 1
1788 1789
1789 1790
1790 1791 def stream_in(self, remote):
1791 1792 fp = remote.stream_out()
1792 1793 l = fp.readline()
1793 1794 try:
1794 1795 resp = int(l)
1795 1796 except ValueError:
1796 1797 raise util.UnexpectedOutput(
1797 1798 _('Unexpected response from remote server:'), l)
1798 1799 if resp == 1:
1799 1800 raise util.Abort(_('operation forbidden by server'))
1800 1801 elif resp == 2:
1801 1802 raise util.Abort(_('locking the remote repository failed'))
1802 1803 elif resp != 0:
1803 1804 raise util.Abort(_('the server sent an unknown error code'))
1804 1805 self.ui.status(_('streaming all changes\n'))
1805 1806 l = fp.readline()
1806 1807 try:
1807 1808 total_files, total_bytes = map(int, l.split(' ', 1))
1808 1809 except ValueError, TypeError:
1809 1810 raise util.UnexpectedOutput(
1810 1811 _('Unexpected response from remote server:'), l)
1811 1812 self.ui.status(_('%d files to transfer, %s of data\n') %
1812 1813 (total_files, util.bytecount(total_bytes)))
1813 1814 start = time.time()
1814 1815 for i in xrange(total_files):
1815 1816 # XXX doesn't support '\n' or '\r' in filenames
1816 1817 l = fp.readline()
1817 1818 try:
1818 1819 name, size = l.split('\0', 1)
1819 1820 size = int(size)
1820 1821 except ValueError, TypeError:
1821 1822 raise util.UnexpectedOutput(
1822 1823 _('Unexpected response from remote server:'), l)
1823 1824 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
1824 1825 ofp = self.sopener(name, 'w')
1825 1826 for chunk in util.filechunkiter(fp, limit=size):
1826 1827 ofp.write(chunk)
1827 1828 ofp.close()
1828 1829 elapsed = time.time() - start
1829 1830 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1830 1831 (util.bytecount(total_bytes), elapsed,
1831 1832 util.bytecount(total_bytes / elapsed)))
1832 1833 self.reload()
1833 1834 return len(self.heads()) + 1
1834 1835
1835 1836 def clone(self, remote, heads=[], stream=False):
1836 1837 '''clone remote repository.
1837 1838
1838 1839 keyword arguments:
1839 1840 heads: list of revs to clone (forces use of pull)
1840 1841 stream: use streaming clone if possible'''
1841 1842
1842 1843 # now, all clients that can request uncompressed clones can
1843 1844 # read repo formats supported by all servers that can serve
1844 1845 # them.
1845 1846
1846 1847 # if revlog format changes, client will have to check version
1847 1848 # and format flags on "stream" capability, and use
1848 1849 # uncompressed only if compatible.
1849 1850
1850 1851 if stream and not heads and remote.capable('stream'):
1851 1852 return self.stream_in(remote)
1852 1853 return self.pull(remote, heads)
1853 1854
1854 1855 # used to avoid circular references so destructors work
1855 1856 def aftertrans(files):
1856 1857 renamefiles = [tuple(t) for t in files]
1857 1858 def a():
1858 1859 for src, dest in renamefiles:
1859 1860 util.rename(src, dest)
1860 1861 return a
1861 1862
1862 1863 def instance(ui, path, create):
1863 1864 return localrepository(ui, util.drop_scheme('file', path), create)
1864 1865
1865 1866 def islocal(path):
1866 1867 return True
@@ -1,497 +1,498 b''
1 1 # merge.py - directory-level update/merge handling for Mercurial
2 2 #
3 3 # Copyright 2006 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7
8 8 from node import *
9 9 from i18n import _
10 10 import errno, util, os, tempfile
11 11
12 12 def filemerge(repo, fw, fo, wctx, mctx):
13 13 """perform a 3-way merge in the working directory
14 14
15 15 fw = filename in the working directory
16 16 fo = filename in other parent
17 17 wctx, mctx = working and merge changecontexts
18 18 """
19 19
20 20 def temp(prefix, ctx):
21 21 pre = "%s~%s." % (os.path.basename(ctx.path()), prefix)
22 22 (fd, name) = tempfile.mkstemp(prefix=pre)
23 data = repo.wwritedata(ctx.path(), ctx.data())
23 24 f = os.fdopen(fd, "wb")
24 repo.wwrite(ctx.path(), ctx.data(), f)
25 f.write(data)
25 26 f.close()
26 27 return name
27 28
28 29 fcm = wctx.filectx(fw)
29 30 fco = mctx.filectx(fo)
30 31
31 32 if not fco.cmp(fcm.data()): # files identical?
32 33 return None
33 34
34 35 fca = fcm.ancestor(fco)
35 36 if not fca:
36 37 fca = repo.filectx(fw, fileid=nullrev)
37 38 a = repo.wjoin(fw)
38 39 b = temp("base", fca)
39 40 c = temp("other", fco)
40 41
41 42 if fw != fo:
42 43 repo.ui.status(_("merging %s and %s\n") % (fw, fo))
43 44 else:
44 45 repo.ui.status(_("merging %s\n") % fw)
45 46
46 47 repo.ui.debug(_("my %s other %s ancestor %s\n") % (fcm, fco, fca))
47 48
48 49 cmd = (os.environ.get("HGMERGE") or repo.ui.config("ui", "merge")
49 50 or "hgmerge")
50 51 r = util.system('%s "%s" "%s" "%s"' % (cmd, a, b, c), cwd=repo.root,
51 52 environ={'HG_FILE': fw,
52 53 'HG_MY_NODE': str(wctx.parents()[0]),
53 54 'HG_OTHER_NODE': str(mctx)})
54 55 if r:
55 56 repo.ui.warn(_("merging %s failed!\n") % fw)
56 57
57 58 os.unlink(b)
58 59 os.unlink(c)
59 60 return r
60 61
61 62 def checkunknown(wctx, mctx):
62 63 "check for collisions between unknown files and files in mctx"
63 64 man = mctx.manifest()
64 65 for f in wctx.unknown():
65 66 if f in man:
66 67 if mctx.filectx(f).cmp(wctx.filectx(f).data()):
67 68 raise util.Abort(_("untracked local file '%s' differs"\
68 69 " from remote version") % f)
69 70
70 71 def checkcollision(mctx):
71 72 "check for case folding collisions in the destination context"
72 73 folded = {}
73 74 for fn in mctx.manifest():
74 75 fold = fn.lower()
75 76 if fold in folded:
76 77 raise util.Abort(_("case-folding collision between %s and %s")
77 78 % (fn, folded[fold]))
78 79 folded[fold] = fn
79 80
80 81 def forgetremoved(wctx, mctx):
81 82 """
82 83 Forget removed files
83 84
84 85 If we're jumping between revisions (as opposed to merging), and if
85 86 neither the working directory nor the target rev has the file,
86 87 then we need to remove it from the dirstate, to prevent the
87 88 dirstate from listing the file when it is no longer in the
88 89 manifest.
89 90 """
90 91
91 92 action = []
92 93 man = mctx.manifest()
93 94 for f in wctx.deleted() + wctx.removed():
94 95 if f not in man:
95 96 action.append((f, "f"))
96 97
97 98 return action
98 99
99 100 def findcopies(repo, m1, m2, ma, limit):
100 101 """
101 102 Find moves and copies between m1 and m2 back to limit linkrev
102 103 """
103 104
104 105 def findold(fctx):
105 106 "find files that path was copied from, back to linkrev limit"
106 107 old = {}
107 108 orig = fctx.path()
108 109 visit = [fctx]
109 110 while visit:
110 111 fc = visit.pop()
111 112 if fc.path() != orig and fc.path() not in old:
112 113 old[fc.path()] = 1
113 114 if fc.rev() < limit:
114 115 continue
115 116 visit += fc.parents()
116 117
117 118 old = old.keys()
118 119 old.sort()
119 120 return old
120 121
121 122 def nonoverlap(d1, d2, d3):
122 123 "Return list of elements in d1 not in d2 or d3"
123 124 l = [d for d in d1 if d not in d3 and d not in d2]
124 125 l.sort()
125 126 return l
126 127
127 128 def checkcopies(c, man):
128 129 '''check possible copies for filectx c'''
129 130 for of in findold(c):
130 131 if of not in man:
131 132 return
132 133 c2 = ctx(of, man[of])
133 134 ca = c.ancestor(c2)
134 135 if not ca: # unrelated
135 136 return
136 137 if ca.path() == c.path() or ca.path() == c2.path():
137 138 fullcopy[c.path()] = of
138 139 if c == ca or c2 == ca: # no merge needed, ignore copy
139 140 return
140 141 copy[c.path()] = of
141 142
142 143 def dirs(files):
143 144 d = {}
144 145 for f in files:
145 146 d[os.path.dirname(f)] = True
146 147 return d
147 148
148 149 if not repo.ui.configbool("merge", "followcopies", True):
149 150 return {}
150 151
151 152 # avoid silly behavior for update from empty dir
152 153 if not m1 or not m2 or not ma:
153 154 return {}
154 155
155 156 dcopies = repo.dirstate.copies()
156 157 copy = {}
157 158 fullcopy = {}
158 159 u1 = nonoverlap(m1, m2, ma)
159 160 u2 = nonoverlap(m2, m1, ma)
160 161 ctx = util.cachefunc(lambda f, n: repo.filectx(f, fileid=n[:20]))
161 162
162 163 for f in u1:
163 164 checkcopies(ctx(dcopies.get(f, f), m1[f]), m2)
164 165
165 166 for f in u2:
166 167 checkcopies(ctx(f, m2[f]), m1)
167 168
168 169 if not fullcopy or not repo.ui.configbool("merge", "followdirs", True):
169 170 return copy
170 171
171 172 # generate a directory move map
172 173 d1, d2 = dirs(m1), dirs(m2)
173 174 invalid = {}
174 175 dirmove = {}
175 176
176 177 for dst, src in fullcopy.items():
177 178 dsrc, ddst = os.path.dirname(src), os.path.dirname(dst)
178 179 if dsrc in invalid:
179 180 continue
180 181 elif (dsrc in d1 and ddst in d1) or (dsrc in d2 and ddst in d2):
181 182 invalid[dsrc] = True
182 183 elif dsrc in dirmove and dirmove[dsrc] != ddst:
183 184 invalid[dsrc] = True
184 185 del dirmove[dsrc]
185 186 else:
186 187 dirmove[dsrc] = ddst
187 188
188 189 del d1, d2, invalid
189 190
190 191 if not dirmove:
191 192 return copy
192 193
193 194 # check unaccounted nonoverlapping files
194 195 for f in u1 + u2:
195 196 if f not in fullcopy:
196 197 d = os.path.dirname(f)
197 198 if d in dirmove:
198 199 copy[f] = dirmove[d] + "/" + os.path.basename(f)
199 200
200 201 return copy
201 202
202 203 def manifestmerge(repo, p1, p2, pa, overwrite, partial):
203 204 """
204 205 Merge p1 and p2 with ancestor ma and generate merge action list
205 206
206 207 overwrite = whether we clobber working files
207 208 partial = function to filter file lists
208 209 """
209 210
210 211 repo.ui.note(_("resolving manifests\n"))
211 212 repo.ui.debug(_(" overwrite %s partial %s\n") % (overwrite, bool(partial)))
212 213 repo.ui.debug(_(" ancestor %s local %s remote %s\n") % (pa, p1, p2))
213 214
214 215 m1 = p1.manifest()
215 216 m2 = p2.manifest()
216 217 ma = pa.manifest()
217 218 backwards = (pa == p2)
218 219 action = []
219 220 copy = {}
220 221
221 222 def fmerge(f, f2=None, fa=None):
222 223 """merge executable flags"""
223 224 if not f2:
224 225 f2 = f
225 226 fa = f
226 227 a, b, c = ma.execf(fa), m1.execf(f), m2.execf(f2)
227 228 return ((a^b) | (a^c)) ^ a
228 229
229 230 def act(msg, m, f, *args):
230 231 repo.ui.debug(" %s: %s -> %s\n" % (f, msg, m))
231 232 action.append((f, m) + args)
232 233
233 234 if not (backwards or overwrite):
234 235 copy = findcopies(repo, m1, m2, ma, pa.rev())
235 236 copied = dict.fromkeys(copy.values())
236 237
237 238 # Compare manifests
238 239 for f, n in m1.iteritems():
239 240 if partial and not partial(f):
240 241 continue
241 242 if f in m2:
242 243 # are files different?
243 244 if n != m2[f]:
244 245 a = ma.get(f, nullid)
245 246 # are both different from the ancestor?
246 247 if not overwrite and n != a and m2[f] != a:
247 248 act("versions differ", "m", f, f, f, fmerge(f), False)
248 249 # are we clobbering?
249 250 # is remote's version newer?
250 251 # or are we going back in time and clean?
251 252 elif overwrite or m2[f] != a or (backwards and not n[20:]):
252 253 act("remote is newer", "g", f, m2.execf(f))
253 254 # local is newer, not overwrite, check mode bits
254 255 elif fmerge(f) != m1.execf(f):
255 256 act("update permissions", "e", f, m2.execf(f))
256 257 # contents same, check mode bits
257 258 elif m1.execf(f) != m2.execf(f):
258 259 if overwrite or fmerge(f) != m1.execf(f):
259 260 act("update permissions", "e", f, m2.execf(f))
260 261 elif f in copied:
261 262 continue
262 263 elif f in copy:
263 264 f2 = copy[f]
264 265 if f2 not in m2: # directory rename
265 266 act("remote renamed directory to " + f2, "d",
266 267 f, None, f2, m1.execf(f))
267 268 elif f2 in m1: # case 2 A,B/B/B
268 269 act("local copied to " + f2, "m",
269 270 f, f2, f, fmerge(f, f2, f2), False)
270 271 else: # case 4,21 A/B/B
271 272 act("local moved to " + f2, "m",
272 273 f, f2, f, fmerge(f, f2, f2), False)
273 274 elif f in ma:
274 275 if n != ma[f] and not overwrite:
275 276 if repo.ui.prompt(
276 277 (_(" local changed %s which remote deleted\n") % f) +
277 278 _("(k)eep or (d)elete?"), _("[kd]"), _("k")) == _("d"):
278 279 act("prompt delete", "r", f)
279 280 else:
280 281 act("other deleted", "r", f)
281 282 else:
282 283 # file is created on branch or in working directory
283 284 if (overwrite and n[20:] != "u") or (backwards and not n[20:]):
284 285 act("remote deleted", "r", f)
285 286
286 287 for f, n in m2.iteritems():
287 288 if partial and not partial(f):
288 289 continue
289 290 if f in m1:
290 291 continue
291 292 if f in copied:
292 293 continue
293 294 if f in copy:
294 295 f2 = copy[f]
295 296 if f2 not in m1: # directory rename
296 297 act("local renamed directory to " + f2, "d",
297 298 None, f, f2, m2.execf(f))
298 299 elif f2 in m2: # rename case 1, A/A,B/A
299 300 act("remote copied to " + f, "m",
300 301 f2, f, f, fmerge(f2, f, f2), False)
301 302 else: # case 3,20 A/B/A
302 303 act("remote moved to " + f, "m",
303 304 f2, f, f, fmerge(f2, f, f2), True)
304 305 elif f in ma:
305 306 if overwrite or backwards:
306 307 act("recreating", "g", f, m2.execf(f))
307 308 elif n != ma[f]:
308 309 if repo.ui.prompt(
309 310 (_("remote changed %s which local deleted\n") % f) +
310 311 _("(k)eep or (d)elete?"), _("[kd]"), _("k")) == _("k"):
311 312 act("prompt recreating", "g", f, m2.execf(f))
312 313 else:
313 314 act("remote created", "g", f, m2.execf(f))
314 315
315 316 return action
316 317
317 318 def applyupdates(repo, action, wctx, mctx):
318 319 "apply the merge action list to the working directory"
319 320
320 321 updated, merged, removed, unresolved = 0, 0, 0, 0
321 322 action.sort()
322 323 for a in action:
323 324 f, m = a[:2]
324 325 if f and f[0] == "/":
325 326 continue
326 327 if m == "r": # remove
327 328 repo.ui.note(_("removing %s\n") % f)
328 329 util.audit_path(f)
329 330 try:
330 331 util.unlink(repo.wjoin(f))
331 332 except OSError, inst:
332 333 if inst.errno != errno.ENOENT:
333 334 repo.ui.warn(_("update failed to remove %s: %s!\n") %
334 335 (f, inst.strerror))
335 336 removed += 1
336 337 elif m == "m": # merge
337 338 f2, fd, flag, move = a[2:]
338 339 r = filemerge(repo, f, f2, wctx, mctx)
339 340 if r > 0:
340 341 unresolved += 1
341 342 else:
342 343 if r is None:
343 344 updated += 1
344 345 else:
345 346 merged += 1
346 347 if f != fd:
347 348 repo.ui.debug(_("copying %s to %s\n") % (f, fd))
348 349 repo.wwrite(fd, repo.wread(f))
349 350 if move:
350 351 repo.ui.debug(_("removing %s\n") % f)
351 352 os.unlink(repo.wjoin(f))
352 353 util.set_exec(repo.wjoin(fd), flag)
353 354 elif m == "g": # get
354 355 flag = a[2]
355 356 repo.ui.note(_("getting %s\n") % f)
356 357 t = mctx.filectx(f).data()
357 358 repo.wwrite(f, t)
358 359 util.set_exec(repo.wjoin(f), flag)
359 360 updated += 1
360 361 elif m == "d": # directory rename
361 362 f2, fd, flag = a[2:]
362 363 if f:
363 364 repo.ui.note(_("moving %s to %s\n") % (f, fd))
364 365 t = wctx.filectx(f).data()
365 366 repo.wwrite(fd, t)
366 367 util.set_exec(repo.wjoin(fd), flag)
367 368 util.unlink(repo.wjoin(f))
368 369 if f2:
369 370 repo.ui.note(_("getting %s to %s\n") % (f2, fd))
370 371 t = mctx.filectx(f2).data()
371 372 repo.wwrite(fd, t)
372 373 util.set_exec(repo.wjoin(fd), flag)
373 374 updated += 1
374 375 elif m == "e": # exec
375 376 flag = a[2]
376 377 util.set_exec(repo.wjoin(f), flag)
377 378
378 379 return updated, merged, removed, unresolved
379 380
380 381 def recordupdates(repo, action, branchmerge):
381 382 "record merge actions to the dirstate"
382 383
383 384 for a in action:
384 385 f, m = a[:2]
385 386 if m == "r": # remove
386 387 if branchmerge:
387 388 repo.dirstate.update([f], 'r')
388 389 else:
389 390 repo.dirstate.forget([f])
390 391 elif m == "f": # forget
391 392 repo.dirstate.forget([f])
392 393 elif m == "g": # get
393 394 if branchmerge:
394 395 repo.dirstate.update([f], 'n', st_mtime=-1)
395 396 else:
396 397 repo.dirstate.update([f], 'n')
397 398 elif m == "m": # merge
398 399 f2, fd, flag, move = a[2:]
399 400 if branchmerge:
400 401 # We've done a branch merge, mark this file as merged
401 402 # so that we properly record the merger later
402 403 repo.dirstate.update([fd], 'm')
403 404 if f != f2: # copy/rename
404 405 if move:
405 406 repo.dirstate.update([f], 'r')
406 407 if f != fd:
407 408 repo.dirstate.copy(f, fd)
408 409 else:
409 410 repo.dirstate.copy(f2, fd)
410 411 else:
411 412 # We've update-merged a locally modified file, so
412 413 # we set the dirstate to emulate a normal checkout
413 414 # of that file some time in the past. Thus our
414 415 # merge will appear as a normal local file
415 416 # modification.
416 417 repo.dirstate.update([fd], 'n', st_size=-1, st_mtime=-1)
417 418 if move:
418 419 repo.dirstate.forget([f])
419 420 elif m == "d": # directory rename
420 421 f2, fd, flag = a[2:]
421 422 if branchmerge:
422 423 repo.dirstate.update([fd], 'a')
423 424 if f:
424 425 repo.dirstate.update([f], 'r')
425 426 repo.dirstate.copy(f, fd)
426 427 if f2:
427 428 repo.dirstate.copy(f2, fd)
428 429 else:
429 430 repo.dirstate.update([fd], 'n')
430 431 if f:
431 432 repo.dirstate.forget([f])
432 433
433 434 def update(repo, node, branchmerge, force, partial, wlock):
434 435 """
435 436 Perform a merge between the working directory and the given node
436 437
437 438 branchmerge = whether to merge between branches
438 439 force = whether to force branch merging or file overwriting
439 440 partial = a function to filter file lists (dirstate not updated)
440 441 wlock = working dir lock, if already held
441 442 """
442 443
443 444 if node is None:
444 445 node = "tip"
445 446
446 447 if not wlock:
447 448 wlock = repo.wlock()
448 449
449 450 overwrite = force and not branchmerge
450 451 forcemerge = force and branchmerge
451 452 wc = repo.workingctx()
452 453 pl = wc.parents()
453 454 p1, p2 = pl[0], repo.changectx(node)
454 455 pa = p1.ancestor(p2)
455 456 fp1, fp2, xp1, xp2 = p1.node(), p2.node(), str(p1), str(p2)
456 457
457 458 ### check phase
458 459 if not overwrite and len(pl) > 1:
459 460 raise util.Abort(_("outstanding uncommitted merges"))
460 461 if pa == p1 or pa == p2: # is there a linear path from p1 to p2?
461 462 if branchmerge:
462 463 raise util.Abort(_("there is nothing to merge, just use "
463 464 "'hg update' or look at 'hg heads'"))
464 465 elif not (overwrite or branchmerge):
465 466 raise util.Abort(_("update spans branches, use 'hg merge' "
466 467 "or 'hg update -C' to lose changes"))
467 468 if branchmerge and not forcemerge:
468 469 if wc.files():
469 470 raise util.Abort(_("outstanding uncommitted changes"))
470 471
471 472 ### calculate phase
472 473 action = []
473 474 if not force:
474 475 checkunknown(wc, p2)
475 476 if not util.checkfolding(repo.path):
476 477 checkcollision(p2)
477 478 if not branchmerge:
478 479 action += forgetremoved(wc, p2)
479 480 action += manifestmerge(repo, wc, p2, pa, overwrite, partial)
480 481
481 482 ### apply phase
482 483 if not branchmerge: # just jump to the new rev
483 484 fp1, fp2, xp1, xp2 = fp2, nullid, xp2, ''
484 485 if not partial:
485 486 repo.hook('preupdate', throw=True, parent1=xp1, parent2=xp2)
486 487
487 488 stats = applyupdates(repo, action, wc, p2)
488 489
489 490 if not partial:
490 491 recordupdates(repo, action, branchmerge)
491 492 repo.dirstate.setparents(fp1, fp2)
492 493 repo.hook('update', parent1=xp1, parent2=xp2, error=stats[3])
493 494 if not branchmerge:
494 495 repo.opener("branch", "w").write(p2.branch() + "\n")
495 496
496 497 return stats
497 498
General Comments 0
You need to be logged in to leave comments. Login now