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