eggs/mercurial-1.7.3-py2.6-linux-x86_64.egg/mercurial/filemerge.py
changeset 69 c6bca38c1cbf
equal deleted inserted replaced
68:5ff1fc726848 69:c6bca38c1cbf
       
     1 # filemerge.py - file-level merge handling for Mercurial
       
     2 #
       
     3 # Copyright 2006, 2007, 2008 Matt Mackall <mpm@selenic.com>
       
     4 #
       
     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.
       
     7 
       
     8 from node import short
       
     9 from i18n import _
       
    10 import util, simplemerge, match, error
       
    11 import os, tempfile, re, filecmp
       
    12 
       
    13 def _toolstr(ui, tool, part, default=""):
       
    14     return ui.config("merge-tools", tool + "." + part, default)
       
    15 
       
    16 def _toolbool(ui, tool, part, default=False):
       
    17     return ui.configbool("merge-tools", tool + "." + part, default)
       
    18 
       
    19 def _toollist(ui, tool, part, default=[]):
       
    20     return ui.configlist("merge-tools", tool + "." + part, default)
       
    21 
       
    22 _internal = ['internal:' + s
       
    23              for s in 'fail local other merge prompt dump'.split()]
       
    24 
       
    25 def _findtool(ui, tool):
       
    26     if tool in _internal:
       
    27         return tool
       
    28     k = _toolstr(ui, tool, "regkey")
       
    29     if k:
       
    30         p = util.lookup_reg(k, _toolstr(ui, tool, "regname"))
       
    31         if p:
       
    32             p = util.find_exe(p + _toolstr(ui, tool, "regappend"))
       
    33             if p:
       
    34                 return p
       
    35     return util.find_exe(_toolstr(ui, tool, "executable", tool))
       
    36 
       
    37 def _picktool(repo, ui, path, binary, symlink):
       
    38     def check(tool, pat, symlink, binary):
       
    39         tmsg = tool
       
    40         if pat:
       
    41             tmsg += " specified for " + pat
       
    42         if not _findtool(ui, tool):
       
    43             if pat: # explicitly requested tool deserves a warning
       
    44                 ui.warn(_("couldn't find merge tool %s\n") % tmsg)
       
    45             else: # configured but non-existing tools are more silent
       
    46                 ui.note(_("couldn't find merge tool %s\n") % tmsg)
       
    47         elif symlink and not _toolbool(ui, tool, "symlink"):
       
    48             ui.warn(_("tool %s can't handle symlinks\n") % tmsg)
       
    49         elif binary and not _toolbool(ui, tool, "binary"):
       
    50             ui.warn(_("tool %s can't handle binary\n") % tmsg)
       
    51         elif not util.gui() and _toolbool(ui, tool, "gui"):
       
    52             ui.warn(_("tool %s requires a GUI\n") % tmsg)
       
    53         else:
       
    54             return True
       
    55         return False
       
    56 
       
    57     # forcemerge comes from command line arguments, highest priority
       
    58     force = ui.config('ui', 'forcemerge')
       
    59     if force:
       
    60         toolpath = _findtool(ui, force)
       
    61         if toolpath:
       
    62             return (force, '"' + toolpath + '"')
       
    63         else:
       
    64             # mimic HGMERGE if given tool not found
       
    65             return (force, force)
       
    66 
       
    67     # HGMERGE takes next precedence
       
    68     hgmerge = os.environ.get("HGMERGE")
       
    69     if hgmerge:
       
    70         return (hgmerge, hgmerge)
       
    71 
       
    72     # then patterns
       
    73     for pat, tool in ui.configitems("merge-patterns"):
       
    74         mf = match.match(repo.root, '', [pat])
       
    75         if mf(path) and check(tool, pat, symlink, False):
       
    76             toolpath = _findtool(ui, tool)
       
    77             return (tool, '"' + toolpath + '"')
       
    78 
       
    79     # then merge tools
       
    80     tools = {}
       
    81     for k, v in ui.configitems("merge-tools"):
       
    82         t = k.split('.')[0]
       
    83         if t not in tools:
       
    84             tools[t] = int(_toolstr(ui, t, "priority", "0"))
       
    85     names = tools.keys()
       
    86     tools = sorted([(-p, t) for t, p in tools.items()])
       
    87     uimerge = ui.config("ui", "merge")
       
    88     if uimerge:
       
    89         if uimerge not in names:
       
    90             return (uimerge, uimerge)
       
    91         tools.insert(0, (None, uimerge)) # highest priority
       
    92     tools.append((None, "hgmerge")) # the old default, if found
       
    93     for p, t in tools:
       
    94         if check(t, None, symlink, binary):
       
    95             toolpath = _findtool(ui, t)
       
    96             return (t, '"' + toolpath + '"')
       
    97     # internal merge as last resort
       
    98     return (not (symlink or binary) and "internal:merge" or None, None)
       
    99 
       
   100 def _eoltype(data):
       
   101     "Guess the EOL type of a file"
       
   102     if '\0' in data: # binary
       
   103         return None
       
   104     if '\r\n' in data: # Windows
       
   105         return '\r\n'
       
   106     if '\r' in data: # Old Mac
       
   107         return '\r'
       
   108     if '\n' in data: # UNIX
       
   109         return '\n'
       
   110     return None # unknown
       
   111 
       
   112 def _matcheol(file, origfile):
       
   113     "Convert EOL markers in a file to match origfile"
       
   114     tostyle = _eoltype(open(origfile, "rb").read())
       
   115     if tostyle:
       
   116         data = open(file, "rb").read()
       
   117         style = _eoltype(data)
       
   118         if style:
       
   119             newdata = data.replace(style, tostyle)
       
   120             if newdata != data:
       
   121                 open(file, "wb").write(newdata)
       
   122 
       
   123 def filemerge(repo, mynode, orig, fcd, fco, fca):
       
   124     """perform a 3-way merge in the working directory
       
   125 
       
   126     mynode = parent node before merge
       
   127     orig = original local filename before merge
       
   128     fco = other file context
       
   129     fca = ancestor file context
       
   130     fcd = local file context for current/destination file
       
   131     """
       
   132 
       
   133     def temp(prefix, ctx):
       
   134         pre = "%s~%s." % (os.path.basename(ctx.path()), prefix)
       
   135         (fd, name) = tempfile.mkstemp(prefix=pre)
       
   136         data = repo.wwritedata(ctx.path(), ctx.data())
       
   137         f = os.fdopen(fd, "wb")
       
   138         f.write(data)
       
   139         f.close()
       
   140         return name
       
   141 
       
   142     def isbin(ctx):
       
   143         try:
       
   144             return util.binary(ctx.data())
       
   145         except IOError:
       
   146             return False
       
   147 
       
   148     if not fco.cmp(fcd): # files identical?
       
   149         return None
       
   150 
       
   151     ui = repo.ui
       
   152     fd = fcd.path()
       
   153     binary = isbin(fcd) or isbin(fco) or isbin(fca)
       
   154     symlink = 'l' in fcd.flags() + fco.flags()
       
   155     tool, toolpath = _picktool(repo, ui, fd, binary, symlink)
       
   156     ui.debug("picked tool '%s' for %s (binary %s symlink %s)\n" %
       
   157                (tool, fd, binary, symlink))
       
   158 
       
   159     if not tool or tool == 'internal:prompt':
       
   160         tool = "internal:local"
       
   161         if ui.promptchoice(_(" no tool found to merge %s\n"
       
   162                              "keep (l)ocal or take (o)ther?") % fd,
       
   163                            (_("&Local"), _("&Other")), 0):
       
   164             tool = "internal:other"
       
   165     if tool == "internal:local":
       
   166         return 0
       
   167     if tool == "internal:other":
       
   168         repo.wwrite(fd, fco.data(), fco.flags())
       
   169         return 0
       
   170     if tool == "internal:fail":
       
   171         return 1
       
   172 
       
   173     # do the actual merge
       
   174     a = repo.wjoin(fd)
       
   175     b = temp("base", fca)
       
   176     c = temp("other", fco)
       
   177     out = ""
       
   178     back = a + ".orig"
       
   179     util.copyfile(a, back)
       
   180 
       
   181     if orig != fco.path():
       
   182         ui.status(_("merging %s and %s to %s\n") % (orig, fco.path(), fd))
       
   183     else:
       
   184         ui.status(_("merging %s\n") % fd)
       
   185 
       
   186     ui.debug("my %s other %s ancestor %s\n" % (fcd, fco, fca))
       
   187 
       
   188     # do we attempt to simplemerge first?
       
   189     try:
       
   190         premerge = _toolbool(ui, tool, "premerge", not (binary or symlink))
       
   191     except error.ConfigError:
       
   192         premerge = _toolstr(ui, tool, "premerge").lower()
       
   193         valid = 'keep'.split()
       
   194         if premerge not in valid:
       
   195             _valid = ', '.join(["'" + v + "'" for v in valid])
       
   196             raise error.ConfigError(_("%s.premerge not valid "
       
   197                                       "('%s' is neither boolean nor %s)") %
       
   198                                     (tool, premerge, _valid))
       
   199 
       
   200     if premerge:
       
   201         r = simplemerge.simplemerge(ui, a, b, c, quiet=True)
       
   202         if not r:
       
   203             ui.debug(" premerge successful\n")
       
   204             os.unlink(back)
       
   205             os.unlink(b)
       
   206             os.unlink(c)
       
   207             return 0
       
   208         if premerge != 'keep':
       
   209             util.copyfile(back, a) # restore from backup and try again
       
   210 
       
   211     env = dict(HG_FILE=fd,
       
   212                HG_MY_NODE=short(mynode),
       
   213                HG_OTHER_NODE=str(fco.changectx()),
       
   214                HG_BASE_NODE=str(fca.changectx()),
       
   215                HG_MY_ISLINK='l' in fcd.flags(),
       
   216                HG_OTHER_ISLINK='l' in fco.flags(),
       
   217                HG_BASE_ISLINK='l' in fca.flags())
       
   218 
       
   219     if tool == "internal:merge":
       
   220         r = simplemerge.simplemerge(ui, a, b, c, label=['local', 'other'])
       
   221     elif tool == 'internal:dump':
       
   222         a = repo.wjoin(fd)
       
   223         util.copyfile(a, a + ".local")
       
   224         repo.wwrite(fd + ".other", fco.data(), fco.flags())
       
   225         repo.wwrite(fd + ".base", fca.data(), fca.flags())
       
   226         return 1 # unresolved
       
   227     else:
       
   228         args = _toolstr(ui, tool, "args", '$local $base $other')
       
   229         if "$output" in args:
       
   230             out, a = a, back # read input from backup, write to original
       
   231         replace = dict(local=a, base=b, other=c, output=out)
       
   232         args = util.interpolate(r'\$', replace, args,
       
   233                                 lambda s: '"%s"' % util.localpath(s))
       
   234         r = util.system(toolpath + ' ' + args, cwd=repo.root, environ=env)
       
   235 
       
   236     if not r and (_toolbool(ui, tool, "checkconflicts") or
       
   237                   'conflicts' in _toollist(ui, tool, "check")):
       
   238         if re.search("^(<<<<<<< .*|=======|>>>>>>> .*)$", fcd.data(),
       
   239                      re.MULTILINE):
       
   240             r = 1
       
   241 
       
   242     checked = False
       
   243     if 'prompt' in _toollist(ui, tool, "check"):
       
   244         checked = True
       
   245         if ui.promptchoice(_("was merge of '%s' successful (yn)?") % fd,
       
   246                            (_("&Yes"), _("&No")), 1):
       
   247             r = 1
       
   248 
       
   249     if not r and not checked and (_toolbool(ui, tool, "checkchanged") or
       
   250                                   'changed' in _toollist(ui, tool, "check")):
       
   251         if filecmp.cmp(repo.wjoin(fd), back):
       
   252             if ui.promptchoice(_(" output file %s appears unchanged\n"
       
   253                                  "was merge successful (yn)?") % fd,
       
   254                                (_("&Yes"), _("&No")), 1):
       
   255                 r = 1
       
   256 
       
   257     if _toolbool(ui, tool, "fixeol"):
       
   258         _matcheol(repo.wjoin(fd), back)
       
   259 
       
   260     if r:
       
   261         ui.warn(_("merging %s failed!\n") % fd)
       
   262     else:
       
   263         os.unlink(back)
       
   264 
       
   265     os.unlink(b)
       
   266     os.unlink(c)
       
   267     return r