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