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