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
706 if not stat.has_key('depotFile'):
707 sys.stderr.write("p4 print fails with: %s\n" % repr(stat))
708 continue
709
710 contents[stat['depotFile']] = text
711
712 for f in files:
713 assert not f.has_key('data')
714 f['data'] = contents[f['path']]
715
716 def commit(self, details, files, branch, branchPrefixes, parent = ""):
717 epoch = details["time"]
718 author = details["user"]
719
720 if self.verbose:
721 print "commit into %s" % branch
722
723 # start with reading files; if that fails, we should not
724 # create a commit.
725 new_files = []
726 for f in files:
727 if [p for p in branchPrefixes if f['path'].startswith(p)]:
728 new_files.append (f)
729 else:
730 sys.stderr.write("Ignoring file outside of prefix: %s\n" % path)
731 files = new_files
732 self.readP4Files(files)
733
734
735
736
737 self.gitStream.write("commit %s\n" % branch)
738# gitStream.write("mark :%s\n" % details["change"])
739 self.committedChanges.add(int(details["change"]))
740 committer = ""
741 if author not in self.users:
742 self.getUserMapFromPerforceServer()
743 if author in self.users:
744 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
745 else:
746 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
747
748 self.gitStream.write("committer %s\n" % committer)
749
750 self.gitStream.write("data <<EOT\n")
751 self.gitStream.write(details["desc"])
752 self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s: "
753 "options = %s]\n"
754 % (','.join (branchPrefixes), details["change"],
755 details['options']
756 ))
757 self.gitStream.write("EOT\n\n")
758
759 if len(parent) > 0:
760 if self.verbose:
761 print "parent %s" % parent
762 self.gitStream.write("from %s\n" % parent)
763
764 for file in files:
765 if file["type"] == "apple":
766 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
767 continue
768
769 relPath = self.stripRepoPath(file['path'], branchPrefixes)
770 if file["action"] == "delete":
771 self.gitStream.write("D %s\n" % relPath)
772 else:
773 mode = 644
774 if file["type"].startswith("x"):
775 mode = 755
776
777 data = file['data']
778
779 if self.isWindows and file["type"].endswith("text"):
780 data = data.replace("\r\n", "\n")
781
782 self.gitStream.write("M %d inline %s\n" % (mode, relPath))
783 self.gitStream.write("data %s\n" % len(data))
784 self.gitStream.write(data)
785 self.gitStream.write("\n")
786
787 self.gitStream.write("\n")
788
789 change = int(details["change"])
790
791 if self.labels.has_key(change):
792 label = self.labels[change]
793 labelDetails = label[0]
794 labelRevisions = label[1]
795 if self.verbose:
796 print "Change %s is labelled %s" % (change, labelDetails)
797
798 files = p4CmdList("files " + ' '.join (["%s...@%s" % (p, change)
799 for p in branchPrefixes]))
800
801 if len(files) == len(labelRevisions):
802
803 cleanedFiles = {}
804 for info in files:
805 if info["action"] == "delete":
806 continue
807 cleanedFiles[info["depotFile"]] = info["rev"]
808
809 if cleanedFiles == labelRevisions:
810 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
811 self.gitStream.write("from %s\n" % branch)
812
813 owner = labelDetails["Owner"]
814 tagger = ""
815 if author in self.users:
816 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
817 else:
818 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
819 self.gitStream.write("tagger %s\n" % tagger)
820 self.gitStream.write("data <<EOT\n")
821 self.gitStream.write(labelDetails["Description"])
822 self.gitStream.write("EOT\n\n")
823
824 else:
825 if not self.silent:
826 print ("Tag %s does not match with change %s: files do not match."
827 % (labelDetails["label"], change))
828
829 else:
830 if not self.silent:
831 print ("Tag %s does not match with change %s: file count is different."
832 % (labelDetails["label"], change))
833
834 def getUserCacheFilename(self):
835 return os.environ["HOME"] + "/.gitp4-usercache.txt"
836
837 def getUserMapFromPerforceServer(self):
838 if self.userMapFromPerforceServer:
839 return
840 self.users = {}
841
842 for output in p4CmdList("users"):
843 if not output.has_key("User"):
844 continue
845 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
846
847
848 s = ''
849 for (key, val) in self.users.items():
850 s += "%s\t%s\n" % (key, val)
851
852 open(self.getUserCacheFilename(), "wb").write(s)
853 self.userMapFromPerforceServer = True
854
855 def loadUserMapFromCache(self):
856 self.users = {}
857 self.userMapFromPerforceServer = False
858 try:
859 cache = open(self.getUserCacheFilename(), "rb")
860 lines = cache.readlines()
861 cache.close()
862 for line in lines:
863 entry = line.strip().split("\t")
864 self.users[entry[0]] = entry[1]
865 except IOError:
866 self.getUserMapFromPerforceServer()
867
868 def getLabels(self):
869 self.labels = {}
870
871 l = p4CmdList("labels %s..." % ' '.join (self.depotPaths))
872 if len(l) > 0 and not self.silent:
873 print "Finding files belonging to labels in %s" % `self.depotPath`
874
875 for output in l:
876 label = output["label"]
877 revisions = {}
878 newestChange = 0
879 if self.verbose:
880 print "Querying files for label %s" % label
881 for file in p4CmdList("files "
882 + ' '.join (["%s...@%s" % (p, label)
883 for p in self.depotPaths])):
884 revisions[file["depotFile"]] = file["rev"]
885 change = int(file["change"])
886 if change > newestChange:
887 newestChange = change
888
889 self.labels[newestChange] = [output, revisions]
890
891 if self.verbose:
892 print "Label changes: %s" % self.labels.keys()
893
894 def guessProjectName(self):
895 for p in self.depotPaths:
896 return p [p.strip().rfind("/") + 1:]
897
898 def getBranchMapping(self):
899
900 ## FIXME - what's a P4 projectName ?
901 self.projectName = self.guessProjectName()
902
903 for info in p4CmdList("branches"):
904 details = p4Cmd("branch -o %s" % info["branch"])
905 viewIdx = 0
906 while details.has_key("View%s" % viewIdx):
907 paths = details["View%s" % viewIdx].split(" ")
908 viewIdx = viewIdx + 1
909 # require standard //depot/foo/... //depot/bar/... mapping
910 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
911 continue
912 source = paths[0]
913 destination = paths[1]
914 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
915 source = source[len(self.depotPath):-4]
916 destination = destination[len(self.depotPath):-4]
917 if destination not in self.knownBranches:
918 self.knownBranches[destination] = source
919 if source not in self.knownBranches:
920 self.knownBranches[source] = source
921
922 def listExistingP4GitBranches(self):
923 self.p4BranchesInGit = []
924
925 cmdline = "git rev-parse --symbolic "
926 if self.importIntoRemotes:
927 cmdline += " --remotes"
928 else:
929 cmdline += " --branches"
930
931 for line in read_pipe_lines(cmdline):
932 line = line.strip()
933
934 ## only import to p4/
935 if not line.startswith('p4/'):
936 continue
937 branch = line
938 if self.importIntoRemotes:
939 # strip off p4
940 branch = re.sub ("^p4/", "", line)
941
942 self.p4BranchesInGit.append(branch)
943 self.initialParents[self.refPrefix + branch] = parseRevision(line)
944
945 def createOrUpdateBranchesFromOrigin(self):
946 if not self.silent:
947 print ("Creating/updating branch(es) in %s based on origin branch(es)"
948 % self.refPrefix)
949
950 for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
951 line = line.strip()
952 if (not line.startswith("origin/")) or line.endswith("HEAD\n"):
953 continue
954
955 headName = line[len("origin/"):]
956 remoteHead = self.refPrefix + headName
957 originHead = "origin/" + headName
958
959 original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
960 if (not original.has_key('depot-paths')
961 or not original.has_key('change')):
962 continue
963
964 update = False
965 if not gitBranchExists(remoteHead):
966 if self.verbose:
967 print "creating %s" % remoteHead
968 update = True
969 else:
970 settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
971 if settings.has_key('change') > 0:
972 if settings['depot-paths'] == original['depot-paths']:
973 originP4Change = int(original['change'])
974 p4Change = int(settings['change'])
975 if originP4Change > p4Change:
976 print ("%s (%s) is newer than %s (%s). "
977 "Updating p4 branch from origin."
978 % (originHead, originP4Change,
979 remoteHead, p4Change))
980 update = True
981 else:
982 print ("Ignoring: %s was imported from %s while "
983 "%s was imported from %s"
984 % (originHead, ','.join(original['depot-paths']),
985 remoteHead, ','.join(settings['depot-paths'])))
986
987 if update:
988 system("git update-ref %s %s" % (remoteHead, originHead))
989
990 def updateOptionDict(self, d):
991 option_keys = {}
992 if self.keepRepoPath:
993 option_keys['keepRepoPath'] = 1
994
995 d["options"] = ' '.join(sorted(option_keys.keys()))
996
997 def readOptions(self, d):
998 self.keepRepoPath = (d.has_key('options')
999 and ('keepRepoPath' in d['options']))
1000
1001 def run(self, args):
1002 self.depotPaths = []
1003 self.changeRange = ""
1004 self.initialParent = ""
1005 self.previousDepotPaths = []
1006
1007 # map from branch depot path to parent branch
1008 self.knownBranches = {}
1009 self.initialParents = {}
1010 self.hasOrigin = gitBranchExists("origin")
1011
1012 if self.importIntoRemotes:
1013 self.refPrefix = "refs/remotes/p4/"
1014 else:
1015 self.refPrefix = "refs/heads/"
1016
1017 if self.syncWithOrigin and self.hasOrigin:
1018 if not self.silent:
1019 print "Syncing with origin first by calling git fetch origin"
1020 system("git fetch origin")
1021
1022 if len(self.branch) == 0:
1023 self.branch = self.refPrefix + "p4/master"
1024 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
1025 system("git update-ref %s refs/heads/p4" % self.branch)
1026 system("git branch -D p4");
1027 # create it /after/ importing, when master exists
1028 if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
1029 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
1030
1031 # TODO: should always look at previous commits,
1032 # merge with previous imports, if possible.
1033 if args == []:
1034 if self.hasOrigin:
1035 self.createOrUpdateBranchesFromOrigin()
1036 self.listExistingP4GitBranches()
1037
1038 if len(self.p4BranchesInGit) > 1:
1039 if not self.silent:
1040 print "Importing from/into multiple branches"
1041 self.detectBranches = True
1042
1043 if self.verbose:
1044 print "branches: %s" % self.p4BranchesInGit
1045
1046 p4Change = 0
1047 for branch in self.p4BranchesInGit:
1048 logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
1049
1050 settings = extractSettingsGitLog(logMsg)
1051
1052 self.readOptions(settings)
1053 if (settings.has_key('depot-paths')
1054 and settings.has_key ('change')):
1055 change = int(settings['change']) + 1
1056 p4Change = max(p4Change, change)
1057
1058 depotPaths = sorted(settings['depot-paths'])
1059 if self.previousDepotPaths == []:
1060 self.previousDepotPaths = depotPaths
1061 else:
1062 paths = []
1063 for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
1064 for i in range(0, max(len(cur), len(prev))):
1065 if cur[i] <> prev[i]:
1066 break
1067
1068 paths.append (cur[:i])
1069
1070 self.previousDepotPaths = paths
1071
1072 if p4Change > 0:
1073 self.depotPaths = sorted(self.previousDepotPaths)
1074 self.changeRange = "@%s,#head" % p4Change
1075 self.initialParent = parseRevision(self.branch)
1076 if not self.silent and not self.detectBranches:
1077 print "Performing incremental import into %s git branch" % self.branch
1078
1079 if not self.branch.startswith("refs/"):
1080 self.branch = "refs/heads/" + self.branch
1081
1082 if len(args) == 0 and self.depotPaths:
1083 if not self.silent:
1084 print "Depot paths: %s" % ' '.join(self.depotPaths)
1085 else:
1086 if self.depotPaths and self.depotPaths != args:
1087 print ("previous import used depot path %s and now %s was specified. "
1088 "This doesn't work!" % (' '.join (self.depotPaths),
1089 ' '.join (args)))
1090 sys.exit(1)
1091
1092 self.depotPaths = sorted(args)
1093
1094 self.revision = ""
1095 self.users = {}
1096
1097 newPaths = []
1098 for p in self.depotPaths:
1099 if p.find("@") != -1:
1100 atIdx = p.index("@")
1101 self.changeRange = p[atIdx:]
1102 if self.changeRange == "@all":
1103 self.changeRange = ""
1104 elif ',' not in self.changeRange:
1105 self.revision = self.changeRange
1106 self.changeRange = ""
1107 p = p[0:atIdx]
1108 elif p.find("#") != -1:
1109 hashIdx = p.index("#")
1110 self.revision = p[hashIdx:]
1111 p = p[0:hashIdx]
1112 elif self.previousDepotPaths == []:
1113 self.revision = "#head"
1114
1115 p = re.sub ("\.\.\.$", "", p)
1116 if not p.endswith("/"):
1117 p += "/"
1118
1119 newPaths.append(p)
1120
1121 self.depotPaths = newPaths
1122
1123
1124 self.loadUserMapFromCache()
1125 self.labels = {}
1126 if self.detectLabels:
1127 self.getLabels();
1128
1129 if self.detectBranches:
1130 self.getBranchMapping();
1131 if self.verbose:
1132 print "p4-git branches: %s" % self.p4BranchesInGit
1133 print "initial parents: %s" % self.initialParents
1134 for b in self.p4BranchesInGit:
1135 if b != "master":
1136
1137 ## FIXME
1138 b = b[len(self.projectName):]
1139 self.createdBranches.add(b)
1140
1141 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
1142
1143 importProcess = subprocess.Popen(["git", "fast-import"],
1144 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1145 stderr=subprocess.PIPE);
1146 self.gitOutput = importProcess.stdout
1147 self.gitStream = importProcess.stdin
1148 self.gitError = importProcess.stderr
1149
1150 if self.revision:
1151 print "Doing initial import of %s from revision %s" % (' '.join(self.depotPaths), self.revision)
1152
1153 details = { "user" : "git perforce import user", "time" : int(time.time()) }
1154 details["desc"] = ("Initial import of %s from the state at revision %s"
1155 % (' '.join(self.depotPaths), self.revision))
1156 details["change"] = self.revision
1157 newestRevision = 0
1158
1159 fileCnt = 0
1160 for info in p4CmdList("files "
1161 + ' '.join(["%s...%s"
1162 % (p, self.revision)
1163 for p in self.depotPaths])):
1164
1165 if info['code'] == 'error':
1166 sys.stderr.write("p4 returned an error: %s\n"
1167 % info['data'])
1168 sys.exit(1)
1169
1170
1171 change = int(info["change"])
1172 if change > newestRevision:
1173 newestRevision = change
1174
1175 if info["action"] == "delete":
1176 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1177 #fileCnt = fileCnt + 1
1178 continue
1179
1180 for prop in ["depotFile", "rev", "action", "type" ]:
1181 details["%s%s" % (prop, fileCnt)] = info[prop]
1182
1183 fileCnt = fileCnt + 1
1184
1185 details["change"] = newestRevision
1186 self.updateOptionDict(details)
1187 try:
1188 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths)
1189 except IOError:
1190 print "IO error with git fast-import. Is your git version recent enough?"
1191 print self.gitError.read()
1192
1193 else:
1194 changes = []
1195
1196 if len(self.changesFile) > 0:
1197 output = open(self.changesFile).readlines()
1198 changeSet = Set()
1199 for line in output:
1200 changeSet.add(int(line))
1201
1202 for change in changeSet:
1203 changes.append(change)
1204
1205 changes.sort()
1206 else:
1207 if self.verbose:
1208 print "Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
1209 self.changeRange)
1210 assert self.depotPaths
1211 output = read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p, self.changeRange)
1212 for p in self.depotPaths]))
1213
1214 for line in output:
1215 changeNum = line.split(" ")[1]
1216 changes.append(changeNum)
1217
1218 changes.reverse()
1219
1220 if len(self.maxChanges) > 0:
1221 changes = changes[0:min(int(self.maxChanges), len(changes))]
1222
1223 if len(changes) == 0:
1224 if not self.silent:
1225 print "No changes to import!"
1226 return True
1227
1228 self.updatedBranches = set()
1229
1230 cnt = 1
1231 for change in changes:
1232 description = p4Cmd("describe %s" % change)
1233 self.updateOptionDict(description)
1234
1235 if not self.silent:
1236 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1237 sys.stdout.flush()
1238 cnt = cnt + 1
1239
1240 try:
1241 if self.detectBranches:
1242 branches = self.splitFilesIntoBranches(description)
1243 for branch in branches.keys():
1244 ## HACK --hwn
1245 branchPrefix = self.depotPaths[0] + branch + "/"
1246
1247 parent = ""
1248
1249 filesForCommit = branches[branch]
1250
1251 if self.verbose:
1252 print "branch is %s" % branch
1253
1254 self.updatedBranches.add(branch)
1255
1256 if branch not in self.createdBranches:
1257 self.createdBranches.add(branch)
1258 parent = self.knownBranches[branch]
1259 if parent == branch:
1260 parent = ""
1261 elif self.verbose:
1262 print "parent determined through known branches: %s" % parent
1263
1264 # main branch? use master
1265 if branch == "main":
1266 branch = "master"
1267 else:
1268
1269 ## FIXME
1270 branch = self.projectName + branch
1271
1272 if parent == "main":
1273 parent = "master"
1274 elif len(parent) > 0:
1275 ## FIXME
1276 parent = self.projectName + parent
1277
1278 branch = self.refPrefix + branch
1279 if len(parent) > 0:
1280 parent = self.refPrefix + parent
1281
1282 if self.verbose:
1283 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1284
1285 if len(parent) == 0 and branch in self.initialParents:
1286 parent = self.initialParents[branch]
1287 del self.initialParents[branch]
1288
1289 self.commit(description, filesForCommit, branch, branchPrefix, parent)
1290 else:
1291 files = self.extractFilesFromCommit(description)
1292 self.commit(description, files, self.branch, self.depotPaths,
1293 self.initialParent)
1294 self.initialParent = ""
1295 except IOError:
1296 print self.gitError.read()
1297 sys.exit(1)
1298
1299 if not self.silent:
1300 print ""
1301 if len(self.updatedBranches) > 0:
1302 sys.stdout.write("Updated branches: ")
1303 for b in self.updatedBranches:
1304 sys.stdout.write("%s " % b)
1305 sys.stdout.write("\n")
1306
1307
1308 self.gitStream.close()
1309 if importProcess.wait() != 0:
1310 die("fast-import failed: %s" % self.gitError.read())
1311 self.gitOutput.close()
1312 self.gitError.close()
1313
1314 return True
1315
1316class P4Rebase(Command):
1317 def __init__(self):
1318 Command.__init__(self)
1319 self.options = [ ]
1320 self.description = ("Fetches the latest revision from perforce and "
1321 + "rebases the current work (branch) against it")
1322
1323 def run(self, args):
1324 sync = P4Sync()
1325 sync.run([])
1326 print "Rebasing the current branch"
1327 oldHead = read_pipe("git rev-parse HEAD").strip()
1328 system("git rebase p4")
1329 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1330 return True
1331
1332class P4Clone(P4Sync):
1333 def __init__(self):
1334 P4Sync.__init__(self)
1335 self.description = "Creates a new git repository and imports from Perforce into it"
1336 self.usage = "usage: %prog [options] //depot/path[@revRange]"
1337 self.options.append(
1338 optparse.make_option("--destination", dest="cloneDestination",
1339 action='store', default=None,
1340 help="where to leave result of the clone"))
1341 self.cloneDestination = None
1342 self.needsGit = False
1343
1344 def defaultDestination(self, args):
1345 ## TODO: use common prefix of args?
1346 depotPath = args[0]
1347 depotDir = re.sub("(@[^@]*)$", "", depotPath)
1348 depotDir = re.sub("(#[^#]*)$", "", depotDir)
1349 depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1350 depotDir = re.sub(r"/$", "", depotDir)
1351 return os.path.split(depotDir)[1]
1352
1353 def run(self, args):
1354 if len(args) < 1:
1355 return False
1356
1357 if self.keepRepoPath and not self.cloneDestination:
1358 sys.stderr.write("Must specify destination for --keep-path\n")
1359 sys.exit(1)
1360
1361 depotPaths = args
1362 for p in depotPaths:
1363 if not p.startswith("//"):
1364 return False
1365
1366 if not self.cloneDestination:
1367 self.cloneDestination = self.defaultDestination()
1368
1369 print "Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination)
1370 os.makedirs(self.cloneDestination)
1371 os.chdir(self.cloneDestination)
1372 system("git init")
1373 self.gitdir = os.getcwd() + "/.git"
1374 if not P4Sync.run(self, depotPaths):
1375 return False
1376 if self.branch != "master":
1377 if gitBranchExists("refs/remotes/p4/master"):
1378 system("git branch master refs/remotes/p4/master")
1379 system("git checkout -f")
1380 else:
1381 print "Could not detect main branch. No checkout/master branch created."
1382
1383 return True
1384
1385class HelpFormatter(optparse.IndentedHelpFormatter):
1386 def __init__(self):
1387 optparse.IndentedHelpFormatter.__init__(self)
1388
1389 def format_description(self, description):
1390 if description:
1391 return description + "\n"
1392 else:
1393 return ""
1394
1395def printUsage(commands):
1396 print "usage: %s <command> [options]" % sys.argv[0]
1397 print ""
1398 print "valid commands: %s" % ", ".join(commands)
1399 print ""
1400 print "Try %s <command> --help for command specific help." % sys.argv[0]
1401 print ""
1402
1403commands = {
1404 "debug" : P4Debug,
1405 "submit" : P4Submit,
1406 "sync" : P4Sync,
1407 "rebase" : P4Rebase,
1408 "clone" : P4Clone,
1409 "rollback" : P4RollBack
1410}
1411
1412
1413def main():
1414 if len(sys.argv[1:]) == 0:
1415 printUsage(commands.keys())
1416 sys.exit(2)
1417
1418 cmd = ""
1419 cmdName = sys.argv[1]
1420 try:
1421 klass = commands[cmdName]
1422 cmd = klass()
1423 except KeyError:
1424 print "unknown command %s" % cmdName
1425 print ""
1426 printUsage(commands.keys())
1427 sys.exit(2)
1428
1429 options = cmd.options
1430 cmd.gitdir = os.environ.get("GIT_DIR", None)
1431
1432 args = sys.argv[2:]
1433
1434 if len(options) > 0:
1435 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1436
1437 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1438 options,
1439 description = cmd.description,
1440 formatter = HelpFormatter())
1441
1442 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1443 global verbose
1444 verbose = cmd.verbose
1445 if cmd.needsGit:
1446 if cmd.gitdir == None:
1447 cmd.gitdir = os.path.abspath(".git")
1448 if not isValidGitDir(cmd.gitdir):
1449 cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
1450 if os.path.exists(cmd.gitdir):
1451 cdup = read_pipe("git rev-parse --show-cdup").strip()
1452 if len(cdup) > 0:
1453 os.chdir(cdup);
1454
1455 if not isValidGitDir(cmd.gitdir):
1456 if isValidGitDir(cmd.gitdir + "/.git"):
1457 cmd.gitdir += "/.git"
1458 else:
1459 die("fatal: cannot locate git repository at %s" % cmd.gitdir)
1460
1461 os.environ["GIT_DIR"] = cmd.gitdir
1462
1463 if not cmd.run(args):
1464 parser.print_help()
1465
1466
1467if __name__ == '__main__':
1468 main()