Let "stg applied" and "stg unapplied" use the new infrastructure
[stgit] / stgit / gitmergeonefile.py
CommitLineData
3659ef88
CM
1"""Performs a 3-way merge for GIT files
2"""
3
4__copyright__ = """
5Copyright (C) 2006, Catalin Marinas <catalin.marinas@gmail.com>
6
7This program is free software; you can redistribute it and/or modify
8it under the terms of the GNU General Public License version 2 as
9published by the Free Software Foundation.
10
11This program is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with this program; if not, write to the Free Software
18Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19"""
20
21import sys, os
87c93eab 22from stgit.exception import *
170f576b 23from stgit import basedir
f7ed76a9 24from stgit.config import config, file_extensions, ConfigOption
5e888f30
KH
25from stgit.utils import append_string
26from stgit.out import *
f0de3f92 27from stgit.run import *
3659ef88 28
87c93eab 29class GitMergeException(StgException):
3659ef88
CM
30 pass
31
32
33#
34# Options
35#
eee7283e
CM
36merger = ConfigOption('stgit', 'merger')
37keeporig = ConfigOption('stgit', 'keeporig')
3659ef88
CM
38
39#
40# Utility functions
41#
42def __str2none(x):
43 if x == '':
44 return None
45 else:
46 return x
47
f0de3f92
KH
48class MRun(Run):
49 exc = GitMergeException # use a custom exception class on errors
3659ef88
CM
50
51def __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
1e075406
CM
58 extensions = file_extensions()
59
3659ef88 60 if orig_hash:
1e075406 61 orig = path + extensions['ancestor']
1576d681 62 tmp = MRun('git', 'unpack-file', orig_hash).output_one_line()
3659ef88
CM
63 os.chmod(tmp, int(orig_mode, 8))
64 os.renames(tmp, orig)
65 if file1_hash:
1e075406 66 src1 = path + extensions['current']
1576d681 67 tmp = MRun('git', 'unpack-file', file1_hash).output_one_line()
3659ef88
CM
68 os.chmod(tmp, int(file1_mode, 8))
69 os.renames(tmp, src1)
70 if file2_hash:
1e075406 71 src2 = path + extensions['patched']
1576d681 72 tmp = MRun('git', 'unpack-file', file2_hash).output_one_line()
3659ef88
CM
73 os.chmod(tmp, int(file2_mode, 8))
74 os.renames(tmp, src2)
75
8d415553
CM
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
1576d681 79 tmp = MRun('git', 'unpack-file', file1_hash).output_one_line()
8d415553
CM
80 os.chmod(tmp, int(file1_mode, 8))
81 os.renames(tmp, path)
82
3659ef88
CM
83def __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)
3659ef88 92
3659ef88
CM
93def __conflict(path):
94 """Write the conflict file for the 'path' variable and exit
95 """
170f576b 96 append_string(os.path.join(basedir.get(), 'conflicts'), path)
3659ef88
CM
97
98
f7ed76a9 99def interactive_merge(filename):
c5bd7632
KH
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)
f7ed76a9 154
3659ef88
CM
155#
156# Main algorithm
157#
158def 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:
1576d681 173 if os.system('git update-index --cacheinfo %s %s %s'
3659ef88 174 % (file1_mode, file1_hash, path)) != 0:
1576d681 175 out.error('git update-index failed')
3659ef88
CM
176 __conflict(path)
177 return 1
1576d681
CM
178 if os.system('git checkout-index -u -f -- %s' % path):
179 out.error('git checkout-index failed')
3659ef88
CM
180 __conflict(path)
181 return 1
182 if file1_mode != file2_mode:
27ac2b7e 183 out.error('File added in both, permissions conflict')
3659ef88
CM
184 __conflict(path)
185 return 1
186 # 3-way merge
187 else:
5b99888b
CM
188 merge_ok = os.system(str(merger) % {'branch1': src1,
189 'ancestor': orig,
190 'branch2': src2,
191 'output': path }) == 0
3659ef88
CM
192
193 if merge_ok:
1576d681 194 os.system('git update-index -- %s' % path)
3659ef88
CM
195 __remove_files(orig_hash, file1_hash, file2_hash)
196 return 0
197 else:
27ac2b7e
KH
198 out.error('Three-way merge tool failed for file "%s"'
199 % path)
3659ef88 200 # reset the cache to the first branch
1576d681 201 os.system('git update-index --cacheinfo %s %s %s'
3659ef88 202 % (file1_mode, file1_hash, path))
f7ed76a9 203
c73e63b7 204 if config.get('stgit.autoimerge') == 'yes':
f7ed76a9
CM
205 try:
206 interactive_merge(path)
207 except GitMergeException, ex:
208 # interactive merge failed
f0b5d4dd 209 out.error(str(ex))
f7ed76a9
CM
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
1576d681 216 os.system('git update-index -- %s' % path)
3659ef88 217 __remove_files(orig_hash, file1_hash, file2_hash)
f7ed76a9
CM
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
3659ef88
CM
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)
1576d681 232 return os.system('git update-index --remove -- %s' % path)
3659ef88
CM
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.
1576d681 240 os.system('git update-index --remove -- %s' % path)
3659ef88
CM
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
1576d681 247 #os.system('git update-index --remove -- %s' % path)
3659ef88
CM
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
1576d681 255 #os.system('git update-index --cacheinfo %s %s %s'
3659ef88
CM
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:
1576d681 266 if os.system('git update-index --add --cacheinfo %s %s %s'
3659ef88 267 % (file1_mode, file1_hash, path)) != 0:
1576d681 268 out.error('git update-index failed')
3659ef88
CM
269 __conflict(path)
270 return 1
1576d681
CM
271 if os.system('git checkout-index -u -f -- %s' % path):
272 out.error('git checkout-index failed')
3659ef88
CM
273 __conflict(path)
274 return 1
275 if file1_mode != file2_mode:
27ac2b7e
KH
276 out.error('File "s" added in both, permissions conflict'
277 % path)
3659ef88
CM
278 __conflict(path)
279 return 1
b6e961f2 280 # files added in both but different
3659ef88 281 else:
27ac2b7e 282 out.error('File "%s" added in branches but different' % path)
b6e961f2 283 # reset the cache to the first branch
1576d681 284 os.system('git update-index --cacheinfo %s %s %s'
b6e961f2
CM
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
f0b5d4dd 292 out.error(str(ex))
b6e961f2
CM
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
1576d681 299 os.system('git update-index -- %s' % path)
b6e961f2
CM
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
3659ef88
CM
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
1576d681 316 if os.system('git update-index --add --cacheinfo %s %s %s'
3659ef88 317 % (mode, obj, path)) != 0:
1576d681 318 out.error('git update-index failed')
3659ef88
CM
319 __conflict(path)
320 return 1
321 __remove_files(orig_hash, file1_hash, file2_hash)
1576d681 322 return os.system('git checkout-index -u -f -- %s' % path)
3659ef88
CM
323
324 # Unhandled case
27ac2b7e
KH
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))
3659ef88
CM
329 __conflict(path)
330 return 1