Code

Fix branch setup after initial clone.
[git.git] / contrib / fast-import / git-p4
index 2633f299424056308f57fd93505803bb008fe8cd..2f3615bd7274f22c1132ec96670ba23f519f2d27 100755 (executable)
@@ -67,6 +67,9 @@ def isValidGitDir(path):
         return True;
     return False
 
+def parseRevision(ref):
+    return mypopen("git rev-parse %s" % ref).read()[:-1]
+
 def system(cmd):
     if os.system(cmd) != 0:
         die("command failed: %s" % cmd)
@@ -124,44 +127,6 @@ class P4Debug(Command):
             print output
         return True
 
-class P4CleanTags(Command):
-    def __init__(self):
-        Command.__init__(self)
-        self.options = [
-#                optparse.make_option("--branch", dest="branch", default="refs/heads/master")
-        ]
-        self.description = "A tool to remove stale unused tags from incremental perforce imports."
-    def run(self, args):
-        branch = currentGitBranch()
-        print "Cleaning out stale p4 import tags..."
-        sout, sin, serr = popen2.popen3("git name-rev --tags `git rev-parse %s`" % branch)
-        output = sout.read()
-        try:
-            tagIdx = output.index(" tags/p4/")
-        except:
-            print "Cannot find any p4/* tag. Nothing to do."
-            sys.exit(0)
-
-        try:
-            caretIdx = output.index("^")
-        except:
-            caretIdx = len(output) - 1
-        rev = int(output[tagIdx + 9 : caretIdx])
-
-        allTags = mypopen("git tag -l p4/").readlines()
-        for i in range(len(allTags)):
-            allTags[i] = int(allTags[i][3:-1])
-
-        allTags.sort()
-
-        allTags.remove(rev)
-
-        for rev in allTags:
-            print mypopen("git tag -d p4/%s" % rev).read()
-
-        print "%s tags removed." % len(allTags)
-        return True
-
 class P4Submit(Command):
     def __init__(self):
         Command.__init__(self)
@@ -193,7 +158,7 @@ class P4Submit(Command):
 
     def start(self):
         if len(self.config) > 0 and not self.reset:
