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