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