-            die("Cannot start sync. Previous sync config found at %s" % self.configFile)
+            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)
 
         commits = []
         for line in mypopen("git rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
@@ -230,11 +195,13 @@ class P4Submit(Command):
         diff = mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
         filesToAdd = set()
         filesToDelete = set()
+        editedFiles = set()
         for line in diff:
             modifier = line[0]
             path = line[1:].strip()
             if modifier == "M":
-                system("p4 edit %s" % path)
+                system("p4 edit \"%s\"" % path)
+                editedFiles.add(path)
             elif modifier == "A":
                 filesToAdd.add(path)
                 if path in filesToDelete:
@@ -308,7 +275,7 @@ class P4Submit(Command):
             firstIteration = True
             while response == "e":
                 if not firstIteration:
-                    response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o  ")
+                    response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
                 firstIteration = False
                 if response == "e":
                     [handle, fileName] = tempfile.mkstemp()
@@ -334,6 +301,15 @@ class P4Submit(Command):
                     pipe = os.popen("p4 submit -i", "wb")
                     pipe.write(submitTemplate)
                     pipe.close()
+            elif response == "s":
+                for f in editedFiles:
+                    system("p4 revert \"%s\"" % f);
+                for f in filesToAdd:
+                    system("p4 revert \"%s\"" % f);
+                    system("rm %s" %f)
+                for f in filesToDelete:
+                    system("p4 delete \"%s\"" % f);
+                return
             else:
                 print "Not submitting!"
                 self.interactive = False
@@ -441,7 +417,8 @@ class P4Sync(Command):
                 optparse.make_option("--known-branches", dest="knownBranches"),
                 optparse.make_option("--data-cache", dest="dataCache", action="store_true"),
                 optparse.make_option("--command-cache", dest="commandCache", action="store_true"),
-                optparse.make_option("--detect-labels", dest="detectLabels", action="store_true")
+                optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
+                optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true")
         ]
         self.description = """Imports from Perforce into a git repository.\n
     example:
@@ -463,6 +440,7 @@ class P4Sync(Command):
         self.detectBranches = False
         self.detectLabels = False
         self.changesFile = ""
+        self.syncWithOrigin = False
 
     def p4File(self, depotPath):
         return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
@@ -851,25 +829,49 @@ class P4Sync(Command):
         self.initialParent = ""
         self.previousDepotPath = ""
 
+        if self.syncWithOrigin and gitBranchExists("origin") and gitBranchExists("refs/remotes/p4/master"):
+            print "Syncing with origin first as requested by calling git fetch origin"
+            system("git fetch origin")
+            [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
+            [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
+            if len(originPreviousDepotPath) > 0 and len(originP4Change) > 0 and len(p4Change) > 0:
+                if originPreviousDepotPath == p4PreviousDepotPath:
+                    originP4Change = int(originP4Change)
+                    p4Change = int(p4Change)
+                    if originP4Change > p4Change:
+                        print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change, p4Change)
+                        system("git update-ref refs/remotes/p4/master origin");
+                else:
+                    print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath, p4PreviousDepotPath)
+
         if len(self.branch) == 0:
-            self.branch = "p4"
+            self.branch = "refs/remotes/p4/master"
+            if gitBranchExists("refs/heads/p4"):
+                system("git update-ref %s refs/heads/p4" % self.branch)
+                system("git branch -D p4");
+            if not gitBranchExists("refs/remotes/p4/HEAD"):
+                system("git symbolic-ref refs/remotes/p4/HEAD %s" % self.branch)
 
         if len(args) == 0:
             if not gitBranchExists(self.branch) and gitBranchExists("origin"):
                 if not self.silent:
                     print "Creating %s branch in git repository based on origin" % self.branch
-                system("git branch %s origin" % self.branch)
+                branch = self.branch
+                if not branch.startswith("refs"):
+                    branch = "refs/heads/" + branch
+                system("git update-ref %s origin" % branch)
 
             [self.previousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(self.branch))
             if len(self.previousDepotPath) > 0 and len(p4Change) > 0:
                 p4Change = int(p4Change) + 1
                 self.depotPath = self.previousDepotPath
                 self.changeRange = "@%s,#head" % p4Change
-                self.initialParent = self.branch
+                self.initialParent = parseRevision(self.branch)
                 if not self.silent:
                     print "Performing incremental import into %s git branch" % self.branch
 
-        self.branch = "refs/heads/" + self.branch
+        if not self.branch.startswith("refs/"):
+            self.branch = "refs/heads/" + self.branch
 
         if len(self.depotPath) != 0:
             self.depotPath = self.depotPath[:-1]
@@ -916,23 +918,6 @@ class P4Sync(Command):
         if self.detectLabels:
             self.getLabels();
 
-        if len(self.changeRange) == 0:
-            try:
-                sout, sin, serr = popen2.popen3("git name-rev --tags `git rev-parse %s`" % self.branch)
-                output = sout.read()
-                if output.endswith("\n"):
-                    output = output[:-1]
-                tagIdx = output.index(" tags/p4/")
-                caretIdx = output.find("^")
-                endPos = len(output)
-                if caretIdx != -1:
-                    endPos = caretIdx
-                self.rev = int(output[tagIdx + 9 : endPos]) + 1
-                self.changeRange = "@%s,#head" % self.rev
-                self.initialParent = mypopen("git rev-parse %s" % self.branch).read()[:-1]
-            except:
-                pass
-
         self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
 
         importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
@@ -1062,11 +1047,13 @@ class P4Sync(Command):
 class P4Rebase(Command):
     def __init__(self):
         Command.__init__(self)
-        self.options = [ ]
+        self.options = [ optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true") ]
         self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it"
+        self.syncWithOrigin = False
 
     def run(self, args):
         sync = P4Sync()
+        sync.syncWithOrigin = self.syncWithOrigin
         sync.run([])
         print "Rebasing the current branch"
         oldHead = mypopen("git rev-parse HEAD").read()[:-1]
@@ -1144,7 +1131,6 @@ def printUsage(commands):
 
 commands = {
     "debug" : P4Debug(),
-    "clean-tags" : P4CleanTags(),
     "submit" : P4Submit(),
     "sync" : P4Sync(),
     "rebase" : P4Rebase(),
@@ -1185,9 +1171,11 @@ if cmd.needsGit:
     if len(gitdir) == 0:
         gitdir = ".git"
         if not isValidGitDir(gitdir):
-            cdup = mypopen("git rev-parse --show-cdup").read()[:-1]
-            if isValidGitDir(cdup + "/" + gitdir):
-                os.chdir(cdup)
+            gitdir = mypopen("git rev-parse --git-dir").read()[:-1]
+            if os.path.exists(gitdir):
+                cdup = mypopen("git rev-parse --show-cdup").read()[:-1];
+                if len(cdup) > 0:
+                    os.chdir(cdup);
 
     if not isValidGitDir(gitdir):
         if isValidGitDir(gitdir + "/.git"):