3 # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
5 # Author: Simon Hausmann <hausmann@kde.org>
6 # Copyright: 2007 Simon Hausmann <hausmann@kde.org>
8 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
11 import optparse
, sys
, os
, marshal
, popen2
, subprocess
, shelve
12 import tempfile
, getopt
, sha
, os
.path
, time
, platform
15 gitdir
= os
.environ
.get("GIT_DIR", "")
18 return os
.popen(command
, "rb");
21 cmd
= "p4 -G %s" % cmd
22 pipe
= os
.popen(cmd
, "rb")
27 entry
= marshal
.load(pipe
)
42 def p4Where(depotPath
):
43 if not depotPath
.endswith("/"):
45 output
= p4Cmd("where %s..." % depotPath
)
48 clientPath
= output
.get("path")
49 elif "data" in output
:
50 data
= output
.get("data")
51 lastSpace
= data
.rfind(" ")
52 clientPath
= data
[lastSpace
+ 1:]
54 if clientPath
.endswith("..."):
55 clientPath
= clientPath
[:-3]
59 sys
.stderr
.write(msg
+ "\n")
62 def currentGitBranch():
63 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
65 def isValidGitDir(path
):
66 if os
.path
.exists(path
+ "/HEAD") and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects"):
70 def parseRevision(ref
):
71 return mypopen("git rev-parse %s" % ref
).read()[:-1]
74 if os
.system(cmd
) != 0:
75 die("command failed: %s" % cmd
)
77 def extractLogMessageFromGitCommit(commit
):
80 for log
in mypopen("git cat-file commit %s" % commit
).readlines():
89 def extractDepotPathAndChangeFromGitLog(log
):
91 for line
in log
.split("\n"):
93 if line
.startswith("[git-p4:") and line
.endswith("]"):
94 line
= line
[8:-1].strip()
95 for assignment
in line
.split(":"):
96 variable
= assignment
.strip()
98 equalPos
= assignment
.find("=")
100 variable
= assignment
[:equalPos
].strip()
101 value
= assignment
[equalPos
+ 1:].strip()
102 if value
.startswith("\"") and value
.endswith("\""):
104 values
[variable
] = value
106 return values
.get("depot-path"), values
.get("change")
108 def gitBranchExists(branch
):
109 proc
= subprocess
.Popen(["git", "rev-parse", branch
], stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
110 return proc
.wait() == 0;
114 self
.usage
= "usage: %prog [options]"
117 class P4Debug(Command
):
119 Command
.__init
__(self
)
122 self
.description
= "A tool to debug the output of p4 -G."
123 self
.needsGit
= False
126 for output
in p4CmdList(" ".join(args
)):
130 class P4Submit(Command
):
132 Command
.__init
__(self
)
134 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
135 optparse
.make_option("--origin", dest
="origin"),
136 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
137 optparse
.make_option("--log-substitutions", dest
="substFile"),
138 optparse
.make_option("--noninteractive", action
="store_false"),
139 optparse
.make_option("--dry-run", action
="store_true"),
140 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
142 self
.description
= "Submit changes from git to the perforce depot."
143 self
.usage
+= " [name of git branch to submit into perforce depot]"
144 self
.firstTime
= True
146 self
.interactive
= True
149 self
.firstTime
= True
151 self
.directSubmit
= False
153 self
.logSubstitutions
= {}
154 self
.logSubstitutions
["<enter description here>"] = "%log%"
155 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
158 if len(p4CmdList("opened ...")) > 0:
159 die("You have files opened with perforce! Close them before starting the sync.")
162 if len(self
.config
) > 0 and not self
.reset
:
163 die("Cannot start sync. Previous sync config found at %s\nIf you want to start submitting again from scratch maybe you want to call git-p4 submit --reset" % self
.configFile
)
166 if self
.directSubmit
:
169 for line
in mypopen("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)).readlines():
170 commits
.append(line
[:-1])
173 self
.config
["commits"] = commits
175 def prepareLogMessage(self
, template
, message
):
178 for line
in template
.split("\n"):
179 if line
.startswith("#"):
180 result
+= line
+ "\n"
184 for key
in self
.logSubstitutions
.keys():
185 if line
.find(key
) != -1:
186 value
= self
.logSubstitutions
[key
]
187 value
= value
.replace("%log%", message
)
188 if value
!= "@remove@":
189 result
+= line
.replace(key
, value
) + "\n"
194 result
+= line
+ "\n"
199 if self
.directSubmit
:
200 print "Applying local change in working directory/index"
201 diff
= self
.diffStatus
203 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
204 diff
= mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
206 filesToDelete
= set()
210 path
= line
[1:].strip()
212 system("p4 edit \"%s\"" % path
)
213 editedFiles
.add(path
)
214 elif modifier
== "A":
216 if path
in filesToDelete
:
217 filesToDelete
.remove(path
)
218 elif modifier
== "D":
219 filesToDelete
.add(path
)
220 if path
in filesToAdd
:
221 filesToAdd
.remove(path
)
223 die("unknown modifier %s for %s" % (modifier
, path
))
225 if self
.directSubmit
:
226 diffcmd
= "cat \"%s\"" % self
.diffFile
228 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
229 patchcmd
= diffcmd
+ " | git apply "
230 tryPatchCmd
= patchcmd
+ "--check -"
231 applyPatchCmd
= patchcmd
+ "--check --apply -"
233 if os
.system(tryPatchCmd
) != 0:
234 print "Unfortunately applying the change failed!"
235 print "What do you want to do?"
237 while response
!= "s" and response
!= "a" and response
!= "w":
238 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly and with .rej files / [w]rite the patch to a file (patch.txt) ")
240 print "Skipping! Good luck with the next patches..."
242 elif response
== "a":
243 os
.system(applyPatchCmd
)
244 if len(filesToAdd
) > 0:
245 print "You may also want to call p4 add on the following files:"
246 print " ".join(filesToAdd
)
247 if len(filesToDelete
):
248 print "The following files should be scheduled for deletion with p4 delete:"
249 print " ".join(filesToDelete
)
250 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
251 elif response
== "w":
252 system(diffcmd
+ " > patch.txt")
253 print "Patch saved to patch.txt in %s !" % self
.clientPath
254 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
256 system(applyPatchCmd
)
259 system("p4 add %s" % f
)
260 for f
in filesToDelete
:
261 system("p4 revert %s" % f
)
262 system("p4 delete %s" % f
)
265 if not self
.directSubmit
:
266 logMessage
= extractLogMessageFromGitCommit(id)
267 logMessage
= logMessage
.replace("\n", "\n\t")
268 logMessage
= logMessage
[:-1]
270 template
= mypopen("p4 change -o").read()
273 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
274 diff
= mypopen("p4 diff -du ...").read()
276 for newFile
in filesToAdd
:
277 diff
+= "==== new file ====\n"
278 diff
+= "--- /dev/null\n"
279 diff
+= "+++ %s\n" % newFile
280 f
= open(newFile
, "r")
281 for line
in f
.readlines():
285 separatorLine
= "######## everything below this line is just the diff #######"
286 if platform
.system() == "Windows":
287 separatorLine
+= "\r"
288 separatorLine
+= "\n"
291 firstIteration
= True
292 while response
== "e":
293 if not firstIteration
:
294 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
295 firstIteration
= False
297 [handle
, fileName
] = tempfile
.mkstemp()
298 tmpFile
= os
.fdopen(handle
, "w+")
299 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
302 if platform
.system() == "Windows":
303 defaultEditor
= "notepad"
304 editor
= os
.environ
.get("EDITOR", defaultEditor
);
305 system(editor
+ " " + fileName
)
306 tmpFile
= open(fileName
, "rb")
307 message
= tmpFile
.read()
310 submitTemplate
= message
[:message
.index(separatorLine
)]
312 if response
== "y" or response
== "yes":
315 raw_input("Press return to continue...")
317 pipe
= os
.popen("p4 submit -i", "wb")
318 pipe
.write(submitTemplate
)
320 elif response
== "s":
321 for f
in editedFiles
:
322 system("p4 revert \"%s\"" % f
);
324 system("p4 revert \"%s\"" % f
);
326 for f
in filesToDelete
:
327 system("p4 delete \"%s\"" % f
);
330 print "Not submitting!"
331 self
.interactive
= False
333 fileName
= "submit.txt"
334 file = open(fileName
, "w+")
335 file.write(self
.prepareLogMessage(template
, logMessage
))
337 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName
, fileName
)
341 # make gitdir absolute so we can cd out into the perforce checkout
342 gitdir
= os
.path
.abspath(gitdir
)
343 os
.environ
["GIT_DIR"] = gitdir
346 self
.master
= currentGitBranch()
347 if len(self
.master
) == 0 or not os
.path
.exists("%s/refs/heads/%s" % (gitdir
, self
.master
)):
348 die("Detecting current git branch failed!")
350 self
.master
= args
[0]
355 if gitBranchExists("p4"):
356 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
357 if len(depotPath
) == 0 and gitBranchExists("origin"):
358 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
360 if len(depotPath
) == 0:
361 print "Internal error: cannot locate perforce depot path from existing branches"
364 self
.clientPath
= p4Where(depotPath
)
366 if len(self
.clientPath
) == 0:
367 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
370 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
371 oldWorkingDirectory
= os
.getcwd()
373 if self
.directSubmit
:
374 self
.diffStatus
= mypopen("git diff -r --name-status HEAD").readlines()
375 patch
= mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
376 self
.diffFile
= gitdir
+ "/p4-git-diff"
377 f
= open(self
.diffFile
, "wb")
381 os
.chdir(self
.clientPath
)
382 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
383 if response
== "y" or response
== "yes":
384 system("p4 sync ...")
386 if len(self
.origin
) == 0:
387 if gitBranchExists("p4"):
390 self
.origin
= "origin"
393 self
.firstTime
= True
395 if len(self
.substFile
) > 0:
396 for line
in open(self
.substFile
, "r").readlines():
397 tokens
= line
[:-1].split("=")
398 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
401 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
402 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
407 commits
= self
.config
.get("commits", [])
409 while len(commits
) > 0:
410 self
.firstTime
= False
412 commits
= commits
[1:]
413 self
.config
["commits"] = commits
415 if not self
.interactive
:
420 if self
.directSubmit
:
421 os
.remove(self
.diffFile
)
423 if len(commits
) == 0:
425 print "No changes found to apply between %s and current HEAD" % self
.origin
427 print "All changes applied!"
429 os
.chdir(oldWorkingDirectory
)
431 if self
.directSubmit
:
432 response
= raw_input("Do you want to DISCARD your git WORKING DIRECTORY CHANGES and sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
433 if response
== "y" or response
== "yes":
434 system("git reset --hard")
436 if len(response
) == 0:
437 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
438 if response
== "y" or response
== "yes":
441 os
.remove(self
.configFile
)
445 class P4Sync(Command
):
447 Command
.__init
__(self
)
449 optparse
.make_option("--branch", dest
="branch"),
450 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
451 optparse
.make_option("--changesfile", dest
="changesFile"),
452 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
453 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
454 optparse
.make_option("--with-origin", dest
="syncWithOrigin", action
="store_true"),
455 optparse
.make_option("--verbose", dest
="verbose", action
="store_true")
457 self
.description
= """Imports from Perforce into a git repository.\n
459 //depot/my/project/ -- to import the current head
460 //depot/my/project/@all -- to import everything
461 //depot/my/project/@1,6 -- to import only from revision 1 to 6
463 (a ... is not needed in the path p4 specification, it's added implicitly)"""
465 self
.usage
+= " //depot/path[@revRange]"
468 self
.createdBranches
= Set()
469 self
.committedChanges
= Set()
471 self
.detectBranches
= False
472 self
.detectLabels
= False
473 self
.changesFile
= ""
474 self
.syncWithOrigin
= False
477 def p4File(self
, depotPath
):
478 return os
.popen("p4 print -q \"%s\"" % depotPath
, "rb").read()
480 def extractFilesFromCommit(self
, commit
):
483 while commit
.has_key("depotFile%s" % fnum
):
484 path
= commit
["depotFile%s" % fnum
]
485 if not path
.startswith(self
.depotPath
):
486 # if not self.silent:
487 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
493 file["rev"] = commit
["rev%s" % fnum
]
494 file["action"] = commit
["action%s" % fnum
]
495 file["type"] = commit
["type%s" % fnum
]
500 def splitFilesIntoBranches(self
, commit
):
504 while commit
.has_key("depotFile%s" % fnum
):
505 path
= commit
["depotFile%s" % fnum
]
506 if not path
.startswith(self
.depotPath
):
507 # if not self.silent:
508 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
514 file["rev"] = commit
["rev%s" % fnum
]
515 file["action"] = commit
["action%s" % fnum
]
516 file["type"] = commit
["type%s" % fnum
]
519 relPath
= path
[len(self
.depotPath
):]
521 for branch
in self
.knownBranches
.keys():
522 if relPath
.startswith(branch
):
523 if branch
not in branches
:
524 branches
[branch
] = []
525 branches
[branch
].append(file)
529 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= ""):
530 epoch
= details
["time"]
531 author
= details
["user"]
534 print "commit into %s" % branch
536 self
.gitStream
.write("commit %s\n" % branch
)
537 # gitStream.write("mark :%s\n" % details["change"])
538 self
.committedChanges
.add(int(details
["change"]))
540 if author
not in self
.users
:
541 self
.getUserMapFromPerforceServer()
542 if author
in self
.users
:
543 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
545 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
547 self
.gitStream
.write("committer %s\n" % committer
)
549 self
.gitStream
.write("data <<EOT\n")
550 self
.gitStream
.write(details
["desc"])
551 self
.gitStream
.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix
, details
["change"]))
552 self
.gitStream
.write("EOT\n\n")
556 print "parent %s" % parent
557 self
.gitStream
.write("from %s\n" % parent
)
561 if not path
.startswith(branchPrefix
):
563 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
566 depotPath
= path
+ "#" + rev
567 relPath
= path
[len(branchPrefix
):]
568 action
= file["action"]
570 if file["type"] == "apple":
571 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
574 if action
== "delete":
575 self
.gitStream
.write("D %s\n" % relPath
)
578 if file["type"].startswith("x"):
581 data
= self
.p4File(depotPath
)
583 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
584 self
.gitStream
.write("data %s\n" % len(data
))
585 self
.gitStream
.write(data
)
586 self
.gitStream
.write("\n")
588 self
.gitStream
.write("\n")
590 change
= int(details
["change"])
592 if self
.labels
.has_key(change
):
593 label
= self
.labels
[change
]
594 labelDetails
= label
[0]
595 labelRevisions
= label
[1]
597 print "Change %s is labelled %s" % (change
, labelDetails
)
599 files
= p4CmdList("files %s...@%s" % (branchPrefix
, change
))
601 if len(files
) == len(labelRevisions
):
605 if info
["action"] == "delete":
607 cleanedFiles
[info
["depotFile"]] = info
["rev"]
609 if cleanedFiles
== labelRevisions
:
610 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
611 self
.gitStream
.write("from %s\n" % branch
)
613 owner
= labelDetails
["Owner"]
615 if author
in self
.users
:
616 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
618 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
619 self
.gitStream
.write("tagger %s\n" % tagger
)
620 self
.gitStream
.write("data <<EOT\n")
621 self
.gitStream
.write(labelDetails
["Description"])
622 self
.gitStream
.write("EOT\n\n")
626 print "Tag %s does not match with change %s: files do not match." % (labelDetails
["label"], change
)
630 print "Tag %s does not match with change %s: file count is different." % (labelDetails
["label"], change
)
632 def getUserMapFromPerforceServer(self
):
635 for output
in p4CmdList("users"):
636 if not output
.has_key("User"):
638 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
640 cache
= open(gitdir
+ "/p4-usercache.txt", "wb")
641 for user
in self
.users
.keys():
642 cache
.write("%s\t%s\n" % (user
, self
.users
[user
]))
645 def loadUserMapFromCache(self
):
648 cache
= open(gitdir
+ "/p4-usercache.txt", "rb")
649 lines
= cache
.readlines()
652 entry
= line
[:-1].split("\t")
653 self
.users
[entry
[0]] = entry
[1]
655 self
.getUserMapFromPerforceServer()
660 l
= p4CmdList("labels %s..." % self
.depotPath
)
661 if len(l
) > 0 and not self
.silent
:
662 print "Finding files belonging to labels in %s" % self
.depotPath
665 label
= output
["label"]
669 print "Querying files for label %s" % label
670 for file in p4CmdList("files %s...@%s" % (self
.depotPath
, label
)):
671 revisions
[file["depotFile"]] = file["rev"]
672 change
= int(file["change"])
673 if change
> newestChange
:
674 newestChange
= change
676 self
.labels
[newestChange
] = [output
, revisions
]
679 print "Label changes: %s" % self
.labels
.keys()
681 def getBranchMapping(self
):
682 self
.projectName
= self
.depotPath
[self
.depotPath
[:-1].rfind("/") + 1:]
684 for info
in p4CmdList("branches"):
685 details
= p4Cmd("branch -o %s" % info
["branch"])
687 while details
.has_key("View%s" % viewIdx
):
688 paths
= details
["View%s" % viewIdx
].split(" ")
689 viewIdx
= viewIdx
+ 1
690 # require standard //depot/foo/... //depot/bar/... mapping
691 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
694 destination
= paths
[1]
695 if source
.startswith(self
.depotPath
) and destination
.startswith(self
.depotPath
):
696 source
= source
[len(self
.depotPath
):-4]
697 destination
= destination
[len(self
.depotPath
):-4]
698 if destination
not in self
.knownBranches
:
699 self
.knownBranches
[destination
] = source
700 if source
not in self
.knownBranches
:
701 self
.knownBranches
[source
] = source
703 def listExistingP4GitBranches(self
):
704 self
.p4BranchesInGit
= []
706 for line
in mypopen("git rev-parse --symbolic --remotes").readlines():
707 if line
.startswith("p4/") and line
!= "p4/HEAD\n":
709 self
.p4BranchesInGit
.append(branch
)
710 self
.initialParents
["refs/remotes/p4/" + branch
] = parseRevision(line
[:-1])
714 self
.changeRange
= ""
715 self
.initialParent
= ""
716 self
.previousDepotPath
= ""
717 # map from branch depot path to parent branch
718 self
.knownBranches
= {}
719 self
.initialParents
= {}
721 self
.listExistingP4GitBranches()
722 if len(self
.p4BranchesInGit
) > 1:
723 print "Importing from/into multiple branches"
724 self
.detectBranches
= True
726 if self
.syncWithOrigin
and gitBranchExists("origin") and gitBranchExists("refs/remotes/p4/master") and not self
.detectBranches
:
727 ### needs to be ported to multi branch import
729 print "Syncing with origin first as requested by calling git fetch origin"
730 system("git fetch origin")
731 [originPreviousDepotPath
, originP4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
732 [p4PreviousDepotPath
, p4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
733 if len(originPreviousDepotPath
) > 0 and len(originP4Change
) > 0 and len(p4Change
) > 0:
734 if originPreviousDepotPath
== p4PreviousDepotPath
:
735 originP4Change
= int(originP4Change
)
736 p4Change
= int(p4Change
)
737 if originP4Change
> p4Change
:
738 print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change
, p4Change
)
739 system("git update-ref refs/remotes/p4/master origin");
741 print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath
, p4PreviousDepotPath
)
743 if len(self
.branch
) == 0:
744 self
.branch
= "refs/remotes/p4/master"
745 if gitBranchExists("refs/heads/p4"):
746 system("git update-ref %s refs/heads/p4" % self
.branch
)
747 system("git branch -D p4");
748 if not gitBranchExists("refs/remotes/p4/HEAD"):
749 system("git symbolic-ref refs/remotes/p4/HEAD %s" % self
.branch
)
752 if not gitBranchExists(self
.branch
) and gitBranchExists("origin") and not self
.detectBranches
:
753 ### needs to be ported to multi branch import
755 print "Creating %s branch in git repository based on origin" % self
.branch
757 if not branch
.startswith("refs"):
758 branch
= "refs/heads/" + branch
759 system("git update-ref %s origin" % branch
)
762 print "branches: %s" % self
.p4BranchesInGit
765 for branch
in self
.p4BranchesInGit
:
766 depotPath
, change
= extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("refs/remotes/p4/" + branch
))
769 print "path %s change %s" % (depotPath
, change
)
771 if len(depotPath
) > 0 and len(change
) > 0:
772 change
= int(change
) + 1
773 p4Change
= max(p4Change
, change
)
775 if len(self
.previousDepotPath
) == 0:
776 self
.previousDepotPath
= depotPath
779 l
= min(len(self
.previousDepotPath
), len(depotPath
))
780 while i
< l
and self
.previousDepotPath
[i
] == depotPath
[i
]:
782 self
.previousDepotPath
= self
.previousDepotPath
[:i
]
785 self
.depotPath
= self
.previousDepotPath
786 self
.changeRange
= "@%s,#head" % p4Change
787 self
.initialParent
= parseRevision(self
.branch
)
789 print "Performing incremental import into %s git branch" % self
.branch
791 if not self
.branch
.startswith("refs/"):
792 self
.branch
= "refs/heads/" + self
.branch
794 if len(self
.depotPath
) != 0:
795 self
.depotPath
= self
.depotPath
[:-1]
797 if len(args
) == 0 and len(self
.depotPath
) != 0:
799 print "Depot path: %s" % self
.depotPath
803 if len(self
.depotPath
) != 0 and self
.depotPath
!= args
[0]:
804 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self
.depotPath
, args
[0])
806 self
.depotPath
= args
[0]
811 if self
.depotPath
.find("@") != -1:
812 atIdx
= self
.depotPath
.index("@")
813 self
.changeRange
= self
.depotPath
[atIdx
:]
814 if self
.changeRange
== "@all":
815 self
.changeRange
= ""
816 elif self
.changeRange
.find(",") == -1:
817 self
.revision
= self
.changeRange
818 self
.changeRange
= ""
819 self
.depotPath
= self
.depotPath
[0:atIdx
]
820 elif self
.depotPath
.find("#") != -1:
821 hashIdx
= self
.depotPath
.index("#")
822 self
.revision
= self
.depotPath
[hashIdx
:]
823 self
.depotPath
= self
.depotPath
[0:hashIdx
]
824 elif len(self
.previousDepotPath
) == 0:
825 self
.revision
= "#head"
827 if self
.depotPath
.endswith("..."):
828 self
.depotPath
= self
.depotPath
[:-3]
830 if not self
.depotPath
.endswith("/"):
831 self
.depotPath
+= "/"
833 self
.loadUserMapFromCache()
835 if self
.detectLabels
:
838 if self
.detectBranches
:
839 self
.getBranchMapping();
841 print "p4-git branches: %s" % self
.p4BranchesInGit
842 print "initial parents: %s" % self
.initialParents
843 for b
in self
.p4BranchesInGit
:
845 b
= b
[len(self
.projectName
):]
846 self
.createdBranches
.add(b
)
848 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
850 importProcess
= subprocess
.Popen(["git", "fast-import"], stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
);
851 self
.gitOutput
= importProcess
.stdout
852 self
.gitStream
= importProcess
.stdin
853 self
.gitError
= importProcess
.stderr
855 if len(self
.revision
) > 0:
856 print "Doing initial import of %s from revision %s" % (self
.depotPath
, self
.revision
)
858 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
859 details
["desc"] = "Initial import of %s from the state at revision %s" % (self
.depotPath
, self
.revision
)
860 details
["change"] = self
.revision
864 for info
in p4CmdList("files %s...%s" % (self
.depotPath
, self
.revision
)):
865 change
= int(info
["change"])
866 if change
> newestRevision
:
867 newestRevision
= change
869 if info
["action"] == "delete":
870 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
871 #fileCnt = fileCnt + 1
874 for prop
in [ "depotFile", "rev", "action", "type" ]:
875 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
877 fileCnt
= fileCnt
+ 1
879 details
["change"] = newestRevision
882 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPath
)
884 print "IO error with git fast-import. Is your git version recent enough?"
885 print self
.gitError
.read()
890 if len(self
.changesFile
) > 0:
891 output
= open(self
.changesFile
).readlines()
894 changeSet
.add(int(line
))
896 for change
in changeSet
:
897 changes
.append(change
)
902 print "Getting p4 changes for %s...%s" % (self
.depotPath
, self
.changeRange
)
903 output
= mypopen("p4 changes %s...%s" % (self
.depotPath
, self
.changeRange
)).readlines()
906 changeNum
= line
.split(" ")[1]
907 changes
.append(changeNum
)
911 if len(changes
) == 0:
913 print "no changes to import!"
917 for change
in changes
:
918 description
= p4Cmd("describe %s" % change
)
921 sys
.stdout
.write("\rimporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
926 if self
.detectBranches
:
927 branches
= self
.splitFilesIntoBranches(description
)
928 for branch
in branches
.keys():
929 branchPrefix
= self
.depotPath
+ branch
+ "/"
933 filesForCommit
= branches
[branch
]
936 print "branch is %s" % branch
938 if branch
not in self
.createdBranches
:
939 self
.createdBranches
.add(branch
)
940 parent
= self
.knownBranches
[branch
]
944 print "parent determined through known branches: %s" % parent
946 # main branch? use master
950 branch
= self
.projectName
+ branch
954 elif len(parent
) > 0:
955 parent
= self
.projectName
+ parent
957 branch
= "refs/remotes/p4/" + branch
959 parent
= "refs/remotes/p4/" + parent
962 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
964 if len(parent
) == 0 and branch
in self
.initialParents
:
965 parent
= self
.initialParents
[branch
]
966 del self
.initialParents
[branch
]
968 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
970 files
= self
.extractFilesFromCommit(description
)
971 self
.commit(description
, files
, self
.branch
, self
.depotPath
, self
.initialParent
)
972 self
.initialParent
= ""
974 print self
.gitError
.read()
981 self
.gitStream
.close()
982 if importProcess
.wait() != 0:
983 die("fast-import failed: %s" % self
.gitError
.read())
984 self
.gitOutput
.close()
985 self
.gitError
.close()
989 class P4Rebase(Command
):
991 Command
.__init
__(self
)
992 self
.options
= [ optparse
.make_option("--with-origin", dest
="syncWithOrigin", action
="store_true") ]
993 self
.description
= "Fetches the latest revision from perforce and rebases the current work (branch) against it"
994 self
.syncWithOrigin
= False
998 sync
.syncWithOrigin
= self
.syncWithOrigin
1000 print "Rebasing the current branch"
1001 oldHead
= mypopen("git rev-parse HEAD").read()[:-1]
1002 system("git rebase p4")
1003 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1006 class P4Clone(P4Sync
):
1008 P4Sync
.__init
__(self
)
1009 self
.description
= "Creates a new git repository and imports from Perforce into it"
1010 self
.usage
= "usage: %prog [options] //depot/path[@revRange] [directory]"
1011 self
.needsGit
= False
1013 def run(self
, args
):
1025 if not depotPath
.startswith("//"):
1030 atPos
= dir.rfind("@")
1033 hashPos
= dir.rfind("#")
1035 dir = dir[0:hashPos
]
1037 if dir.endswith("..."):
1040 if dir.endswith("/"):
1043 slashPos
= dir.rfind("/")
1045 dir = dir[slashPos
+ 1:]
1047 print "Importing from %s into %s" % (depotPath
, dir)
1051 gitdir
= os
.getcwd() + "/.git"
1052 if not P4Sync
.run(self
, [depotPath
]):
1054 if self
.branch
!= "master":
1055 if gitBranchExists("refs/remotes/p4/master"):
1056 system("git branch master refs/remotes/p4/master")
1057 system("git checkout -f")
1059 print "Could not detect main branch. No checkout/master branch created."
1062 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1064 optparse
.IndentedHelpFormatter
.__init
__(self
)
1066 def format_description(self
, description
):
1068 return description
+ "\n"
1072 def printUsage(commands
):
1073 print "usage: %s <command> [options]" % sys
.argv
[0]
1075 print "valid commands: %s" % ", ".join(commands
)
1077 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1081 "debug" : P4Debug(),
1082 "submit" : P4Submit(),
1084 "rebase" : P4Rebase(),
1088 if len(sys
.argv
[1:]) == 0:
1089 printUsage(commands
.keys())
1093 cmdName
= sys
.argv
[1]
1095 cmd
= commands
[cmdName
]
1097 print "unknown command %s" % cmdName
1099 printUsage(commands
.keys())
1102 options
= cmd
.options
1107 if len(options
) > 0:
1108 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1110 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1112 description
= cmd
.description
,
1113 formatter
= HelpFormatter())
1115 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1119 if len(gitdir
) == 0:
1121 if not isValidGitDir(gitdir
):
1122 gitdir
= mypopen("git rev-parse --git-dir").read()[:-1]
1123 if os
.path
.exists(gitdir
):
1124 cdup
= mypopen("git rev-parse --show-cdup").read()[:-1];
1128 if not isValidGitDir(gitdir
):
1129 if isValidGitDir(gitdir
+ "/.git"):
1132 die("fatal: cannot locate git repository at %s" % gitdir
)
1134 os
.environ
["GIT_DIR"] = gitdir
1136 if not cmd
.run(args
):