]> git.ipfire.org Git - thirdparty/git.git/blame - contrib/fast-import/git-p4
Fixes for rollback, delete branches that did not exist at the specified p4 change
[thirdparty/git.git] / contrib / fast-import / git-p4
CommitLineData
86949eef
SH
1#!/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>
83dce55a
SH
6# Copyright: 2007 Simon Hausmann <hausmann@kde.org>
7# 2007 Trolltech ASA
86949eef
SH
8# License: MIT <http://www.opensource.org/licenses/mit-license.php>
9#
5834684d 10# TODO: * Consider making --with-origin the default, assuming that the git
341dc1c1 11# protocol is always more efficient. (needs manual testing first :)
24f7b53f 12#
86949eef 13
08483580 14import optparse, sys, os, marshal, popen2, subprocess, shelve
25df95cc 15import tempfile, getopt, sha, os.path, time, platform
b984733c 16from sets import Set;
4f5cf76a
SH
17
18gitdir = os.environ.get("GIT_DIR", "")
86949eef 19
caace111
SH
20def mypopen(command):
21 return os.popen(command, "rb");
22
86949eef
SH
23def 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
34 pipe.close()
35
36 return result
37
38def p4Cmd(cmd):
39 list = p4CmdList(cmd)
40 result = {}
41 for entry in list:
42 result.update(entry)
43 return result;
44
cb2c9db5
SH
45def p4Where(depotPath):
46 if not depotPath.endswith("/"):
47 depotPath += "/"
48 output = p4Cmd("where %s..." % depotPath)
dc524036
SH
49 if output["code"] == "error":
50 return ""
cb2c9db5
SH
51 clientPath = ""
52 if "path" in output:
53 clientPath = output.get("path")
54 elif "data" in output:
55 data = output.get("data")
56 lastSpace = data.rfind(" ")
57 clientPath = data[lastSpace + 1:]
58
59 if clientPath.endswith("..."):
60 clientPath = clientPath[:-3]
61 return clientPath
62
86949eef
SH
63def die(msg):
64 sys.stderr.write(msg + "\n")
65 sys.exit(1)
66
67def currentGitBranch():
caace111 68 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
86949eef 69
4f5cf76a
SH
70def isValidGitDir(path):
71 if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
72 return True;
73 return False
74
463e8af6
SH
75def parseRevision(ref):
76 return mypopen("git rev-parse %s" % ref).read()[:-1]
77
4f5cf76a
SH
78def system(cmd):
79 if os.system(cmd) != 0:
80 die("command failed: %s" % cmd)
81
6ae8de88
SH
82def extractLogMessageFromGitCommit(commit):
83 logMessage = ""
84 foundTitle = False
caace111 85 for log in mypopen("git cat-file commit %s" % commit).readlines():
6ae8de88
SH
86 if not foundTitle:
87 if len(log) == 1:
1c094184 88 foundTitle = True
6ae8de88
SH
89 continue
90
91 logMessage += log
92 return logMessage
93
94def extractDepotPathAndChangeFromGitLog(log):
95 values = {}
96 for line in log.split("\n"):
97 line = line.strip()
98 if line.startswith("[git-p4:") and line.endswith("]"):
99 line = line[8:-1].strip()
100 for assignment in line.split(":"):
101 variable = assignment.strip()
102 value = ""
103 equalPos = assignment.find("=")
104 if equalPos != -1:
105 variable = assignment[:equalPos].strip()
106 value = assignment[equalPos + 1:].strip()
107 if value.startswith("\"") and value.endswith("\""):
108 value = value[1:-1]
109 values[variable] = value
110
111 return values.get("depot-path"), values.get("change")
112
8136a639 113def gitBranchExists(branch):
caace111
SH
114 proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
115 return proc.wait() == 0;
8136a639 116
b984733c
SH
117class Command:
118 def __init__(self):
119 self.usage = "usage: %prog [options]"
8910ac0e 120 self.needsGit = True
b984733c
SH
121
122class P4Debug(Command):
86949eef 123 def __init__(self):
6ae8de88 124 Command.__init__(self)
86949eef
SH
125 self.options = [
126 ]
c8c39116 127 self.description = "A tool to debug the output of p4 -G."
8910ac0e 128 self.needsGit = False
86949eef
SH
129
130 def run(self, args):
131 for output in p4CmdList(" ".join(args)):
132 print output
b984733c 133 return True
86949eef 134
5834684d
SH
135class P4RollBack(Command):
136 def __init__(self):
137 Command.__init__(self)
138 self.options = [
52102d47 139 optparse.make_option("--verbose", dest="verbose", action="store_true")
5834684d
SH
140 ]
141 self.description = "A tool to debug the multi-branch import. Don't use :)"
52102d47 142 self.verbose = False
5834684d
SH
143
144 def run(self, args):
145 if len(args) != 1:
146 return False
147 maxChange = int(args[0])
148 for line in mypopen("git rev-parse --symbolic --remotes").readlines():
149 if line.startswith("p4/") and line != "p4/HEAD\n":
150 ref = "refs/remotes/" + line[:-1]
151 log = extractLogMessageFromGitCommit(ref)
152 depotPath, change = extractDepotPathAndChangeFromGitLog(log)
153 changed = False
52102d47
SH
154
155 if len(p4Cmd("changes -m 1 %s...@%s" % (depotPath, maxChange))) == 0:
156 print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
157 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
158 continue
159
5834684d
SH
160 while len(change) > 0 and int(change) > maxChange:
161 changed = True
52102d47
SH
162 if self.verbose:
163 print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
5834684d
SH
164 system("git update-ref %s \"%s^\"" % (ref, ref))
165 log = extractLogMessageFromGitCommit(ref)
166 depotPath, change = extractDepotPathAndChangeFromGitLog(log)
167
168 if changed:
52102d47 169 print "%s rewound to %s" % (ref, change)
5834684d
SH
170
171 return True
172
711544b0 173class P4Submit(Command):
4f5cf76a 174 def __init__(self):
b984733c 175 Command.__init__(self)
4f5cf76a
SH
176 self.options = [
177 optparse.make_option("--continue", action="store_false", dest="firstTime"),
178 optparse.make_option("--origin", dest="origin"),
179 optparse.make_option("--reset", action="store_true", dest="reset"),
4f5cf76a
SH
180 optparse.make_option("--log-substitutions", dest="substFile"),
181 optparse.make_option("--noninteractive", action="store_false"),
04219c04 182 optparse.make_option("--dry-run", action="store_true"),
c1b296b9 183 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
4f5cf76a
SH
184 ]
185 self.description = "Submit changes from git to the perforce depot."
c9b50e63 186 self.usage += " [name of git branch to submit into perforce depot]"
4f5cf76a
SH
187 self.firstTime = True
188 self.reset = False
189 self.interactive = True
190 self.dryRun = False
191 self.substFile = ""
192 self.firstTime = True
9512497b 193 self.origin = ""
c1b296b9 194 self.directSubmit = False
4f5cf76a
SH
195
196 self.logSubstitutions = {}
197 self.logSubstitutions["<enter description here>"] = "%log%"
198 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
199
200 def check(self):
201 if len(p4CmdList("opened ...")) > 0:
202 die("You have files opened with perforce! Close them before starting the sync.")
203
204 def start(self):
205 if len(self.config) > 0 and not self.reset:
c3c46244 206 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)
4f5cf76a
SH
207
208 commits = []
c1b296b9
SH
209 if self.directSubmit:
210 commits.append("0")
211 else:
212 for line in mypopen("git rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
213 commits.append(line[:-1])
214 commits.reverse()
4f5cf76a
SH
215
216 self.config["commits"] = commits
217
4f5cf76a
SH
218 def prepareLogMessage(self, template, message):
219 result = ""
220
221 for line in template.split("\n"):
222 if line.startswith("#"):
223 result += line + "\n"
224 continue
225
226 substituted = False
227 for key in self.logSubstitutions.keys():
228 if line.find(key) != -1:
229 value = self.logSubstitutions[key]
230 value = value.replace("%log%", message)
231 if value != "@remove@":
232 result += line.replace(key, value) + "\n"
233 substituted = True
234 break
235
236 if not substituted:
237 result += line + "\n"
238
239 return result
240
241 def apply(self, id):
c1b296b9
SH
242 if self.directSubmit:
243 print "Applying local change in working directory/index"
244 diff = self.diffStatus
245 else:
246 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
247 diff = mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
4f5cf76a
SH
248 filesToAdd = set()
249 filesToDelete = set()
d336c158 250 editedFiles = set()
4f5cf76a
SH
251 for line in diff:
252 modifier = line[0]
253 path = line[1:].strip()
254 if modifier == "M":
d336c158
SH
255 system("p4 edit \"%s\"" % path)
256 editedFiles.add(path)
4f5cf76a
SH
257 elif modifier == "A":
258 filesToAdd.add(path)
259 if path in filesToDelete:
260 filesToDelete.remove(path)
261 elif modifier == "D":
262 filesToDelete.add(path)
263 if path in filesToAdd:
264 filesToAdd.remove(path)
265 else:
266 die("unknown modifier %s for %s" % (modifier, path))
267
c1b296b9
SH
268 if self.directSubmit:
269 diffcmd = "cat \"%s\"" % self.diffFile
270 else:
271 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
47a130b7 272 patchcmd = diffcmd + " | git apply "
c1b296b9
SH
273 tryPatchCmd = patchcmd + "--check -"
274 applyPatchCmd = patchcmd + "--check --apply -"
51a2640a 275
47a130b7 276 if os.system(tryPatchCmd) != 0:
51a2640a
SH
277 print "Unfortunately applying the change failed!"
278 print "What do you want to do?"
279 response = "x"
280 while response != "s" and response != "a" and response != "w":
281 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) ")
282 if response == "s":
283 print "Skipping! Good luck with the next patches..."
284 return
285 elif response == "a":
47a130b7 286 os.system(applyPatchCmd)
51a2640a
SH
287 if len(filesToAdd) > 0:
288 print "You may also want to call p4 add on the following files:"
289 print " ".join(filesToAdd)
290 if len(filesToDelete):
291 print "The following files should be scheduled for deletion with p4 delete:"
292 print " ".join(filesToDelete)
293 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
294 elif response == "w":
295 system(diffcmd + " > patch.txt")
296 print "Patch saved to patch.txt in %s !" % self.clientPath
297 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
298
47a130b7 299 system(applyPatchCmd)
4f5cf76a
SH
300
301 for f in filesToAdd:
302 system("p4 add %s" % f)
303 for f in filesToDelete:
304 system("p4 revert %s" % f)
305 system("p4 delete %s" % f)
306
c1b296b9
SH
307 logMessage = ""
308 if not self.directSubmit:
309 logMessage = extractLogMessageFromGitCommit(id)
310 logMessage = logMessage.replace("\n", "\n\t")
311 logMessage = logMessage[:-1]
4f5cf76a 312
caace111 313 template = mypopen("p4 change -o").read()
4f5cf76a
SH
314
315 if self.interactive:
316 submitTemplate = self.prepareLogMessage(template, logMessage)
caace111 317 diff = mypopen("p4 diff -du ...").read()
4f5cf76a
SH
318
319 for newFile in filesToAdd:
320 diff += "==== new file ====\n"
321 diff += "--- /dev/null\n"
322 diff += "+++ %s\n" % newFile
323 f = open(newFile, "r")
324 for line in f.readlines():
325 diff += "+" + line
326 f.close()
327
25df95cc
SH
328 separatorLine = "######## everything below this line is just the diff #######"
329 if platform.system() == "Windows":
330 separatorLine += "\r"
331 separatorLine += "\n"
4f5cf76a
SH
332
333 response = "e"
53150250 334 firstIteration = True
4f5cf76a 335 while response == "e":
53150250 336 if not firstIteration:
d336c158 337 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
53150250 338 firstIteration = False
4f5cf76a
SH
339 if response == "e":
340 [handle, fileName] = tempfile.mkstemp()
341 tmpFile = os.fdopen(handle, "w+")
53150250 342 tmpFile.write(submitTemplate + separatorLine + diff)
4f5cf76a 343 tmpFile.close()
25df95cc
SH
344 defaultEditor = "vi"
345 if platform.system() == "Windows":
346 defaultEditor = "notepad"
347 editor = os.environ.get("EDITOR", defaultEditor);
4f5cf76a 348 system(editor + " " + fileName)
25df95cc 349 tmpFile = open(fileName, "rb")
53150250 350 message = tmpFile.read()
4f5cf76a
SH
351 tmpFile.close()
352 os.remove(fileName)
53150250 353 submitTemplate = message[:message.index(separatorLine)]
4f5cf76a
SH
354
355 if response == "y" or response == "yes":
356 if self.dryRun:
357 print submitTemplate
358 raw_input("Press return to continue...")
359 else:
7944f142
SH
360 if self.directSubmit:
361 print "Submitting to git first"
362 os.chdir(self.oldWorkingDirectory)
363 pipe = os.popen("git commit -a -F -", "wb")
364 pipe.write(submitTemplate)
365 pipe.close()
366 os.chdir(self.clientPath)
367
368 pipe = os.popen("p4 submit -i", "wb")
369 pipe.write(submitTemplate)
370 pipe.close()
d336c158
SH
371 elif response == "s":
372 for f in editedFiles:
373 system("p4 revert \"%s\"" % f);
374 for f in filesToAdd:
375 system("p4 revert \"%s\"" % f);
376 system("rm %s" %f)
377 for f in filesToDelete:
378 system("p4 delete \"%s\"" % f);
379 return
4f5cf76a
SH
380 else:
381 print "Not submitting!"
382 self.interactive = False
383 else:
384 fileName = "submit.txt"
385 file = open(fileName, "w+")
386 file.write(self.prepareLogMessage(template, logMessage))
387 file.close()
388 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
389
390 def run(self, args):
9512497b
SH
391 global gitdir
392 # make gitdir absolute so we can cd out into the perforce checkout
393 gitdir = os.path.abspath(gitdir)
394 os.environ["GIT_DIR"] = gitdir
c9b50e63
SH
395
396 if len(args) == 0:
397 self.master = currentGitBranch()
398 if len(self.master) == 0 or not os.path.exists("%s/refs/heads/%s" % (gitdir, self.master)):
399 die("Detecting current git branch failed!")
400 elif len(args) == 1:
401 self.master = args[0]
402 else:
403 return False
404
9512497b
SH
405 depotPath = ""
406 if gitBranchExists("p4"):
407 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
408 if len(depotPath) == 0 and gitBranchExists("origin"):
409 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
410
411 if len(depotPath) == 0:
412 print "Internal error: cannot locate perforce depot path from existing branches"
413 sys.exit(128)
414
51a2640a 415 self.clientPath = p4Where(depotPath)
9512497b 416
51a2640a 417 if len(self.clientPath) == 0:
9512497b
SH
418 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
419 sys.exit(128)
420
51a2640a 421 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
7944f142 422 self.oldWorkingDirectory = os.getcwd()
c1b296b9
SH
423
424 if self.directSubmit:
425 self.diffStatus = mypopen("git diff -r --name-status HEAD").readlines()
cbf5efa6
SH
426 if len(self.diffStatus) == 0:
427 print "No changes in working directory to submit."
428 return True
c1b296b9
SH
429 patch = mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
430 self.diffFile = gitdir + "/p4-git-diff"
431 f = open(self.diffFile, "wb")
432 f.write(patch)
433 f.close();
434
51a2640a
SH
435 os.chdir(self.clientPath)
436 response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
9512497b
SH
437 if response == "y" or response == "yes":
438 system("p4 sync ...")
439
440 if len(self.origin) == 0:
441 if gitBranchExists("p4"):
442 self.origin = "p4"
443 else:
444 self.origin = "origin"
445
4f5cf76a
SH
446 if self.reset:
447 self.firstTime = True
448
449 if len(self.substFile) > 0:
450 for line in open(self.substFile, "r").readlines():
451 tokens = line[:-1].split("=")
452 self.logSubstitutions[tokens[0]] = tokens[1]
453
4f5cf76a
SH
454 self.check()
455 self.configFile = gitdir + "/p4-git-sync.cfg"
456 self.config = shelve.open(self.configFile, writeback=True)
457
458 if self.firstTime:
459 self.start()
460
461 commits = self.config.get("commits", [])
462
463 while len(commits) > 0:
464 self.firstTime = False
465 commit = commits[0]
466 commits = commits[1:]
467 self.config["commits"] = commits
468 self.apply(commit)
469 if not self.interactive:
470 break
471
472 self.config.close()
473
c1b296b9
SH
474 if self.directSubmit:
475 os.remove(self.diffFile)
476
4f5cf76a
SH
477 if len(commits) == 0:
478 if self.firstTime:
479 print "No changes found to apply between %s and current HEAD" % self.origin
480 else:
481 print "All changes applied!"
7944f142
SH
482 os.chdir(self.oldWorkingDirectory)
483 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
80b5910f 484 if response == "y" or response == "yes":
80b5910f
SH
485 rebase = P4Rebase()
486 rebase.run([])
4f5cf76a
SH
487 os.remove(self.configFile)
488
b984733c
SH
489 return True
490
711544b0 491class P4Sync(Command):
b984733c
SH
492 def __init__(self):
493 Command.__init__(self)
494 self.options = [
495 optparse.make_option("--branch", dest="branch"),
496 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
497 optparse.make_option("--changesfile", dest="changesFile"),
498 optparse.make_option("--silent", dest="silent", action="store_true"),
ef48f909 499 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
4b97ffb1
SH
500 optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true"),
501 optparse.make_option("--verbose", dest="verbose", action="store_true")
b984733c
SH
502 ]
503 self.description = """Imports from Perforce into a git repository.\n
504 example:
505 //depot/my/project/ -- to import the current head
506 //depot/my/project/@all -- to import everything
507 //depot/my/project/@1,6 -- to import only from revision 1 to 6
508
509 (a ... is not needed in the path p4 specification, it's added implicitly)"""
510
511 self.usage += " //depot/path[@revRange]"
512
b984733c 513 self.silent = False
b984733c
SH
514 self.createdBranches = Set()
515 self.committedChanges = Set()
569d1bd4 516 self.branch = ""
b984733c 517 self.detectBranches = False
cb53e1f8 518 self.detectLabels = False
b984733c 519 self.changesFile = ""
ef48f909 520 self.syncWithOrigin = False
4b97ffb1 521 self.verbose = False
b984733c
SH
522
523 def p4File(self, depotPath):
524 return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
525
526 def extractFilesFromCommit(self, commit):
527 files = []
528 fnum = 0
529 while commit.has_key("depotFile%s" % fnum):
530 path = commit["depotFile%s" % fnum]
8f872531 531 if not path.startswith(self.depotPath):
b984733c 532 # if not self.silent:
8f872531 533 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
b984733c
SH
534 fnum = fnum + 1
535 continue
536
537 file = {}
538 file["path"] = path
539 file["rev"] = commit["rev%s" % fnum]
540 file["action"] = commit["action%s" % fnum]
541 file["type"] = commit["type%s" % fnum]
542 files.append(file)
543 fnum = fnum + 1
544 return files
545
71b112d4 546 def splitFilesIntoBranches(self, commit):
d5904674 547 branches = {}
b984733c 548
71b112d4
SH
549 fnum = 0
550 while commit.has_key("depotFile%s" % fnum):
551 path = commit["depotFile%s" % fnum]
552 if not path.startswith(self.depotPath):
553 # if not self.silent:
554 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
555 fnum = fnum + 1
556 continue
557
558 file = {}
559 file["path"] = path
560 file["rev"] = commit["rev%s" % fnum]
561 file["action"] = commit["action%s" % fnum]
562 file["type"] = commit["type%s" % fnum]
563 fnum = fnum + 1
564
565 relPath = path[len(self.depotPath):]
b984733c 566
4b97ffb1 567 for branch in self.knownBranches.keys():
af8da89c 568 if relPath.startswith(branch + "/"): # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
d5904674
SH
569 if branch not in branches:
570 branches[branch] = []
71b112d4 571 branches[branch].append(file)
b984733c
SH
572
573 return branches
574
4b97ffb1 575 def commit(self, details, files, branch, branchPrefix, parent = ""):
b984733c
SH
576 epoch = details["time"]
577 author = details["user"]
578
4b97ffb1
SH
579 if self.verbose:
580 print "commit into %s" % branch
581
b984733c
SH
582 self.gitStream.write("commit %s\n" % branch)
583 # gitStream.write("mark :%s\n" % details["change"])
584 self.committedChanges.add(int(details["change"]))
585 committer = ""
b607e71e
SH
586 if author not in self.users:
587 self.getUserMapFromPerforceServer()
b984733c 588 if author in self.users:
0828ab14 589 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
b984733c 590 else:
0828ab14 591 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
b984733c
SH
592
593 self.gitStream.write("committer %s\n" % committer)
594
595 self.gitStream.write("data <<EOT\n")
596 self.gitStream.write(details["desc"])
6ae8de88 597 self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
b984733c
SH
598 self.gitStream.write("EOT\n\n")
599
600 if len(parent) > 0:
4b97ffb1
SH
601 if self.verbose:
602 print "parent %s" % parent
b984733c
SH
603 self.gitStream.write("from %s\n" % parent)
604
b984733c
SH
605 for file in files:
606 path = file["path"]
607 if not path.startswith(branchPrefix):
608 # if not silent:
609 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
610 continue
611 rev = file["rev"]
612 depotPath = path + "#" + rev
613 relPath = path[len(branchPrefix):]
614 action = file["action"]
615
616 if file["type"] == "apple":
617 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
618 continue
619
620 if action == "delete":
621 self.gitStream.write("D %s\n" % relPath)
622 else:
623 mode = 644
624 if file["type"].startswith("x"):
625 mode = 755
626
627 data = self.p4File(depotPath)
628
629 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
630 self.gitStream.write("data %s\n" % len(data))
631 self.gitStream.write(data)
632 self.gitStream.write("\n")
633
634 self.gitStream.write("\n")
635
1f4ba1cb
SH
636 change = int(details["change"])
637
9bda3a85 638 if self.labels.has_key(change):
1f4ba1cb
SH
639 label = self.labels[change]
640 labelDetails = label[0]
641 labelRevisions = label[1]
71b112d4
SH
642 if self.verbose:
643 print "Change %s is labelled %s" % (change, labelDetails)
1f4ba1cb
SH
644
645 files = p4CmdList("files %s...@%s" % (branchPrefix, change))
646
647 if len(files) == len(labelRevisions):
648
649 cleanedFiles = {}
650 for info in files:
651 if info["action"] == "delete":
652 continue
653 cleanedFiles[info["depotFile"]] = info["rev"]
654
655 if cleanedFiles == labelRevisions:
656 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
657 self.gitStream.write("from %s\n" % branch)
658
659 owner = labelDetails["Owner"]
660 tagger = ""
661 if author in self.users:
662 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
663 else:
664 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
665 self.gitStream.write("tagger %s\n" % tagger)
666 self.gitStream.write("data <<EOT\n")
667 self.gitStream.write(labelDetails["Description"])
668 self.gitStream.write("EOT\n\n")
669
670 else:
a46668fa 671 if not self.silent:
1f4ba1cb
SH
672 print "Tag %s does not match with change %s: files do not match." % (labelDetails["label"], change)
673
674 else:
a46668fa 675 if not self.silent:
1f4ba1cb 676 print "Tag %s does not match with change %s: file count is different." % (labelDetails["label"], change)
b984733c 677
b607e71e 678 def getUserMapFromPerforceServer(self):
b984733c
SH
679 self.users = {}
680
681 for output in p4CmdList("users"):
682 if not output.has_key("User"):
683 continue
684 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
685
b607e71e
SH
686 cache = open(gitdir + "/p4-usercache.txt", "wb")
687 for user in self.users.keys():
688 cache.write("%s\t%s\n" % (user, self.users[user]))
689 cache.close();
690
691 def loadUserMapFromCache(self):
692 self.users = {}
693 try:
694 cache = open(gitdir + "/p4-usercache.txt", "rb")
695 lines = cache.readlines()
696 cache.close()
697 for line in lines:
698 entry = line[:-1].split("\t")
699 self.users[entry[0]] = entry[1]
700 except IOError:
701 self.getUserMapFromPerforceServer()
702
1f4ba1cb
SH
703 def getLabels(self):
704 self.labels = {}
705
8f872531 706 l = p4CmdList("labels %s..." % self.depotPath)
10c3211b 707 if len(l) > 0 and not self.silent:
8f872531 708 print "Finding files belonging to labels in %s" % self.depotPath
01ce1fe9
SH
709
710 for output in l:
1f4ba1cb
SH
711 label = output["label"]
712 revisions = {}
713 newestChange = 0
71b112d4
SH
714 if self.verbose:
715 print "Querying files for label %s" % label
716 for file in p4CmdList("files %s...@%s" % (self.depotPath, label)):
1f4ba1cb
SH
717 revisions[file["depotFile"]] = file["rev"]
718 change = int(file["change"])
719 if change > newestChange:
720 newestChange = change
721
9bda3a85
SH
722 self.labels[newestChange] = [output, revisions]
723
724 if self.verbose:
725 print "Label changes: %s" % self.labels.keys()
1f4ba1cb 726
4b97ffb1 727 def getBranchMapping(self):
29bdbac1 728 self.projectName = self.depotPath[self.depotPath[:-1].rfind("/") + 1:]
4b97ffb1
SH
729
730 for info in p4CmdList("branches"):
731 details = p4Cmd("branch -o %s" % info["branch"])
732 viewIdx = 0
733 while details.has_key("View%s" % viewIdx):
734 paths = details["View%s" % viewIdx].split(" ")
735 viewIdx = viewIdx + 1
736 # require standard //depot/foo/... //depot/bar/... mapping
737 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
738 continue
739 source = paths[0]
740 destination = paths[1]
741 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
742 source = source[len(self.depotPath):-4]
743 destination = destination[len(self.depotPath):-4]
29bdbac1
SH
744 if destination not in self.knownBranches:
745 self.knownBranches[destination] = source
746 if source not in self.knownBranches:
747 self.knownBranches[source] = source
748
749 def listExistingP4GitBranches(self):
750 self.p4BranchesInGit = []
751
752 for line in mypopen("git rev-parse --symbolic --remotes").readlines():
753 if line.startswith("p4/") and line != "p4/HEAD\n":
754 branch = line[3:-1]
755 self.p4BranchesInGit.append(branch)
756 self.initialParents["refs/remotes/p4/" + branch] = parseRevision(line[:-1])
4b97ffb1 757
b984733c 758 def run(self, args):
8f872531 759 self.depotPath = ""
179caebf
SH
760 self.changeRange = ""
761 self.initialParent = ""
cd6cc0d3 762 self.previousDepotPath = ""
29bdbac1
SH
763 # map from branch depot path to parent branch
764 self.knownBranches = {}
765 self.initialParents = {}
766
faf1bd20
SH
767 createP4HeadRef = False;
768
29bdbac1
SH
769 if self.syncWithOrigin and gitBranchExists("origin") and gitBranchExists("refs/remotes/p4/master") and not self.detectBranches:
770 ### needs to be ported to multi branch import
179caebf 771
ef48f909
SH
772 print "Syncing with origin first as requested by calling git fetch origin"
773 system("git fetch origin")
774 [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
775 [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
776 if len(originPreviousDepotPath) > 0 and len(originP4Change) > 0 and len(p4Change) > 0:
777 if originPreviousDepotPath == p4PreviousDepotPath:
778 originP4Change = int(originP4Change)
779 p4Change = int(p4Change)
780 if originP4Change > p4Change:
781 print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change, p4Change)
782 system("git update-ref refs/remotes/p4/master origin");
783 else:
784 print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath, p4PreviousDepotPath)
785
569d1bd4 786 if len(self.branch) == 0:
48df6fd8 787 self.branch = "refs/remotes/p4/master"
c6d44cb1 788 if gitBranchExists("refs/heads/p4"):
48df6fd8 789 system("git update-ref %s refs/heads/p4" % self.branch)
48df6fd8 790 system("git branch -D p4");
faf1bd20 791 # create it /after/ importing, when master exists
05094f98 792 if not gitBranchExists("refs/remotes/p4/HEAD"):
faf1bd20 793 createP4HeadRef = True
967f72e2 794
33be3e65
SH
795 # this needs to be called after the conversion from heads/p4 to remotes/p4/master
796 self.listExistingP4GitBranches()
797 if len(self.p4BranchesInGit) > 1 and not self.silent:
798 print "Importing from/into multiple branches"
799 self.detectBranches = True
800
967f72e2 801 if len(args) == 0:
29bdbac1
SH
802 if not gitBranchExists(self.branch) and gitBranchExists("origin") and not self.detectBranches:
803 ### needs to be ported to multi branch import
967f72e2
SH
804 if not self.silent:
805 print "Creating %s branch in git repository based on origin" % self.branch
8ead4fda
SH
806 branch = self.branch
807 if not branch.startswith("refs"):
808 branch = "refs/heads/" + branch
809 system("git update-ref %s origin" % branch)
967f72e2 810
29bdbac1
SH
811 if self.verbose:
812 print "branches: %s" % self.p4BranchesInGit
813
814 p4Change = 0
815 for branch in self.p4BranchesInGit:
816 depotPath, change = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("refs/remotes/p4/" + branch))
817
818 if self.verbose:
819 print "path %s change %s" % (depotPath, change)
820
821 if len(depotPath) > 0 and len(change) > 0:
822 change = int(change) + 1
823 p4Change = max(p4Change, change)
824
825 if len(self.previousDepotPath) == 0:
826 self.previousDepotPath = depotPath
827 else:
828 i = 0
829 l = min(len(self.previousDepotPath), len(depotPath))
830 while i < l and self.previousDepotPath[i] == depotPath[i]:
831 i = i + 1
832 self.previousDepotPath = self.previousDepotPath[:i]
833
834 if p4Change > 0:
8f872531 835 self.depotPath = self.previousDepotPath
d5904674 836 self.changeRange = "@%s,#head" % p4Change
463e8af6 837 self.initialParent = parseRevision(self.branch)
341dc1c1 838 if not self.silent and not self.detectBranches:
967f72e2 839 print "Performing incremental import into %s git branch" % self.branch
569d1bd4 840
f9162f6a
SH
841 if not self.branch.startswith("refs/"):
842 self.branch = "refs/heads/" + self.branch
179caebf 843
8f872531
SH
844 if len(self.depotPath) != 0:
845 self.depotPath = self.depotPath[:-1]
b984733c 846
8f872531 847 if len(args) == 0 and len(self.depotPath) != 0:
b984733c 848 if not self.silent:
8f872531 849 print "Depot path: %s" % self.depotPath
b984733c
SH
850 elif len(args) != 1:
851 return False
852 else:
8f872531
SH
853 if len(self.depotPath) != 0 and self.depotPath != args[0]:
854 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.depotPath, args[0])
b984733c 855 sys.exit(1)
8f872531 856 self.depotPath = args[0]
b984733c 857
b984733c
SH
858 self.revision = ""
859 self.users = {}
b984733c 860
8f872531
SH
861 if self.depotPath.find("@") != -1:
862 atIdx = self.depotPath.index("@")
863 self.changeRange = self.depotPath[atIdx:]
b984733c
SH
864 if self.changeRange == "@all":
865 self.changeRange = ""
866 elif self.changeRange.find(",") == -1:
867 self.revision = self.changeRange
868 self.changeRange = ""
8f872531
SH
869 self.depotPath = self.depotPath[0:atIdx]
870 elif self.depotPath.find("#") != -1:
871 hashIdx = self.depotPath.index("#")
872 self.revision = self.depotPath[hashIdx:]
873 self.depotPath = self.depotPath[0:hashIdx]
b984733c
SH
874 elif len(self.previousDepotPath) == 0:
875 self.revision = "#head"
876
8f872531
SH
877 if self.depotPath.endswith("..."):
878 self.depotPath = self.depotPath[:-3]
b984733c 879
8f872531
SH
880 if not self.depotPath.endswith("/"):
881 self.depotPath += "/"
b984733c 882
b607e71e 883 self.loadUserMapFromCache()
cb53e1f8
SH
884 self.labels = {}
885 if self.detectLabels:
886 self.getLabels();
b984733c 887
4b97ffb1
SH
888 if self.detectBranches:
889 self.getBranchMapping();
29bdbac1
SH
890 if self.verbose:
891 print "p4-git branches: %s" % self.p4BranchesInGit
892 print "initial parents: %s" % self.initialParents
893 for b in self.p4BranchesInGit:
894 if b != "master":
895 b = b[len(self.projectName):]
896 self.createdBranches.add(b)
4b97ffb1 897
f291b4e3 898 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
b984733c 899
08483580
SH
900 importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
901 self.gitOutput = importProcess.stdout
902 self.gitStream = importProcess.stdin
903 self.gitError = importProcess.stderr
b984733c
SH
904
905 if len(self.revision) > 0:
8f872531 906 print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
b984733c
SH
907
908 details = { "user" : "git perforce import user", "time" : int(time.time()) }
8f872531 909 details["desc"] = "Initial import of %s from the state at revision %s" % (self.depotPath, self.revision)
b984733c
SH
910 details["change"] = self.revision
911 newestRevision = 0
912
913 fileCnt = 0
8f872531 914 for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
b984733c
SH
915 change = int(info["change"])
916 if change > newestRevision:
917 newestRevision = change
918
919 if info["action"] == "delete":
c45b1cfe
SH
920 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
921 #fileCnt = fileCnt + 1
b984733c
SH
922 continue
923
924 for prop in [ "depotFile", "rev", "action", "type" ]:
925 details["%s%s" % (prop, fileCnt)] = info[prop]
926
927 fileCnt = fileCnt + 1
928
929 details["change"] = newestRevision
930
931 try:
8f872531 932 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
c715706b 933 except IOError:
fd4ca86a 934 print "IO error with git fast-import. Is your git version recent enough?"
b984733c
SH
935 print self.gitError.read()
936
937 else:
938 changes = []
939
0828ab14 940 if len(self.changesFile) > 0:
b984733c
SH
941 output = open(self.changesFile).readlines()
942 changeSet = Set()
943 for line in output:
944 changeSet.add(int(line))
945
946 for change in changeSet:
947 changes.append(change)
948
949 changes.sort()
950 else:
29bdbac1
SH
951 if self.verbose:
952 print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
caace111 953 output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines()
b984733c
SH
954
955 for line in output:
956 changeNum = line.split(" ")[1]
957 changes.append(changeNum)
958
959 changes.reverse()
960
961 if len(changes) == 0:
0828ab14 962 if not self.silent:
341dc1c1 963 print "No changes to import!"
1f52af6c 964 return True
b984733c 965
341dc1c1
SH
966 self.updatedBranches = set()
967
b984733c
SH
968 cnt = 1
969 for change in changes:
970 description = p4Cmd("describe %s" % change)
971
0828ab14 972 if not self.silent:
341dc1c1 973 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
b984733c
SH
974 sys.stdout.flush()
975 cnt = cnt + 1
976
977 try:
b984733c 978 if self.detectBranches:
71b112d4 979 branches = self.splitFilesIntoBranches(description)
d5904674 980 for branch in branches.keys():
8f872531 981 branchPrefix = self.depotPath + branch + "/"
b984733c 982
b984733c 983 parent = ""
4b97ffb1 984
d5904674 985 filesForCommit = branches[branch]
4b97ffb1 986
29bdbac1
SH
987 if self.verbose:
988 print "branch is %s" % branch
989
341dc1c1
SH
990 self.updatedBranches.add(branch)
991
8f9b2e08 992 if branch not in self.createdBranches:
b984733c 993 self.createdBranches.add(branch)
4b97ffb1 994 parent = self.knownBranches[branch]
b984733c
SH
995 if parent == branch:
996 parent = ""
29bdbac1
SH
997 elif self.verbose:
998 print "parent determined through known branches: %s" % parent
b984733c 999
8f9b2e08
SH
1000 # main branch? use master
1001 if branch == "main":
1002 branch = "master"
1003 else:
29bdbac1 1004 branch = self.projectName + branch
8f9b2e08
SH
1005
1006 if parent == "main":
1007 parent = "master"
1008 elif len(parent) > 0:
29bdbac1 1009 parent = self.projectName + parent
8f9b2e08 1010
4b97ffb1 1011 branch = "refs/remotes/p4/" + branch
b984733c 1012 if len(parent) > 0:
4b97ffb1 1013 parent = "refs/remotes/p4/" + parent
29bdbac1
SH
1014
1015 if self.verbose:
1016 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1017
1018 if len(parent) == 0 and branch in self.initialParents:
1019 parent = self.initialParents[branch]
1020 del self.initialParents[branch]
1021
71b112d4 1022 self.commit(description, filesForCommit, branch, branchPrefix, parent)
b984733c 1023 else:
71b112d4 1024 files = self.extractFilesFromCommit(description)
8f872531 1025 self.commit(description, files, self.branch, self.depotPath, self.initialParent)
b984733c
SH
1026 self.initialParent = ""
1027 except IOError:
1028 print self.gitError.read()
1029 sys.exit(1)
1030
341dc1c1
SH
1031 if not self.silent:
1032 print ""
1033 if len(self.updatedBranches) > 0:
1034 sys.stdout.write("Updated branches: ")
1035 for b in self.updatedBranches:
1036 sys.stdout.write("%s " % b)
1037 sys.stdout.write("\n")
b984733c 1038
b984733c
SH
1039
1040 self.gitStream.close()
29bdbac1
SH
1041 if importProcess.wait() != 0:
1042 die("fast-import failed: %s" % self.gitError.read())
b984733c
SH
1043 self.gitOutput.close()
1044 self.gitError.close()
1045
faf1bd20
SH
1046 if createP4HeadRef:
1047 system("git symbolic-ref refs/remotes/p4/HEAD %s" % self.branch)
1048
b984733c
SH
1049 return True
1050
01ce1fe9
SH
1051class P4Rebase(Command):
1052 def __init__(self):
1053 Command.__init__(self)
ef48f909 1054 self.options = [ optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true") ]
01ce1fe9 1055 self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it"
ef48f909 1056 self.syncWithOrigin = False
01ce1fe9
SH
1057
1058 def run(self, args):
1059 sync = P4Sync()
ef48f909 1060 sync.syncWithOrigin = self.syncWithOrigin
01ce1fe9
SH
1061 sync.run([])
1062 print "Rebasing the current branch"
caace111 1063 oldHead = mypopen("git rev-parse HEAD").read()[:-1]
01ce1fe9 1064 system("git rebase p4")
1f52af6c 1065 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
01ce1fe9
SH
1066 return True
1067
f9a3a4f7
SH
1068class P4Clone(P4Sync):
1069 def __init__(self):
1070 P4Sync.__init__(self)
1071 self.description = "Creates a new git repository and imports from Perforce into it"
1072 self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1073 self.needsGit = False
f9a3a4f7
SH
1074
1075 def run(self, args):
59fa4171
SH
1076 global gitdir
1077
f9a3a4f7
SH
1078 if len(args) < 1:
1079 return False
1080 depotPath = args[0]
1081 dir = ""
1082 if len(args) == 2:
1083 dir = args[1]
1084 elif len(args) > 2:
1085 return False
1086
1087 if not depotPath.startswith("//"):
1088 return False
1089
1090 if len(dir) == 0:
1091 dir = depotPath
1092 atPos = dir.rfind("@")
1093 if atPos != -1:
1094 dir = dir[0:atPos]
1095 hashPos = dir.rfind("#")
1096 if hashPos != -1:
1097 dir = dir[0:hashPos]
1098
1099 if dir.endswith("..."):
1100 dir = dir[:-3]
1101
1102 if dir.endswith("/"):
1103 dir = dir[:-1]
1104
1105 slashPos = dir.rfind("/")
1106 if slashPos != -1:
1107 dir = dir[slashPos + 1:]
1108
1109 print "Importing from %s into %s" % (depotPath, dir)
1110 os.makedirs(dir)
1111 os.chdir(dir)
1112 system("git init")
64ffb06a 1113 gitdir = os.getcwd() + "/.git"
f9a3a4f7
SH
1114 if not P4Sync.run(self, [depotPath]):
1115 return False
f9a3a4f7 1116 if self.branch != "master":
8f9b2e08
SH
1117 if gitBranchExists("refs/remotes/p4/master"):
1118 system("git branch master refs/remotes/p4/master")
1119 system("git checkout -f")
1120 else:
1121 print "Could not detect main branch. No checkout/master branch created."
f9a3a4f7
SH
1122 return True
1123
b984733c
SH
1124class HelpFormatter(optparse.IndentedHelpFormatter):
1125 def __init__(self):
1126 optparse.IndentedHelpFormatter.__init__(self)
1127
1128 def format_description(self, description):
1129 if description:
1130 return description + "\n"
1131 else:
1132 return ""
4f5cf76a 1133
86949eef
SH
1134def printUsage(commands):
1135 print "usage: %s <command> [options]" % sys.argv[0]
1136 print ""
1137 print "valid commands: %s" % ", ".join(commands)
1138 print ""
1139 print "Try %s <command> --help for command specific help." % sys.argv[0]
1140 print ""
1141
1142commands = {
1143 "debug" : P4Debug(),
711544b0 1144 "submit" : P4Submit(),
01ce1fe9 1145 "sync" : P4Sync(),
f9a3a4f7 1146 "rebase" : P4Rebase(),
5834684d
SH
1147 "clone" : P4Clone(),
1148 "rollback" : P4RollBack()
86949eef
SH
1149}
1150
1151if len(sys.argv[1:]) == 0:
1152 printUsage(commands.keys())
1153 sys.exit(2)
1154
1155cmd = ""
1156cmdName = sys.argv[1]
1157try:
1158 cmd = commands[cmdName]
1159except KeyError:
1160 print "unknown command %s" % cmdName
1161 print ""
1162 printUsage(commands.keys())
1163 sys.exit(2)
1164
4f5cf76a
SH
1165options = cmd.options
1166cmd.gitdir = gitdir
4f5cf76a 1167
e20a9e53 1168args = sys.argv[2:]
86949eef 1169
e20a9e53
SH
1170if len(options) > 0:
1171 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1172
1173 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1174 options,
1175 description = cmd.description,
1176 formatter = HelpFormatter())
1177
1178 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
86949eef 1179
8910ac0e
SH
1180if cmd.needsGit:
1181 gitdir = cmd.gitdir
1182 if len(gitdir) == 0:
1183 gitdir = ".git"
1184 if not isValidGitDir(gitdir):
81f2373f 1185 gitdir = mypopen("git rev-parse --git-dir").read()[:-1]
dc1a93b6 1186 if os.path.exists(gitdir):
5c4153e4
SH
1187 cdup = mypopen("git rev-parse --show-cdup").read()[:-1];
1188 if len(cdup) > 0:
1189 os.chdir(cdup);
4f5cf76a 1190
8910ac0e
SH
1191 if not isValidGitDir(gitdir):
1192 if isValidGitDir(gitdir + "/.git"):
1193 gitdir += "/.git"
1194 else:
1195 die("fatal: cannot locate git repository at %s" % gitdir)
4f5cf76a 1196
8910ac0e 1197 os.environ["GIT_DIR"] = gitdir
4f5cf76a 1198
b984733c
SH
1199if not cmd.run(args):
1200 parser.print_help()
1201