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