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