@matheusbsbs / matheus-bagliano / commits / 720d150c48
Fork 0

Add a new merge strategy by Fredrik Kuivinen.

I really wanted to try this out, instead of asking for an adjustment to the 'git merge' driver and waiting. For now the new strategy is called 'fredrik' and not in the list of default strategies to be tried. The script wants Python 2.4 so this commit also adjusts Debian and RPM build procecure files. Signed-off-by: Junio C Hamano <junkio@cox.net>

Junio C Hamano committed Sep 10, 2005 at 17:46 UTC 720d150c48fc35fca13c6dfb3c76d60e4ee83b87
9 files changed +741 -7
.gitignore
+1
@@ -43,6 +43,7 @@ git-mailinfo
43 git-mailsplit
44 git-merge
45 git-merge-base
46 +git-merge-fredrik
47 git-merge-index
48 git-merge-octopus
49 git-merge-one-file
Makefile
+22 -1
@@ -48,6 +48,7 @@ ALL_CFLAGS = $(CFLAGS) $(PLATFORM_DEFINES) $(DEFINES)
48 prefix = $(HOME)
49 bindir = $(prefix)/bin
50 template_dir = $(prefix)/share/git-core/templates/
51 +GIT_PYTHON_DIR = $(prefix)/share/git-core/python
52 # DESTDIR=
53
54 CC = gcc
@@ -81,6 +82,9 @@ SCRIPT_PERL = \
82 git-archimport.perl git-cvsimport.perl git-relink.perl \
83 git-rename.perl git-shortlog.perl
84
85 +SCRIPT_PYTHON = \
86 + git-merge-fredrik.py
87 +
88 # The ones that do not have to link with lcrypto nor lz.
89 SIMPLE_PROGRAMS = \
90 git-get-tar-commit-id git-mailinfo git-mailsplit git-stripspace \
@@ -105,6 +109,9 @@ PROGRAMS = \
109 git-upload-pack git-verify-pack git-write-tree \
110 $(SIMPLE_PROGRAMS)
111
112 +PYMODULES = \
113 + gitMergeCommon.py
114 +
115 ifdef WITH_SEND_EMAIL
116 SCRIPT_PERL += git-send-email.perl
117 endif
@@ -150,6 +157,9 @@ endif
157 ifndef PERL_PATH
158 PERL_PATH = /usr/bin/perl
159 endif
160 +ifndef PYTHON_PATH
161 + PYTHON_PATH = /usr/bin/python
162 +endif
163
164 ifndef NO_OPENSSL
165 LIB_OBJS += epoch.o
@@ -189,7 +199,9 @@ endif
199 DEFINES += '-DSHA1_HEADER=$(SHA1_HEADER)'
200
201 SCRIPTS = $(patsubst %.sh,%,$(SCRIPT_SH)) \
192 - $(patsubst %.perl,%,$(SCRIPT_PERL)) gitk
202 + $(patsubst %.perl,%,$(SCRIPT_PERL)) \
203 + $(patsubst %.py,%,$(SCRIPT_PYTHON)) \
204 + gitk
205
206 ### Build rules
207
@@ -214,6 +226,13 @@ $(patsubst %.perl,%,$(SCRIPT_PERL)) : % : %.perl
226 sed -e '1s|#!.*perl|#!$(PERL_PATH)|' $@.perl >$@
227 chmod +x $@
228
229 +$(patsubst %.py,%,$(SCRIPT_PYTHON)) : % : %.py
230 + rm -f $@
231 + sed -e '1s|#!.*python|#!$(PYTHON_PATH)|' \
232 + -e 's|@@GIT_PYTHON_PATH@@|$(GIT_PYTHON_DIR)|g' \
233 + $@.py >$@
234 + chmod +x $@
235 +
236 %.o: %.c
237 $(CC) -o $*.o -c $(ALL_CFLAGS) $<
238 %.o: %.S
@@ -274,6 +293,8 @@ install: $(PROGRAMS) $(SCRIPTS)
293 $(INSTALL) git-revert $(DESTDIR)$(bindir)/git-cherry-pick
294 sh ./cmd-rename.sh $(DESTDIR)$(bindir)
295 $(MAKE) -C templates install
296 + $(INSTALL) -m755 -d $(DESTDIR)$(GIT_PYTHON_DIR)
297 + $(INSTALL) $(PYMODULES) $(DESTDIR)$(GIT_PYTHON_DIR)
298
299 install-doc:
300 $(MAKE) -C Documentation install
debian/control
+1 -1
@@ -8,7 +8,7 @@ Standards-Version: 3.6.1
8 Package: git-core
9 Architecture: any
10 Depends: ${shlibs:Depends}, ${perl:Depends}, ${misc:Depends}, patch, rcs
11 -Recommends: rsync, curl, ssh, libmail-sendmail-perl, libemail-valid-perl
11 +Recommends: rsync, curl, ssh, libmail-sendmail-perl, libemail-valid-perl, python (>= 2.4.0)
12 Suggests: cogito
13 Conflicts: git, cogito (<< 0.13)
14 Description: The git content addressable filesystem
debian/rules
+1 -1
@@ -41,7 +41,7 @@ MAN_DESTDIR := $(DESTDIR)/$(MANDIR)
41 build: debian/build-stamp
42 debian/build-stamp:
43 dh_testdir
44 - $(MAKE) prefix=$(PREFIX) all doc
44 + $(MAKE) prefix=$(PREFIX) PYTHON_PATH=/usr/bin/python2.4 all doc
45 touch debian/build-stamp
46
47 debian-clean:
git-core.spec.in
+1 -1
@@ -10,7 +10,7 @@ URL: http://kernel.org/pub/software/scm/git/
10 Source: http://kernel.org/pub/software/scm/git/%{name}-%{version}.tar.gz
11 BuildRequires: zlib-devel, openssl-devel, curl-devel %{!?_without_docs:, xmlto, asciidoc > 6.0.3}
12 BuildRoot: %{_tmppath}/%{name}-%{version}-root
13 -Requires: sh-utils, diffutils, rsync, rcs, mktemp >= 1.5
13 +Requires: sh-utils, diffutils, rsync, rcs, python >= 2.4
14
15 %description
16 This is a stupid (but extremely fast) directory content manager. It
git-merge-fredrik.py new
+426
@@ -0,0 +1,426 @@
1 +#!/usr/bin/python
2 +
3 +import sys, math, random, os, re, signal, tempfile, stat, errno
4 +from heapq import heappush, heappop
5 +from sets import Set
6 +
7 +sys.path.append('@@GIT_PYTHON_PATH@@')
8 +from gitMergeCommon import *
9 +
10 +alwaysWriteTree = False
11 +
12 +# The actual merge code
13 +# ---------------------
14 +
15 +def merge(h1, h2, branch1Name, branch2Name, graph, callDepth=0):
16 + '''Merge the commits h1 and h2, return the resulting virtual
17 + commit object and a flag indicating the cleaness of the merge.'''
18 + assert(isinstance(h1, Commit) and isinstance(h2, Commit))
19 + assert(isinstance(graph, Graph))
20 +
21 + def infoMsg(*args):
22 + sys.stdout.write(' '*callDepth)
23 + printList(args)
24 + infoMsg('Merging:')
25 + infoMsg(h1)
26 + infoMsg(h2)
27 + sys.stdout.flush()
28 +
29 + ca = getCommonAncestors(graph, h1, h2)
30 + infoMsg('found', len(ca), 'common ancestor(s):')
31 + for x in ca:
32 + infoMsg(x)
33 + sys.stdout.flush()
34 +
35 + Ms = ca[0]
36 + for h in ca[1:]:
37 + [Ms, ignore] = merge(Ms, h,
38 + 'Temporary shared merge branch 1',
39 + 'Temporary shared merge branch 2',
40 + graph, callDepth+1)
41 + assert(isinstance(Ms, Commit))
42 +
43 + if callDepth == 0:
44 + if len(ca) > 1:
45 + runProgram(['git-read-tree', h1.tree()])
46 + runProgram(['git-update-cache', '-q', '--refresh'])
47 + # Use the original index if we only have one common ancestor
48 +
49 + updateWd = True
50 + if alwaysWriteTree:
51 + cleanCache = True
52 + else:
53 + cleanCache = False
54 + else:
55 + runProgram(['git-read-tree', h1.tree()])
56 + updateWd = False
57 + cleanCache = True
58 +
59 + [shaRes, clean] = mergeTrees(h1.tree(), h2.tree(), Ms.tree(),
60 + branch1Name, branch2Name,
61 + cleanCache, updateWd)
62 +
63 + if clean or alwaysWriteTree:
64 + res = Commit(None, [h1, h2], tree=shaRes)
65 + graph.addNode(res)
66 + else:
67 + res = None
68 +
69 + return [res, clean]
70 +
71 +getFilesRE = re.compile('([0-9]+) ([a-z0-9]+) ([0-9a-f]{40})\t(.*)')
72 +def getFilesAndDirs(tree):
73 + files = Set()
74 + dirs = Set()
75 + out = runProgram(['git-ls-tree', '-r', '-z', tree])
76 + for l in out.split('\0'):
77 + m = getFilesRE.match(l)
78 + if m:
79 + if m.group(2) == 'tree':
80 + dirs.add(m.group(4))
81 + elif m.group(2) == 'blob':
82 + files.add(m.group(4))
83 +
84 + return [files, dirs]
85 +
86 +class CacheEntry:
87 + def __init__(self, path):
88 + class Stage:
89 + def __init__(self):
90 + self.sha1 = None
91 + self.mode = None
92 +
93 + self.stages = [Stage(), Stage(), Stage()]
94 + self.path = path
95 +
96 +unmergedRE = re.compile('^([0-9]+) ([0-9a-f]{40}) ([1-3])\t(.*)$')
97 +def unmergedCacheEntries():
98 + '''Create a dictionary mapping file names to CacheEntry
99 + objects. The dictionary contains one entry for every path with a
100 + non-zero stage entry.'''
101 +
102 + lines = runProgram(['git-ls-files', '-z', '--unmerged']).split('\0')
103 + lines.pop()
104 +
105 + res = {}
106 + for l in lines:
107 + m = unmergedRE.match(l)
108 + if m:
109 + mode = int(m.group(1), 8)
110 + sha1 = m.group(2)
111 + stage = int(m.group(3)) - 1
112 + path = m.group(4)
113 +
114 + if res.has_key(path):
115 + e = res[path]
116 + else:
117 + e = CacheEntry(path)
118 + res[path] = e
119 +
120 + e.stages[stage].mode = mode
121 + e.stages[stage].sha1 = sha1
122 + else:
123 + print 'Error: Merge program failed: Unexpected output from', \
124 + 'git-ls-files:', l
125 + sys.exit(2)
126 + return res
127 +
128 +def mergeTrees(head, merge, common, branch1Name, branch2Name,
129 + cleanCache, updateWd):
130 + '''Merge the trees 'head' and 'merge' with the common ancestor
131 + 'common'. The name of the head branch is 'branch1Name' and the name of
132 + the merge branch is 'branch2Name'. Return a tuple (tree, cleanMerge)
133 + where tree is the resulting tree and cleanMerge is True iff the
134 + merge was clean.'''
135 +
136 + assert(isSha(head) and isSha(merge) and isSha(common))
137 +
138 + if common == merge:
139 + print 'Already uptodate!'
140 + return [head, True]
141 +
142 + if updateWd:
143 + updateArg = '-u'
144 + else:
145 + updateArg = '-i'
146 + runProgram(['git-read-tree', updateArg, '-m', common, head, merge])
147 + cleanMerge = True
148 +
149 + [tree, code] = runProgram('git-write-tree', returnCode=True)
150 + tree = tree.rstrip()
151 + if code != 0:
152 + [files, dirs] = getFilesAndDirs(head)
153 + [filesM, dirsM] = getFilesAndDirs(merge)
154 + files.union_update(filesM)
155 + dirs.union_update(dirsM)
156 +
157 + cleanMerge = True
158 + entries = unmergedCacheEntries()
159 + for name in entries:
160 + if not processEntry(entries[name], branch1Name, branch2Name,
161 + files, dirs, cleanCache, updateWd):
162 + cleanMerge = False
163 +
164 + if cleanMerge or cleanCache:
165 + tree = runProgram('git-write-tree').rstrip()
166 + else:
167 + tree = None
168 + else:
169 + cleanMerge = True
170 +
171 + return [tree, cleanMerge]
172 +
173 +def processEntry(entry, branch1Name, branch2Name, files, dirs,
174 + cleanCache, updateWd):
175 + '''Merge one cache entry. 'files' is a Set with the files in both of
176 + the heads that we are going to merge. 'dirs' contains the
177 + corresponding data for directories. If 'cleanCache' is True no
178 + non-zero stages will be left in the cache for the path
179 + corresponding to the entry 'entry'.'''
180 +
181 +# cleanCache == True => Don't leave any non-stage 0 entries in the cache.
182 +# False => Leave unmerged entries
183 +
184 +# updateWd == True => Update the working directory to correspond to the cache
185 +# False => Leave the working directory unchanged
186 +
187 +# clean == True => non-conflict case
188 +# False => conflict case
189 +
190 +# If cleanCache == False then the cache shouldn't be updated if clean == False
191 +
192 + def updateFile(clean, sha, mode, path):
193 + if cleanCache or (not cleanCache and clean):
194 + runProgram(['git-update-cache', '--add', '--cacheinfo',
195 + '0%o' % mode, sha, path])
196 +
197 + if updateWd:
198 + prog = ['git-cat-file', 'blob', sha]
199 + if stat.S_ISREG(mode):
200 + try:
201 + os.unlink(path)
202 + except OSError:
203 + pass
204 + if mode & 0100:
205 + mode = 0777
206 + else:
207 + mode = 0666
208 + fd = os.open(path, os.O_WRONLY | os.O_TRUNC | os.O_CREAT, mode)
209 + proc = subprocess.Popen(prog, stdout=fd)
210 + proc.wait()
211 + os.close(fd)
212 + elif stat.S_ISLNK(mode):
213 + linkTarget = runProgram(prog)
214 + os.symlink(linkTarget, path)
215 + else:
216 + assert(False)
217 + runProgram(['git-update-cache', '--', path])
218 +
219 + def removeFile(clean, path):
220 + if cleanCache or (not cleanCache and clean):
221 + runProgram(['git-update-cache', '--force-remove', '--', path])
222 +
223 + if updateWd:
224 + try:
225 + os.unlink(path)
226 + except OSError, e:
227 + if e.errno != errno.ENOENT and e.errno != errno.EISDIR:
228 + raise
229 +
230 + def uniquePath(path, branch):
231 + newPath = path + '_' + branch
232 + suffix = 0
233 + while newPath in files or newPath in dirs:
234 + suffix += 1
235 + newPath = path + '_' + branch + '_' + str(suffix)
236 + files.add(newPath)
237 + return newPath
238 +
239 + debug('processing', entry.path, 'clean cache:', cleanCache,
240 + 'wd:', updateWd)
241 +
242 + cleanMerge = True
243 +
244 + path = entry.path
245 + oSha = entry.stages[0].sha1
246 + oMode = entry.stages[0].mode
247 + aSha = entry.stages[1].sha1
248 + aMode = entry.stages[1].mode
249 + bSha = entry.stages[2].sha1
250 + bMode = entry.stages[2].mode
251 +
252 + assert(oSha == None or isSha(oSha))
253 + assert(aSha == None or isSha(aSha))
254 + assert(bSha == None or isSha(bSha))
255 +
256 + assert(oMode == None or type(oMode) is int)
257 + assert(aMode == None or type(aMode) is int)
258 + assert(bMode == None or type(bMode) is int)
259 +
260 + if (oSha and (not aSha or not bSha)):
261 + #
262 + # Case A: Deleted in one
263 + #
264 + if (not aSha and not bSha) or \
265 + (aSha == oSha and not bSha) or \
266 + (not aSha and bSha == oSha):
267 + # Deleted in both or deleted in one and unchanged in the other
268 + if aSha:
269 + print 'Removing ' + path
270 + removeFile(True, path)
271 + else:
272 + # Deleted in one and changed in the other
273 + cleanMerge = False
274 + if not aSha:
275 + print 'CONFLICT (del/mod): "' + path + '" deleted in', \
276 + branch1Name, 'and modified in', branch2Name, \
277 + '. Version', branch2Name, ' of "' + path + \
278 + '" left in tree'
279 + mode = bMode
280 + sha = bSha
281 + else:
282 + print 'CONFLICT (mod/del): "' + path + '" deleted in', \
283 + branch2Name, 'and modified in', branch1Name + \
284 + '. Version', branch1Name, 'of "' + path + \
285 + '" left in tree'
286 + mode = aMode
287 + sha = aSha
288 +
289 + updateFile(False, sha, mode, path)
290 +
291 + elif (not oSha and aSha and not bSha) or \
292 + (not oSha and not aSha and bSha):
293 + #
294 + # Case B: Added in one.
295 + #
296 + if aSha:
297 + addBranch = branch1Name
298 + otherBranch = branch2Name
299 + mode = aMode
300 + sha = aSha
301 + conf = 'file/dir'
302 + else:
303 + addBranch = branch2Name
304 + otherBranch = branch1Name
305 + mode = bMode
306 + sha = bSha
307 + conf = 'dir/file'
308 +
309 + if path in dirs:
310 + cleanMerge = False
311 + newPath = uniquePath(path, addBranch)
312 + print 'CONFLICT (' + conf + \
313 + '): There is a directory with name "' + path + '" in', \
314 + otherBranch + '. Adding "' + path + '" as "' + newPath + '"'
315 +
316 + removeFile(False, path)
317 + path = newPath
318 + else:
319 + print 'Adding "' + path + '"'
320 +
321 + updateFile(True, sha, mode, path)
322 +
323 + elif not oSha and aSha and bSha:
324 + #
325 + # Case C: Added in both (check for same permissions).
326 + #
327 + if aSha == bSha:
328 + if aMode != bMode:
329 + cleanMerge = False
330 + print 'CONFLICT: File "' + path + \
331 + '" added identically in both branches,'
332 + print 'CONFLICT: but permissions conflict', '0%o' % aMode, \
333 + '->', '0%o' % bMode
334 + print 'CONFLICT: adding with permission:', '0%o' % aMode
335 +
336 + updateFile(False, aSha, aMode, path)
337 + else:
338 + # This case is handled by git-read-tree
339 + assert(False)
340 + else:
341 + cleanMerge = False
342 + newPath1 = uniquePath(path, branch1Name)
343 + newPath2 = uniquePath(path, branch2Name)
344 + print 'CONFLICT (add/add): File "' + path + \
345 + '" added non-identically in both branches.', \
346 + 'Adding "' + newPath1 + '" and "' + newPath2 + '" instead.'
347 + removeFile(False, path)
348 + updateFile(False, aSha, aMode, newPath1)
349 + updateFile(False, bSha, bMode, newPath2)
350 +
351 + elif oSha and aSha and bSha:
352 + #
353 + # case D: Modified in both, but differently.
354 + #
355 + print 'Auto-merging', path
356 + orig = runProgram(['git-unpack-file', oSha]).rstrip()
357 + src1 = runProgram(['git-unpack-file', aSha]).rstrip()
358 + src2 = runProgram(['git-unpack-file', bSha]).rstrip()
359 + [out, ret] = runProgram(['merge',
360 + '-L', branch1Name + '/' + path,
361 + '-L', 'orig/' + path,
362 + '-L', branch2Name + '/' + path,
363 + src1, orig, src2], returnCode=True)
364 +
365 + if aMode == oMode:
366 + mode = bMode
367 + else:
368 + mode = aMode
369 +
370 + sha = runProgram(['git-hash-object', '-t', 'blob', '-w',
371 + src1]).rstrip()
372 +
373 + if ret != 0:
374 + cleanMerge = False
375 + print 'CONFLICT (content): Merge conflict in "' + path + '".'
376 + updateFile(False, sha, mode, path)
377 + else:
378 + updateFile(True, sha, mode, path)
379 +
380 + os.unlink(orig)
381 + os.unlink(src1)
382 + os.unlink(src2)
383 + else:
384 + print 'ERROR: Fatal merge failure.'
385 + print "ERROR: Shouldn't happen"
386 + sys.exit(2)
387 +
388 + return cleanMerge
389 +
390 +def usage():
391 + print 'Usage:', sys.argv[0], ' <base>... -- <head> <remote>..'
392 + sys.exit(2)
393 +
394 +# main entry point as merge strategy module
395 +# The first parameters up to -- are merge bases, and the rest are heads.
396 +# This strategy module figures out merge bases itself, so we only
397 +# get heads.
398 +
399 +for nextArg in xrange(1, len(sys.argv)):
400 + if sys.argv[nextArg] == '--':
401 + if len(sys.argv) != nextArg + 3:
402 + print 'Not handling anything other than two heads merge.'
403 + sys.exit(2)
404 + try:
405 + h1 = firstBranch = sys.argv[nextArg + 1]
406 + h2 = secondBranch = sys.argv[nextArg + 2]
407 + except IndexError:
408 + usage()
409 + break
410 +
411 +print 'Merging', h1, 'with', h2
412 +h1 = runProgram(['git-rev-parse', '--verify', h1 + '^0']).rstrip()
413 +h2 = runProgram(['git-rev-parse', '--verify', h2 + '^0']).rstrip()
414 +
415 +graph = buildGraph([h1, h2])
416 +
417 +[res, clean] = merge(graph.shaMap[h1], graph.shaMap[h2],
418 + firstBranch, secondBranch, graph)
419 +
420 +print ''
421 +
422 +if clean:
423 + sys.exit(0)
424 +else:
425 + print 'Automatic merge failed, fix up by hand'
426 + sys.exit(1)
git-merge.sh
+1 -1
@@ -14,7 +14,7 @@ usage () {
14
15 # all_strategies='resolve fredrik stupid octopus'
16
17 -all_strategies='resolve octopus stupid'
17 +all_strategies='fredrik octopus resolve stupid'
18 default_strategies='resolve octopus'
19 use_strategies=
20
gitMergeCommon.py new
+268
@@ -0,0 +1,268 @@
1 +import sys, re, os, traceback
2 +from sets import Set
3 +
4 +if sys.version_info[0] < 2 or \
5 + (sys.version_info[0] == 2 and sys.version_info[1] < 4):
6 + print 'Python version 2.4 required, found', \
7 + str(sys.version_info[0])+'.'+str(sys.version_info[1])+'.'+ \
8 + str(sys.version_info[2])
9 + sys.exit(1)
10 +
11 +import subprocess
12 +
13 +# Debugging machinery
14 +# -------------------
15 +
16 +DEBUG = 0
17 +functionsToDebug = Set()
18 +
19 +def addDebug(func):
20 + if type(func) == str:
21 + functionsToDebug.add(func)
22 + else:
23 + functionsToDebug.add(func.func_name)
24 +
25 +def debug(*args):
26 + if DEBUG:
27 + funcName = traceback.extract_stack()[-2][2]
28 + if funcName in functionsToDebug:
29 + printList(args)
30 +
31 +def printList(list):
32 + for x in list:
33 + sys.stdout.write(str(x))
34 + sys.stdout.write(' ')
35 + sys.stdout.write('\n')
36 +
37 +# Program execution
38 +# -----------------
39 +
40 +class ProgramError(Exception):
41 + def __init__(self, progStr, error):
42 + self.progStr = progStr
43 + self.error = error
44 +
45 +addDebug('runProgram')
46 +def runProgram(prog, input=None, returnCode=False, env=None, pipeOutput=True):
47 + debug('runProgram prog:', str(prog), 'input:', str(input))
48 + if type(prog) is str:
49 + progStr = prog
50 + else:
51 + progStr = ' '.join(prog)
52 +
53 + try:
54 + if pipeOutput:
55 + stderr = subprocess.STDOUT
56 + stdout = subprocess.PIPE
57 + else:
58 + stderr = None
59 + stdout = None
60 + pop = subprocess.Popen(prog,
61 + shell = type(prog) is str,
62 + stderr=stderr,
63 + stdout=stdout,
64 + stdin=subprocess.PIPE,
65 + env=env)
66 + except OSError, e:
67 + debug('strerror:', e.strerror)
68 + raise ProgramError(progStr, e.strerror)
69 +
70 + if input != None:
71 + pop.stdin.write(input)
72 + pop.stdin.close()
73 +
74 + if pipeOutput:
75 + out = pop.stdout.read()
76 + else:
77 + out = ''
78 +
79 + code = pop.wait()
80 + if returnCode:
81 + ret = [out, code]
82 + else:
83 + ret = out
84 + if code != 0 and not returnCode:
85 + debug('error output:', out)
86 + debug('prog:', prog)
87 + raise ProgramError(progStr, out)
88 +# debug('output:', out.replace('\0', '\n'))
89 + return ret
90 +
91 +# Code for computing common ancestors
92 +# -----------------------------------
93 +
94 +currentId = 0
95 +def getUniqueId():
96 + global currentId
97 + currentId += 1
98 + return currentId
99 +
100 +# The 'virtual' commit objects have SHAs which are integers
101 +shaRE = re.compile('^[0-9a-f]{40}$')
102 +def isSha(obj):
103 + return (type(obj) is str and bool(shaRE.match(obj))) or \
104 + (type(obj) is int and obj >= 1)
105 +
106 +class Commit:
107 + def __init__(self, sha, parents, tree=None):
108 + self.parents = parents
109 + self.firstLineMsg = None
110 + self.children = []
111 +
112 + if tree:
113 + tree = tree.rstrip()
114 + assert(isSha(tree))
115 + self._tree = tree
116 +
117 + if not sha:
118 + self.sha = getUniqueId()
119 + self.virtual = True
120 + self.firstLineMsg = 'virtual commit'
121 + assert(isSha(tree))
122 + else:
123 + self.virtual = False
124 + self.sha = sha.rstrip()
125 + assert(isSha(self.sha))
126 +
127 + def tree(self):
128 + self.getInfo()
129 + assert(self._tree != None)
130 + return self._tree
131 +
132 + def shortInfo(self):
133 + self.getInfo()
134 + return str(self.sha) + ' ' + self.firstLineMsg
135 +
136 + def __str__(self):
137 + return self.shortInfo()
138 +
139 + def getInfo(self):
140 + if self.virtual or self.firstLineMsg != None:
141 + return
142 + else:
143 + info = runProgram(['git-cat-file', 'commit', self.sha])
144 + info = info.split('\n')
145 + msg = False
146 + for l in info:
147 + if msg:
148 + self.firstLineMsg = l
149 + break
150 + else:
151 + if l.startswith('tree'):
152 + self._tree = l[5:].rstrip()
153 + elif l == '':
154 + msg = True
155 +
156 +class Graph:
157 + def __init__(self):
158 + self.commits = []
159 + self.shaMap = {}
160 +
161 + def addNode(self, node):
162 + assert(isinstance(node, Commit))
163 + self.shaMap[node.sha] = node
164 + self.commits.append(node)
165 + for p in node.parents:
166 + p.children.append(node)
167 + return node
168 +
169 + def reachableNodes(self, n1, n2):
170 + res = {}
171 + def traverse(n):
172 + res[n] = True
173 + for p in n.parents:
174 + traverse(p)
175 +
176 + traverse(n1)
177 + traverse(n2)
178 + return res
179 +
180 + def fixParents(self, node):
181 + for x in range(0, len(node.parents)):
182 + node.parents[x] = self.shaMap[node.parents[x]]
183 +
184 +# addDebug('buildGraph')
185 +def buildGraph(heads):
186 + debug('buildGraph heads:', heads)
187 + for h in heads:
188 + assert(isSha(h))
189 +
190 + g = Graph()
191 +
192 + out = runProgram(['git-rev-list', '--parents'] + heads)
193 + for l in out.split('\n'):
194 + if l == '':
195 + continue
196 + shas = l.split(' ')
197 +
198 + # This is a hack, we temporarily use the 'parents' attribute
199 + # to contain a list of SHA1:s. They are later replaced by proper
200 + # Commit objects.
201 + c = Commit(shas[0], shas[1:])
202 +
203 + g.commits.append(c)
204 + g.shaMap[c.sha] = c
205 +
206 + for c in g.commits:
207 + g.fixParents(c)
208 +
209 + for c in g.commits:
210 + for p in c.parents:
211 + p.children.append(c)
212 + return g
213 +
214 +# Write the empty tree to the object database and return its SHA1
215 +def writeEmptyTree():
216 + tmpIndex = os.environ['GIT_DIR'] + '/merge-tmp-index'
217 + def delTmpIndex():
218 + try:
219 + os.unlink(tmpIndex)
220 + except OSError:
221 + pass
222 + delTmpIndex()
223 + newEnv = os.environ.copy()
224 + newEnv['GIT_INDEX_FILE'] = tmpIndex
225 + res = runProgram(['git-write-tree'], env=newEnv).rstrip()
226 + delTmpIndex()
227 + return res
228 +
229 +def addCommonRoot(graph):
230 + roots = []
231 + for c in graph.commits:
232 + if len(c.parents) == 0:
233 + roots.append(c)
234 +
235 + superRoot = Commit(sha=None, parents=[], tree=writeEmptyTree())
236 + graph.addNode(superRoot)
237 + for r in roots:
238 + r.parents = [superRoot]
239 + superRoot.children = roots
240 + return superRoot
241 +
242 +def getCommonAncestors(graph, commit1, commit2):
243 + '''Find the common ancestors for commit1 and commit2'''
244 + assert(isinstance(commit1, Commit) and isinstance(commit2, Commit))
245 +
246 + def traverse(start, set):
247 + stack = [start]
248 + while len(stack) > 0:
249 + el = stack.pop()
250 + set.add(el)
251 + for p in el.parents:
252 + if p not in set:
253 + stack.append(p)
254 + h1Set = Set()
255 + h2Set = Set()
256 + traverse(commit1, h1Set)
257 + traverse(commit2, h2Set)
258 + shared = h1Set.intersection(h2Set)
259 +
260 + if len(shared) == 0:
261 + shared = [addCommonRoot(graph)]
262 +
263 + res = Set()
264 +
265 + for s in shared:
266 + if len([c for c in s.children if c in shared]) == 0:
267 + res.add(s)
268 + return list(res)
read-tree.c
+20 -2
@@ -12,6 +12,7 @@
12
13 static int merge = 0;
14 static int update = 0;
15 +static int index_only = 0;
16
17 static int head_idx = -1;
18 static int merge_size = 0;
@@ -306,6 +307,9 @@ static void verify_uptodate(struct cache_entry *ce)
307 {
308 struct stat st;
309
310 + if (index_only)
311 + return;
312 +
313 if (!lstat(ce->name, &st)) {
314 unsigned changed = ce_match_stat(ce, &st);
315 if (!changed)
@@ -576,7 +580,7 @@ static int read_cache_unmerged(void)
580 return deleted;
581 }
582
579 -static const char read_tree_usage[] = "git-read-tree (<sha> | -m [-u] <sha1> [<sha2> [<sha3>]])";
583 +static const char read_tree_usage[] = "git-read-tree (<sha> | -m [-u | -i] <sha1> [<sha2> [<sha3>]])";
584
585 static struct cache_file cache_file;
586
@@ -595,12 +599,22 @@ int main(int argc, char **argv)
599 for (i = 1; i < argc; i++) {
600 const char *arg = argv[i];
601
598 - /* "-u" means "update", meaning that a merge will update the working directory */
602 + /* "-u" means "update", meaning that a merge will update
603 + * the working tree.
604 + */
605 if (!strcmp(arg, "-u")) {
606 update = 1;
607 continue;
608 }
609
610 + /* "-i" means "index only", meaning that a merge will
611 + * not even look at the working tree.
612 + */
613 + if (!strcmp(arg, "-i")) {
614 + index_only = 1;
615 + continue;
616 + }
617 +
618 /* This differs from "-m" in that we'll silently ignore unmerged entries */
619 if (!strcmp(arg, "--reset")) {
620 if (stage || merge)
@@ -628,6 +642,10 @@ int main(int argc, char **argv)
642 continue;
643 }
644
645 + /* using -u and -i at the same time makes no sense */
646 + if (1 < index_only + update)
647 + usage(read_tree_usage);
648 +
649 if (get_sha1(arg, sha1) < 0)
650 usage(read_tree_usage);
651 if (list_tree(sha1) < 0)