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 <simon@lst.de>
6# Copyright: 2007 Simon Hausmann <simon@lst.de>
7# 2007 Trolltech ASA
8# License: MIT <http://www.opensource.org/licenses/mit-license.php>
9#
10
11import optparse, sys, os, marshal, popen2, subprocess, shelve
12import tempfile, getopt, sha, os.path, time, platform
13import re
14
15from sets import Set;
16
17verbose = False
18
19def die(msg):
20 if verbose:
21 raise Exception(msg)
22 else:
23 sys.stderr.write(msg + "\n")
24 sys.exit(1)
25
26def write_pipe(c, str):
27 if verbose:
28 sys.stderr.write('Writing pipe: %s\n' % c)
29
30 pipe = os.popen(c, 'w')
31 val = pipe.write(str)
32 if pipe.close():
33 die('Command failed: %s' % c)
34
35 return val
36
37def read_pipe(c, ignore_error=False):
38 if verbose:
39 sys.stderr.write('Reading pipe: %s\n' % c)
40
41 pipe = os.popen(c, 'rb')
42 val = pipe.read()
43 if pipe.close() and not ignore_error:
44 die('Command failed: %s' % c)
45
46 return val
47
48
49def read_pipe_lines(c):
50 if verbose:
51 sys.stderr.write('Reading pipe: %s\n' % c)
52 ## todo: check return status
53 pipe = os.popen(c, 'rb')
54 val = pipe.readlines()
55 if pipe.close():
56 die('Command failed: %s' % c)
57
58 return val
59
60def system(cmd):
61 if verbose:
62 sys.stderr.write("executing %s\n" % cmd)
63 if os.system(cmd) != 0:
64 die("command failed: %s" % cmd)
65
66def p4CmdList(cmd):
67 cmd = "p4 -G %s" % cmd
68 if verbose:
69 sys.stderr.write("Opening pipe: %s\n" % cmd)
70 pipe = os.popen(cmd, "rb")
71
72 result = []
73 try:
74 while True:
75 entry = marshal.load(pipe)
76 result.append(entry)
77 except EOFError:
78 pass
79 exitCode = pipe.close()
80 if exitCode != None:
81 entry = {}
82 entry["p4ExitCode"] = exitCode
83 result.append(entry)
84
85 return result
86
87def p4Cmd(cmd):
88 list = p4CmdList(cmd)
89 result = {}
90 for entry in list:
91 result.update(entry)
92 return result;
93
94def p4Where(depotPath):
95 if not depotPath.endswith("/"):
96 depotPath += "/"
97 output = p4Cmd("where %s..." % depotPath)
98 if output["code"] == "error":
99 return ""
100 clientPath = ""
101 if "path" in output:
102 clientPath = output.get("path")
103 elif "data" in output:
104 data = output.get("data")
105 lastSpace = data.rfind(" ")
106 clientPath = data[lastSpace + 1:]
107
108 if clientPath.endswith("..."):
109 clientPath = clientPath[:-3]
110 return clientPath
111
112def currentGitBranch():
113 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
114
115def isValidGitDir(path):
116 if (os.path.exists(path + "/HEAD")
117 and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")):
118 return True;
119 return False
120
121def parseRevision(ref):
122 return read_pipe("git rev-parse %s" % ref).strip()
123
124def extractLogMessageFromGitCommit(commit):
125 logMessage = ""
126
127 ## fixme: title is first line of commit, not 1st paragraph.
128 foundTitle = False
129 for log in read_pipe_lines("git cat-file commit %s" % commit):
130 if not foundTitle:
131 if len(log) == 1:
132 foundTitle = True
133 continue
134
135 logMessage += log
136 return logMessage
137
138def extractSettingsGitLog(log):
139 values = {}
140 for line in log.split("\n"):
141 line = line.strip()
142 m = re.search (r"^ *\[git-p4: (.*)\]$", line)
143 if not m:
144 continue
145
146 assignments = m.group(1).split (':')
147 for a in assignments:
148 vals = a.split ('=')
149 key = vals[0].strip()
150 val = ('='.join (vals[1:])).strip()
151 if val.endswith ('\"') and val.startswith('"'):
152 val = val[1:-1]
153
154 values[key] = val
155
156 values['depot-paths'] = values.get("depot-paths").split(',')
157 return values
158
159def gitBranchExists(branch):
160 proc = subprocess.Popen(["git", "rev-parse", branch],
161 stderr=subprocess.PIPE, stdout=subprocess.PIPE);
162 return proc.wait() == 0;
163
164def gitConfig(key):
165 return read_pipe("git config %s" % key, ignore_error=True).strip()
166
167class Command:
168 def __init__(self):
169 self.usage = "usage: %prog [options]"
170 self.needsGit = True
171
172class P4Debug(Command):
173 def __init__(self):
174 Command.__init__(self)
175 self.options = [
176 optparse.make_option("--verbose", dest="verbose", action="store_true",
177 default=False),
178 ]
179 self.description = "A tool to debug the output of p4 -G."
180 self.needsGit = False
181 self.verbose = False
182
183 def run(self, args):
184 j = 0
185 for output in p4CmdList(" ".join(args)):
186 print 'Element: %d' % j
187 j += 1
188 print output
189 return True
190
191class P4RollBack(Command):
192 def __init__(self):
193 Command.__init__(self)
194 self.options = [
195 optparse.make_option("--verbose", dest="verbose", action="store_true"),
196 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
197 ]
198 self.description = "A tool to debug the multi-branch import. Don't use :)"
199 self.verbose = False
200 self.rollbackLocalBranches = False
201
202 def run(self, args):
203 if len(args) != 1:
204 return False
205 maxChange = int(args[0])
206
207 if "p4ExitCode" in p4Cmd("changes -m 1"):
208 die("Problems executing p4");
209
210 if self.rollbackLocalBranches:
211 refPrefix = "refs/heads/"
212 lines = read_pipe_lines("git rev-parse --symbolic --branches")
213 else:
214 refPrefix = "refs/remotes/"
215 lines = read_pipe_lines("git rev-parse --symbolic --remotes")
216
217 for line in lines:
218 if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
219 line = line.strip()
220 ref = refPrefix + line
221 log = extractLogMessageFromGitCommit(ref)
222 settings = extractSettingsGitLog(log)
223
224 depotPaths = settings['depot-paths']
225 change = settings['change']
226
227 changed = False
228
229 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
230 for p in depotPaths]))) == 0:
231 print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
232 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
233 continue
234
235 while change and int(change) > maxChange:
236 changed = True
237 if self.verbose:
238 print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
239 system("git update-ref %s \"%s^\"" % (ref, ref))
240 log = extractLogMessageFromGitCommit(ref)
241 settings = extractSettingsGitLog(log)
242
243
244 depotPaths = settings['depot-paths']
245 change = settings['change']
246
247 if changed:
248 print "%s rewound to %s" % (ref, change)
249
250 return True
251
252class P4Submit(Command):
253 def __init__(self):
254 Command.__init__(self)
255 self.options = [
256 optparse.make_option("--continue", action="store_false", dest="firstTime"),
257 optparse.make_option("--verbose", dest="verbose", action="store_true"),
258 optparse.make_option("--origin", dest="origin"),
259 optparse.make_option("--reset", action="store_true", dest="reset"),
260 optparse.make_option("--log-substitutions", dest="substFile"),
261 optparse.make_option("--dry-run", action="store_true"),
262 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
263 optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"),
264 ]
265 self.description = "Submit changes from git to the perforce depot."
266 self.usage += " [name of git branch to submit into perforce depot]"
267 self.firstTime = True
268 self.reset = False
269 self.interactive = True
270 self.dryRun = False
271 self.substFile = ""
272 self.firstTime = True
273 self.origin = ""
274 self.directSubmit = False
275 self.trustMeLikeAFool = False
276
277 self.logSubstitutions = {}
278 self.logSubstitutions["<enter description here>"] = "%log%"
279 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
280
281 def check(self):
282 if len(p4CmdList("opened ...")) > 0:
283 die("You have files opened with perforce! Close them before starting the sync.")
284
285 def start(self):
286 if len(self.config) > 0 and not self.reset:
287 die("Cannot start sync. Previous sync config found at %s\n"
288 "If you want to start submitting again from scratch "
289 "maybe you want to call git-p4 submit --reset" % self.configFile)
290
291 commits = []
292 if self.directSubmit:
293 commits.append("0")
294 else:
295 for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
296 commits.append(line.strip())
297 commits.reverse()
298
299 self.config["commits"] = commits
300
301 def prepareLogMessage(self, template, message):
302 result = ""
303
304 for line in template.split("\n"):
305 if line.startswith("#"):
306 result += line + "\n"
307 continue
308
309 substituted = False
310 for key in self.logSubstitutions.keys():
311 if line.find(key) != -1:
312 value = self.logSubstitutions[key]
313 value = value.replace("%log%", message)
314 if value != "@remove@":
315 result += line.replace(key, value) + "\n"
316 substituted = True
317 break
318
319 if not substituted:
320 result += line + "\n"
321
322 return result
323
324 def applyCommit(self, id):
325 if self.directSubmit:
326 print "Applying local change in working directory/index"
327 diff = self.diffStatus
328 else:
329 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
330 diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
331 filesToAdd = set()
332 filesToDelete = set()
333 editedFiles = set()
334 for line in diff:
335 modifier = line[0]
336 path = line[1:].strip()
337 if modifier == "M":
338 system("p4 edit \"%s\"" % path)
339 editedFiles.add(path)
340 elif modifier == "A":
341 filesToAdd.add(path)
342 if path in filesToDelete:
343 filesToDelete.remove(path)
344 elif modifier == "D":
345 filesToDelete.add(path)
346 if path in filesToAdd:
347 filesToAdd.remove(path)
348 else:
349 die("unknown modifier %s for %s" % (modifier, path))
350
351 if self.directSubmit:
352 diffcmd = "cat \"%s\"" % self.diffFile
353 else:
354 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
355 patchcmd = diffcmd + " | git apply "
356 tryPatchCmd = patchcmd + "--check -"
357 applyPatchCmd = patchcmd + "--check --apply -"
358
359 if os.system(tryPatchCmd) != 0:
360 print "Unfortunately applying the change failed!"
361 print "What do you want to do?"
362 response = "x"
363 while response != "s" and response != "a" and response != "w":
364 response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
365 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
366 if response == "s":
367 print "Skipping! Good luck with the next patches..."
368 return
369 elif response == "a":
370 os.system(applyPatchCmd)
371 if len(filesToAdd) > 0:
372 print "You may also want to call p4 add on the following files:"
373 print " ".join(filesToAdd)
374 if len(filesToDelete):
375 print "The following files should be scheduled for deletion with p4 delete:"
376 print " ".join(filesToDelete)
377 die("Please resolve and submit the conflict manually and "
378 + "continue afterwards with git-p4 submit --continue")
379 elif response == "w":
380 system(diffcmd + " > patch.txt")
381 print "Patch saved to patch.txt in %s !" % self.clientPath
382 die("Please resolve and submit the conflict manually and "
383 "continue afterwards with git-p4 submit --continue")
384
385 system(applyPatchCmd)
386
387 for f in filesToAdd:
388 system("p4 add %s" % f)
389 for f in filesToDelete:
390 system("p4 revert %s" % f)
391 system("p4 delete %s" % f)
392
393 logMessage = ""
394 if not self.directSubmit:
395 logMessage = extractLogMessageFromGitCommit(id)
396 logMessage = logMessage.replace("\n", "\n\t")
397 logMessage = logMessage.strip()
398
399 template = read_pipe("p4 change -o")
400
401 if self.interactive:
402 submitTemplate = self.prepareLogMessage(template, logMessage)
403 diff = read_pipe("p4 diff -du ...")
404
405 for newFile in filesToAdd:
406 diff += "==== new file ====\n"
407 diff += "--- /dev/null\n"
408 diff += "+++ %s\n" % newFile
409 f = open(newFile, "r")
410 for line in f.readlines():
411 diff += "+" + line
412 f.close()
413
414 separatorLine = "######## everything below this line is just the diff #######"
415 if platform.system() == "Windows":
416 separatorLine += "\r"
417 separatorLine += "\n"
418
419 response = "e"
420 if self.trustMeLikeAFool:
421 response = "y"
422
423 firstIteration = True
424 while response == "e":
425 if not firstIteration:
426 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
427 firstIteration = False
428 if response == "e":
429 [handle, fileName] = tempfile.mkstemp()
430 tmpFile = os.fdopen(handle, "w+")
431 tmpFile.write(submitTemplate + separatorLine + diff)
432 tmpFile.close()
433 defaultEditor = "vi"
434 if platform.system() == "Windows":
435 defaultEditor = "notepad"
436 editor = os.environ.get("EDITOR", defaultEditor);
437 system(editor + " " + fileName)
438 tmpFile = open(fileName, "rb")
439 message = tmpFile.read()
440 tmpFile.close()
441 os.remove(fileName)
442 submitTemplate = message[:message.index(separatorLine)]
443
444 if response == "y" or response == "yes":
445 if self.dryRun:
446 print submitTemplate
447 raw_input("Press return to continue...")
448 else:
449 if self.directSubmit:
450 print "Submitting to git first"
451 os.chdir(self.oldWorkingDirectory)
452 write_pipe("git commit -a -F -", submitTemplate)
453 os.chdir(self.clientPath)
454
455 write_pipe("p4 submit -i", submitTemplate)
456 elif response == "s":
457 for f in editedFiles:
458 system("p4 revert \"%s\"" % f);
459 for f in filesToAdd:
460 system("p4 revert \"%s\"" % f);
461 system("rm %s" %f)
462 for f in filesToDelete:
463 system("p4 delete \"%s\"" % f);
464 return
465 else:
466 print "Not submitting!"
467 self.interactive = False
468 else:
469 fileName = "submit.txt"
470 file = open(fileName, "w+")
471 file.write(self.prepareLogMessage(template, logMessage))
472 file.close()
473 print ("Perforce submit template written as %s. "
474 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
475 % (fileName, fileName))
476
477 def run(self, args):
478 # make gitdir absolute so we can cd out into the perforce checkout
479 os.environ["GIT_DIR"] = gitdir
480
481 if len(args) == 0:
482 self.master = currentGitBranch()
483 if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
484 die("Detecting current git branch failed!")
485 elif len(args) == 1:
486 self.master = args[0]
487 else:
488 return False
489
490 depotPath = ""
491 settings = None
492 if gitBranchExists("p4"):
493 settings = extractSettingsGitLog(extractLogMessageFromGitCommit("p4"))
494 if len(depotPath) == 0 and gitBranchExists("origin"):
495 settings = extractSettingsGitLog(extractLogMessageFromGitCommit("origin"))
496 depotPaths = settings['depot-paths']
497
498 if len(depotPath) == 0:
499 print "Internal error: cannot locate perforce depot path from existing branches"
500 sys.exit(128)
501
502 self.clientPath = p4Where(depotPath)
503
504 if len(self.clientPath) == 0:
505 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
506 sys.exit(128)
507
508 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
509 self.oldWorkingDirectory = os.getcwd()
510
511 if self.directSubmit:
512 self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD")
513 if len(self.diffStatus) == 0:
514 print "No changes in working directory to submit."
515 return True
516 patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
517 self.diffFile = self.gitdir + "/p4-git-diff"
518 f = open(self.diffFile, "wb")
519 f.write(patch)
520 f.close();
521
522 os.chdir(self.clientPath)
523 response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
524 if response == "y" or response == "yes":
525 system("p4 sync ...")
526
527 if len(self.origin) == 0:
528 if gitBranchExists("p4"):
529 self.origin = "p4"
530 else:
531 self.origin = "origin"
532
533 if self.reset:
534 self.firstTime = True
535
536 if len(self.substFile) > 0:
537 for line in open(self.substFile, "r").readlines():
538 tokens = line.strip().split("=")
539 self.logSubstitutions[tokens[0]] = tokens[1]
540
541 self.check()
542 self.configFile = self.gitdir + "/p4-git-sync.cfg"
543 self.config = shelve.open(self.configFile, writeback=True)
544
545 if self.firstTime:
546 self.start()
547
548 commits = self.config.get("commits", [])
549
550 while len(commits) > 0:
551 self.firstTime = False
552 commit = commits[0]
553 commits = commits[1:]
554 self.config["commits"] = commits
555 self.applyCommit(commit)
556 if not self.interactive:
557 break
558
559 self.config.close()
560
561 if self.directSubmit:
562 os.remove(self.diffFile)
563
564 if len(commits) == 0:
565 if self.firstTime:
566 print "No changes found to apply between %s and current HEAD" % self.origin
567 else:
568 print "All changes applied!"
569 os.chdir(self.oldWorkingDirectory)
570 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
571 if response == "y" or response == "yes":
572 rebase = P4Rebase()
573 rebase.run([])
574 os.remove(self.configFile)
575
576 return True
577
578class P4Sync(Command):
579 def __init__(self):
580 Command.__init__(self)
581 self.options = [
582 optparse.make_option("--branch", dest="branch"),
583 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
584 optparse.make_option("--changesfile", dest="changesFile"),
585 optparse.make_option("--silent", dest="silent", action="store_true"),
586 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
587 optparse.make_option("--verbose", dest="verbose", action="store_true"),
588 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
589 help="Import into refs/heads/ , not refs/remotes"),
590 optparse.make_option("--max-changes", dest="maxChanges"),
591 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
592 help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
593 ]
594 self.description = """Imports from Perforce into a git repository.\n
595 example:
596 //depot/my/project/ -- to import the current head
597 //depot/my/project/@all -- to import everything
598 //depot/my/project/@1,6 -- to import only from revision 1 to 6
599
600 (a ... is not needed in the path p4 specification, it's added implicitly)"""
601
602 self.usage += " //depot/path[@revRange]"
603 self.silent = False
604 self.createdBranches = Set()
605 self.committedChanges = Set()
606 self.branch = ""
607 self.detectBranches = False
608 self.detectLabels = False
609 self.changesFile = ""
610 self.syncWithOrigin = True
611 self.verbose = False
612 self.importIntoRemotes = True
613 self.maxChanges = ""
614 self.isWindows = (platform.system() == "Windows")
615 self.keepRepoPath = False
616 self.depotPaths = None
617
618 if gitConfig("git-p4.syncFromOrigin") == "false":
619 self.syncWithOrigin = False
620
621 def extractFilesFromCommit(self, commit):
622 files = []
623 fnum = 0
624 while commit.has_key("depotFile%s" % fnum):
625 path = commit["depotFile%s" % fnum]
626
627 found = [p for p in self.depotPaths
628 if path.startswith (p)]
629 if not found:
630 fnum = fnum + 1
631 continue
632
633 file = {}
634 file["path"] = path
635 file["rev"] = commit["rev%s" % fnum]
636 file["action"] = commit["action%s" % fnum]
637 file["type"] = commit["type%s" % fnum]
638 files.append(file)
639 fnum = fnum + 1
640 return files
641
642 def stripRepoPath(self, path, prefixes):
643 if self.keepRepoPath:
644 prefixes = [re.sub("^(//[^/]+/).*", r'\1', prefixes[0])]
645
646 for p in prefixes:
647 if path.startswith(p):
648 path = path[len(p):]
649
650 return path
651
652 def splitFilesIntoBranches(self, commit):
653 branches = {}
654 fnum = 0
655 while commit.has_key("depotFile%s" % fnum):
656 path = commit["depotFile%s" % fnum]
657 found = [p for p in self.depotPaths
658 if path.startswith (p)]
659 if not found:
660 fnum = fnum + 1
661 continue
662
663 file = {}
664 file["path"] = path
665 file["rev"] = commit["rev%s" % fnum]
666 file["action"] = commit["action%s" % fnum]
667 file["type"] = commit["type%s" % fnum]
668 fnum = fnum + 1
669
670 relPath = self.stripRepoPath(path, self.depotPaths)
671
672 for branch in self.knownBranches.keys():
673
674 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
675 if relPath.startswith(branch + "/"):
676 if branch not in branches:
677 branches[branch] = []
678 branches[branch].append(file)
679
680 return branches
681
682 ## Should move this out, doesn't use SELF.
683 def readP4Files(self, files):
684 files = [f for f in files
685 if f['action'] != 'delete']
686
687 if not files:
688 return
689
690 filedata = p4CmdList('print %s' % ' '.join(['"%s#%s"' % (f['path'],
691 f['rev'])
692 for f in files]))
693
694 j = 0;
695 contents = {}
696 while j < len(filedata):
697 stat = filedata[j]
698 j += 1
699 text = ''
700 while j < len(filedata) and filedata[j]['code'] in ('text',
701 'binary'):
702 text += filedata[j]['data']
703 j += 1
704
705 contents[stat['depotFile']] = text
706
707 for f in files:
708 assert not f.has_key('data')
709 f['data'] = contents[f['path']]
710
711 def commit(self, details, files, branch, branchPrefixes, parent = ""):
712 epoch = details["time"]
713 author = details["user"]
714
715 if self.verbose:
716 print "commit into %s" % branch
717
718 # start with reading files; if that fails, we should not
719 # create a commit.
720 new_files = []
721 for f in files:
722 if [p for p in branchPrefixes if f['path'].startswith(p)]:
723 new_files.append (f)
724 else:
725 sys.stderr.write("Ignoring file outside of prefix: %s\n" % path)
726 files = new_files
727 self.readP4Files(files)
728
729
730
731
732 self.gitStream.write("commit %s\n" % branch)
733# gitStream.write("mark :%s\n" % details["change"])
734 self.committedChanges.add(int(details["change"]))
735 committer = ""
736 if author not in self.users:
737 self.getUserMapFromPerforceServer()
738 if author in self.users:
739 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
740 else:
741 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
742
743 self.gitStream.write("committer %s\n" % committer)
744
745 self.gitStream.write("data <<EOT\n")
746 self.gitStream.write(details["desc"])
747 self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s: "
748 "options = %s]\n"
749 % (','.join (branchPrefixes), details["change"],
750 details['options']
751 ))
752 self.gitStream.write("EOT\n\n")
753
754 if len(parent) > 0:
755 if self.verbose:
756 print "parent %s" % parent
757 self.gitStream.write("from %s\n" % parent)
758
759 for file in files:
760 if file["type"] == "apple":
761 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
762 continue
763
764 relPath = self.stripRepoPath(file['path'], branchPrefixes)
765 if file["action"] == "delete":
766 self.gitStream.write("D %s\n" % relPath)
767 else:
768 mode = 644
769 if file["type"].startswith("x"):
770 mode = 755
771
772 data = file['data']
773
774 if self.isWindows and file["type"].endswith("text"):
775 data = data.replace("\r\n", "\n")
776
777 self.gitStream.write("M %d inline %s\n" % (mode, relPath))
778 self.gitStream.write("data %s\n" % len(data))
779 self.gitStream.write(data)
780 self.gitStream.write("\n")
781
782 self.gitStream.write("\n")
783
784 change = int(details["change"])
785
786 if self.labels.has_key(change):
787 label = self.labels[change]
788 labelDetails = label[0]
789 labelRevisions = label[1]
790 if self.verbose:
791 print "Change %s is labelled %s" % (change, labelDetails)
792
793 files = p4CmdList("files " + ' '.join (["%s...@%s" % (p, change)
794 for p in branchPrefixes]))
795
796 if len(files) == len(labelRevisions):
797
798 cleanedFiles = {}
799 for info in files:
800 if info["action"] == "delete":
801 continue
802 cleanedFiles[info["depotFile"]] = info["rev"]
803
804 if cleanedFiles == labelRevisions:
805 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
806 self.gitStream.write("from %s\n" % branch)
807
808 owner = labelDetails["Owner"]
809 tagger = ""
810 if author in self.users:
811 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
812 else:
813 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
814 self.gitStream.write("tagger %s\n" % tagger)
815 self.gitStream.write("data <<EOT\n")
816 self.gitStream.write(labelDetails["Description"])
817 self.gitStream.write("EOT\n\n")
818
819 else:
820 if not self.silent:
821 print ("Tag %s does not match with change %s: files do not match."
822 % (labelDetails["label"], change))
823
824 else:
825 if not self.silent:
826 print ("Tag %s does not match with change %s: file count is different."
827 % (labelDetails["label"], change))
828
829 def getUserCacheFilename(self):
830 return os.environ["HOME"] + "/.gitp4-usercache.txt"
831
832 def getUserMapFromPerforceServer(self):
833 if self.userMapFromPerforceServer:
834 return
835 self.users = {}
836
837 for output in p4CmdList("users"):
838 if not output.has_key("User"):
839 continue
840 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
841
842
843 s = ''
844 for (key, val) in self.users.items():
845 s += "%s\t%s\n" % (key, val)
846
847 open(self.getUserCacheFilename(), "wb").write(s)
848 self.userMapFromPerforceServer = True
849
850 def loadUserMapFromCache(self):
851 self.users = {}
852 self.userMapFromPerforceServer = False
853 try:
854 cache = open(self.getUserCacheFilename(), "rb")
855 lines = cache.readlines()
856 cache.close()
857 for line in lines:
858 entry = line.strip().split("\t")
859 self.users[entry[0]] = entry[1]
860 except IOError:
861 self.getUserMapFromPerforceServer()
862
863 def getLabels(self):
864 self.labels = {}
865
866 l = p4CmdList("labels %s..." % ' '.join (self.depotPaths))
867 if len(l) > 0 and not self.silent:
868 print "Finding files belonging to labels in %s" % `self.depotPath`
869
870 for output in l:
871 label = output["label"]
872 revisions = {}
873 newestChange = 0
874 if self.verbose:
875 print "Querying files for label %s" % label
876 for file in p4CmdList("files "
877 + ' '.join (["%s...@%s" % (p, label)
878 for p in self.depotPaths])):
879 revisions[file["depotFile"]] = file["rev"]
880 change = int(file["change"])
881 if change > newestChange:
882 newestChange = change
883
884 self.labels[newestChange] = [output, revisions]
885
886 if self.verbose:
887 print "Label changes: %s" % self.labels.keys()
888
889 def guessProjectName(self):
890 for p in self.depotPaths:
891 return p [p.strip().rfind("/") + 1:]
892
893 def getBranchMapping(self):
894
895 ## FIXME - what's a P4 projectName ?
896 self.projectName = self.guessProjectName()
897
898 for info in p4CmdList("branches"):
899 details = p4Cmd("branch -o %s" % info["branch"])
900 viewIdx = 0
901 while details.has_key("View%s" % viewIdx):
902 paths = details["View%s" % viewIdx].split(" ")
903 viewIdx = viewIdx + 1
904 # require standard //depot/foo/... //depot/bar/... mapping
905 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
906 continue
907 source = paths[0]
908 destination = paths[1]
909 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
910 source = source[len(self.depotPath):-4]
911 destination = destination[len(self.depotPath):-4]
912 if destination not in self.knownBranches:
913 self.knownBranches[destination] = source
914 if source not in self.knownBranches:
915 self.knownBranches[source] = source
916
917 def listExistingP4GitBranches(self):
918 self.p4BranchesInGit = []
919
920 cmdline = "git rev-parse --symbolic "
921 if self.importIntoRemotes:
922 cmdline += " --remotes"
923 else:
924 cmdline += " --branches"
925
926 for line in read_pipe_lines(cmdline):
927 line = line.strip()
928
929 ## only import to p4/
930 if not line.startswith('p4/'):
931 continue
932 branch = line
933 if self.importIntoRemotes:
934 # strip off p4
935 branch = re.sub ("^p4/", "", line)
936
937 self.p4BranchesInGit.append(branch)
938 self.initialParents[self.refPrefix + branch] = parseRevision(line)
939
940 def createOrUpdateBranchesFromOrigin(self):
941 if not self.silent:
942 print ("Creating/updating branch(es) in %s based on origin branch(es)"
943 % self.refPrefix)
944
945 for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
946 line = line.strip()
947 if (not line.startswith("origin/")) or line.endswith("HEAD\n"):
948 continue
949
950 headName = line[len("origin/"):]
951 remoteHead = self.refPrefix + headName
952 originHead = "origin/" + headName
953
954 original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
955 if (not original.has_key('depot-paths')
956 or not original.has_key('change')):
957 continue
958
959 update = False
960 if not gitBranchExists(remoteHead):
961 if self.verbose:
962 print "creating %s" % remoteHead
963 update = True
964 else:
965 settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
966 if settings.has_key('change') > 0:
967 if settings['depot-paths'] == original['depot-paths']:
968 originP4Change = int(original['change'])
969 p4Change = int(settings['change'])
970 if originP4Change > p4Change:
971 print ("%s (%s) is newer than %s (%s). "
972 "Updating p4 branch from origin."
973 % (originHead, originP4Change,
974 remoteHead, p4Change))
975 update = True
976 else:
977 print ("Ignoring: %s was imported from %s while "
978 "%s was imported from %s"
979 % (originHead, ','.join(original['depot-paths']),
980 remoteHead, ','.join(settings['depot-paths'])))
981
982 if update:
983 system("git update-ref %s %s" % (remoteHead, originHead))
984
985 def updateOptionDict(self, d):
986 option_keys = {}
987 if self.keepRepoPath:
988 option_keys['keepRepoPath'] = 1
989
990 d["options"] = ' '.join(sorted(option_keys.keys()))
991
992 def readOptions(self, d):
993 self.keepRepoPath = (d.has_key('options')
994 and ('keepRepoPath' in d['options']))
995
996 def run(self, args):
997 self.depotPaths = []
998 self.changeRange = ""
999 self.initialParent = ""
1000 self.previousDepotPaths = []
1001
1002 # map from branch depot path to parent branch
1003 self.knownBranches = {}
1004 self.initialParents = {}
1005 self.hasOrigin = gitBranchExists("origin")
1006
1007 if self.importIntoRemotes:
1008 self.refPrefix = "refs/remotes/p4/"
1009 else:
1010 self.refPrefix = "refs/heads/"
1011
1012 if self.syncWithOrigin and self.hasOrigin:
1013 if not self.silent:
1014 print "Syncing with origin first by calling git fetch origin"
1015 system("git fetch origin")
1016
1017 if len(self.branch) == 0:
1018 self.branch = self.refPrefix + "p4/master"
1019 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
1020 system("git update-ref %s refs/heads/p4" % self.branch)
1021 system("git branch -D p4");
1022 # create it /after/ importing, when master exists
1023 if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
1024 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
1025
1026 # TODO: should always look at previous commits,
1027 # merge with previous imports, if possible.
1028 if args == []:
1029 if self.hasOrigin:
1030 self.createOrUpdateBranchesFromOrigin()
1031 self.listExistingP4GitBranches()
1032
1033 if len(self.p4BranchesInGit) > 1:
1034 if not self.silent:
1035 print "Importing from/into multiple branches"
1036 self.detectBranches = True
1037
1038 if self.verbose:
1039 print "branches: %s" % self.p4BranchesInGit
1040
1041 p4Change = 0
1042 for branch in self.p4BranchesInGit:
1043 logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
1044
1045 settings = extractSettingsGitLog(logMsg)
1046
1047 self.readOptions(settings)
1048 if (settings.has_key('depot-paths')
1049 and settings.has_key ('change')):
1050 change = int(settings['change']) + 1
1051 p4Change = max(p4Change, change)
1052
1053 depotPaths = sorted(settings['depot-paths'])
1054 if self.previousDepotPaths == []:
1055 self.previousDepotPaths = depotPaths
1056 else:
1057 paths = []
1058 for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
1059 for i in range(0, max(len(cur), len(prev))):
1060 if cur[i] <> prev[i]:
1061 break
1062
1063 paths.append (cur[:i])
1064
1065 self.previousDepotPaths = paths
1066
1067 if p4Change > 0:
1068 self.depotPaths = sorted(self.previousDepotPaths)
1069 self.changeRange = "@%s,#head" % p4Change
1070 self.initialParent = parseRevision(self.branch)
1071 if not self.silent and not self.detectBranches:
1072 print "Performing incremental import into %s git branch" % self.branch
1073
1074 if not self.branch.startswith("refs/"):
1075 self.branch = "refs/heads/" + self.branch
1076
1077 if len(args) == 0 and self.depotPaths:
1078 if not self.silent:
1079 print "Depot paths: %s" % ' '.join(self.depotPaths)
1080 else:
1081 if self.depotPaths and self.depotPaths != args:
1082 print ("previous import used depot path %s and now %s was specified. "
1083 "This doesn't work!" % (' '.join (self.depotPaths),
1084 ' '.join (args)))
1085 sys.exit(1)
1086
1087 self.depotPaths = sorted(args)
1088
1089 self.revision = ""
1090 self.users = {}
1091
1092 newPaths = []
1093 for p in self.depotPaths:
1094 if p.find("@") != -1:
1095 atIdx = p.index("@")
1096 self.changeRange = p[atIdx:]
1097 if self.changeRange == "@all":
1098 self.changeRange = ""
1099 elif ',' not in self.changeRange:
1100 self.revision = self.changeRange
1101 self.changeRange = ""
1102 p = p[0:atIdx]
1103 elif p.find("#") != -1:
1104 hashIdx = p.index("#")
1105 self.revision = p[hashIdx:]
1106 p = p[0:hashIdx]
1107 elif self.previousDepotPaths == []:
1108 self.revision = "#head"
1109
1110 p = re.sub ("\.\.\.$", "", p)
1111 if not p.endswith("/"):
1112 p += "/"
1113
1114 newPaths.append(p)
1115
1116 self.depotPaths = newPaths
1117
1118
1119 self.loadUserMapFromCache()
1120 self.labels = {}
1121 if self.detectLabels:
1122 self.getLabels();
1123
1124 if self.detectBranches:
1125 self.getBranchMapping();
1126 if self.verbose:
1127 print "p4-git branches: %s" % self.p4BranchesInGit
1128 print "initial parents: %s" % self.initialParents
1129 for b in self.p4BranchesInGit:
1130 if b != "master":
1131
1132 ## FIXME
1133 b = b[len(self.projectName):]
1134 self.createdBranches.add(b)
1135
1136 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
1137
1138 importProcess = subprocess.Popen(["git", "fast-import"],
1139 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1140 stderr=subprocess.PIPE);
1141 self.gitOutput = importProcess.stdout
1142 self.gitStream = importProcess.stdin
1143 self.gitError = importProcess.stderr
1144
1145 if self.revision:
1146 print "Doing initial import of %s from revision %s" % (' '.join(self.depotPaths), self.revision)
1147
1148 details = { "user" : "git perforce import user", "time" : int(time.time()) }
1149 details["desc"] = ("Initial import of %s from the state at revision %s"
1150 % (' '.join(self.depotPaths), self.revision))
1151 details["change"] = self.revision
1152 newestRevision = 0
1153
1154 fileCnt = 0
1155 for info in p4CmdList("files "
1156 + ' '.join(["%s...%s"
1157 % (p, self.revision)
1158 for p in self.depotPaths])):
1159
1160 if info['code'] == 'error':
1161 sys.stderr.write("p4 returned an error: %s\n"
1162 % info['data'])
1163 sys.exit(1)
1164
1165
1166 change = int(info["change"])
1167 if change > newestRevision:
1168 newestRevision = change
1169
1170 if info["action"] == "delete":
1171 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1172 #fileCnt = fileCnt + 1
1173 continue
1174
1175 for prop in ["depotFile", "rev", "action", "type" ]:
1176 details["%s%s" % (prop, fileCnt)] = info[prop]
1177
1178 fileCnt = fileCnt + 1
1179
1180 details["change"] = newestRevision
1181 self.updateOptionDict(details)
1182 try:
1183 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths)
1184 except IOError:
1185 print "IO error with git fast-import. Is your git version recent enough?"
1186 print self.gitError.read()
1187
1188 else:
1189 changes = []
1190
1191 if len(self.changesFile) > 0:
1192 output = open(self.changesFile).readlines()
1193 changeSet = Set()
1194 for line in output:
1195 changeSet.add(int(line))
1196
1197 for change in changeSet:
1198 changes.append(change)
1199
1200 changes.sort()
1201 else:
1202 if self.verbose:
1203 print "Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
1204 self.changeRange)
1205 assert self.depotPaths
1206 output = read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p, self.changeRange)
1207 for p in self.depotPaths]))
1208
1209 for line in output:
1210 changeNum = line.split(" ")[1]
1211 changes.append(changeNum)
1212
1213 changes.reverse()
1214
1215 if len(self.maxChanges) > 0:
1216 changes = changes[0:min(int(self.maxChanges), len(changes))]
1217
1218 if len(changes) == 0:
1219 if not self.silent:
1220 print "No changes to import!"
1221 return True
1222
1223 self.updatedBranches = set()
1224
1225 cnt = 1
1226 for change in changes:
1227 description = p4Cmd("describe %s" % change)
1228 self.updateOptionDict(description)
1229
1230 if not self.silent:
1231 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1232 sys.stdout.flush()
1233 cnt = cnt + 1
1234
1235 try:
1236 if self.detectBranches:
1237 branches = self.splitFilesIntoBranches(description)
1238 for branch in branches.keys():
1239 ## HACK --hwn
1240 branchPrefix = self.depotPaths[0] + branch + "/"
1241
1242 parent = ""
1243
1244 filesForCommit = branches[branch]
1245
1246 if self.verbose:
1247 print "branch is %s" % branch
1248
1249 self.updatedBranches.add(branch)
1250
1251 if branch not in self.createdBranches:
1252 self.createdBranches.add(branch)
1253 parent = self.knownBranches[branch]
1254 if parent == branch:
1255 parent = ""
1256 elif self.verbose:
1257 print "parent determined through known branches: %s" % parent
1258
1259 # main branch? use master
1260 if branch == "main":
1261 branch = "master"
1262 else:
1263
1264 ## FIXME
1265 branch = self.projectName + branch
1266
1267 if parent == "main":
1268 parent = "master"
1269 elif len(parent) > 0:
1270 ## FIXME
1271 parent = self.projectName + parent
1272
1273 branch = self.refPrefix + branch
1274 if len(parent) > 0:
1275 parent = self.refPrefix + parent
1276
1277 if self.verbose:
1278 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1279
1280 if len(parent) == 0 and branch in self.initialParents:
1281 parent = self.initialParents[branch]
1282 del self.initialParents[branch]
1283
1284 self.commit(description, filesForCommit, branch, branchPrefix, parent)
1285 else:
1286 files = self.extractFilesFromCommit(description)
1287 self.commit(description, files, self.branch, self.depotPaths,
1288 self.initialParent)
1289 self.initialParent = ""
1290 except IOError:
1291 print self.gitError.read()
1292 sys.exit(1)
1293
1294 if not self.silent:
1295 print ""
1296 if len(self.updatedBranches) > 0:
1297 sys.stdout.write("Updated branches: ")
1298 for b in self.updatedBranches:
1299 sys.stdout.write("%s " % b)
1300 sys.stdout.write("\n")
1301
1302
1303 self.gitStream.close()
1304 if importProcess.wait() != 0:
1305 die("fast-import failed: %s" % self.gitError.read())
1306 self.gitOutput.close()
1307 self.gitError.close()
1308
1309 return True
1310
1311class P4Rebase(Command):
1312 def __init__(self):
1313 Command.__init__(self)
1314 self.options = [ ]
1315 self.description = ("Fetches the latest revision from perforce and "
1316 + "rebases the current work (branch) against it")
1317
1318 def run(self, args):
1319 sync = P4Sync()
1320 sync.run([])
1321 print "Rebasing the current branch"
1322 oldHead = read_pipe("git rev-parse HEAD").strip()
1323 system("git rebase p4")
1324 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1325 return True
1326
1327class P4Clone(P4Sync):
1328 def __init__(self):
1329 P4Sync.__init__(self)
1330 self.description = "Creates a new git repository and imports from Perforce into it"
1331 self.usage = "usage: %prog [options] //depot/path[@revRange]"
1332 self.options.append(
1333 optparse.make_option("--destination", dest="cloneDestination",
1334 action='store', default=None,
1335 help="where to leave result of the clone"))
1336 self.cloneDestination = None
1337 self.needsGit = False
1338
1339 def defaultDestination(self, args):
1340 ## TODO: use common prefix of args?
1341 depotPath = args[0]
1342 depotDir = re.sub("(@[^@]*)$", "", depotPath)
1343 depotDir = re.sub("(#[^#]*)$", "", depotDir)
1344 depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1345 depotDir = re.sub(r"/$", "", depotDir)
1346 return os.path.split(depotDir)[1]
1347
1348 def run(self, args):
1349 if len(args) < 1:
1350 return False
1351
1352 if self.keepRepoPath and not self.cloneDestination:
1353 sys.stderr.write("Must specify destination for --keep-path\n")
1354 sys.exit(1)
1355
1356 depotPaths = args
1357 for p in depotPaths:
1358 if not p.startswith("//"):
1359 return False
1360
1361 if not self.cloneDestination:
1362 self.cloneDestination = self.defaultDestination()
1363
1364 print "Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination)
1365 os.makedirs(self.cloneDestination)
1366 os.chdir(self.cloneDestination)
1367 system("git init")
1368 self.gitdir = os.getcwd() + "/.git"
1369 if not P4Sync.run(self, depotPaths):
1370 return False
1371 if self.branch != "master":
1372 if gitBranchExists("refs/remotes/p4/master"):
1373 system("git branch master refs/remotes/p4/master")
1374 system("git checkout -f")
1375 else:
1376 print "Could not detect main branch. No checkout/master branch created."
1377
1378 return True
1379
1380class HelpFormatter(optparse.IndentedHelpFormatter):
1381 def __init__(self):
1382 optparse.IndentedHelpFormatter.__init__(self)
1383
1384 def format_description(self, description):
1385 if description:
1386 return description + "\n"
1387 else:
1388 return ""
1389
1390def printUsage(commands):
1391 print "usage: %s <command> [options]" % sys.argv[0]
1392 print ""
1393 print "valid commands: %s" % ", ".join(commands)
1394 print ""
1395 print "Try %s <command> --help for command specific help." % sys.argv[0]
1396 print ""
1397
1398commands = {
1399 "debug" : P4Debug,
1400 "submit" : P4Submit,
1401 "sync" : P4Sync,
1402 "rebase" : P4Rebase,
1403 "clone" : P4Clone,
1404 "rollback" : P4RollBack
1405}
1406
1407
1408def main():
1409 if len(sys.argv[1:]) == 0:
1410 printUsage(commands.keys())
1411 sys.exit(2)
1412
1413 cmd = ""
1414 cmdName = sys.argv[1]
1415 try:
1416 klass = commands[cmdName]
1417 cmd = klass()
1418 except KeyError:
1419 print "unknown command %s" % cmdName
1420 print ""
1421 printUsage(commands.keys())
1422 sys.exit(2)
1423
1424 options = cmd.options
1425 cmd.gitdir = os.environ.get("GIT_DIR", None)
1426
1427 args = sys.argv[2:]
1428
1429 if len(options) > 0:
1430 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1431
1432 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1433 options,
1434 description = cmd.description,
1435 formatter = HelpFormatter())
1436
1437 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1438 global verbose
1439 verbose = cmd.verbose
1440 if cmd.needsGit:
1441 if cmd.gitdir == None:
1442 cmd.gitdir = os.path.abspath(".git")
1443 if not isValidGitDir(cmd.gitdir):
1444 cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
1445 if os.path.exists(cmd.gitdir):
1446 cdup = read_pipe("git rev-parse --show-cdup").strip()
1447 if len(cdup) > 0:
1448 os.chdir(cdup);
1449
1450 if not isValidGitDir(cmd.gitdir):
1451 if isValidGitDir(cmd.gitdir + "/.git"):
1452 cmd.gitdir += "/.git"
1453 else:
1454 die("fatal: cannot locate git repository at %s" % cmd.gitdir)
1455
1456 os.environ["GIT_DIR"] = cmd.gitdir
1457
1458 if not cmd.run(args):
1459 parser.print_help()
1460
1461
1462if __name__ == '__main__':
1463 main()