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