##// END OF EJS Templates
filemerge: refactoring of 'filemerge()'...
FUJIWARA Katsunori -
r16125:83925d3a default
parent child Browse files
Show More
@@ -1,269 +1,342 b''
1 # filemerge.py - file-level merge handling for Mercurial
1 # filemerge.py - file-level merge handling for Mercurial
2 #
2 #
3 # Copyright 2006, 2007, 2008 Matt Mackall <mpm@selenic.com>
3 # Copyright 2006, 2007, 2008 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from node import short
8 from node import short
9 from i18n import _
9 from i18n import _
10 import util, simplemerge, match, error
10 import util, simplemerge, match, error
11 import os, tempfile, re, filecmp
11 import os, tempfile, re, filecmp
12
12
13 def _toolstr(ui, tool, part, default=""):
13 def _toolstr(ui, tool, part, default=""):
14 return ui.config("merge-tools", tool + "." + part, default)
14 return ui.config("merge-tools", tool + "." + part, default)
15
15
16 def _toolbool(ui, tool, part, default=False):
16 def _toolbool(ui, tool, part, default=False):
17 return ui.configbool("merge-tools", tool + "." + part, default)
17 return ui.configbool("merge-tools", tool + "." + part, default)
18
18
19 def _toollist(ui, tool, part, default=[]):
19 def _toollist(ui, tool, part, default=[]):
20 return ui.configlist("merge-tools", tool + "." + part, default)
20 return ui.configlist("merge-tools", tool + "." + part, default)
21
21
22 _internal = ['internal:' + s
22 _internal = {}
23 for s in 'fail local other merge prompt dump'.split()]
23
24 def internaltool(name, trymerge, onfailure=None):
25 '''return a decorator for populating internal merge tool table'''
26 def decorator(func):
27 _internal[name] = func
28 func.trymerge = trymerge
29 func.onfailure = onfailure
30 return func
31 return decorator
24
32
25 def _findtool(ui, tool):
33 def _findtool(ui, tool):
26 if tool in _internal:
34 if tool in _internal:
27 return tool
35 return tool
28 for kn in ("regkey", "regkeyalt"):
36 for kn in ("regkey", "regkeyalt"):
29 k = _toolstr(ui, tool, kn)
37 k = _toolstr(ui, tool, kn)
30 if not k:
38 if not k:
31 continue
39 continue
32 p = util.lookupreg(k, _toolstr(ui, tool, "regname"))
40 p = util.lookupreg(k, _toolstr(ui, tool, "regname"))
33 if p:
41 if p:
34 p = util.findexe(p + _toolstr(ui, tool, "regappend"))
42 p = util.findexe(p + _toolstr(ui, tool, "regappend"))
35 if p:
43 if p:
36 return p
44 return p
37 exe = _toolstr(ui, tool, "executable", tool)
45 exe = _toolstr(ui, tool, "executable", tool)
38 return util.findexe(util.expandpath(exe))
46 return util.findexe(util.expandpath(exe))
39
47
40 def _picktool(repo, ui, path, binary, symlink):
48 def _picktool(repo, ui, path, binary, symlink):
41 def check(tool, pat, symlink, binary):
49 def check(tool, pat, symlink, binary):
42 tmsg = tool
50 tmsg = tool
43 if pat:
51 if pat:
44 tmsg += " specified for " + pat
52 tmsg += " specified for " + pat
45 if not _findtool(ui, tool):
53 if not _findtool(ui, tool):
46 if pat: # explicitly requested tool deserves a warning
54 if pat: # explicitly requested tool deserves a warning
47 ui.warn(_("couldn't find merge tool %s\n") % tmsg)
55 ui.warn(_("couldn't find merge tool %s\n") % tmsg)
48 else: # configured but non-existing tools are more silent
56 else: # configured but non-existing tools are more silent
49 ui.note(_("couldn't find merge tool %s\n") % tmsg)
57 ui.note(_("couldn't find merge tool %s\n") % tmsg)
50 elif symlink and not _toolbool(ui, tool, "symlink"):
58 elif symlink and not _toolbool(ui, tool, "symlink"):
51 ui.warn(_("tool %s can't handle symlinks\n") % tmsg)
59 ui.warn(_("tool %s can't handle symlinks\n") % tmsg)
52 elif binary and not _toolbool(ui, tool, "binary"):
60 elif binary and not _toolbool(ui, tool, "binary"):
53 ui.warn(_("tool %s can't handle binary\n") % tmsg)
61 ui.warn(_("tool %s can't handle binary\n") % tmsg)
54 elif not util.gui() and _toolbool(ui, tool, "gui"):
62 elif not util.gui() and _toolbool(ui, tool, "gui"):
55 ui.warn(_("tool %s requires a GUI\n") % tmsg)
63 ui.warn(_("tool %s requires a GUI\n") % tmsg)
56 else:
64 else:
57 return True
65 return True
58 return False
66 return False
59
67
60 # forcemerge comes from command line arguments, highest priority
68 # forcemerge comes from command line arguments, highest priority
61 force = ui.config('ui', 'forcemerge')
69 force = ui.config('ui', 'forcemerge')
62 if force:
70 if force:
63 toolpath = _findtool(ui, force)
71 toolpath = _findtool(ui, force)
64 if toolpath:
72 if toolpath:
65 return (force, '"' + toolpath + '"')
73 return (force, '"' + toolpath + '"')
66 else:
74 else:
67 # mimic HGMERGE if given tool not found
75 # mimic HGMERGE if given tool not found
68 return (force, force)
76 return (force, force)
69
77
70 # HGMERGE takes next precedence
78 # HGMERGE takes next precedence
71 hgmerge = os.environ.get("HGMERGE")
79 hgmerge = os.environ.get("HGMERGE")
72 if hgmerge:
80 if hgmerge:
73 return (hgmerge, hgmerge)
81 return (hgmerge, hgmerge)
74
82
75 # then patterns
83 # then patterns
76 for pat, tool in ui.configitems("merge-patterns"):
84 for pat, tool in ui.configitems("merge-patterns"):
77 mf = match.match(repo.root, '', [pat])
85 mf = match.match(repo.root, '', [pat])
78 if mf(path) and check(tool, pat, symlink, False):
86 if mf(path) and check(tool, pat, symlink, False):
79 toolpath = _findtool(ui, tool)
87 toolpath = _findtool(ui, tool)
80 return (tool, '"' + toolpath + '"')
88 return (tool, '"' + toolpath + '"')
81
89
82 # then merge tools
90 # then merge tools
83 tools = {}
91 tools = {}
84 for k, v in ui.configitems("merge-tools"):
92 for k, v in ui.configitems("merge-tools"):
85 t = k.split('.')[0]
93 t = k.split('.')[0]
86 if t not in tools:
94 if t not in tools:
87 tools[t] = int(_toolstr(ui, t, "priority", "0"))
95 tools[t] = int(_toolstr(ui, t, "priority", "0"))
88 names = tools.keys()
96 names = tools.keys()
89 tools = sorted([(-p, t) for t, p in tools.items()])
97 tools = sorted([(-p, t) for t, p in tools.items()])
90 uimerge = ui.config("ui", "merge")
98 uimerge = ui.config("ui", "merge")
91 if uimerge:
99 if uimerge:
92 if uimerge not in names:
100 if uimerge not in names:
93 return (uimerge, uimerge)
101 return (uimerge, uimerge)
94 tools.insert(0, (None, uimerge)) # highest priority
102 tools.insert(0, (None, uimerge)) # highest priority
95 tools.append((None, "hgmerge")) # the old default, if found
103 tools.append((None, "hgmerge")) # the old default, if found
96 for p, t in tools:
104 for p, t in tools:
97 if check(t, None, symlink, binary):
105 if check(t, None, symlink, binary):
98 toolpath = _findtool(ui, t)
106 toolpath = _findtool(ui, t)
99 return (t, '"' + toolpath + '"')
107 return (t, '"' + toolpath + '"')
100 # internal merge as last resort
108 # internal merge as last resort
101 return (not (symlink or binary) and "internal:merge" or None, None)
109 return (not (symlink or binary) and "internal:merge" or None, None)
102
110
103 def _eoltype(data):
111 def _eoltype(data):
104 "Guess the EOL type of a file"
112 "Guess the EOL type of a file"
105 if '\0' in data: # binary
113 if '\0' in data: # binary
106 return None
114 return None
107 if '\r\n' in data: # Windows
115 if '\r\n' in data: # Windows
108 return '\r\n'
116 return '\r\n'
109 if '\r' in data: # Old Mac
117 if '\r' in data: # Old Mac
110 return '\r'
118 return '\r'
111 if '\n' in data: # UNIX
119 if '\n' in data: # UNIX
112 return '\n'
120 return '\n'
113 return None # unknown
121 return None # unknown
114
122
115 def _matcheol(file, origfile):
123 def _matcheol(file, origfile):
116 "Convert EOL markers in a file to match origfile"
124 "Convert EOL markers in a file to match origfile"
117 tostyle = _eoltype(util.readfile(origfile))
125 tostyle = _eoltype(util.readfile(origfile))
118 if tostyle:
126 if tostyle:
119 data = util.readfile(file)
127 data = util.readfile(file)
120 style = _eoltype(data)
128 style = _eoltype(data)
121 if style:
129 if style:
122 newdata = data.replace(style, tostyle)
130 newdata = data.replace(style, tostyle)
123 if newdata != data:
131 if newdata != data:
124 util.writefile(file, newdata)
132 util.writefile(file, newdata)
125
133
134 @internaltool('internal:prompt', False)
135 def _iprompt(repo, mynode, orig, fcd, fco, fca, toolconf):
136 ui = repo.ui
137 fd = fcd.path()
138
139 if ui.promptchoice(_(" no tool found to merge %s\n"
140 "keep (l)ocal or take (o)ther?") % fd,
141 (_("&Local"), _("&Other")), 0):
142 return _iother(repo, mynode, orig, fcd, fco, fca, toolconf)
143 else:
144 return _ilocal(repo, mynode, orig, fcd, fco, fca, toolconf)
145
146 @internaltool('internal:local', False)
147 def _ilocal(repo, mynode, orig, fcd, fco, fca, toolconf):
148 return 0
149
150 @internaltool('internal:other', False)
151 def _iother(repo, mynode, orig, fcd, fco, fca, toolconf):
152 repo.wwrite(fcd.path(), fco.data(), fco.flags())
153 return 0
154
155 @internaltool('internal:fail', False)
156 def _ifail(repo, mynode, orig, fcd, fco, fca, toolconf):
157 return 1
158
159 def _premerge(repo, toolconf, files):
160 tool, toolpath, binary, symlink = toolconf
161 a, b, c, back = files
162
163 ui = repo.ui
164
165 # do we attempt to simplemerge first?
166 try:
167 premerge = _toolbool(ui, tool, "premerge", not (binary or symlink))
168 except error.ConfigError:
169 premerge = _toolstr(ui, tool, "premerge").lower()
170 valid = 'keep'.split()
171 if premerge not in valid:
172 _valid = ', '.join(["'" + v + "'" for v in valid])
173 raise error.ConfigError(_("%s.premerge not valid "
174 "('%s' is neither boolean nor %s)") %
175 (tool, premerge, _valid))
176
177 if premerge:
178 r = simplemerge.simplemerge(ui, a, b, c, quiet=True)
179 if not r:
180 ui.debug(" premerge successful\n")
181 return 0
182 if premerge != 'keep':
183 util.copyfile(back, a) # restore from backup and try again
184 return 1 # continue merging
185
186 @internaltool('internal:merge', True,
187 _("merging %s incomplete! "
188 "(edit conflicts, then use 'hg resolve --mark')\n"))
189 def _imerge(repo, mynode, orig, fcd, fco, fca, toolconf, files):
190 r = _premerge(repo, toolconf, files)
191 if r:
192 a, b, c, back = files
193
194 ui = repo.ui
195
196 r = simplemerge.simplemerge(ui, a, b, c, label=['local', 'other'])
197 return True, r
198 return False, 0
199
200 @internaltool('internal:dump', True)
201 def _idump(repo, mynode, orig, fcd, fco, fca, toolconf, files):
202 r = _premerge(repo, toolconf, files)
203 if r:
204 a, b, c, back = files
205
206 fd = fcd.path()
207
208 util.copyfile(a, a + ".local")
209 repo.wwrite(fd + ".other", fco.data(), fco.flags())
210 repo.wwrite(fd + ".base", fca.data(), fca.flags())
211 return False, r
212
213 def _xmerge(repo, mynode, orig, fcd, fco, fca, toolconf, files):
214 r = _premerge(repo, toolconf, files)
215 if r:
216 tool, toolpath, binary, symlink = toolconf
217 a, b, c, back = files
218 out = ""
219 env = dict(HG_FILE=fcd.path(),
220 HG_MY_NODE=short(mynode),
221 HG_OTHER_NODE=str(fco.changectx()),
222 HG_BASE_NODE=str(fca.changectx()),
223 HG_MY_ISLINK='l' in fcd.flags(),
224 HG_OTHER_ISLINK='l' in fco.flags(),
225 HG_BASE_ISLINK='l' in fca.flags())
226
227 ui = repo.ui
228
229 args = _toolstr(ui, tool, "args", '$local $base $other')
230 if "$output" in args:
231 out, a = a, back # read input from backup, write to original
232 replace = dict(local=a, base=b, other=c, output=out)
233 args = util.interpolate(r'\$', replace, args,
234 lambda s: '"%s"' % util.localpath(s))
235 r = util.system(toolpath + ' ' + args, cwd=repo.root, environ=env,
236 out=ui.fout)
237 return True, r
238 return False, 0
239
126 def filemerge(repo, mynode, orig, fcd, fco, fca):
240 def filemerge(repo, mynode, orig, fcd, fco, fca):
127 """perform a 3-way merge in the working directory
241 """perform a 3-way merge in the working directory
128
242
129 mynode = parent node before merge
243 mynode = parent node before merge
130 orig = original local filename before merge
244 orig = original local filename before merge
131 fco = other file context
245 fco = other file context
132 fca = ancestor file context
246 fca = ancestor file context
133 fcd = local file context for current/destination file
247 fcd = local file context for current/destination file
134 """
248 """
135
249
136 def temp(prefix, ctx):
250 def temp(prefix, ctx):
137 pre = "%s~%s." % (os.path.basename(ctx.path()), prefix)
251 pre = "%s~%s." % (os.path.basename(ctx.path()), prefix)
138 (fd, name) = tempfile.mkstemp(prefix=pre)
252 (fd, name) = tempfile.mkstemp(prefix=pre)
139 data = repo.wwritedata(ctx.path(), ctx.data())
253 data = repo.wwritedata(ctx.path(), ctx.data())
140 f = os.fdopen(fd, "wb")
254 f = os.fdopen(fd, "wb")
141 f.write(data)
255 f.write(data)
142 f.close()
256 f.close()
143 return name
257 return name
144
258
145 if not fco.cmp(fcd): # files identical?
259 if not fco.cmp(fcd): # files identical?
146 return None
260 return None
147
261
148 ui = repo.ui
262 ui = repo.ui
149 fd = fcd.path()
263 fd = fcd.path()
150 binary = fcd.isbinary() or fco.isbinary() or fca.isbinary()
264 binary = fcd.isbinary() or fco.isbinary() or fca.isbinary()
151 symlink = 'l' in fcd.flags() + fco.flags()
265 symlink = 'l' in fcd.flags() + fco.flags()
152 tool, toolpath = _picktool(repo, ui, fd, binary, symlink)
266 tool, toolpath = _picktool(repo, ui, fd, binary, symlink)
153 ui.debug("picked tool '%s' for %s (binary %s symlink %s)\n" %
267 ui.debug("picked tool '%s' for %s (binary %s symlink %s)\n" %
154 (tool, fd, binary, symlink))
268 (tool, fd, binary, symlink))
155
269
156 if not tool or tool == 'internal:prompt':
270 if tool in _internal:
157 tool = "internal:local"
271 func = _internal[tool]
158 if ui.promptchoice(_(" no tool found to merge %s\n"
272 trymerge = func.trymerge
159 "keep (l)ocal or take (o)ther?") % fd,
273 onfailure = func.onfailure
160 (_("&Local"), _("&Other")), 0):
274 else:
161 tool = "internal:other"
275 func = _xmerge
162 if tool == "internal:local":
276 trymerge = True
163 return 0
277 onfailure = _("merging %s failed!\n")
164 if tool == "internal:other":
165 repo.wwrite(fd, fco.data(), fco.flags())
166 return 0
167 if tool == "internal:fail":
168 return 1
169
278
170 # do the actual merge
279 toolconf = tool, toolpath, binary, symlink
280
281 if not trymerge:
282 return func(repo, mynode, orig, fcd, fco, fca, toolconf)
283
171 a = repo.wjoin(fd)
284 a = repo.wjoin(fd)
172 b = temp("base", fca)
285 b = temp("base", fca)
173 c = temp("other", fco)
286 c = temp("other", fco)
174 out = ""
175 back = a + ".orig"
287 back = a + ".orig"
176 util.copyfile(a, back)
288 util.copyfile(a, back)
177
289
178 if orig != fco.path():
290 if orig != fco.path():
179 ui.status(_("merging %s and %s to %s\n") % (orig, fco.path(), fd))
291 ui.status(_("merging %s and %s to %s\n") % (orig, fco.path(), fd))
180 else:
292 else:
181 ui.status(_("merging %s\n") % fd)
293 ui.status(_("merging %s\n") % fd)
182
294
183 ui.debug("my %s other %s ancestor %s\n" % (fcd, fco, fca))
295 ui.debug("my %s other %s ancestor %s\n" % (fcd, fco, fca))
184
296
185 # do we attempt to simplemerge first?
297 needcheck, r = func(repo, mynode, orig, fcd, fco, fca, toolconf,
186 try:
298 (a, b, c, back))
187 premerge = _toolbool(ui, tool, "premerge", not (binary or symlink))
299 if not needcheck:
188 except error.ConfigError:
300 if r:
189 premerge = _toolstr(ui, tool, "premerge").lower()
301 if onfailure:
190 valid = 'keep'.split()
302 ui.warn(onfailure % fd)
191 if premerge not in valid:
303 else:
192 _valid = ', '.join(["'" + v + "'" for v in valid])
193 raise error.ConfigError(_("%s.premerge not valid "
194 "('%s' is neither boolean nor %s)") %
195 (tool, premerge, _valid))
196
197 if premerge:
198 r = simplemerge.simplemerge(ui, a, b, c, quiet=True)
199 if not r:
200 ui.debug(" premerge successful\n")
201 os.unlink(back)
304 os.unlink(back)
202 os.unlink(b)
203 os.unlink(c)
204 return 0
205 if premerge != 'keep':
206 util.copyfile(back, a) # restore from backup and try again
207
305
208 env = dict(HG_FILE=fd,
306 os.unlink(b)
209 HG_MY_NODE=short(mynode),
307 os.unlink(c)
210 HG_OTHER_NODE=str(fco.changectx()),
308 return r
211 HG_BASE_NODE=str(fca.changectx()),
212 HG_MY_ISLINK='l' in fcd.flags(),
213 HG_OTHER_ISLINK='l' in fco.flags(),
214 HG_BASE_ISLINK='l' in fca.flags())
215
216 if tool == "internal:merge":
217 r = simplemerge.simplemerge(ui, a, b, c, label=['local', 'other'])
218 elif tool == 'internal:dump':
219 a = repo.wjoin(fd)
220 util.copyfile(a, a + ".local")
221 repo.wwrite(fd + ".other", fco.data(), fco.flags())
222 repo.wwrite(fd + ".base", fca.data(), fca.flags())
223 return 1 # unresolved
224 else:
225 args = _toolstr(ui, tool, "args", '$local $base $other')
226 if "$output" in args:
227 out, a = a, back # read input from backup, write to original
228 replace = dict(local=a, base=b, other=c, output=out)
229 args = util.interpolate(r'\$', replace, args,
230 lambda s: '"%s"' % util.localpath(s))
231 r = util.system(toolpath + ' ' + args, cwd=repo.root, environ=env,
232 out=ui.fout)
233
309
234 if not r and (_toolbool(ui, tool, "checkconflicts") or
310 if not r and (_toolbool(ui, tool, "checkconflicts") or
235 'conflicts' in _toollist(ui, tool, "check")):
311 'conflicts' in _toollist(ui, tool, "check")):
236 if re.search("^(<<<<<<< .*|=======|>>>>>>> .*)$", fcd.data(),
312 if re.search("^(<<<<<<< .*|=======|>>>>>>> .*)$", fcd.data(),
237 re.MULTILINE):
313 re.MULTILINE):
238 r = 1
314 r = 1
239
315
240 checked = False
316 checked = False
241 if 'prompt' in _toollist(ui, tool, "check"):
317 if 'prompt' in _toollist(ui, tool, "check"):
242 checked = True
318 checked = True
243 if ui.promptchoice(_("was merge of '%s' successful (yn)?") % fd,
319 if ui.promptchoice(_("was merge of '%s' successful (yn)?") % fd,
244 (_("&Yes"), _("&No")), 1):
320 (_("&Yes"), _("&No")), 1):
245 r = 1
321 r = 1
246
322
247 if not r and not checked and (_toolbool(ui, tool, "checkchanged") or
323 if not r and not checked and (_toolbool(ui, tool, "checkchanged") or
248 'changed' in _toollist(ui, tool, "check")):
324 'changed' in _toollist(ui, tool, "check")):
249 if filecmp.cmp(repo.wjoin(fd), back):
325 if filecmp.cmp(a, back):
250 if ui.promptchoice(_(" output file %s appears unchanged\n"
326 if ui.promptchoice(_(" output file %s appears unchanged\n"
251 "was merge successful (yn)?") % fd,
327 "was merge successful (yn)?") % fd,
252 (_("&Yes"), _("&No")), 1):
328 (_("&Yes"), _("&No")), 1):
253 r = 1
329 r = 1
254
330
255 if _toolbool(ui, tool, "fixeol"):
331 if _toolbool(ui, tool, "fixeol"):
256 _matcheol(repo.wjoin(fd), back)
332 _matcheol(a, back)
257
333
258 if r:
334 if r:
259 if tool == "internal:merge":
335 if onfailure:
260 ui.warn(_("merging %s incomplete! "
336 ui.warn(onfailure % fd)
261 "(edit conflicts, then use 'hg resolve --mark')\n") % fd)
262 else:
263 ui.warn(_("merging %s failed!\n") % fd)
264 else:
337 else:
265 os.unlink(back)
338 os.unlink(back)
266
339
267 os.unlink(b)
340 os.unlink(b)
268 os.unlink(c)
341 os.unlink(c)
269 return r
342 return r
General Comments 0
You need to be logged in to leave comments. Login now