Detect with git-p4 submit --direct when there are no changes in the working directory
[git/git.git] / contrib / fast-import / git-p4
CommitLineData
86949eef
SH
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 <hausmann@kde.org>
83dce55a
SH
6# Copyright: 2007 Simon Hausmann <hausmann@kde.org>
7# 2007 Trolltech ASA
86949eef
SH
8# License: MIT <http://www.opensource.org/licenses/mit-license.php>
9#
24f7b53f
SH
10# TODO: * implement git-p4 rollback <perforce change number> for debugging
11# to roll back all p4 remote branches to a commit older or equal to
12# the specified change.
b1561ee2
SH
13# * for git-p4 submit --direct it would be nice to still create a
14# git commit without updating HEAD before submitting to perforce.
15# With the commit sha1 printed (or recoded in a .git/foo file?)
16# it's possible to recover if anything goes wrong instead of potentially
17# loosing a change entirely because it was never comitted to git and
18# the p4 submit failed (or resulted in lots of conflicts, etc.)
341dc1c1
SH
19# * Consider making --with-origin the default, assuming that the git
20# protocol is always more efficient. (needs manual testing first :)
24f7b53f 21#
86949eef 22
08483580 23import optparse, sys, os, marshal, popen2, subprocess, shelve
25df95cc 24import tempfile, getopt, sha, os.path, time, platform
b984733c 25from sets import Set;
4f5cf76a
SH
26
27gitdir = os.environ.get("GIT_DIR", "")
86949eef 28
caace111
SH
29def mypopen(command):
30 return os.popen(command, "rb");
31
86949eef
SH
32def p4CmdList(cmd):
33 cmd = "p4 -G %s" % cmd
34 pipe = os.popen(cmd, "rb")
35
36 result = []
37 try:
38 while True:
39 entry = marshal.load(pipe)
40 result.append(entry)
41 except EOFError:
42 pass
43 pipe.close()
44
45 return result
46
47def p4Cmd(cmd):
48 list = p4CmdList(cmd)
49 result = {}
50 for entry in list:
51 result.update(entry)
52 return result;
53
cb2c9db5
SH
54def p4Where(depotPath):
55 if not depotPath.endswith("/"):
56 depotPath += "/"
57 output = p4Cmd("where %s..." % depotPath)
dc524036
SH
58 if output["code"] == "error":
59 return ""
cb2c9db5
SH
60 clientPath = ""
61 if "path" in output:
62 clientPath = output.get("path")
63 elif "data" in output:
64 data = output.get("data")
65 lastSpace = data.rfind(" ")
66 clientPath = data[lastSpace + 1:]
67
68 if clientPath.endswith("..."):
69 clientPath = clientPath[:-3]
70 return clientPath
71
86949eef
SH
72def die(msg):
73 sys.stderr.write(msg + "\n")
74 sys.exit(1)
75
76def currentGitBranch():
caace111 77 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
86949eef 78
4f5cf76a
SH
79def isValidGitDir(path):
80 if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
81 return True;
82 return False
83
463e8af6
SH
84def parseRevision(ref):
85 return mypopen("git rev-parse %s" % ref).read()[:-1]
86
4f5cf76a
SH
87def system(cmd):
88 if os.system(cmd) != 0:
89 die("command failed: %s" % cmd)
90
6ae8de88
SH
91def extractLogMessageFromGitCommit(commit):
92 logMessage = ""
93 foundTitle = False
caace111 94 for log in mypopen("git cat-file commit %s" % commit).readlines():
6ae8de88
SH
95 if not foundTitle:
96 if len(log) == 1:
1c094184 97 foundTitle = True
6ae8de88
SH
98 continue
99
100 logMessage += log
101 return logMessage
102
103def extractDepotPathAndChangeFromGitLog(log):
104 values = {}
105 for line in log.split("\n"):
106 line = line.strip()
107 if line.startswith("[git-p4:") and line.endswith("]"):
108 line = line[8:-1].strip()
109 for assignment in line.split(":"):
110 variable = assignment.strip()
111 value = ""
112 equalPos = assignment.find("=")
113 if equalPos != -1:
114 variable = assignment[:equalPos].strip()
115 value = assignment[equalPos + 1:].strip()
116 if value.startswith("\"") and value.endswith("\""):
117 value = value[1:-1]
118 values[variable] = value
119
120 return values.get("depot-path"), values.get("change")
121
8136a639 122def gitBranchExists(branch):
caace111
SH
123 proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
124 return proc.wait() == 0;
8136a639 125
b984733c
SH
126class Command:
127 def __init__(self):
128 self.usage = "usage: %prog [options]"
8910ac0e 129 self.needsGit = True
b984733c
SH
130
131class P4Debug(Command):
86949eef 132 def __init__(self):
6ae8de88 133 Command.__init__(self)
86949eef
SH
134 self.options = [
135 ]
c8c39116 136 self.description = "A tool to debug the output of p4 -G."
8910ac0e 137 self.needsGit = False
86949eef
SH
138
139 def run(self, args):
140 for output in p4CmdList(" ".join(args)):
141 print output
b984733c 142 return True
86949eef 143
711544b0 144class P4Submit(Command):
4f5cf76a 145 def __init__(self):
b984733c 146 Command.__init__(self)
4f5cf76a
SH
147 self.options = [
148 optparse.make_option("--continue", action="store_false", dest="firstTime"),
149 optparse.make_option("--origin", dest="origin"),
150 optparse.make_option("--reset", action="store_true", dest="reset"),
4f5cf76a
SH
151 optparse.make_option("--log-substitutions", dest="substFile"),
152 optparse.make_option("--noninteractive", action="store_false"),
04219c04 153 optparse.make_option("--dry-run", action="store_true"),
c1b296b9 154 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
4f5cf76a
SH
155 ]
156 self.description = "Submit changes from git to the perforce depot."
c9b50e63 157 self.usage += " [name of git branch to submit into perforce depot]"
4f5cf76a
SH
158 self.firstTime = True
159 self.reset = False
160 self.interactive = True
161 self.dryRun = False
162 self.substFile = ""
163 self.firstTime = True
9512497b 164 self.origin = ""
c1b296b9 165 self.directSubmit = False
4f5cf76a
SH
166
167 self.logSubstitutions = {}
168 self.logSubstitutions["<enter description here>"] = "%log%"
169 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
170
171 def check(self):
172 if len(p4CmdList("opened ...")) > 0:
173 die("You have files opened with perforce! Close them before starting the sync.")
174
175 def start(self):
176 if len(self.config) > 0 and not self.reset:
c3c46244 177 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)
4f5cf76a
SH
178
179 commits = []
c1b296b9
SH
180 if self.directSubmit:
181 commits.append("0")
182 else:
183 for line in mypopen("git rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
184 commits.append(line[:-1])
185 commits.reverse()
4f5cf76a
SH
186
187 self.config["commits"] = commits
188
4f5cf76a
SH
189 def prepareLogMessage(self, template, message):
190 result = ""
191
192 for line in template.split("\n"):
193 if line.startswith("#"):
194 result += line + "\n"
195 continue
196
197 substituted = False
198 for key in self.logSubstitutions.keys():
199 if line.find(key) != -1:
200 value = self.logSubstitutions[key]
201 value = value.replace("%log%", message)
202 if value != "@remove@":
203 result += line.replace(key, value) + "\n"
204 substituted = True
205 break
206
207 if not substituted:
208 result += line + "\n"
209
210 return result
211
212 def apply(self, id):
c1b296b9
SH
213 if self.directSubmit:
214 print "Applying local change in working directory/index"
215 diff = self.diffStatus
216 else:
217 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
218 diff = mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
4f5cf76a
SH
219 filesToAdd = set()
220 filesToDelete = set()
d336c158 221 editedFiles = set()
4f5cf76a
SH
222 for line in diff:
223 modifier = line[0]
224 path = line[1:].strip()
225 if modifier == "M":
d336c158
SH
226 system("p4 edit \"%s\"" % path)
227 editedFiles.add(path)
4f5cf76a
SH
228 elif modifier == "A":
229 filesToAdd.add(path)
230 if path in filesToDelete:
231 filesToDelete.remove(path)
232 elif modifier == "D":
233 filesToDelete.add(path)
234 if path in filesToAdd:
235 filesToAdd.remove(path)
236 else:
237 die("unknown modifier %s for %s" % (modifier, path))
238
c1b296b9
SH
239 if self.directSubmit:
240 diffcmd = "cat \"%s\"" % self.diffFile
241 else:
242 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
47a130b7 243 patchcmd = diffcmd + " | git apply "
c1b296b9
SH
244 tryPatchCmd = patchcmd + "--check -"
245 applyPatchCmd = patchcmd + "--check --apply -"
51a2640a 246
47a130b7 247 if os.system(tryPatchCmd) != 0:
51a2640a
SH
248 print "Unfortunately applying the change failed!"
249 print "What do you want to do?"
250 response = "x"
251 while response != "s" and response != "a" and response != "w":
252 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) ")
253 if response == "s":
254 print "Skipping! Good luck with the next patches..."
255 return
256 elif response == "a":
47a130b7 257 os.system(applyPatchCmd)
51a2640a
SH
258 if len(filesToAdd) > 0:
259 print "You may also want to call p4 add on the following files:"
260 print " ".join(filesToAdd)
261 if len(filesToDelete):
262 print "The following files should be scheduled for deletion with p4 delete:"
263 print " ".join(filesToDelete)
264 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
265 elif response == "w":
266 system(diffcmd + " > patch.txt")
267 print "Patch saved to patch.txt in %s !" % self.clientPath
268 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
269
47a130b7 270 system(applyPatchCmd)
4f5cf76a
SH
271
272 for f in filesToAdd:
273 system("p4 add %s" % f)
274 for f in filesToDelete:
275 system("p4 revert %s" % f)
276 system("p4 delete %s" % f)
277
c1b296b9
SH
278 logMessage = ""
279 if not self.directSubmit:
280 logMessage = extractLogMessageFromGitCommit(id)
281 logMessage = logMessage.replace("\n", "\n\t")
282 logMessage = logMessage[:-1]
4f5cf76a 283
caace111 284 template = mypopen("p4 change -o").read()
4f5cf76a
SH
285
286 if self.interactive:
287 submitTemplate = self.prepareLogMessage(template, logMessage)
caace111 288 diff = mypopen("p4 diff -du ...").read()
4f5cf76a
SH
289
290 for newFile in filesToAdd:
291 diff += "==== new file ====\n"
292 diff += "--- /dev/null\n"
293 diff += "+++ %s\n" % newFile
294 f = open(newFile, "r")
295 for line in f.readlines():
296 diff += "+" + line
297 f.close()
298
25df95cc
SH
299 separatorLine = "######## everything below this line is just the diff #######"
300 if platform.system() == "Windows":
301 separatorLine += "\r"
302 separatorLine += "\n"
4f5cf76a
SH
303
304 response = "e"
53150250 305 firstIteration = True
4f5cf76a 306 while response == "e":
53150250 307 if not firstIteration:
d336c158 308 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
53150250 309 firstIteration = False
4f5cf76a
SH
310 if response == "e":
311 [handle, fileName] = tempfile.mkstemp()
312 tmpFile = os.fdopen(handle, "w+")
53150250 313 tmpFile.write(submitTemplate + separatorLine + diff)
4f5cf76a 314 tmpFile.close()
25df95cc
SH
315 defaultEditor = "vi"
316 if platform.system() == "Windows":
317 defaultEditor = "notepad"
318 editor = os.environ.get("EDITOR", defaultEditor);
4f5cf76a 319 system(editor + " " + fileName)
25df95cc 320 tmpFile = open(fileName, "rb")
53150250 321 message = tmpFile.read()
4f5cf76a
SH
322 tmpFile.close()
323 os.remove(fileName)
53150250 324 submitTemplate = message[:message.index(separatorLine)]
4f5cf76a
SH
325
326 if response == "y" or response == "yes":
327 if self.dryRun:
328 print submitTemplate
329 raw_input("Press return to continue...")
330 else:
25df95cc 331 pipe = os.popen("p4 submit -i", "wb")
4f5cf76a
SH
332 pipe.write(submitTemplate)
333 pipe.close()
d336c158
SH
334 elif response == "s":
335 for f in editedFiles:
336 system("p4 revert \"%s\"" % f);
337 for f in filesToAdd:
338 system("p4 revert \"%s\"" % f);
339 system("rm %s" %f)
340 for f in filesToDelete:
341 system("p4 delete \"%s\"" % f);
342 return
4f5cf76a
SH
343 else:
344 print "Not submitting!"
345 self.interactive = False
346 else:
347 fileName = "submit.txt"
348 file = open(fileName, "w+")
349 file.write(self.prepareLogMessage(template, logMessage))
350 file.close()
351 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
352
353 def run(self, args):
9512497b
SH
354 global gitdir
355 # make gitdir absolute so we can cd out into the perforce checkout
356 gitdir = os.path.abspath(gitdir)
357 os.environ["GIT_DIR"] = gitdir
c9b50e63
SH
358
359 if len(args) == 0:
360 self.master = currentGitBranch()
361 if len(self.master) == 0 or not os.path.exists("%s/refs/heads/%s" % (gitdir, self.master)):
362 die("Detecting current git branch failed!")
363 elif len(args) == 1:
364 self.master = args[0]
365 else:
366 return False
367
9512497b
SH
368 depotPath = ""
369 if gitBranchExists("p4"):
370 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
371 if len(depotPath) == 0 and gitBranchExists("origin"):
372 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
373
374 if len(depotPath) == 0:
375 print "Internal error: cannot locate perforce depot path from existing branches"
376 sys.exit(128)
377
51a2640a 378 self.clientPath = p4Where(depotPath)
9512497b 379
51a2640a 380 if len(self.clientPath) == 0:
9512497b
SH
381 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
382 sys.exit(128)
383
51a2640a 384 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
80b5910f 385 oldWorkingDirectory = os.getcwd()
c1b296b9
SH
386
387 if self.directSubmit:
388 self.diffStatus = mypopen("git diff -r --name-status HEAD").readlines()
cbf5efa6
SH
389 if len(self.diffStatus) == 0:
390 print "No changes in working directory to submit."
391 return True
c1b296b9
SH
392 patch = mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
393 self.diffFile = gitdir + "/p4-git-diff"
394 f = open(self.diffFile, "wb")
395 f.write(patch)
396 f.close();
397
51a2640a
SH
398 os.chdir(self.clientPath)
399 response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
9512497b
SH
400 if response == "y" or response == "yes":
401 system("p4 sync ...")
402
403 if len(self.origin) == 0:
404 if gitBranchExists("p4"):
405 self.origin = "p4"
406 else:
407 self.origin = "origin"
408
4f5cf76a
SH
409 if self.reset:
410 self.firstTime = True
411
412 if len(self.substFile) > 0:
413 for line in open(self.substFile, "r").readlines():
414 tokens = line[:-1].split("=")
415 self.logSubstitutions[tokens[0]] = tokens[1]
416
4f5cf76a
SH
417 self.check()
418 self.configFile = gitdir + "/p4-git-sync.cfg"
419 self.config = shelve.open(self.configFile, writeback=True)
420
421 if self.firstTime:
422 self.start()
423
424 commits = self.config.get("commits", [])
425
426 while len(commits) > 0:
427 self.firstTime = False
428 commit = commits[0]
429 commits = commits[1:]
430 self.config["commits"] = commits
431 self.apply(commit)
432 if not self.interactive:
433 break
434
435 self.config.close()
436
c1b296b9
SH
437 if self.directSubmit:
438 os.remove(self.diffFile)
439
4f5cf76a
SH
440 if len(commits) == 0:
441 if self.firstTime:
442 print "No changes found to apply between %s and current HEAD" % self.origin
443 else:
444 print "All changes applied!"
c1b296b9
SH
445 response = ""
446 os.chdir(oldWorkingDirectory)
447
448 if self.directSubmit:
449 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 ")
450 if response == "y" or response == "yes":
451 system("git reset --hard")
452
453 if len(response) == 0:
454 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
80b5910f 455 if response == "y" or response == "yes":
80b5910f
SH
456 rebase = P4Rebase()
457 rebase.run([])
4f5cf76a
SH
458 os.remove(self.configFile)
459
b984733c
SH
460 return True
461
711544b0 462class P4Sync(Command):
b984733c
SH
463 def __init__(self):
464 Command.__init__(self)
465 self.options = [
466 optparse.make_option("--branch", dest="branch"),
467 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
468 optparse.make_option("--changesfile", dest="changesFile"),
469 optparse.make_option("--silent", dest="silent", action="store_true"),
ef48f909 470 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
4b97ffb1
SH
471 optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true"),
472 optparse.make_option("--verbose", dest="verbose", action="store_true")
b984733c
SH
473 ]
474 self.description = """Imports from Perforce into a git repository.\n
475 example:
476 //depot/my/project/ -- to import the current head
477 //depot/my/project/@all -- to import everything
478 //depot/my/project/@1,6 -- to import only from revision 1 to 6
479
480 (a ... is not needed in the path p4 specification, it's added implicitly)"""
481
482 self.usage += " //depot/path[@revRange]"
483
b984733c 484 self.silent = False
b984733c
SH
485 self.createdBranches = Set()
486 self.committedChanges = Set()
569d1bd4 487 self.branch = ""
b984733c 488 self.detectBranches = False
cb53e1f8 489 self.detectLabels = False
b984733c 490 self.changesFile = ""
ef48f909 491 self.syncWithOrigin = False
4b97ffb1 492 self.verbose = False
b984733c
SH
493
494 def p4File(self, depotPath):
495 return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
496
497 def extractFilesFromCommit(self, commit):
498 files = []
499 fnum = 0
500 while commit.has_key("depotFile%s" % fnum):
501 path = commit["depotFile%s" % fnum]
8f872531 502 if not path.startswith(self.depotPath):
b984733c 503 # if not self.silent:
8f872531 504 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
b984733c
SH
505 fnum = fnum + 1
506 continue
507
508 file = {}
509 file["path"] = path
510 file["rev"] = commit["rev%s" % fnum]
511 file["action"] = commit["action%s" % fnum]
512 file["type"] = commit["type%s" % fnum]
513 files.append(file)
514 fnum = fnum + 1
515 return files
516
71b112d4 517 def splitFilesIntoBranches(self, commit):
d5904674 518 branches = {}
b984733c 519
71b112d4
SH
520 fnum = 0
521 while commit.has_key("depotFile%s" % fnum):
522 path = commit["depotFile%s" % fnum]
523 if not path.startswith(self.depotPath):
524 # if not self.silent:
525 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
526 fnum = fnum + 1
527 continue
528
529 file = {}
530 file["path"] = path
531 file["rev"] = commit["rev%s" % fnum]
532 file["action"] = commit["action%s" % fnum]
533 file["type"] = commit["type%s" % fnum]
534 fnum = fnum + 1
535
536 relPath = path[len(self.depotPath):]
b984733c 537
4b97ffb1 538 for branch in self.knownBranches.keys():
71b112d4 539 if relPath.startswith(branch):
d5904674
SH
540 if branch not in branches:
541 branches[branch] = []
71b112d4 542 branches[branch].append(file)
b984733c
SH
543
544 return branches
545
4b97ffb1 546 def commit(self, details, files, branch, branchPrefix, parent = ""):
b984733c
SH
547 epoch = details["time"]
548 author = details["user"]
549
4b97ffb1
SH
550 if self.verbose:
551 print "commit into %s" % branch
552
b984733c
SH
553 self.gitStream.write("commit %s\n" % branch)
554 # gitStream.write("mark :%s\n" % details["change"])
555 self.committedChanges.add(int(details["change"]))
556 committer = ""
b607e71e
SH
557 if author not in self.users:
558 self.getUserMapFromPerforceServer()
b984733c 559 if author in self.users:
0828ab14 560 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
b984733c 561 else:
0828ab14 562 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
b984733c
SH
563
564 self.gitStream.write("committer %s\n" % committer)
565
566 self.gitStream.write("data <<EOT\n")
567 self.gitStream.write(details["desc"])
6ae8de88 568 self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
b984733c
SH
569 self.gitStream.write("EOT\n\n")
570
571 if len(parent) > 0:
4b97ffb1
SH
572 if self.verbose:
573 print "parent %s" % parent
b984733c
SH
574 self.gitStream.write("from %s\n" % parent)
575
b984733c
SH
576 for file in files:
577 path = file["path"]
578 if not path.startswith(branchPrefix):
579 # if not silent:
580 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
581 continue
582 rev = file["rev"]
583 depotPath = path + "#" + rev
584 relPath = path[len(branchPrefix):]
585 action = file["action"]
586
587 if file["type"] == "apple":
588 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
589 continue
590
591 if action == "delete":
592 self.gitStream.write("D %s\n" % relPath)
593 else:
594 mode = 644
595 if file["type"].startswith("x"):
596 mode = 755
597
598 data = self.p4File(depotPath)
599
600 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
601 self.gitStream.write("data %s\n" % len(data))
602 self.gitStream.write(data)
603 self.gitStream.write("\n")
604
605 self.gitStream.write("\n")
606
1f4ba1cb
SH
607 change = int(details["change"])
608
9bda3a85 609 if self.labels.has_key(change):
1f4ba1cb
SH
610 label = self.labels[change]
611 labelDetails = label[0]
612 labelRevisions = label[1]
71b112d4
SH
613 if self.verbose:
614 print "Change %s is labelled %s" % (change, labelDetails)
1f4ba1cb
SH
615
616 files = p4CmdList("files %s...@%s" % (branchPrefix, change))
617
618 if len(files) == len(labelRevisions):
619
620 cleanedFiles = {}
621 for info in files:
622 if info["action"] == "delete":
623 continue
624 cleanedFiles[info["depotFile"]] = info["rev"]
625
626 if cleanedFiles == labelRevisions:
627 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
628 self.gitStream.write("from %s\n" % branch)
629
630 owner = labelDetails["Owner"]
631 tagger = ""
632 if author in self.users:
633 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
634 else:
635 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
636 self.gitStream.write("tagger %s\n" % tagger)
637 self.gitStream.write("data <<EOT\n")
638 self.gitStream.write(labelDetails["Description"])
639 self.gitStream.write("EOT\n\n")
640
641 else:
a46668fa 642 if not self.silent:
1f4ba1cb
SH
643 print "Tag %s does not match with change %s: files do not match." % (labelDetails["label"], change)
644
645 else:
a46668fa 646 if not self.silent:
1f4ba1cb 647 print "Tag %s does not match with change %s: file count is different." % (labelDetails["label"], change)
b984733c 648
b607e71e 649 def getUserMapFromPerforceServer(self):
b984733c
SH
650 self.users = {}
651
652 for output in p4CmdList("users"):
653 if not output.has_key("User"):
654 continue
655 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
656
b607e71e
SH
657 cache = open(gitdir + "/p4-usercache.txt", "wb")
658 for user in self.users.keys():
659 cache.write("%s\t%s\n" % (user, self.users[user]))
660 cache.close();
661
662 def loadUserMapFromCache(self):
663 self.users = {}
664 try:
665 cache = open(gitdir + "/p4-usercache.txt", "rb")
666 lines = cache.readlines()
667 cache.close()
668 for line in lines:
669 entry = line[:-1].split("\t")
670 self.users[entry[0]] = entry[1]
671 except IOError:
672 self.getUserMapFromPerforceServer()
673
1f4ba1cb
SH
674 def getLabels(self):
675 self.labels = {}
676
8f872531 677 l = p4CmdList("labels %s..." % self.depotPath)
10c3211b 678 if len(l) > 0 and not self.silent:
8f872531 679 print "Finding files belonging to labels in %s" % self.depotPath
01ce1fe9
SH
680
681 for output in l:
1f4ba1cb
SH
682 label = output["label"]
683 revisions = {}
684 newestChange = 0
71b112d4
SH
685 if self.verbose:
686 print "Querying files for label %s" % label
687 for file in p4CmdList("files %s...@%s" % (self.depotPath, label)):
1f4ba1cb
SH
688 revisions[file["depotFile"]] = file["rev"]
689 change = int(file["change"])
690 if change > newestChange:
691 newestChange = change
692
9bda3a85
SH
693 self.labels[newestChange] = [output, revisions]
694
695 if self.verbose:
696 print "Label changes: %s" % self.labels.keys()
1f4ba1cb 697
4b97ffb1 698 def getBranchMapping(self):
29bdbac1 699 self.projectName = self.depotPath[self.depotPath[:-1].rfind("/") + 1:]
4b97ffb1
SH
700
701 for info in p4CmdList("branches"):
702 details = p4Cmd("branch -o %s" % info["branch"])
703 viewIdx = 0
704 while details.has_key("View%s" % viewIdx):
705 paths = details["View%s" % viewIdx].split(" ")
706 viewIdx = viewIdx + 1
707 # require standard //depot/foo/... //depot/bar/... mapping
708 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
709 continue
710 source = paths[0]
711 destination = paths[1]
712 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
713 source = source[len(self.depotPath):-4]
714 destination = destination[len(self.depotPath):-4]
29bdbac1
SH
715 if destination not in self.knownBranches:
716 self.knownBranches[destination] = source
717 if source not in self.knownBranches:
718 self.knownBranches[source] = source
719
720 def listExistingP4GitBranches(self):
721 self.p4BranchesInGit = []
722
723 for line in mypopen("git rev-parse --symbolic --remotes").readlines():
724 if line.startswith("p4/") and line != "p4/HEAD\n":
725 branch = line[3:-1]
726 self.p4BranchesInGit.append(branch)
727 self.initialParents["refs/remotes/p4/" + branch] = parseRevision(line[:-1])
4b97ffb1 728
b984733c 729 def run(self, args):
8f872531 730 self.depotPath = ""
179caebf
SH
731 self.changeRange = ""
732 self.initialParent = ""
cd6cc0d3 733 self.previousDepotPath = ""
29bdbac1
SH
734 # map from branch depot path to parent branch
735 self.knownBranches = {}
736 self.initialParents = {}
737
faf1bd20
SH
738 createP4HeadRef = False;
739
29bdbac1
SH
740 if self.syncWithOrigin and gitBranchExists("origin") and gitBranchExists("refs/remotes/p4/master") and not self.detectBranches:
741 ### needs to be ported to multi branch import
179caebf 742
ef48f909
SH
743 print "Syncing with origin first as requested by calling git fetch origin"
744 system("git fetch origin")
745 [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
746 [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
747 if len(originPreviousDepotPath) > 0 and len(originP4Change) > 0 and len(p4Change) > 0:
748 if originPreviousDepotPath == p4PreviousDepotPath:
749 originP4Change = int(originP4Change)
750 p4Change = int(p4Change)
751 if originP4Change > p4Change:
752 print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change, p4Change)
753 system("git update-ref refs/remotes/p4/master origin");
754 else:
755 print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath, p4PreviousDepotPath)
756
569d1bd4 757 if len(self.branch) == 0:
48df6fd8 758 self.branch = "refs/remotes/p4/master"
c6d44cb1 759 if gitBranchExists("refs/heads/p4"):
48df6fd8 760 system("git update-ref %s refs/heads/p4" % self.branch)
48df6fd8 761 system("git branch -D p4");
faf1bd20 762 # create it /after/ importing, when master exists
05094f98 763 if not gitBranchExists("refs/remotes/p4/HEAD"):
faf1bd20 764 createP4HeadRef = True
967f72e2 765
33be3e65
SH
766 # this needs to be called after the conversion from heads/p4 to remotes/p4/master
767 self.listExistingP4GitBranches()
768 if len(self.p4BranchesInGit) > 1 and not self.silent:
769 print "Importing from/into multiple branches"
770 self.detectBranches = True
771
967f72e2 772 if len(args) == 0:
29bdbac1
SH
773 if not gitBranchExists(self.branch) and gitBranchExists("origin") and not self.detectBranches:
774 ### needs to be ported to multi branch import
967f72e2
SH
775 if not self.silent:
776 print "Creating %s branch in git repository based on origin" % self.branch
8ead4fda
SH
777 branch = self.branch
778 if not branch.startswith("refs"):
779 branch = "refs/heads/" + branch
780 system("git update-ref %s origin" % branch)
967f72e2 781
29bdbac1
SH
782 if self.verbose:
783 print "branches: %s" % self.p4BranchesInGit
784
785 p4Change = 0
786 for branch in self.p4BranchesInGit:
787 depotPath, change = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("refs/remotes/p4/" + branch))
788
789 if self.verbose:
790 print "path %s change %s" % (depotPath, change)
791
792 if len(depotPath) > 0 and len(change) > 0:
793 change = int(change) + 1
794 p4Change = max(p4Change, change)
795
796 if len(self.previousDepotPath) == 0:
797 self.previousDepotPath = depotPath
798 else:
799 i = 0
800 l = min(len(self.previousDepotPath), len(depotPath))
801 while i < l and self.previousDepotPath[i] == depotPath[i]:
802 i = i + 1
803 self.previousDepotPath = self.previousDepotPath[:i]
804
805 if p4Change > 0:
8f872531 806 self.depotPath = self.previousDepotPath
d5904674 807 self.changeRange = "@%s,#head" % p4Change
463e8af6 808 self.initialParent = parseRevision(self.branch)
341dc1c1 809 if not self.silent and not self.detectBranches:
967f72e2 810 print "Performing incremental import into %s git branch" % self.branch
569d1bd4 811
f9162f6a
SH
812 if not self.branch.startswith("refs/"):
813 self.branch = "refs/heads/" + self.branch
179caebf 814
8f872531
SH
815 if len(self.depotPath) != 0:
816 self.depotPath = self.depotPath[:-1]
b984733c 817
8f872531 818 if len(args) == 0 and len(self.depotPath) != 0:
b984733c 819 if not self.silent:
8f872531 820 print "Depot path: %s" % self.depotPath
b984733c
SH
821 elif len(args) != 1:
822 return False
823 else:
8f872531
SH
824 if len(self.depotPath) != 0 and self.depotPath != args[0]:
825 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.depotPath, args[0])
b984733c 826 sys.exit(1)
8f872531 827 self.depotPath = args[0]
b984733c 828
b984733c
SH
829 self.revision = ""
830 self.users = {}
b984733c 831
8f872531
SH
832 if self.depotPath.find("@") != -1:
833 atIdx = self.depotPath.index("@")
834 self.changeRange = self.depotPath[atIdx:]
b984733c
SH
835 if self.changeRange == "@all":
836 self.changeRange = ""
837 elif self.changeRange.find(",") == -1:
838 self.revision = self.changeRange
839 self.changeRange = ""
8f872531
SH
840 self.depotPath = self.depotPath[0:atIdx]
841 elif self.depotPath.find("#") != -1:
842 hashIdx = self.depotPath.index("#")
843 self.revision = self.depotPath[hashIdx:]
844 self.depotPath = self.depotPath[0:hashIdx]
b984733c
SH
845 elif len(self.previousDepotPath) == 0:
846 self.revision = "#head"
847
8f872531
SH
848 if self.depotPath.endswith("..."):
849 self.depotPath = self.depotPath[:-3]
b984733c 850
8f872531
SH
851 if not self.depotPath.endswith("/"):
852 self.depotPath += "/"
b984733c 853
b607e71e 854 self.loadUserMapFromCache()
cb53e1f8
SH
855 self.labels = {}
856 if self.detectLabels:
857 self.getLabels();
b984733c 858
4b97ffb1
SH
859 if self.detectBranches:
860 self.getBranchMapping();
29bdbac1
SH
861 if self.verbose:
862 print "p4-git branches: %s" % self.p4BranchesInGit
863 print "initial parents: %s" % self.initialParents
864 for b in self.p4BranchesInGit:
865 if b != "master":
866 b = b[len(self.projectName):]
867 self.createdBranches.add(b)
4b97ffb1 868
f291b4e3 869 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
b984733c 870
08483580
SH
871 importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
872 self.gitOutput = importProcess.stdout
873 self.gitStream = importProcess.stdin
874 self.gitError = importProcess.stderr
b984733c
SH
875
876 if len(self.revision) > 0:
8f872531 877 print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
b984733c
SH
878
879 details = { "user" : "git perforce import user", "time" : int(time.time()) }
8f872531 880 details["desc"] = "Initial import of %s from the state at revision %s" % (self.depotPath, self.revision)
b984733c
SH
881 details["change"] = self.revision
882 newestRevision = 0
883
884 fileCnt = 0
8f872531 885 for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
b984733c
SH
886 change = int(info["change"])
887 if change > newestRevision:
888 newestRevision = change
889
890 if info["action"] == "delete":
c45b1cfe
SH
891 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
892 #fileCnt = fileCnt + 1
b984733c
SH
893 continue
894
895 for prop in [ "depotFile", "rev", "action", "type" ]:
896 details["%s%s" % (prop, fileCnt)] = info[prop]
897
898 fileCnt = fileCnt + 1
899
900 details["change"] = newestRevision
901
902 try:
8f872531 903 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
c715706b 904 except IOError:
fd4ca86a 905 print "IO error with git fast-import. Is your git version recent enough?"
b984733c
SH
906 print self.gitError.read()
907
908 else:
909 changes = []
910
0828ab14 911 if len(self.changesFile) > 0:
b984733c
SH
912 output = open(self.changesFile).readlines()
913 changeSet = Set()
914 for line in output:
915 changeSet.add(int(line))
916
917 for change in changeSet:
918 changes.append(change)
919
920 changes.sort()
921 else:
29bdbac1
SH
922 if self.verbose:
923 print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
caace111 924 output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines()
b984733c
SH
925
926 for line in output:
927 changeNum = line.split(" ")[1]
928 changes.append(changeNum)
929
930 changes.reverse()
931
932 if len(changes) == 0:
0828ab14 933 if not self.silent:
341dc1c1 934 print "No changes to import!"
1f52af6c 935 return True
b984733c 936
341dc1c1
SH
937 self.updatedBranches = set()
938
b984733c
SH
939 cnt = 1
940 for change in changes:
941 description = p4Cmd("describe %s" % change)
942
0828ab14 943 if not self.silent:
341dc1c1 944 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
b984733c
SH
945 sys.stdout.flush()
946 cnt = cnt + 1
947
948 try:
b984733c 949 if self.detectBranches:
71b112d4 950 branches = self.splitFilesIntoBranches(description)
d5904674 951 for branch in branches.keys():
8f872531 952 branchPrefix = self.depotPath + branch + "/"
b984733c 953
b984733c 954 parent = ""
4b97ffb1 955
d5904674 956 filesForCommit = branches[branch]
4b97ffb1 957
29bdbac1
SH
958 if self.verbose:
959 print "branch is %s" % branch
960
341dc1c1
SH
961 self.updatedBranches.add(branch)
962
8f9b2e08 963 if branch not in self.createdBranches:
b984733c 964 self.createdBranches.add(branch)
4b97ffb1 965 parent = self.knownBranches[branch]
b984733c
SH
966 if parent == branch:
967 parent = ""
29bdbac1
SH
968 elif self.verbose:
969 print "parent determined through known branches: %s" % parent
b984733c 970
8f9b2e08
SH
971 # main branch? use master
972 if branch == "main":
973 branch = "master"
974 else:
29bdbac1 975 branch = self.projectName + branch
8f9b2e08
SH
976
977 if parent == "main":
978 parent = "master"
979 elif len(parent) > 0:
29bdbac1 980 parent = self.projectName + parent
8f9b2e08 981
4b97ffb1 982 branch = "refs/remotes/p4/" + branch
b984733c 983 if len(parent) > 0:
4b97ffb1 984 parent = "refs/remotes/p4/" + parent
29bdbac1
SH
985
986 if self.verbose:
987 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
988
989 if len(parent) == 0 and branch in self.initialParents:
990 parent = self.initialParents[branch]
991 del self.initialParents[branch]
992
71b112d4 993 self.commit(description, filesForCommit, branch, branchPrefix, parent)
b984733c 994 else:
71b112d4 995 files = self.extractFilesFromCommit(description)
8f872531 996 self.commit(description, files, self.branch, self.depotPath, self.initialParent)
b984733c
SH
997 self.initialParent = ""
998 except IOError:
999 print self.gitError.read()
1000 sys.exit(1)
1001
341dc1c1
SH
1002 if not self.silent:
1003 print ""
1004 if len(self.updatedBranches) > 0:
1005 sys.stdout.write("Updated branches: ")
1006 for b in self.updatedBranches:
1007 sys.stdout.write("%s " % b)
1008 sys.stdout.write("\n")
b984733c 1009
b984733c
SH
1010
1011 self.gitStream.close()
29bdbac1
SH
1012 if importProcess.wait() != 0:
1013 die("fast-import failed: %s" % self.gitError.read())
b984733c
SH
1014 self.gitOutput.close()
1015 self.gitError.close()
1016
faf1bd20
SH
1017 if createP4HeadRef:
1018 system("git symbolic-ref refs/remotes/p4/HEAD %s" % self.branch)
1019
b984733c
SH
1020 return True
1021
01ce1fe9
SH
1022class P4Rebase(Command):
1023 def __init__(self):
1024 Command.__init__(self)
ef48f909 1025 self.options = [ optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true") ]
01ce1fe9 1026 self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it"
ef48f909 1027 self.syncWithOrigin = False
01ce1fe9
SH
1028
1029 def run(self, args):
1030 sync = P4Sync()
ef48f909 1031 sync.syncWithOrigin = self.syncWithOrigin
01ce1fe9
SH
1032 sync.run([])
1033 print "Rebasing the current branch"
caace111 1034 oldHead = mypopen("git rev-parse HEAD").read()[:-1]
01ce1fe9 1035 system("git rebase p4")
1f52af6c 1036 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
01ce1fe9
SH
1037 return True
1038
f9a3a4f7
SH
1039class P4Clone(P4Sync):
1040 def __init__(self):
1041 P4Sync.__init__(self)
1042 self.description = "Creates a new git repository and imports from Perforce into it"
1043 self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1044 self.needsGit = False
f9a3a4f7
SH
1045
1046 def run(self, args):
59fa4171
SH
1047 global gitdir
1048
f9a3a4f7
SH
1049 if len(args) < 1:
1050 return False
1051 depotPath = args[0]
1052 dir = ""
1053 if len(args) == 2:
1054 dir = args[1]
1055 elif len(args) > 2:
1056 return False
1057
1058 if not depotPath.startswith("//"):
1059 return False
1060
1061 if len(dir) == 0:
1062 dir = depotPath
1063 atPos = dir.rfind("@")
1064 if atPos != -1:
1065 dir = dir[0:atPos]
1066 hashPos = dir.rfind("#")
1067 if hashPos != -1:
1068 dir = dir[0:hashPos]
1069
1070 if dir.endswith("..."):
1071 dir = dir[:-3]
1072
1073 if dir.endswith("/"):
1074 dir = dir[:-1]
1075
1076 slashPos = dir.rfind("/")
1077 if slashPos != -1:
1078 dir = dir[slashPos + 1:]
1079
1080 print "Importing from %s into %s" % (depotPath, dir)
1081 os.makedirs(dir)
1082 os.chdir(dir)
1083 system("git init")
64ffb06a 1084 gitdir = os.getcwd() + "/.git"
f9a3a4f7
SH
1085 if not P4Sync.run(self, [depotPath]):
1086 return False
f9a3a4f7 1087 if self.branch != "master":
8f9b2e08
SH
1088 if gitBranchExists("refs/remotes/p4/master"):
1089 system("git branch master refs/remotes/p4/master")
1090 system("git checkout -f")
1091 else:
1092 print "Could not detect main branch. No checkout/master branch created."
f9a3a4f7
SH
1093 return True
1094
b984733c
SH
1095class HelpFormatter(optparse.IndentedHelpFormatter):
1096 def __init__(self):
1097 optparse.IndentedHelpFormatter.__init__(self)
1098
1099 def format_description(self, description):
1100 if description:
1101 return description + "\n"
1102 else:
1103 return ""
4f5cf76a 1104
86949eef
SH
1105def printUsage(commands):
1106 print "usage: %s <command> [options]" % sys.argv[0]
1107 print ""
1108 print "valid commands: %s" % ", ".join(commands)
1109 print ""
1110 print "Try %s <command> --help for command specific help." % sys.argv[0]
1111 print ""
1112
1113commands = {
1114 "debug" : P4Debug(),
711544b0 1115 "submit" : P4Submit(),
01ce1fe9 1116 "sync" : P4Sync(),
f9a3a4f7
SH
1117 "rebase" : P4Rebase(),
1118 "clone" : P4Clone()
86949eef
SH
1119}
1120
1121if len(sys.argv[1:]) == 0:
1122 printUsage(commands.keys())
1123 sys.exit(2)
1124
1125cmd = ""
1126cmdName = sys.argv[1]
1127try:
1128 cmd = commands[cmdName]
1129except KeyError:
1130 print "unknown command %s" % cmdName
1131 print ""
1132 printUsage(commands.keys())
1133 sys.exit(2)
1134
4f5cf76a
SH
1135options = cmd.options
1136cmd.gitdir = gitdir
4f5cf76a 1137
e20a9e53 1138args = sys.argv[2:]
86949eef 1139
e20a9e53
SH
1140if len(options) > 0:
1141 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1142
1143 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1144 options,
1145 description = cmd.description,
1146 formatter = HelpFormatter())
1147
1148 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
86949eef 1149
8910ac0e
SH
1150if cmd.needsGit:
1151 gitdir = cmd.gitdir
1152 if len(gitdir) == 0:
1153 gitdir = ".git"
1154 if not isValidGitDir(gitdir):
81f2373f 1155 gitdir = mypopen("git rev-parse --git-dir").read()[:-1]
dc1a93b6 1156 if os.path.exists(gitdir):
5c4153e4
SH
1157 cdup = mypopen("git rev-parse --show-cdup").read()[:-1];
1158 if len(cdup) > 0:
1159 os.chdir(cdup);
4f5cf76a 1160
8910ac0e
SH
1161 if not isValidGitDir(gitdir):
1162 if isValidGitDir(gitdir + "/.git"):
1163 gitdir += "/.git"
1164 else:
1165 die("fatal: cannot locate git repository at %s" % gitdir)
4f5cf76a 1166
8910ac0e 1167 os.environ["GIT_DIR"] = gitdir
4f5cf76a 1168
b984733c
SH
1169if not cmd.run(args):
1170 parser.print_help()
1171