chiark / gitweb /
e76f9b1701fcda32e30fd08cf625412533f47b49
[stgit] / stgit / gitmergeonefile.py
1 """Performs a 3-way merge for GIT files
2 """
3
4 __copyright__ = """
5 Copyright (C) 2006, Catalin Marinas <catalin.marinas@gmail.com>
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License version 2 as
9 published by the Free Software Foundation.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 """
20
21 import sys, os
22 from stgit import basedir
23 from stgit.config import config, file_extensions, ConfigOption
24 from stgit.utils import append_string
25 from stgit.out import *
26
27
28 class GitMergeException(Exception):
29     pass
30
31
32 #
33 # Options
34 #
35 merger = ConfigOption('stgit', 'merger')
36 keeporig = ConfigOption('stgit', 'keeporig')
37
38 #
39 # Utility functions
40 #
41 def __str2none(x):
42     if x == '':
43         return None
44     else:
45         return x
46
47 def __output(cmd):
48     f = os.popen(cmd, 'r')
49     string = f.readline().rstrip()
50     if f.close():
51         raise GitMergeException, 'Error: failed to execute "%s"' % cmd
52     return string
53
54 def __checkout_files(orig_hash, file1_hash, file2_hash,
55                      path,
56                      orig_mode, file1_mode, file2_mode):
57     """Check out the files passed as arguments
58     """
59     global orig, src1, src2
60
61     extensions = file_extensions()
62
63     if orig_hash:
64         orig = path + extensions['ancestor']
65         tmp = __output('git-unpack-file %s' % orig_hash)
66         os.chmod(tmp, int(orig_mode, 8))
67         os.renames(tmp, orig)
68     if file1_hash:
69         src1 = path + extensions['current']
70         tmp = __output('git-unpack-file %s' % file1_hash)
71         os.chmod(tmp, int(file1_mode, 8))
72         os.renames(tmp, src1)
73     if file2_hash:
74         src2 = path + extensions['patched']
75         tmp = __output('git-unpack-file %s' % file2_hash)
76         os.chmod(tmp, int(file2_mode, 8))
77         os.renames(tmp, src2)
78
79     if file1_hash and not os.path.exists(path):
80         # the current file might be removed by GIT when it is a new
81         # file added in both branches. Just re-generate it
82         tmp = __output('git-unpack-file %s' % file1_hash)
83         os.chmod(tmp, int(file1_mode, 8))
84         os.renames(tmp, path)
85
86 def __remove_files(orig_hash, file1_hash, file2_hash):
87     """Remove any temporary files
88     """
89     if orig_hash:
90         os.remove(orig)
91     if file1_hash:
92         os.remove(src1)
93     if file2_hash:
94         os.remove(src2)
95
96 def __conflict(path):
97     """Write the conflict file for the 'path' variable and exit
98     """
99     append_string(os.path.join(basedir.get(), 'conflicts'), path)
100
101
102 def interactive_merge(filename):
103     """Run the interactive merger on the given file. Note that the
104     index should not have any conflicts.
105     """
106     extensions = file_extensions()
107
108     ancestor = filename + extensions['ancestor']
109     current = filename + extensions['current']
110     patched = filename + extensions['patched']
111
112     if os.path.isfile(ancestor):
113         three_way = True
114         files_dict = {'branch1': current,
115                       'ancestor': ancestor,
116                       'branch2': patched,
117                       'output': filename}
118         imerger = config.get('stgit.i3merge')
119     else:
120         three_way = False
121         files_dict = {'branch1': current,
122                       'branch2': patched,
123                       'output': filename}
124         imerger = config.get('stgit.i2merge')
125
126     if not imerger:
127         raise GitMergeException, 'No interactive merge command configured'
128
129     # check whether we have all the files for the merge
130     for fn in [filename, current, patched]:
131         if not os.path.isfile(fn):
132             raise GitMergeException, \
133                   'Cannot run the interactive merge: "%s" missing' % fn
134
135     mtime = os.path.getmtime(filename)
136
137     out.info('Trying the interactive %s merge'
138              % (three_way and 'three-way' or 'two-way'))
139
140     err = os.system(imerger % files_dict)
141     if err != 0:
142         raise GitMergeException, 'The interactive merge failed: %d' % err
143     if not os.path.isfile(filename):
144         raise GitMergeException, 'The "%s" file is missing' % filename
145     if mtime == os.path.getmtime(filename):
146         raise GitMergeException, 'The "%s" file was not modified' % filename
147
148
149 #
150 # Main algorithm
151 #
152 def merge(orig_hash, file1_hash, file2_hash,
153           path,
154           orig_mode, file1_mode, file2_mode):
155     """Three-way merge for one file algorithm
156     """
157     __checkout_files(orig_hash, file1_hash, file2_hash,
158                      path,
159                      orig_mode, file1_mode, file2_mode)
160
161     # file exists in origin
162     if orig_hash:
163         # modified in both
164         if file1_hash and file2_hash:
165             # if modes are the same (git-read-tree probably dealt with it)
166             if file1_hash == file2_hash:
167                 if os.system('git-update-index --cacheinfo %s %s %s'
168                              % (file1_mode, file1_hash, path)) != 0:
169                     out.error('git-update-index failed')
170                     __conflict(path)
171                     return 1
172                 if os.system('git-checkout-index -u -f -- %s' % path):
173                     out.error('git-checkout-index failed')
174                     __conflict(path)
175                     return 1
176                 if file1_mode != file2_mode:
177                     out.error('File added in both, permissions conflict')
178                     __conflict(path)
179                     return 1
180             # 3-way merge
181             else:
182                 merge_ok = os.system(str(merger) % {'branch1': src1,
183                                                     'ancestor': orig,
184                                                     'branch2': src2,
185                                                     'output': path }) == 0
186
187                 if merge_ok:
188                     os.system('git-update-index -- %s' % path)
189                     __remove_files(orig_hash, file1_hash, file2_hash)
190                     return 0
191                 else:
192                     out.error('Three-way merge tool failed for file "%s"'
193                               % path)
194                     # reset the cache to the first branch
195                     os.system('git-update-index --cacheinfo %s %s %s'
196                               % (file1_mode, file1_hash, path))
197
198                     if config.get('stgit.autoimerge') == 'yes':
199                         try:
200                             interactive_merge(path)
201                         except GitMergeException, ex:
202                             # interactive merge failed
203                             out.error(str(ex))
204                             if str(keeporig) != 'yes':
205                                 __remove_files(orig_hash, file1_hash,
206                                                file2_hash)
207                             __conflict(path)
208                             return 1
209                         # successful interactive merge
210                         os.system('git-update-index -- %s' % path)
211                         __remove_files(orig_hash, file1_hash, file2_hash)
212                         return 0
213                     else:
214                         # no interactive merge, just mark it as conflict
215                         if str(keeporig) != 'yes':
216                             __remove_files(orig_hash, file1_hash, file2_hash)
217                         __conflict(path)
218                         return 1
219
220         # file deleted in both or deleted in one and unchanged in the other
221         elif not (file1_hash or file2_hash) \
222                or file1_hash == orig_hash or file2_hash == orig_hash:
223             if os.path.exists(path):
224                 os.remove(path)
225             __remove_files(orig_hash, file1_hash, file2_hash)
226             return os.system('git-update-index --remove -- %s' % path)
227         # file deleted in one and changed in the other
228         else:
229             # Do something here - we must at least merge the entry in
230             # the cache, instead of leaving it in U(nmerged) state. In
231             # fact, stg resolved does not handle that.
232
233             # Do the same thing cogito does - remove the file in any case.
234             os.system('git-update-index --remove -- %s' % path)
235
236             #if file1_hash:
237                 ## file deleted upstream and changed in the patch. The
238                 ## patch is probably going to move the changes
239                 ## elsewhere.
240
241                 #os.system('git-update-index --remove -- %s' % path)
242             #else:
243                 ## file deleted in the patch and changed upstream. We
244                 ## could re-delete it, but for now leave it there -
245                 ## and let the user check if he still wants to remove
246                 ## the file.
247
248                 ## reset the cache to the first branch
249                 #os.system('git-update-index --cacheinfo %s %s %s'
250                 #          % (file1_mode, file1_hash, path))
251             __conflict(path)
252             return 1
253
254     # file does not exist in origin
255     else:
256         # file added in both
257         if file1_hash and file2_hash:
258             # files are the same
259             if file1_hash == file2_hash:
260                 if os.system('git-update-index --add --cacheinfo %s %s %s'
261                              % (file1_mode, file1_hash, path)) != 0:
262                     out.error('git-update-index failed')
263                     __conflict(path)
264                     return 1
265                 if os.system('git-checkout-index -u -f -- %s' % path):
266                     out.error('git-checkout-index failed')
267                     __conflict(path)
268                     return 1
269                 if file1_mode != file2_mode:
270                     out.error('File "s" added in both, permissions conflict'
271                               % path)
272                     __conflict(path)
273                     return 1
274             # files added in both but different
275             else:
276                 out.error('File "%s" added in branches but different' % path)
277                 # reset the cache to the first branch
278                 os.system('git-update-index --cacheinfo %s %s %s'
279                           % (file1_mode, file1_hash, path))
280
281                 if config.get('stgit.autoimerge') == 'yes':
282                     try:
283                         interactive_merge(path)
284                     except GitMergeException, ex:
285                         # interactive merge failed
286                         out.error(str(ex))
287                         if str(keeporig) != 'yes':
288                             __remove_files(orig_hash, file1_hash,
289                                            file2_hash)
290                         __conflict(path)
291                         return 1
292                     # successful interactive merge
293                     os.system('git-update-index -- %s' % path)
294                     __remove_files(orig_hash, file1_hash, file2_hash)
295                     return 0
296                 else:
297                     # no interactive merge, just mark it as conflict
298                     if str(keeporig) != 'yes':
299                         __remove_files(orig_hash, file1_hash, file2_hash)
300                     __conflict(path)
301                     return 1
302         # file added in one
303         elif file1_hash or file2_hash:
304             if file1_hash:
305                 mode = file1_mode
306                 obj = file1_hash
307             else:
308                 mode = file2_mode
309                 obj = file2_hash
310             if os.system('git-update-index --add --cacheinfo %s %s %s'
311                          % (mode, obj, path)) != 0:
312                 out.error('git-update-index failed')
313                 __conflict(path)
314                 return 1
315             __remove_files(orig_hash, file1_hash, file2_hash)
316             return os.system('git-checkout-index -u -f -- %s' % path)
317
318     # Unhandled case
319     out.error('Unhandled merge conflict: "%s" "%s" "%s" "%s" "%s" "%s" "%s"'
320               % (orig_hash, file1_hash, file2_hash,
321                  path,
322                  orig_mode, file1_mode, file2_mode))
323     __conflict(path)
324     return 1