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