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