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