blob: b587e79b482975cff1e366a1d3c33ea95e944a3a [file] [log] [blame]
Simon Hausmann86949ee2007-03-19 20:59:12 +01001#!/usr/bin/env python
2#
3# git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
4#
5# Author: Simon Hausmann <hausmann@kde.org>
Simon Hausmann83dce552007-03-19 22:26:36 +01006# Copyright: 2007 Simon Hausmann <hausmann@kde.org>
7# 2007 Trolltech ASA
Simon Hausmann86949ee2007-03-19 20:59:12 +01008# License: MIT <http://www.opensource.org/licenses/mit-license.php>
9#
Simon Hausmann58346842007-05-21 22:57:06 +020010# TODO: * Consider making --with-origin the default, assuming that the git
Simon Hausmann341dc1c2007-05-21 00:39:16 +020011# protocol is always more efficient. (needs manual testing first :)
Simon Hausmann24f7b532007-05-20 23:42:22 +020012#
Simon Hausmann86949ee2007-03-19 20:59:12 +010013
Simon Hausmann08483582007-05-15 14:31:06 +020014import optparse, sys, os, marshal, popen2, subprocess, shelve
Simon Hausmann25df95c2007-05-15 15:15:39 +020015import tempfile, getopt, sha, os.path, time, platform
Simon Hausmannb9847332007-03-20 20:54:23 +010016from sets import Set;
Simon Hausmann4f5cf762007-03-19 22:25:17 +010017
18gitdir = os.environ.get("GIT_DIR", "")
Simon Hausmann86949ee2007-03-19 20:59:12 +010019
Simon Hausmanncaace112007-05-15 14:57:57 +020020def mypopen(command):
21 return os.popen(command, "rb");
22
Simon Hausmann86949ee2007-03-19 20:59:12 +010023def p4CmdList(cmd):
24 cmd = "p4 -G %s" % cmd
25 pipe = os.popen(cmd, "rb")
26
27 result = []
28 try:
29 while True:
30 entry = marshal.load(pipe)
31 result.append(entry)
32 except EOFError:
33 pass
Simon Hausmanna6d5da32007-05-23 23:27:31 +020034 exitCode = pipe.close()
35 if exitCode != None:
Simon Hausmannac3e0d72007-05-23 23:32:32 +020036 entry = {}
37 entry["p4ExitCode"] = exitCode
38 result.append(entry)
Simon Hausmann86949ee2007-03-19 20:59:12 +010039
40 return result
41
42def p4Cmd(cmd):
43 list = p4CmdList(cmd)
44 result = {}
45 for entry in list:
46 result.update(entry)
47 return result;
48
Simon Hausmanncb2c9db2007-03-24 09:15:11 +010049def p4Where(depotPath):
50 if not depotPath.endswith("/"):
51 depotPath += "/"
52 output = p4Cmd("where %s..." % depotPath)
Simon Hausmanndc524032007-05-21 09:34:56 +020053 if output["code"] == "error":
54 return ""
Simon Hausmanncb2c9db2007-03-24 09:15:11 +010055 clientPath = ""
56 if "path" in output:
57 clientPath = output.get("path")
58 elif "data" in output:
59 data = output.get("data")
60 lastSpace = data.rfind(" ")
61 clientPath = data[lastSpace + 1:]
62
63 if clientPath.endswith("..."):
64 clientPath = clientPath[:-3]
65 return clientPath
66
Simon Hausmann86949ee2007-03-19 20:59:12 +010067def die(msg):
68 sys.stderr.write(msg + "\n")
69 sys.exit(1)
70
71def currentGitBranch():
Simon Hausmanncaace112007-05-15 14:57:57 +020072 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
Simon Hausmann86949ee2007-03-19 20:59:12 +010073
Simon Hausmann4f5cf762007-03-19 22:25:17 +010074def isValidGitDir(path):
75 if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
76 return True;
77 return False
78
Simon Hausmann463e8af2007-05-17 09:13:54 +020079def parseRevision(ref):
80 return mypopen("git rev-parse %s" % ref).read()[:-1]
81
Simon Hausmann4f5cf762007-03-19 22:25:17 +010082def system(cmd):
83 if os.system(cmd) != 0:
84 die("command failed: %s" % cmd)
85
Simon Hausmann6ae8de82007-03-22 21:10:25 +010086def extractLogMessageFromGitCommit(commit):
87 logMessage = ""
88 foundTitle = False
Simon Hausmanncaace112007-05-15 14:57:57 +020089 for log in mypopen("git cat-file commit %s" % commit).readlines():
Simon Hausmann6ae8de82007-03-22 21:10:25 +010090 if not foundTitle:
91 if len(log) == 1:
Simon Hausmann1c094182007-05-01 23:15:48 +020092 foundTitle = True
Simon Hausmann6ae8de82007-03-22 21:10:25 +010093 continue
94
95 logMessage += log
96 return logMessage
97
98def extractDepotPathAndChangeFromGitLog(log):
99 values = {}
100 for line in log.split("\n"):
101 line = line.strip()
102 if line.startswith("[git-p4:") and line.endswith("]"):
103 line = line[8:-1].strip()
104 for assignment in line.split(":"):
105 variable = assignment.strip()
106 value = ""
107 equalPos = assignment.find("=")
108 if equalPos != -1:
109 variable = assignment[:equalPos].strip()
110 value = assignment[equalPos + 1:].strip()
111 if value.startswith("\"") and value.endswith("\""):
112 value = value[1:-1]
113 values[variable] = value
114
115 return values.get("depot-path"), values.get("change")
116
Simon Hausmann8136a632007-03-22 21:27:14 +0100117def gitBranchExists(branch):
Simon Hausmanncaace112007-05-15 14:57:57 +0200118 proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
119 return proc.wait() == 0;
Simon Hausmann8136a632007-03-22 21:27:14 +0100120
Simon Hausmannb9847332007-03-20 20:54:23 +0100121class Command:
122 def __init__(self):
123 self.usage = "usage: %prog [options]"
Simon Hausmann8910ac02007-03-26 08:18:55 +0200124 self.needsGit = True
Simon Hausmannb9847332007-03-20 20:54:23 +0100125
126class P4Debug(Command):
Simon Hausmann86949ee2007-03-19 20:59:12 +0100127 def __init__(self):
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100128 Command.__init__(self)
Simon Hausmann86949ee2007-03-19 20:59:12 +0100129 self.options = [
130 ]
Simon Hausmannc8c39112007-03-19 21:02:30 +0100131 self.description = "A tool to debug the output of p4 -G."
Simon Hausmann8910ac02007-03-26 08:18:55 +0200132 self.needsGit = False
Simon Hausmann86949ee2007-03-19 20:59:12 +0100133
134 def run(self, args):
135 for output in p4CmdList(" ".join(args)):
136 print output
Simon Hausmannb9847332007-03-20 20:54:23 +0100137 return True
Simon Hausmann86949ee2007-03-19 20:59:12 +0100138
Simon Hausmann58346842007-05-21 22:57:06 +0200139class P4RollBack(Command):
140 def __init__(self):
141 Command.__init__(self)
142 self.options = [
Simon Hausmann0c66a782007-05-23 20:07:57 +0200143 optparse.make_option("--verbose", dest="verbose", action="store_true"),
144 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
Simon Hausmann58346842007-05-21 22:57:06 +0200145 ]
146 self.description = "A tool to debug the multi-branch import. Don't use :)"
Simon Hausmann52102d42007-05-21 23:44:24 +0200147 self.verbose = False
Simon Hausmann0c66a782007-05-23 20:07:57 +0200148 self.rollbackLocalBranches = False
Simon Hausmann58346842007-05-21 22:57:06 +0200149
150 def run(self, args):
151 if len(args) != 1:
152 return False
153 maxChange = int(args[0])
Simon Hausmann0c66a782007-05-23 20:07:57 +0200154
Simon Hausmannad192f22007-05-23 23:44:19 +0200155 if "p4ExitCode" in p4Cmd("changes -m 1"):
Simon Hausmann66a2f522007-05-23 23:40:48 +0200156 die("Problems executing p4");
157
Simon Hausmann0c66a782007-05-23 20:07:57 +0200158 if self.rollbackLocalBranches:
159 refPrefix = "refs/heads/"
160 lines = mypopen("git rev-parse --symbolic --branches").readlines()
161 else:
162 refPrefix = "refs/remotes/"
163 lines = mypopen("git rev-parse --symbolic --remotes").readlines()
164
165 for line in lines:
166 if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
167 ref = refPrefix + line[:-1]
Simon Hausmann58346842007-05-21 22:57:06 +0200168 log = extractLogMessageFromGitCommit(ref)
169 depotPath, change = extractDepotPathAndChangeFromGitLog(log)
170 changed = False
Simon Hausmann52102d42007-05-21 23:44:24 +0200171
172 if len(p4Cmd("changes -m 1 %s...@%s" % (depotPath, maxChange))) == 0:
173 print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
174 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
175 continue
176
Simon Hausmann58346842007-05-21 22:57:06 +0200177 while len(change) > 0 and int(change) > maxChange:
178 changed = True
Simon Hausmann52102d42007-05-21 23:44:24 +0200179 if self.verbose:
180 print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
Simon Hausmann58346842007-05-21 22:57:06 +0200181 system("git update-ref %s \"%s^\"" % (ref, ref))
182 log = extractLogMessageFromGitCommit(ref)
183 depotPath, change = extractDepotPathAndChangeFromGitLog(log)
184
185 if changed:
Simon Hausmann52102d42007-05-21 23:44:24 +0200186 print "%s rewound to %s" % (ref, change)
Simon Hausmann58346842007-05-21 22:57:06 +0200187
188 return True
189
Simon Hausmann711544b2007-04-01 15:40:46 +0200190class P4Submit(Command):
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100191 def __init__(self):
Simon Hausmannb9847332007-03-20 20:54:23 +0100192 Command.__init__(self)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100193 self.options = [
194 optparse.make_option("--continue", action="store_false", dest="firstTime"),
195 optparse.make_option("--origin", dest="origin"),
196 optparse.make_option("--reset", action="store_true", dest="reset"),
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100197 optparse.make_option("--log-substitutions", dest="substFile"),
198 optparse.make_option("--noninteractive", action="store_false"),
Simon Hausmann04219c02007-03-21 10:11:20 +0100199 optparse.make_option("--dry-run", action="store_true"),
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200200 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100201 ]
202 self.description = "Submit changes from git to the perforce depot."
Simon Hausmannc9b50e62007-03-29 19:15:24 +0200203 self.usage += " [name of git branch to submit into perforce depot]"
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100204 self.firstTime = True
205 self.reset = False
206 self.interactive = True
207 self.dryRun = False
208 self.substFile = ""
209 self.firstTime = True
Simon Hausmann95124972007-03-23 09:16:07 +0100210 self.origin = ""
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200211 self.directSubmit = False
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100212
213 self.logSubstitutions = {}
214 self.logSubstitutions["<enter description here>"] = "%log%"
215 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
216
217 def check(self):
218 if len(p4CmdList("opened ...")) > 0:
219 die("You have files opened with perforce! Close them before starting the sync.")
220
221 def start(self):
222 if len(self.config) > 0 and not self.reset:
Simon Hausmannc3c46242007-05-16 09:43:13 +0200223 die("Cannot start sync. Previous sync config found at %s\nIf you want to start submitting again from scratch maybe you want to call git-p4 submit --reset" % self.configFile)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100224
225 commits = []
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200226 if self.directSubmit:
227 commits.append("0")
228 else:
229 for line in mypopen("git rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
230 commits.append(line[:-1])
231 commits.reverse()
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100232
233 self.config["commits"] = commits
234
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100235 def prepareLogMessage(self, template, message):
236 result = ""
237
238 for line in template.split("\n"):
239 if line.startswith("#"):
240 result += line + "\n"
241 continue
242
243 substituted = False
244 for key in self.logSubstitutions.keys():
245 if line.find(key) != -1:
246 value = self.logSubstitutions[key]
247 value = value.replace("%log%", message)
248 if value != "@remove@":
249 result += line.replace(key, value) + "\n"
250 substituted = True
251 break
252
253 if not substituted:
254 result += line + "\n"
255
256 return result
257
258 def apply(self, id):
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200259 if self.directSubmit:
260 print "Applying local change in working directory/index"
261 diff = self.diffStatus
262 else:
263 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
264 diff = mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100265 filesToAdd = set()
266 filesToDelete = set()
Simon Hausmannd336c152007-05-16 09:41:26 +0200267 editedFiles = set()
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100268 for line in diff:
269 modifier = line[0]
270 path = line[1:].strip()
271 if modifier == "M":
Simon Hausmannd336c152007-05-16 09:41:26 +0200272 system("p4 edit \"%s\"" % path)
273 editedFiles.add(path)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100274 elif modifier == "A":
275 filesToAdd.add(path)
276 if path in filesToDelete:
277 filesToDelete.remove(path)
278 elif modifier == "D":
279 filesToDelete.add(path)
280 if path in filesToAdd:
281 filesToAdd.remove(path)
282 else:
283 die("unknown modifier %s for %s" % (modifier, path))
284
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200285 if self.directSubmit:
286 diffcmd = "cat \"%s\"" % self.diffFile
287 else:
288 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
Simon Hausmann47a130b2007-05-20 16:33:21 +0200289 patchcmd = diffcmd + " | git apply "
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200290 tryPatchCmd = patchcmd + "--check -"
291 applyPatchCmd = patchcmd + "--check --apply -"
Simon Hausmann51a26402007-04-15 09:59:56 +0200292
Simon Hausmann47a130b2007-05-20 16:33:21 +0200293 if os.system(tryPatchCmd) != 0:
Simon Hausmann51a26402007-04-15 09:59:56 +0200294 print "Unfortunately applying the change failed!"
295 print "What do you want to do?"
296 response = "x"
297 while response != "s" and response != "a" and response != "w":
298 response = raw_input("[s]kip this patch / [a]pply the patch forcibly and with .rej files / [w]rite the patch to a file (patch.txt) ")
299 if response == "s":
300 print "Skipping! Good luck with the next patches..."
301 return
302 elif response == "a":
Simon Hausmann47a130b2007-05-20 16:33:21 +0200303 os.system(applyPatchCmd)
Simon Hausmann51a26402007-04-15 09:59:56 +0200304 if len(filesToAdd) > 0:
305 print "You may also want to call p4 add on the following files:"
306 print " ".join(filesToAdd)
307 if len(filesToDelete):
308 print "The following files should be scheduled for deletion with p4 delete:"
309 print " ".join(filesToDelete)
310 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
311 elif response == "w":
312 system(diffcmd + " > patch.txt")
313 print "Patch saved to patch.txt in %s !" % self.clientPath
314 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
315
Simon Hausmann47a130b2007-05-20 16:33:21 +0200316 system(applyPatchCmd)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100317
318 for f in filesToAdd:
319 system("p4 add %s" % f)
320 for f in filesToDelete:
321 system("p4 revert %s" % f)
322 system("p4 delete %s" % f)
323
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200324 logMessage = ""
325 if not self.directSubmit:
326 logMessage = extractLogMessageFromGitCommit(id)
327 logMessage = logMessage.replace("\n", "\n\t")
328 logMessage = logMessage[:-1]
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100329
Simon Hausmanncaace112007-05-15 14:57:57 +0200330 template = mypopen("p4 change -o").read()
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100331
332 if self.interactive:
333 submitTemplate = self.prepareLogMessage(template, logMessage)
Simon Hausmanncaace112007-05-15 14:57:57 +0200334 diff = mypopen("p4 diff -du ...").read()
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100335
336 for newFile in filesToAdd:
337 diff += "==== new file ====\n"
338 diff += "--- /dev/null\n"
339 diff += "+++ %s\n" % newFile
340 f = open(newFile, "r")
341 for line in f.readlines():
342 diff += "+" + line
343 f.close()
344
Simon Hausmann25df95c2007-05-15 15:15:39 +0200345 separatorLine = "######## everything below this line is just the diff #######"
346 if platform.system() == "Windows":
347 separatorLine += "\r"
348 separatorLine += "\n"
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100349
350 response = "e"
Simon Hausmann53150252007-03-21 21:04:12 +0100351 firstIteration = True
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100352 while response == "e":
Simon Hausmann53150252007-03-21 21:04:12 +0100353 if not firstIteration:
Simon Hausmannd336c152007-05-16 09:41:26 +0200354 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
Simon Hausmann53150252007-03-21 21:04:12 +0100355 firstIteration = False
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100356 if response == "e":
357 [handle, fileName] = tempfile.mkstemp()
358 tmpFile = os.fdopen(handle, "w+")
Simon Hausmann53150252007-03-21 21:04:12 +0100359 tmpFile.write(submitTemplate + separatorLine + diff)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100360 tmpFile.close()
Simon Hausmann25df95c2007-05-15 15:15:39 +0200361 defaultEditor = "vi"
362 if platform.system() == "Windows":
363 defaultEditor = "notepad"
364 editor = os.environ.get("EDITOR", defaultEditor);
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100365 system(editor + " " + fileName)
Simon Hausmann25df95c2007-05-15 15:15:39 +0200366 tmpFile = open(fileName, "rb")
Simon Hausmann53150252007-03-21 21:04:12 +0100367 message = tmpFile.read()
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100368 tmpFile.close()
369 os.remove(fileName)
Simon Hausmann53150252007-03-21 21:04:12 +0100370 submitTemplate = message[:message.index(separatorLine)]
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100371
372 if response == "y" or response == "yes":
373 if self.dryRun:
374 print submitTemplate
375 raw_input("Press return to continue...")
376 else:
Simon Hausmann7944f142007-05-21 11:04:26 +0200377 if self.directSubmit:
378 print "Submitting to git first"
379 os.chdir(self.oldWorkingDirectory)
380 pipe = os.popen("git commit -a -F -", "wb")
381 pipe.write(submitTemplate)
382 pipe.close()
383 os.chdir(self.clientPath)
384
385 pipe = os.popen("p4 submit -i", "wb")
386 pipe.write(submitTemplate)
387 pipe.close()
Simon Hausmannd336c152007-05-16 09:41:26 +0200388 elif response == "s":
389 for f in editedFiles:
390 system("p4 revert \"%s\"" % f);
391 for f in filesToAdd:
392 system("p4 revert \"%s\"" % f);
393 system("rm %s" %f)
394 for f in filesToDelete:
395 system("p4 delete \"%s\"" % f);
396 return
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100397 else:
398 print "Not submitting!"
399 self.interactive = False
400 else:
401 fileName = "submit.txt"
402 file = open(fileName, "w+")
403 file.write(self.prepareLogMessage(template, logMessage))
404 file.close()
405 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
406
407 def run(self, args):
Simon Hausmann95124972007-03-23 09:16:07 +0100408 global gitdir
409 # make gitdir absolute so we can cd out into the perforce checkout
410 gitdir = os.path.abspath(gitdir)
411 os.environ["GIT_DIR"] = gitdir
Simon Hausmannc9b50e62007-03-29 19:15:24 +0200412
413 if len(args) == 0:
414 self.master = currentGitBranch()
415 if len(self.master) == 0 or not os.path.exists("%s/refs/heads/%s" % (gitdir, self.master)):
416 die("Detecting current git branch failed!")
417 elif len(args) == 1:
418 self.master = args[0]
419 else:
420 return False
421
Simon Hausmann95124972007-03-23 09:16:07 +0100422 depotPath = ""
423 if gitBranchExists("p4"):
424 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
425 if len(depotPath) == 0 and gitBranchExists("origin"):
426 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
427
428 if len(depotPath) == 0:
429 print "Internal error: cannot locate perforce depot path from existing branches"
430 sys.exit(128)
431
Simon Hausmann51a26402007-04-15 09:59:56 +0200432 self.clientPath = p4Where(depotPath)
Simon Hausmann95124972007-03-23 09:16:07 +0100433
Simon Hausmann51a26402007-04-15 09:59:56 +0200434 if len(self.clientPath) == 0:
Simon Hausmann95124972007-03-23 09:16:07 +0100435 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
436 sys.exit(128)
437
Simon Hausmann51a26402007-04-15 09:59:56 +0200438 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
Simon Hausmann7944f142007-05-21 11:04:26 +0200439 self.oldWorkingDirectory = os.getcwd()
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200440
441 if self.directSubmit:
442 self.diffStatus = mypopen("git diff -r --name-status HEAD").readlines()
Simon Hausmanncbf5efa2007-05-21 10:08:11 +0200443 if len(self.diffStatus) == 0:
444 print "No changes in working directory to submit."
445 return True
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200446 patch = mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
447 self.diffFile = gitdir + "/p4-git-diff"
448 f = open(self.diffFile, "wb")
449 f.write(patch)
450 f.close();
451
Simon Hausmann51a26402007-04-15 09:59:56 +0200452 os.chdir(self.clientPath)
453 response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
Simon Hausmann95124972007-03-23 09:16:07 +0100454 if response == "y" or response == "yes":
455 system("p4 sync ...")
456
457 if len(self.origin) == 0:
458 if gitBranchExists("p4"):
459 self.origin = "p4"
460 else:
461 self.origin = "origin"
462
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100463 if self.reset:
464 self.firstTime = True
465
466 if len(self.substFile) > 0:
467 for line in open(self.substFile, "r").readlines():
468 tokens = line[:-1].split("=")
469 self.logSubstitutions[tokens[0]] = tokens[1]
470
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100471 self.check()
472 self.configFile = gitdir + "/p4-git-sync.cfg"
473 self.config = shelve.open(self.configFile, writeback=True)
474
475 if self.firstTime:
476 self.start()
477
478 commits = self.config.get("commits", [])
479
480 while len(commits) > 0:
481 self.firstTime = False
482 commit = commits[0]
483 commits = commits[1:]
484 self.config["commits"] = commits
485 self.apply(commit)
486 if not self.interactive:
487 break
488
489 self.config.close()
490
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200491 if self.directSubmit:
492 os.remove(self.diffFile)
493
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100494 if len(commits) == 0:
495 if self.firstTime:
496 print "No changes found to apply between %s and current HEAD" % self.origin
497 else:
498 print "All changes applied!"
Simon Hausmann7944f142007-05-21 11:04:26 +0200499 os.chdir(self.oldWorkingDirectory)
500 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
Simon Hausmann80b59102007-04-09 12:43:40 +0200501 if response == "y" or response == "yes":
Simon Hausmann80b59102007-04-09 12:43:40 +0200502 rebase = P4Rebase()
503 rebase.run([])
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100504 os.remove(self.configFile)
505
Simon Hausmannb9847332007-03-20 20:54:23 +0100506 return True
507
Simon Hausmann711544b2007-04-01 15:40:46 +0200508class P4Sync(Command):
Simon Hausmannb9847332007-03-20 20:54:23 +0100509 def __init__(self):
510 Command.__init__(self)
511 self.options = [
512 optparse.make_option("--branch", dest="branch"),
513 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
514 optparse.make_option("--changesfile", dest="changesFile"),
515 optparse.make_option("--silent", dest="silent", action="store_true"),
Simon Hausmannef48f902007-05-17 22:17:49 +0200516 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200517 optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true"),
Simon Hausmanna028a982007-05-23 00:03:08 +0200518 optparse.make_option("--verbose", dest="verbose", action="store_true"),
Simon Hausmann01a9c9c2007-05-23 00:07:35 +0200519 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false"),
520 optparse.make_option("--max-changes", dest="maxChanges")
Simon Hausmannb9847332007-03-20 20:54:23 +0100521 ]
522 self.description = """Imports from Perforce into a git repository.\n
523 example:
524 //depot/my/project/ -- to import the current head
525 //depot/my/project/@all -- to import everything
526 //depot/my/project/@1,6 -- to import only from revision 1 to 6
527
528 (a ... is not needed in the path p4 specification, it's added implicitly)"""
529
530 self.usage += " //depot/path[@revRange]"
531
Simon Hausmannb9847332007-03-20 20:54:23 +0100532 self.silent = False
Simon Hausmannb9847332007-03-20 20:54:23 +0100533 self.createdBranches = Set()
534 self.committedChanges = Set()
Simon Hausmann569d1bd2007-03-22 21:34:16 +0100535 self.branch = ""
Simon Hausmannb9847332007-03-20 20:54:23 +0100536 self.detectBranches = False
Simon Hausmanncb53e1f2007-04-08 00:12:02 +0200537 self.detectLabels = False
Simon Hausmannb9847332007-03-20 20:54:23 +0100538 self.changesFile = ""
Simon Hausmannef48f902007-05-17 22:17:49 +0200539 self.syncWithOrigin = False
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200540 self.verbose = False
Simon Hausmanna028a982007-05-23 00:03:08 +0200541 self.importIntoRemotes = True
Simon Hausmann01a9c9c2007-05-23 00:07:35 +0200542 self.maxChanges = ""
Marius Storm-Olsenc1f91972007-05-24 14:07:55 +0200543 self.isWindows = (platform.system() == "Windows")
Simon Hausmannb9847332007-03-20 20:54:23 +0100544
545 def p4File(self, depotPath):
546 return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
547
548 def extractFilesFromCommit(self, commit):
549 files = []
550 fnum = 0
551 while commit.has_key("depotFile%s" % fnum):
552 path = commit["depotFile%s" % fnum]
Simon Hausmann8f872532007-05-01 23:23:00 +0200553 if not path.startswith(self.depotPath):
Simon Hausmannb9847332007-03-20 20:54:23 +0100554 # if not self.silent:
Simon Hausmann8f872532007-05-01 23:23:00 +0200555 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
Simon Hausmannb9847332007-03-20 20:54:23 +0100556 fnum = fnum + 1
557 continue
558
559 file = {}
560 file["path"] = path
561 file["rev"] = commit["rev%s" % fnum]
562 file["action"] = commit["action%s" % fnum]
563 file["type"] = commit["type%s" % fnum]
564 files.append(file)
565 fnum = fnum + 1
566 return files
567
Simon Hausmann71b112d2007-05-19 11:54:11 +0200568 def splitFilesIntoBranches(self, commit):
Simon Hausmannd5904672007-05-19 11:07:32 +0200569 branches = {}
Simon Hausmannb9847332007-03-20 20:54:23 +0100570
Simon Hausmann71b112d2007-05-19 11:54:11 +0200571 fnum = 0
572 while commit.has_key("depotFile%s" % fnum):
573 path = commit["depotFile%s" % fnum]
574 if not path.startswith(self.depotPath):
575 # if not self.silent:
576 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
577 fnum = fnum + 1
578 continue
579
580 file = {}
581 file["path"] = path
582 file["rev"] = commit["rev%s" % fnum]
583 file["action"] = commit["action%s" % fnum]
584 file["type"] = commit["type%s" % fnum]
585 fnum = fnum + 1
586
587 relPath = path[len(self.depotPath):]
Simon Hausmannb9847332007-03-20 20:54:23 +0100588
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200589 for branch in self.knownBranches.keys():
Simon Hausmannaf8da892007-05-21 23:25:51 +0200590 if relPath.startswith(branch + "/"): # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
Simon Hausmannd5904672007-05-19 11:07:32 +0200591 if branch not in branches:
592 branches[branch] = []
Simon Hausmann71b112d2007-05-19 11:54:11 +0200593 branches[branch].append(file)
Simon Hausmannb9847332007-03-20 20:54:23 +0100594
595 return branches
596
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200597 def commit(self, details, files, branch, branchPrefix, parent = ""):
Simon Hausmannb9847332007-03-20 20:54:23 +0100598 epoch = details["time"]
599 author = details["user"]
600
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200601 if self.verbose:
602 print "commit into %s" % branch
603
Simon Hausmannb9847332007-03-20 20:54:23 +0100604 self.gitStream.write("commit %s\n" % branch)
605 # gitStream.write("mark :%s\n" % details["change"])
606 self.committedChanges.add(int(details["change"]))
607 committer = ""
Simon Hausmannb607e712007-05-20 10:55:54 +0200608 if author not in self.users:
609 self.getUserMapFromPerforceServer()
Simon Hausmannb9847332007-03-20 20:54:23 +0100610 if author in self.users:
Simon Hausmann0828ab12007-03-20 20:59:30 +0100611 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
Simon Hausmannb9847332007-03-20 20:54:23 +0100612 else:
Simon Hausmann0828ab12007-03-20 20:59:30 +0100613 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
Simon Hausmannb9847332007-03-20 20:54:23 +0100614
615 self.gitStream.write("committer %s\n" % committer)
616
617 self.gitStream.write("data <<EOT\n")
618 self.gitStream.write(details["desc"])
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100619 self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
Simon Hausmannb9847332007-03-20 20:54:23 +0100620 self.gitStream.write("EOT\n\n")
621
622 if len(parent) > 0:
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200623 if self.verbose:
624 print "parent %s" % parent
Simon Hausmannb9847332007-03-20 20:54:23 +0100625 self.gitStream.write("from %s\n" % parent)
626
Simon Hausmannb9847332007-03-20 20:54:23 +0100627 for file in files:
628 path = file["path"]
629 if not path.startswith(branchPrefix):
630 # if not silent:
631 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
632 continue
633 rev = file["rev"]
634 depotPath = path + "#" + rev
635 relPath = path[len(branchPrefix):]
636 action = file["action"]
637
638 if file["type"] == "apple":
639 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
640 continue
641
642 if action == "delete":
643 self.gitStream.write("D %s\n" % relPath)
644 else:
645 mode = 644
646 if file["type"].startswith("x"):
647 mode = 755
648
649 data = self.p4File(depotPath)
650
Marius Storm-Olsenc1f91972007-05-24 14:07:55 +0200651 if self.isWindows and file["type"].endswith("text"):
652 data = data.replace("\r\n", "\n")
653
Simon Hausmannb9847332007-03-20 20:54:23 +0100654 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
655 self.gitStream.write("data %s\n" % len(data))
656 self.gitStream.write(data)
657 self.gitStream.write("\n")
658
659 self.gitStream.write("\n")
660
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200661 change = int(details["change"])
662
Simon Hausmann9bda3a82007-05-19 12:05:40 +0200663 if self.labels.has_key(change):
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200664 label = self.labels[change]
665 labelDetails = label[0]
666 labelRevisions = label[1]
Simon Hausmann71b112d2007-05-19 11:54:11 +0200667 if self.verbose:
668 print "Change %s is labelled %s" % (change, labelDetails)
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200669
670 files = p4CmdList("files %s...@%s" % (branchPrefix, change))
671
672 if len(files) == len(labelRevisions):
673
674 cleanedFiles = {}
675 for info in files:
676 if info["action"] == "delete":
677 continue
678 cleanedFiles[info["depotFile"]] = info["rev"]
679
680 if cleanedFiles == labelRevisions:
681 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
682 self.gitStream.write("from %s\n" % branch)
683
684 owner = labelDetails["Owner"]
685 tagger = ""
686 if author in self.users:
687 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
688 else:
689 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
690 self.gitStream.write("tagger %s\n" % tagger)
691 self.gitStream.write("data <<EOT\n")
692 self.gitStream.write(labelDetails["Description"])
693 self.gitStream.write("EOT\n\n")
694
695 else:
Simon Hausmanna46668f2007-03-28 17:05:38 +0200696 if not self.silent:
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200697 print "Tag %s does not match with change %s: files do not match." % (labelDetails["label"], change)
698
699 else:
Simon Hausmanna46668f2007-03-28 17:05:38 +0200700 if not self.silent:
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200701 print "Tag %s does not match with change %s: file count is different." % (labelDetails["label"], change)
Simon Hausmannb9847332007-03-20 20:54:23 +0100702
Simon Hausmannb607e712007-05-20 10:55:54 +0200703 def getUserMapFromPerforceServer(self):
Simon Hausmannebd81162007-05-24 00:24:52 +0200704 if self.userMapFromPerforceServer:
705 return
Simon Hausmannb9847332007-03-20 20:54:23 +0100706 self.users = {}
707
708 for output in p4CmdList("users"):
709 if not output.has_key("User"):
710 continue
711 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
712
Simon Hausmannb607e712007-05-20 10:55:54 +0200713 cache = open(gitdir + "/p4-usercache.txt", "wb")
714 for user in self.users.keys():
715 cache.write("%s\t%s\n" % (user, self.users[user]))
716 cache.close();
Simon Hausmannebd81162007-05-24 00:24:52 +0200717 self.userMapFromPerforceServer = True
Simon Hausmannb607e712007-05-20 10:55:54 +0200718
719 def loadUserMapFromCache(self):
720 self.users = {}
Simon Hausmannebd81162007-05-24 00:24:52 +0200721 self.userMapFromPerforceServer = False
Simon Hausmannb607e712007-05-20 10:55:54 +0200722 try:
723 cache = open(gitdir + "/p4-usercache.txt", "rb")
724 lines = cache.readlines()
725 cache.close()
726 for line in lines:
727 entry = line[:-1].split("\t")
728 self.users[entry[0]] = entry[1]
729 except IOError:
730 self.getUserMapFromPerforceServer()
731
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200732 def getLabels(self):
733 self.labels = {}
734
Simon Hausmann8f872532007-05-01 23:23:00 +0200735 l = p4CmdList("labels %s..." % self.depotPath)
Simon Hausmann10c32112007-04-08 10:15:47 +0200736 if len(l) > 0 and not self.silent:
Simon Hausmann8f872532007-05-01 23:23:00 +0200737 print "Finding files belonging to labels in %s" % self.depotPath
Simon Hausmann01ce1fe2007-04-07 23:46:50 +0200738
739 for output in l:
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200740 label = output["label"]
741 revisions = {}
742 newestChange = 0
Simon Hausmann71b112d2007-05-19 11:54:11 +0200743 if self.verbose:
744 print "Querying files for label %s" % label
745 for file in p4CmdList("files %s...@%s" % (self.depotPath, label)):
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200746 revisions[file["depotFile"]] = file["rev"]
747 change = int(file["change"])
748 if change > newestChange:
749 newestChange = change
750
Simon Hausmann9bda3a82007-05-19 12:05:40 +0200751 self.labels[newestChange] = [output, revisions]
752
753 if self.verbose:
754 print "Label changes: %s" % self.labels.keys()
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200755
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200756 def getBranchMapping(self):
Simon Hausmann29bdbac2007-05-19 10:23:12 +0200757 self.projectName = self.depotPath[self.depotPath[:-1].rfind("/") + 1:]
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200758
759 for info in p4CmdList("branches"):
760 details = p4Cmd("branch -o %s" % info["branch"])
761 viewIdx = 0
762 while details.has_key("View%s" % viewIdx):
763 paths = details["View%s" % viewIdx].split(" ")
764 viewIdx = viewIdx + 1
765 # require standard //depot/foo/... //depot/bar/... mapping
766 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
767 continue
768 source = paths[0]
769 destination = paths[1]
770 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
771 source = source[len(self.depotPath):-4]
772 destination = destination[len(self.depotPath):-4]
Simon Hausmann29bdbac2007-05-19 10:23:12 +0200773 if destination not in self.knownBranches:
774 self.knownBranches[destination] = source
775 if source not in self.knownBranches:
776 self.knownBranches[source] = source
777
778 def listExistingP4GitBranches(self):
779 self.p4BranchesInGit = []
780
Simon Hausmanna028a982007-05-23 00:03:08 +0200781 cmdline = "git rev-parse --symbolic "
782 if self.importIntoRemotes:
783 cmdline += " --remotes"
784 else:
785 cmdline += " --branches"
786
787 for line in mypopen(cmdline).readlines():
Simon Hausmann57284052007-05-23 00:15:50 +0200788 if self.importIntoRemotes and ((not line.startswith("p4/")) or line == "p4/HEAD\n"):
789 continue
790 if self.importIntoRemotes:
791 # strip off p4
Simon Hausmann29bdbac2007-05-19 10:23:12 +0200792 branch = line[3:-1]
Simon Hausmann57284052007-05-23 00:15:50 +0200793 else:
794 branch = line[:-1]
795 self.p4BranchesInGit.append(branch)
796 self.initialParents[self.refPrefix + branch] = parseRevision(line[:-1])
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200797
Simon Hausmannd1874ed2007-05-24 21:23:04 +0200798 def createBranchesFromOrigin(self):
799 if not self.silent:
800 print "Creating branch(es) in %s based on origin branch(es)" % self.refPrefix
801
802 for line in mypopen("git rev-parse --symbolic --remotes"):
803 if (not line.startswith("origin/")) or line.endswith("HEAD\n"):
804 continue
805 headName = line[len("origin/"):-1]
806 remoteHead = self.refPrefix + headName
807 if not os.path.exists(gitdir + "/" + remoteHead):
808 if self.verbose:
809 print "creating %s" % remoteHead
810 system("git update-ref %s origin/%s" % (remoteHead, headName))
811
Simon Hausmannb9847332007-03-20 20:54:23 +0100812 def run(self, args):
Simon Hausmann8f872532007-05-01 23:23:00 +0200813 self.depotPath = ""
Simon Hausmann179caeb2007-03-22 22:17:42 +0100814 self.changeRange = ""
815 self.initialParent = ""
Simon Hausmanncd6cc0d2007-05-15 16:15:26 +0200816 self.previousDepotPath = ""
Simon Hausmann29bdbac2007-05-19 10:23:12 +0200817 # map from branch depot path to parent branch
818 self.knownBranches = {}
819 self.initialParents = {}
Simon Hausmann179caeb2007-03-22 22:17:42 +0100820
Simon Hausmanna028a982007-05-23 00:03:08 +0200821 if self.importIntoRemotes:
822 self.refPrefix = "refs/remotes/p4/"
823 else:
Simon Hausmann57284052007-05-23 00:15:50 +0200824 self.refPrefix = "refs/heads/"
Simon Hausmanna028a982007-05-23 00:03:08 +0200825
Simon Hausmannfaf1bd22007-05-21 10:05:30 +0200826 createP4HeadRef = False;
827
Simon Hausmann57284052007-05-23 00:15:50 +0200828 if self.syncWithOrigin and gitBranchExists("origin") and gitBranchExists(self.refPrefix + "master") and not self.detectBranches and self.importIntoRemotes:
Simon Hausmann29bdbac2007-05-19 10:23:12 +0200829 ### needs to be ported to multi branch import
830
Simon Hausmannef48f902007-05-17 22:17:49 +0200831 print "Syncing with origin first as requested by calling git fetch origin"
832 system("git fetch origin")
833 [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
834 [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
835 if len(originPreviousDepotPath) > 0 and len(originP4Change) > 0 and len(p4Change) > 0:
836 if originPreviousDepotPath == p4PreviousDepotPath:
837 originP4Change = int(originP4Change)
838 p4Change = int(p4Change)
839 if originP4Change > p4Change:
840 print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change, p4Change)
Simon Hausmanna028a982007-05-23 00:03:08 +0200841 system("git update-ref " + self.refPrefix + "master origin");
Simon Hausmannef48f902007-05-17 22:17:49 +0200842 else:
843 print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath, p4PreviousDepotPath)
844
Simon Hausmann569d1bd2007-03-22 21:34:16 +0100845 if len(self.branch) == 0:
Simon Hausmanna028a982007-05-23 00:03:08 +0200846 self.branch = self.refPrefix + "master"
847 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
Simon Hausmann48df6fd2007-05-17 21:18:53 +0200848 system("git update-ref %s refs/heads/p4" % self.branch)
Simon Hausmann48df6fd2007-05-17 21:18:53 +0200849 system("git branch -D p4");
Simon Hausmannfaf1bd22007-05-21 10:05:30 +0200850 # create it /after/ importing, when master exists
Simon Hausmanna028a982007-05-23 00:03:08 +0200851 if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
Simon Hausmannfaf1bd22007-05-21 10:05:30 +0200852 createP4HeadRef = True
Simon Hausmann179caeb2007-03-22 22:17:42 +0100853
Simon Hausmann33be3e62007-05-21 08:44:16 +0200854 # this needs to be called after the conversion from heads/p4 to remotes/p4/master
855 self.listExistingP4GitBranches()
Simon Hausmannb3fd1b22007-05-23 23:53:14 +0200856 if len(self.p4BranchesInGit) > 1:
857 if not self.silent:
Simon Hausmannd1874ed2007-05-24 21:23:04 +0200858 print "Importing from/into multiple branches"
Simon Hausmann33be3e62007-05-21 08:44:16 +0200859 self.detectBranches = True
860
Simon Hausmann967f72e2007-03-23 09:30:41 +0100861 if len(args) == 0:
Simon Hausmannd1874ed2007-05-24 21:23:04 +0200862 if len(self.p4BranchesInGit) == 0:
863 self.createBranchesFromOrigin()
864 self.listExistingP4GitBranches()
865 return True
Simon Hausmann967f72e2007-03-23 09:30:41 +0100866
Simon Hausmann29bdbac2007-05-19 10:23:12 +0200867 if self.verbose:
868 print "branches: %s" % self.p4BranchesInGit
869
870 p4Change = 0
871 for branch in self.p4BranchesInGit:
Simon Hausmanna028a982007-05-23 00:03:08 +0200872 depotPath, change = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(self.refPrefix + branch))
Simon Hausmann29bdbac2007-05-19 10:23:12 +0200873
874 if self.verbose:
875 print "path %s change %s" % (depotPath, change)
876
877 if len(depotPath) > 0 and len(change) > 0:
878 change = int(change) + 1
879 p4Change = max(p4Change, change)
880
881 if len(self.previousDepotPath) == 0:
882 self.previousDepotPath = depotPath
883 else:
884 i = 0
885 l = min(len(self.previousDepotPath), len(depotPath))
886 while i < l and self.previousDepotPath[i] == depotPath[i]:
887 i = i + 1
888 self.previousDepotPath = self.previousDepotPath[:i]
889
890 if p4Change > 0:
Simon Hausmann8f872532007-05-01 23:23:00 +0200891 self.depotPath = self.previousDepotPath
Simon Hausmannd5904672007-05-19 11:07:32 +0200892 self.changeRange = "@%s,#head" % p4Change
Simon Hausmann463e8af2007-05-17 09:13:54 +0200893 self.initialParent = parseRevision(self.branch)
Simon Hausmann341dc1c2007-05-21 00:39:16 +0200894 if not self.silent and not self.detectBranches:
Simon Hausmann967f72e2007-03-23 09:30:41 +0100895 print "Performing incremental import into %s git branch" % self.branch
Simon Hausmann569d1bd2007-03-22 21:34:16 +0100896
Simon Hausmannf9162f62007-05-17 09:02:45 +0200897 if not self.branch.startswith("refs/"):
898 self.branch = "refs/heads/" + self.branch
Simon Hausmann179caeb2007-03-22 22:17:42 +0100899
Simon Hausmann8f872532007-05-01 23:23:00 +0200900 if len(self.depotPath) != 0:
901 self.depotPath = self.depotPath[:-1]
Simon Hausmannb9847332007-03-20 20:54:23 +0100902
Simon Hausmann8f872532007-05-01 23:23:00 +0200903 if len(args) == 0 and len(self.depotPath) != 0:
Simon Hausmannb9847332007-03-20 20:54:23 +0100904 if not self.silent:
Simon Hausmann8f872532007-05-01 23:23:00 +0200905 print "Depot path: %s" % self.depotPath
Simon Hausmannb9847332007-03-20 20:54:23 +0100906 elif len(args) != 1:
907 return False
908 else:
Simon Hausmann8f872532007-05-01 23:23:00 +0200909 if len(self.depotPath) != 0 and self.depotPath != args[0]:
910 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.depotPath, args[0])
Simon Hausmannb9847332007-03-20 20:54:23 +0100911 sys.exit(1)
Simon Hausmann8f872532007-05-01 23:23:00 +0200912 self.depotPath = args[0]
Simon Hausmannb9847332007-03-20 20:54:23 +0100913
Simon Hausmannb9847332007-03-20 20:54:23 +0100914 self.revision = ""
915 self.users = {}
Simon Hausmannb9847332007-03-20 20:54:23 +0100916
Simon Hausmann8f872532007-05-01 23:23:00 +0200917 if self.depotPath.find("@") != -1:
918 atIdx = self.depotPath.index("@")
919 self.changeRange = self.depotPath[atIdx:]
Simon Hausmannb9847332007-03-20 20:54:23 +0100920 if self.changeRange == "@all":
921 self.changeRange = ""
922 elif self.changeRange.find(",") == -1:
923 self.revision = self.changeRange
924 self.changeRange = ""
Simon Hausmann8f872532007-05-01 23:23:00 +0200925 self.depotPath = self.depotPath[0:atIdx]
926 elif self.depotPath.find("#") != -1:
927 hashIdx = self.depotPath.index("#")
928 self.revision = self.depotPath[hashIdx:]
929 self.depotPath = self.depotPath[0:hashIdx]
Simon Hausmannb9847332007-03-20 20:54:23 +0100930 elif len(self.previousDepotPath) == 0:
931 self.revision = "#head"
932
Simon Hausmann8f872532007-05-01 23:23:00 +0200933 if self.depotPath.endswith("..."):
934 self.depotPath = self.depotPath[:-3]
Simon Hausmannb9847332007-03-20 20:54:23 +0100935
Simon Hausmann8f872532007-05-01 23:23:00 +0200936 if not self.depotPath.endswith("/"):
937 self.depotPath += "/"
Simon Hausmannb9847332007-03-20 20:54:23 +0100938
Simon Hausmannb607e712007-05-20 10:55:54 +0200939 self.loadUserMapFromCache()
Simon Hausmanncb53e1f2007-04-08 00:12:02 +0200940 self.labels = {}
941 if self.detectLabels:
942 self.getLabels();
Simon Hausmannb9847332007-03-20 20:54:23 +0100943
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200944 if self.detectBranches:
945 self.getBranchMapping();
Simon Hausmann29bdbac2007-05-19 10:23:12 +0200946 if self.verbose:
947 print "p4-git branches: %s" % self.p4BranchesInGit
948 print "initial parents: %s" % self.initialParents
949 for b in self.p4BranchesInGit:
950 if b != "master":
951 b = b[len(self.projectName):]
952 self.createdBranches.add(b)
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200953
Simon Hausmannf291b4e2007-04-14 11:21:50 +0200954 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
Simon Hausmannb9847332007-03-20 20:54:23 +0100955
Simon Hausmann08483582007-05-15 14:31:06 +0200956 importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
957 self.gitOutput = importProcess.stdout
958 self.gitStream = importProcess.stdin
959 self.gitError = importProcess.stderr
Simon Hausmannb9847332007-03-20 20:54:23 +0100960
961 if len(self.revision) > 0:
Simon Hausmann8f872532007-05-01 23:23:00 +0200962 print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
Simon Hausmannb9847332007-03-20 20:54:23 +0100963
964 details = { "user" : "git perforce import user", "time" : int(time.time()) }
Simon Hausmann8f872532007-05-01 23:23:00 +0200965 details["desc"] = "Initial import of %s from the state at revision %s" % (self.depotPath, self.revision)
Simon Hausmannb9847332007-03-20 20:54:23 +0100966 details["change"] = self.revision
967 newestRevision = 0
968
969 fileCnt = 0
Simon Hausmann8f872532007-05-01 23:23:00 +0200970 for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
Simon Hausmannb9847332007-03-20 20:54:23 +0100971 change = int(info["change"])
972 if change > newestRevision:
973 newestRevision = change
974
975 if info["action"] == "delete":
Simon Hausmannc45b1cf2007-04-08 10:13:32 +0200976 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
977 #fileCnt = fileCnt + 1
Simon Hausmannb9847332007-03-20 20:54:23 +0100978 continue
979
980 for prop in [ "depotFile", "rev", "action", "type" ]:
981 details["%s%s" % (prop, fileCnt)] = info[prop]
982
983 fileCnt = fileCnt + 1
984
985 details["change"] = newestRevision
986
987 try:
Simon Hausmann8f872532007-05-01 23:23:00 +0200988 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
Simon Hausmannc7157062007-03-20 21:13:49 +0100989 except IOError:
Simon Hausmannfd4ca862007-04-13 22:21:10 +0200990 print "IO error with git fast-import. Is your git version recent enough?"
Simon Hausmannb9847332007-03-20 20:54:23 +0100991 print self.gitError.read()
992
993 else:
994 changes = []
995
Simon Hausmann0828ab12007-03-20 20:59:30 +0100996 if len(self.changesFile) > 0:
Simon Hausmannb9847332007-03-20 20:54:23 +0100997 output = open(self.changesFile).readlines()
998 changeSet = Set()
999 for line in output:
1000 changeSet.add(int(line))
1001
1002 for change in changeSet:
1003 changes.append(change)
1004
1005 changes.sort()
1006 else:
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001007 if self.verbose:
1008 print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
Simon Hausmanncaace112007-05-15 14:57:57 +02001009 output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines()
Simon Hausmannb9847332007-03-20 20:54:23 +01001010
1011 for line in output:
1012 changeNum = line.split(" ")[1]
1013 changes.append(changeNum)
1014
1015 changes.reverse()
1016
Simon Hausmann01a9c9c2007-05-23 00:07:35 +02001017 if len(self.maxChanges) > 0:
1018 changes = changes[0:min(int(self.maxChanges), len(changes))]
1019
Simon Hausmannb9847332007-03-20 20:54:23 +01001020 if len(changes) == 0:
Simon Hausmann0828ab12007-03-20 20:59:30 +01001021 if not self.silent:
Simon Hausmann341dc1c2007-05-21 00:39:16 +02001022 print "No changes to import!"
Simon Hausmann1f52af62007-04-08 00:07:02 +02001023 return True
Simon Hausmannb9847332007-03-20 20:54:23 +01001024
Simon Hausmann341dc1c2007-05-21 00:39:16 +02001025 self.updatedBranches = set()
1026
Simon Hausmannb9847332007-03-20 20:54:23 +01001027 cnt = 1
1028 for change in changes:
1029 description = p4Cmd("describe %s" % change)
1030
Simon Hausmann0828ab12007-03-20 20:59:30 +01001031 if not self.silent:
Simon Hausmann341dc1c2007-05-21 00:39:16 +02001032 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
Simon Hausmannb9847332007-03-20 20:54:23 +01001033 sys.stdout.flush()
1034 cnt = cnt + 1
1035
1036 try:
Simon Hausmannb9847332007-03-20 20:54:23 +01001037 if self.detectBranches:
Simon Hausmann71b112d2007-05-19 11:54:11 +02001038 branches = self.splitFilesIntoBranches(description)
Simon Hausmannd5904672007-05-19 11:07:32 +02001039 for branch in branches.keys():
Simon Hausmann8f872532007-05-01 23:23:00 +02001040 branchPrefix = self.depotPath + branch + "/"
Simon Hausmannb9847332007-03-20 20:54:23 +01001041
Simon Hausmannb9847332007-03-20 20:54:23 +01001042 parent = ""
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001043
Simon Hausmannd5904672007-05-19 11:07:32 +02001044 filesForCommit = branches[branch]
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001045
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001046 if self.verbose:
1047 print "branch is %s" % branch
1048
Simon Hausmann341dc1c2007-05-21 00:39:16 +02001049 self.updatedBranches.add(branch)
1050
Simon Hausmann8f9b2e02007-05-18 22:13:26 +02001051 if branch not in self.createdBranches:
Simon Hausmannb9847332007-03-20 20:54:23 +01001052 self.createdBranches.add(branch)
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001053 parent = self.knownBranches[branch]
Simon Hausmannb9847332007-03-20 20:54:23 +01001054 if parent == branch:
1055 parent = ""
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001056 elif self.verbose:
1057 print "parent determined through known branches: %s" % parent
Simon Hausmannb9847332007-03-20 20:54:23 +01001058
Simon Hausmann8f9b2e02007-05-18 22:13:26 +02001059 # main branch? use master
1060 if branch == "main":
1061 branch = "master"
1062 else:
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001063 branch = self.projectName + branch
Simon Hausmann8f9b2e02007-05-18 22:13:26 +02001064
1065 if parent == "main":
1066 parent = "master"
1067 elif len(parent) > 0:
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001068 parent = self.projectName + parent
Simon Hausmann8f9b2e02007-05-18 22:13:26 +02001069
Simon Hausmanna028a982007-05-23 00:03:08 +02001070 branch = self.refPrefix + branch
Simon Hausmannb9847332007-03-20 20:54:23 +01001071 if len(parent) > 0:
Simon Hausmanna028a982007-05-23 00:03:08 +02001072 parent = self.refPrefix + parent
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001073
1074 if self.verbose:
1075 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1076
1077 if len(parent) == 0 and branch in self.initialParents:
1078 parent = self.initialParents[branch]
1079 del self.initialParents[branch]
1080
Simon Hausmann71b112d2007-05-19 11:54:11 +02001081 self.commit(description, filesForCommit, branch, branchPrefix, parent)
Simon Hausmannb9847332007-03-20 20:54:23 +01001082 else:
Simon Hausmann71b112d2007-05-19 11:54:11 +02001083 files = self.extractFilesFromCommit(description)
Simon Hausmann8f872532007-05-01 23:23:00 +02001084 self.commit(description, files, self.branch, self.depotPath, self.initialParent)
Simon Hausmannb9847332007-03-20 20:54:23 +01001085 self.initialParent = ""
1086 except IOError:
1087 print self.gitError.read()
1088 sys.exit(1)
1089
Simon Hausmann341dc1c2007-05-21 00:39:16 +02001090 if not self.silent:
1091 print ""
1092 if len(self.updatedBranches) > 0:
1093 sys.stdout.write("Updated branches: ")
1094 for b in self.updatedBranches:
1095 sys.stdout.write("%s " % b)
1096 sys.stdout.write("\n")
Simon Hausmannb9847332007-03-20 20:54:23 +01001097
Simon Hausmannb9847332007-03-20 20:54:23 +01001098
1099 self.gitStream.close()
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001100 if importProcess.wait() != 0:
1101 die("fast-import failed: %s" % self.gitError.read())
Simon Hausmannb9847332007-03-20 20:54:23 +01001102 self.gitOutput.close()
1103 self.gitError.close()
1104
Simon Hausmannfaf1bd22007-05-21 10:05:30 +02001105 if createP4HeadRef:
Simon Hausmann65d2ade2007-05-23 16:41:46 +02001106 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
Simon Hausmannfaf1bd22007-05-21 10:05:30 +02001107
Simon Hausmannb9847332007-03-20 20:54:23 +01001108 return True
1109
Simon Hausmann01ce1fe2007-04-07 23:46:50 +02001110class P4Rebase(Command):
1111 def __init__(self):
1112 Command.__init__(self)
Simon Hausmannef48f902007-05-17 22:17:49 +02001113 self.options = [ optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true") ]
Simon Hausmann01ce1fe2007-04-07 23:46:50 +02001114 self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it"
Simon Hausmannef48f902007-05-17 22:17:49 +02001115 self.syncWithOrigin = False
Simon Hausmann01ce1fe2007-04-07 23:46:50 +02001116
1117 def run(self, args):
1118 sync = P4Sync()
Simon Hausmannef48f902007-05-17 22:17:49 +02001119 sync.syncWithOrigin = self.syncWithOrigin
Simon Hausmann01ce1fe2007-04-07 23:46:50 +02001120 sync.run([])
1121 print "Rebasing the current branch"
Simon Hausmanncaace112007-05-15 14:57:57 +02001122 oldHead = mypopen("git rev-parse HEAD").read()[:-1]
Simon Hausmann01ce1fe2007-04-07 23:46:50 +02001123 system("git rebase p4")
Simon Hausmann1f52af62007-04-08 00:07:02 +02001124 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
Simon Hausmann01ce1fe2007-04-07 23:46:50 +02001125 return True
1126
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001127class P4Clone(P4Sync):
1128 def __init__(self):
1129 P4Sync.__init__(self)
1130 self.description = "Creates a new git repository and imports from Perforce into it"
1131 self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1132 self.needsGit = False
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001133
1134 def run(self, args):
Simon Hausmann59fa4172007-05-20 15:15:34 +02001135 global gitdir
1136
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001137 if len(args) < 1:
1138 return False
1139 depotPath = args[0]
1140 dir = ""
1141 if len(args) == 2:
1142 dir = args[1]
1143 elif len(args) > 2:
1144 return False
1145
1146 if not depotPath.startswith("//"):
1147 return False
1148
1149 if len(dir) == 0:
1150 dir = depotPath
1151 atPos = dir.rfind("@")
1152 if atPos != -1:
1153 dir = dir[0:atPos]
1154 hashPos = dir.rfind("#")
1155 if hashPos != -1:
1156 dir = dir[0:hashPos]
1157
1158 if dir.endswith("..."):
1159 dir = dir[:-3]
1160
1161 if dir.endswith("/"):
1162 dir = dir[:-1]
1163
1164 slashPos = dir.rfind("/")
1165 if slashPos != -1:
1166 dir = dir[slashPos + 1:]
1167
1168 print "Importing from %s into %s" % (depotPath, dir)
1169 os.makedirs(dir)
1170 os.chdir(dir)
1171 system("git init")
Simon Hausmann64ffb062007-05-20 15:24:01 +02001172 gitdir = os.getcwd() + "/.git"
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001173 if not P4Sync.run(self, [depotPath]):
1174 return False
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001175 if self.branch != "master":
Simon Hausmann8f9b2e02007-05-18 22:13:26 +02001176 if gitBranchExists("refs/remotes/p4/master"):
1177 system("git branch master refs/remotes/p4/master")
1178 system("git checkout -f")
1179 else:
1180 print "Could not detect main branch. No checkout/master branch created."
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001181 return True
1182
Simon Hausmannb9847332007-03-20 20:54:23 +01001183class HelpFormatter(optparse.IndentedHelpFormatter):
1184 def __init__(self):
1185 optparse.IndentedHelpFormatter.__init__(self)
1186
1187 def format_description(self, description):
1188 if description:
1189 return description + "\n"
1190 else:
1191 return ""
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001192
Simon Hausmann86949ee2007-03-19 20:59:12 +01001193def printUsage(commands):
1194 print "usage: %s <command> [options]" % sys.argv[0]
1195 print ""
1196 print "valid commands: %s" % ", ".join(commands)
1197 print ""
1198 print "Try %s <command> --help for command specific help." % sys.argv[0]
1199 print ""
1200
1201commands = {
1202 "debug" : P4Debug(),
Simon Hausmann711544b2007-04-01 15:40:46 +02001203 "submit" : P4Submit(),
Simon Hausmann01ce1fe2007-04-07 23:46:50 +02001204 "sync" : P4Sync(),
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001205 "rebase" : P4Rebase(),
Simon Hausmann58346842007-05-21 22:57:06 +02001206 "clone" : P4Clone(),
1207 "rollback" : P4RollBack()
Simon Hausmann86949ee2007-03-19 20:59:12 +01001208}
1209
1210if len(sys.argv[1:]) == 0:
1211 printUsage(commands.keys())
1212 sys.exit(2)
1213
1214cmd = ""
1215cmdName = sys.argv[1]
1216try:
1217 cmd = commands[cmdName]
1218except KeyError:
1219 print "unknown command %s" % cmdName
1220 print ""
1221 printUsage(commands.keys())
1222 sys.exit(2)
1223
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001224options = cmd.options
1225cmd.gitdir = gitdir
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001226
Simon Hausmanne20a9e52007-03-26 00:13:51 +02001227args = sys.argv[2:]
Simon Hausmann86949ee2007-03-19 20:59:12 +01001228
Simon Hausmanne20a9e52007-03-26 00:13:51 +02001229if len(options) > 0:
1230 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1231
1232 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1233 options,
1234 description = cmd.description,
1235 formatter = HelpFormatter())
1236
1237 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
Simon Hausmann86949ee2007-03-19 20:59:12 +01001238
Simon Hausmann8910ac02007-03-26 08:18:55 +02001239if cmd.needsGit:
1240 gitdir = cmd.gitdir
1241 if len(gitdir) == 0:
1242 gitdir = ".git"
1243 if not isValidGitDir(gitdir):
Simon Hausmann81f23732007-05-15 23:06:43 +02001244 gitdir = mypopen("git rev-parse --git-dir").read()[:-1]
Simon Hausmanndc1a93b2007-05-16 12:12:39 +02001245 if os.path.exists(gitdir):
Simon Hausmann5c4153e2007-05-17 07:42:38 +02001246 cdup = mypopen("git rev-parse --show-cdup").read()[:-1];
1247 if len(cdup) > 0:
1248 os.chdir(cdup);
Simon Hausmann8910ac02007-03-26 08:18:55 +02001249
Simon Hausmann20618652007-03-21 13:05:30 +01001250 if not isValidGitDir(gitdir):
Simon Hausmann8910ac02007-03-26 08:18:55 +02001251 if isValidGitDir(gitdir + "/.git"):
1252 gitdir += "/.git"
1253 else:
1254 die("fatal: cannot locate git repository at %s" % gitdir)
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001255
Simon Hausmann8910ac02007-03-26 08:18:55 +02001256 os.environ["GIT_DIR"] = gitdir
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001257
Simon Hausmannb9847332007-03-20 20:54:23 +01001258if not cmd.run(args):
1259 parser.print_help()
1260