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