PageRenderTime 38ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/git-p4.py

https://bitbucket.org/bluezoo/git
Python | 3242 lines | 3134 code | 61 blank | 47 comment | 125 complexity | 9c3354574a939b9049b165a69b54a968 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, Apache-2.0, BSD-2-Clause
  1. #!/usr/bin/env python
  2. #
  3. # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
  4. #
  5. # Author: Simon Hausmann <simon@lst.de>
  6. # Copyright: 2007 Simon Hausmann <simon@lst.de>
  7. # 2007 Trolltech ASA
  8. # License: MIT <http://www.opensource.org/licenses/mit-license.php>
  9. #
  10. import optparse, sys, os, marshal, subprocess, shelve
  11. import tempfile, getopt, os.path, time, platform
  12. import re, shutil
  13. verbose = False
  14. # Only labels/tags matching this will be imported/exported
  15. defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$'
  16. def p4_build_cmd(cmd):
  17. """Build a suitable p4 command line.
  18. This consolidates building and returning a p4 command line into one
  19. location. It means that hooking into the environment, or other configuration
  20. can be done more easily.
  21. """
  22. real_cmd = ["p4"]
  23. user = gitConfig("git-p4.user")
  24. if len(user) > 0:
  25. real_cmd += ["-u",user]
  26. password = gitConfig("git-p4.password")
  27. if len(password) > 0:
  28. real_cmd += ["-P", password]
  29. port = gitConfig("git-p4.port")
  30. if len(port) > 0:
  31. real_cmd += ["-p", port]
  32. host = gitConfig("git-p4.host")
  33. if len(host) > 0:
  34. real_cmd += ["-H", host]
  35. client = gitConfig("git-p4.client")
  36. if len(client) > 0:
  37. real_cmd += ["-c", client]
  38. if isinstance(cmd,basestring):
  39. real_cmd = ' '.join(real_cmd) + ' ' + cmd
  40. else:
  41. real_cmd += cmd
  42. return real_cmd
  43. def chdir(dir):
  44. # P4 uses the PWD environment variable rather than getcwd(). Since we're
  45. # not using the shell, we have to set it ourselves. This path could
  46. # be relative, so go there first, then figure out where we ended up.
  47. os.chdir(dir)
  48. os.environ['PWD'] = os.getcwd()
  49. def die(msg):
  50. if verbose:
  51. raise Exception(msg)
  52. else:
  53. sys.stderr.write(msg + "\n")
  54. sys.exit(1)
  55. def write_pipe(c, stdin):
  56. if verbose:
  57. sys.stderr.write('Writing pipe: %s\n' % str(c))
  58. expand = isinstance(c,basestring)
  59. p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand)
  60. pipe = p.stdin
  61. val = pipe.write(stdin)
  62. pipe.close()
  63. if p.wait():
  64. die('Command failed: %s' % str(c))
  65. return val
  66. def p4_write_pipe(c, stdin):
  67. real_cmd = p4_build_cmd(c)
  68. return write_pipe(real_cmd, stdin)
  69. def read_pipe(c, ignore_error=False):
  70. if verbose:
  71. sys.stderr.write('Reading pipe: %s\n' % str(c))
  72. expand = isinstance(c,basestring)
  73. p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)
  74. pipe = p.stdout
  75. val = pipe.read()
  76. if p.wait() and not ignore_error:
  77. die('Command failed: %s' % str(c))
  78. return val
  79. def p4_read_pipe(c, ignore_error=False):
  80. real_cmd = p4_build_cmd(c)
  81. return read_pipe(real_cmd, ignore_error)
  82. def read_pipe_lines(c):
  83. if verbose:
  84. sys.stderr.write('Reading pipe: %s\n' % str(c))
  85. expand = isinstance(c, basestring)
  86. p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)
  87. pipe = p.stdout
  88. val = pipe.readlines()
  89. if pipe.close() or p.wait():
  90. die('Command failed: %s' % str(c))
  91. return val
  92. def p4_read_pipe_lines(c):
  93. """Specifically invoke p4 on the command supplied. """
  94. real_cmd = p4_build_cmd(c)
  95. return read_pipe_lines(real_cmd)
  96. def p4_has_command(cmd):
  97. """Ask p4 for help on this command. If it returns an error, the
  98. command does not exist in this version of p4."""
  99. real_cmd = p4_build_cmd(["help", cmd])
  100. p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE,
  101. stderr=subprocess.PIPE)
  102. p.communicate()
  103. return p.returncode == 0
  104. def p4_has_move_command():
  105. """See if the move command exists, that it supports -k, and that
  106. it has not been administratively disabled. The arguments
  107. must be correct, but the filenames do not have to exist. Use
  108. ones with wildcards so even if they exist, it will fail."""
  109. if not p4_has_command("move"):
  110. return False
  111. cmd = p4_build_cmd(["move", "-k", "@from", "@to"])
  112. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  113. (out, err) = p.communicate()
  114. # return code will be 1 in either case
  115. if err.find("Invalid option") >= 0:
  116. return False
  117. if err.find("disabled") >= 0:
  118. return False
  119. # assume it failed because @... was invalid changelist
  120. return True
  121. def system(cmd):
  122. expand = isinstance(cmd,basestring)
  123. if verbose:
  124. sys.stderr.write("executing %s\n" % str(cmd))
  125. subprocess.check_call(cmd, shell=expand)
  126. def p4_system(cmd):
  127. """Specifically invoke p4 as the system command. """
  128. real_cmd = p4_build_cmd(cmd)
  129. expand = isinstance(real_cmd, basestring)
  130. subprocess.check_call(real_cmd, shell=expand)
  131. def p4_integrate(src, dest):
  132. p4_system(["integrate", "-Dt", wildcard_encode(src), wildcard_encode(dest)])
  133. def p4_sync(f, *options):
  134. p4_system(["sync"] + list(options) + [wildcard_encode(f)])
  135. def p4_add(f):
  136. # forcibly add file names with wildcards
  137. if wildcard_present(f):
  138. p4_system(["add", "-f", f])
  139. else:
  140. p4_system(["add", f])
  141. def p4_delete(f):
  142. p4_system(["delete", wildcard_encode(f)])
  143. def p4_edit(f):
  144. p4_system(["edit", wildcard_encode(f)])
  145. def p4_revert(f):
  146. p4_system(["revert", wildcard_encode(f)])
  147. def p4_reopen(type, f):
  148. p4_system(["reopen", "-t", type, wildcard_encode(f)])
  149. def p4_move(src, dest):
  150. p4_system(["move", "-k", wildcard_encode(src), wildcard_encode(dest)])
  151. def p4_describe(change):
  152. """Make sure it returns a valid result by checking for
  153. the presence of field "time". Return a dict of the
  154. results."""
  155. ds = p4CmdList(["describe", "-s", str(change)])
  156. if len(ds) != 1:
  157. die("p4 describe -s %d did not return 1 result: %s" % (change, str(ds)))
  158. d = ds[0]
  159. if "p4ExitCode" in d:
  160. die("p4 describe -s %d exited with %d: %s" % (change, d["p4ExitCode"],
  161. str(d)))
  162. if "code" in d:
  163. if d["code"] == "error":
  164. die("p4 describe -s %d returned error code: %s" % (change, str(d)))
  165. if "time" not in d:
  166. die("p4 describe -s %d returned no \"time\": %s" % (change, str(d)))
  167. return d
  168. #
  169. # Canonicalize the p4 type and return a tuple of the
  170. # base type, plus any modifiers. See "p4 help filetypes"
  171. # for a list and explanation.
  172. #
  173. def split_p4_type(p4type):
  174. p4_filetypes_historical = {
  175. "ctempobj": "binary+Sw",
  176. "ctext": "text+C",
  177. "cxtext": "text+Cx",
  178. "ktext": "text+k",
  179. "kxtext": "text+kx",
  180. "ltext": "text+F",
  181. "tempobj": "binary+FSw",
  182. "ubinary": "binary+F",
  183. "uresource": "resource+F",
  184. "uxbinary": "binary+Fx",
  185. "xbinary": "binary+x",
  186. "xltext": "text+Fx",
  187. "xtempobj": "binary+Swx",
  188. "xtext": "text+x",
  189. "xunicode": "unicode+x",
  190. "xutf16": "utf16+x",
  191. }
  192. if p4type in p4_filetypes_historical:
  193. p4type = p4_filetypes_historical[p4type]
  194. mods = ""
  195. s = p4type.split("+")
  196. base = s[0]
  197. mods = ""
  198. if len(s) > 1:
  199. mods = s[1]
  200. return (base, mods)
  201. #
  202. # return the raw p4 type of a file (text, text+ko, etc)
  203. #
  204. def p4_type(file):
  205. results = p4CmdList(["fstat", "-T", "headType", file])
  206. return results[0]['headType']
  207. #
  208. # Given a type base and modifier, return a regexp matching
  209. # the keywords that can be expanded in the file
  210. #
  211. def p4_keywords_regexp_for_type(base, type_mods):
  212. if base in ("text", "unicode", "binary"):
  213. kwords = None
  214. if "ko" in type_mods:
  215. kwords = 'Id|Header'
  216. elif "k" in type_mods:
  217. kwords = 'Id|Header|Author|Date|DateTime|Change|File|Revision'
  218. else:
  219. return None
  220. pattern = r"""
  221. \$ # Starts with a dollar, followed by...
  222. (%s) # one of the keywords, followed by...
  223. (:[^$\n]+)? # possibly an old expansion, followed by...
  224. \$ # another dollar
  225. """ % kwords
  226. return pattern
  227. else:
  228. return None
  229. #
  230. # Given a file, return a regexp matching the possible
  231. # RCS keywords that will be expanded, or None for files
  232. # with kw expansion turned off.
  233. #
  234. def p4_keywords_regexp_for_file(file):
  235. if not os.path.exists(file):
  236. return None
  237. else:
  238. (type_base, type_mods) = split_p4_type(p4_type(file))
  239. return p4_keywords_regexp_for_type(type_base, type_mods)
  240. def setP4ExecBit(file, mode):
  241. # Reopens an already open file and changes the execute bit to match
  242. # the execute bit setting in the passed in mode.
  243. p4Type = "+x"
  244. if not isModeExec(mode):
  245. p4Type = getP4OpenedType(file)
  246. p4Type = re.sub('^([cku]?)x(.*)', '\\1\\2', p4Type)
  247. p4Type = re.sub('(.*?\+.*?)x(.*?)', '\\1\\2', p4Type)
  248. if p4Type[-1] == "+":
  249. p4Type = p4Type[0:-1]
  250. p4_reopen(p4Type, file)
  251. def getP4OpenedType(file):
  252. # Returns the perforce file type for the given file.
  253. result = p4_read_pipe(["opened", wildcard_encode(file)])
  254. match = re.match(".*\((.+)\)\r?$", result)
  255. if match:
  256. return match.group(1)
  257. else:
  258. die("Could not determine file type for %s (result: '%s')" % (file, result))
  259. # Return the set of all p4 labels
  260. def getP4Labels(depotPaths):
  261. labels = set()
  262. if isinstance(depotPaths,basestring):
  263. depotPaths = [depotPaths]
  264. for l in p4CmdList(["labels"] + ["%s..." % p for p in depotPaths]):
  265. label = l['label']
  266. labels.add(label)
  267. return labels
  268. # Return the set of all git tags
  269. def getGitTags():
  270. gitTags = set()
  271. for line in read_pipe_lines(["git", "tag"]):
  272. tag = line.strip()
  273. gitTags.add(tag)
  274. return gitTags
  275. def diffTreePattern():
  276. # This is a simple generator for the diff tree regex pattern. This could be
  277. # a class variable if this and parseDiffTreeEntry were a part of a class.
  278. pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)')
  279. while True:
  280. yield pattern
  281. def parseDiffTreeEntry(entry):
  282. """Parses a single diff tree entry into its component elements.
  283. See git-diff-tree(1) manpage for details about the format of the diff
  284. output. This method returns a dictionary with the following elements:
  285. src_mode - The mode of the source file
  286. dst_mode - The mode of the destination file
  287. src_sha1 - The sha1 for the source file
  288. dst_sha1 - The sha1 fr the destination file
  289. status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc)
  290. status_score - The score for the status (applicable for 'C' and 'R'
  291. statuses). This is None if there is no score.
  292. src - The path for the source file.
  293. dst - The path for the destination file. This is only present for
  294. copy or renames. If it is not present, this is None.
  295. If the pattern is not matched, None is returned."""
  296. match = diffTreePattern().next().match(entry)
  297. if match:
  298. return {
  299. 'src_mode': match.group(1),
  300. 'dst_mode': match.group(2),
  301. 'src_sha1': match.group(3),
  302. 'dst_sha1': match.group(4),
  303. 'status': match.group(5),
  304. 'status_score': match.group(6),
  305. 'src': match.group(7),
  306. 'dst': match.group(10)
  307. }
  308. return None
  309. def isModeExec(mode):
  310. # Returns True if the given git mode represents an executable file,
  311. # otherwise False.
  312. return mode[-3:] == "755"
  313. def isModeExecChanged(src_mode, dst_mode):
  314. return isModeExec(src_mode) != isModeExec(dst_mode)
  315. def p4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None):
  316. if isinstance(cmd,basestring):
  317. cmd = "-G " + cmd
  318. expand = True
  319. else:
  320. cmd = ["-G"] + cmd
  321. expand = False
  322. cmd = p4_build_cmd(cmd)
  323. if verbose:
  324. sys.stderr.write("Opening pipe: %s\n" % str(cmd))
  325. # Use a temporary file to avoid deadlocks without
  326. # subprocess.communicate(), which would put another copy
  327. # of stdout into memory.
  328. stdin_file = None
  329. if stdin is not None:
  330. stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode)
  331. if isinstance(stdin,basestring):
  332. stdin_file.write(stdin)
  333. else:
  334. for i in stdin:
  335. stdin_file.write(i + '\n')
  336. stdin_file.flush()
  337. stdin_file.seek(0)
  338. p4 = subprocess.Popen(cmd,
  339. shell=expand,
  340. stdin=stdin_file,
  341. stdout=subprocess.PIPE)
  342. result = []
  343. try:
  344. while True:
  345. entry = marshal.load(p4.stdout)
  346. if cb is not None:
  347. cb(entry)
  348. else:
  349. result.append(entry)
  350. except EOFError:
  351. pass
  352. exitCode = p4.wait()
  353. if exitCode != 0:
  354. entry = {}
  355. entry["p4ExitCode"] = exitCode
  356. result.append(entry)
  357. return result
  358. def p4Cmd(cmd):
  359. list = p4CmdList(cmd)
  360. result = {}
  361. for entry in list:
  362. result.update(entry)
  363. return result;
  364. def p4Where(depotPath):
  365. if not depotPath.endswith("/"):
  366. depotPath += "/"
  367. depotPath = depotPath + "..."
  368. outputList = p4CmdList(["where", depotPath])
  369. output = None
  370. for entry in outputList:
  371. if "depotFile" in entry:
  372. if entry["depotFile"] == depotPath:
  373. output = entry
  374. break
  375. elif "data" in entry:
  376. data = entry.get("data")
  377. space = data.find(" ")
  378. if data[:space] == depotPath:
  379. output = entry
  380. break
  381. if output == None:
  382. return ""
  383. if output["code"] == "error":
  384. return ""
  385. clientPath = ""
  386. if "path" in output:
  387. clientPath = output.get("path")
  388. elif "data" in output:
  389. data = output.get("data")
  390. lastSpace = data.rfind(" ")
  391. clientPath = data[lastSpace + 1:]
  392. if clientPath.endswith("..."):
  393. clientPath = clientPath[:-3]
  394. return clientPath
  395. def currentGitBranch():
  396. return read_pipe("git name-rev HEAD").split(" ")[1].strip()
  397. def isValidGitDir(path):
  398. if (os.path.exists(path + "/HEAD")
  399. and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")):
  400. return True;
  401. return False
  402. def parseRevision(ref):
  403. return read_pipe("git rev-parse %s" % ref).strip()
  404. def branchExists(ref):
  405. rev = read_pipe(["git", "rev-parse", "-q", "--verify", ref],
  406. ignore_error=True)
  407. return len(rev) > 0
  408. def extractLogMessageFromGitCommit(commit):
  409. logMessage = ""
  410. ## fixme: title is first line of commit, not 1st paragraph.
  411. foundTitle = False
  412. for log in read_pipe_lines("git cat-file commit %s" % commit):
  413. if not foundTitle:
  414. if len(log) == 1:
  415. foundTitle = True
  416. continue
  417. logMessage += log
  418. return logMessage
  419. def extractSettingsGitLog(log):
  420. values = {}
  421. for line in log.split("\n"):
  422. line = line.strip()
  423. m = re.search (r"^ *\[git-p4: (.*)\]$", line)
  424. if not m:
  425. continue
  426. assignments = m.group(1).split (':')
  427. for a in assignments:
  428. vals = a.split ('=')
  429. key = vals[0].strip()
  430. val = ('='.join (vals[1:])).strip()
  431. if val.endswith ('\"') and val.startswith('"'):
  432. val = val[1:-1]
  433. values[key] = val
  434. paths = values.get("depot-paths")
  435. if not paths:
  436. paths = values.get("depot-path")
  437. if paths:
  438. values['depot-paths'] = paths.split(',')
  439. return values
  440. def gitBranchExists(branch):
  441. proc = subprocess.Popen(["git", "rev-parse", branch],
  442. stderr=subprocess.PIPE, stdout=subprocess.PIPE);
  443. return proc.wait() == 0;
  444. _gitConfig = {}
  445. def gitConfig(key, args = None): # set args to "--bool", for instance
  446. if not _gitConfig.has_key(key):
  447. argsFilter = ""
  448. if args != None:
  449. argsFilter = "%s " % args
  450. cmd = "git config %s%s" % (argsFilter, key)
  451. _gitConfig[key] = read_pipe(cmd, ignore_error=True).strip()
  452. return _gitConfig[key]
  453. def gitConfigList(key):
  454. if not _gitConfig.has_key(key):
  455. _gitConfig[key] = read_pipe("git config --get-all %s" % key, ignore_error=True).strip().split(os.linesep)
  456. return _gitConfig[key]
  457. def p4BranchesInGit(branchesAreInRemotes = True):
  458. branches = {}
  459. cmdline = "git rev-parse --symbolic "
  460. if branchesAreInRemotes:
  461. cmdline += " --remotes"
  462. else:
  463. cmdline += " --branches"
  464. for line in read_pipe_lines(cmdline):
  465. line = line.strip()
  466. ## only import to p4/
  467. if not line.startswith('p4/') or line == "p4/HEAD":
  468. continue
  469. branch = line
  470. # strip off p4
  471. branch = re.sub ("^p4/", "", line)
  472. branches[branch] = parseRevision(line)
  473. return branches
  474. def findUpstreamBranchPoint(head = "HEAD"):
  475. branches = p4BranchesInGit()
  476. # map from depot-path to branch name
  477. branchByDepotPath = {}
  478. for branch in branches.keys():
  479. tip = branches[branch]
  480. log = extractLogMessageFromGitCommit(tip)
  481. settings = extractSettingsGitLog(log)
  482. if settings.has_key("depot-paths"):
  483. paths = ",".join(settings["depot-paths"])
  484. branchByDepotPath[paths] = "remotes/p4/" + branch
  485. settings = None
  486. parent = 0
  487. while parent < 65535:
  488. commit = head + "~%s" % parent
  489. log = extractLogMessageFromGitCommit(commit)
  490. settings = extractSettingsGitLog(log)
  491. if settings.has_key("depot-paths"):
  492. paths = ",".join(settings["depot-paths"])
  493. if branchByDepotPath.has_key(paths):
  494. return [branchByDepotPath[paths], settings]
  495. parent = parent + 1
  496. return ["", settings]
  497. def createOrUpdateBranchesFromOrigin(localRefPrefix = "refs/remotes/p4/", silent=True):
  498. if not silent:
  499. print ("Creating/updating branch(es) in %s based on origin branch(es)"
  500. % localRefPrefix)
  501. originPrefix = "origin/p4/"
  502. for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
  503. line = line.strip()
  504. if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
  505. continue
  506. headName = line[len(originPrefix):]
  507. remoteHead = localRefPrefix + headName
  508. originHead = line
  509. original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
  510. if (not original.has_key('depot-paths')
  511. or not original.has_key('change')):
  512. continue
  513. update = False
  514. if not gitBranchExists(remoteHead):
  515. if verbose:
  516. print "creating %s" % remoteHead
  517. update = True
  518. else:
  519. settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
  520. if settings.has_key('change') > 0:
  521. if settings['depot-paths'] == original['depot-paths']:
  522. originP4Change = int(original['change'])
  523. p4Change = int(settings['change'])
  524. if originP4Change > p4Change:
  525. print ("%s (%s) is newer than %s (%s). "
  526. "Updating p4 branch from origin."
  527. % (originHead, originP4Change,
  528. remoteHead, p4Change))
  529. update = True
  530. else:
  531. print ("Ignoring: %s was imported from %s while "
  532. "%s was imported from %s"
  533. % (originHead, ','.join(original['depot-paths']),
  534. remoteHead, ','.join(settings['depot-paths'])))
  535. if update:
  536. system("git update-ref %s %s" % (remoteHead, originHead))
  537. def originP4BranchesExist():
  538. return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
  539. def p4ChangesForPaths(depotPaths, changeRange):
  540. assert depotPaths
  541. cmd = ['changes']
  542. for p in depotPaths:
  543. cmd += ["%s...%s" % (p, changeRange)]
  544. output = p4_read_pipe_lines(cmd)
  545. changes = {}
  546. for line in output:
  547. changeNum = int(line.split(" ")[1])
  548. changes[changeNum] = True
  549. changelist = changes.keys()
  550. changelist.sort()
  551. return changelist
  552. def p4PathStartsWith(path, prefix):
  553. # This method tries to remedy a potential mixed-case issue:
  554. #
  555. # If UserA adds //depot/DirA/file1
  556. # and UserB adds //depot/dira/file2
  557. #
  558. # we may or may not have a problem. If you have core.ignorecase=true,
  559. # we treat DirA and dira as the same directory
  560. ignorecase = gitConfig("core.ignorecase", "--bool") == "true"
  561. if ignorecase:
  562. return path.lower().startswith(prefix.lower())
  563. return path.startswith(prefix)
  564. def getClientSpec():
  565. """Look at the p4 client spec, create a View() object that contains
  566. all the mappings, and return it."""
  567. specList = p4CmdList("client -o")
  568. if len(specList) != 1:
  569. die('Output from "client -o" is %d lines, expecting 1' %
  570. len(specList))
  571. # dictionary of all client parameters
  572. entry = specList[0]
  573. # just the keys that start with "View"
  574. view_keys = [ k for k in entry.keys() if k.startswith("View") ]
  575. # hold this new View
  576. view = View()
  577. # append the lines, in order, to the view
  578. for view_num in range(len(view_keys)):
  579. k = "View%d" % view_num
  580. if k not in view_keys:
  581. die("Expected view key %s missing" % k)
  582. view.append(entry[k])
  583. return view
  584. def getClientRoot():
  585. """Grab the client directory."""
  586. output = p4CmdList("client -o")
  587. if len(output) != 1:
  588. die('Output from "client -o" is %d lines, expecting 1' % len(output))
  589. entry = output[0]
  590. if "Root" not in entry:
  591. die('Client has no "Root"')
  592. return entry["Root"]
  593. #
  594. # P4 wildcards are not allowed in filenames. P4 complains
  595. # if you simply add them, but you can force it with "-f", in
  596. # which case it translates them into %xx encoding internally.
  597. #
  598. def wildcard_decode(path):
  599. # Search for and fix just these four characters. Do % last so
  600. # that fixing it does not inadvertently create new %-escapes.
  601. # Cannot have * in a filename in windows; untested as to
  602. # what p4 would do in such a case.
  603. if not platform.system() == "Windows":
  604. path = path.replace("%2A", "*")
  605. path = path.replace("%23", "#") \
  606. .replace("%40", "@") \
  607. .replace("%25", "%")
  608. return path
  609. def wildcard_encode(path):
  610. # do % first to avoid double-encoding the %s introduced here
  611. path = path.replace("%", "%25") \
  612. .replace("*", "%2A") \
  613. .replace("#", "%23") \
  614. .replace("@", "%40")
  615. return path
  616. def wildcard_present(path):
  617. return path.translate(None, "*#@%") != path
  618. class Command:
  619. def __init__(self):
  620. self.usage = "usage: %prog [options]"
  621. self.needsGit = True
  622. self.verbose = False
  623. class P4UserMap:
  624. def __init__(self):
  625. self.userMapFromPerforceServer = False
  626. self.myP4UserId = None
  627. def p4UserId(self):
  628. if self.myP4UserId:
  629. return self.myP4UserId
  630. results = p4CmdList("user -o")
  631. for r in results:
  632. if r.has_key('User'):
  633. self.myP4UserId = r['User']
  634. return r['User']
  635. die("Could not find your p4 user id")
  636. def p4UserIsMe(self, p4User):
  637. # return True if the given p4 user is actually me
  638. me = self.p4UserId()
  639. if not p4User or p4User != me:
  640. return False
  641. else:
  642. return True
  643. def getUserCacheFilename(self):
  644. home = os.environ.get("HOME", os.environ.get("USERPROFILE"))
  645. return home + "/.gitp4-usercache.txt"
  646. def getUserMapFromPerforceServer(self):
  647. if self.userMapFromPerforceServer:
  648. return
  649. self.users = {}
  650. self.emails = {}
  651. for output in p4CmdList("users"):
  652. if not output.has_key("User"):
  653. continue
  654. self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
  655. self.emails[output["Email"]] = output["User"]
  656. s = ''
  657. for (key, val) in self.users.items():
  658. s += "%s\t%s\n" % (key.expandtabs(1), val.expandtabs(1))
  659. open(self.getUserCacheFilename(), "wb").write(s)
  660. self.userMapFromPerforceServer = True
  661. def loadUserMapFromCache(self):
  662. self.users = {}
  663. self.userMapFromPerforceServer = False
  664. try:
  665. cache = open(self.getUserCacheFilename(), "rb")
  666. lines = cache.readlines()
  667. cache.close()
  668. for line in lines:
  669. entry = line.strip().split("\t")
  670. self.users[entry[0]] = entry[1]
  671. except IOError:
  672. self.getUserMapFromPerforceServer()
  673. class P4Debug(Command):
  674. def __init__(self):
  675. Command.__init__(self)
  676. self.options = []
  677. self.description = "A tool to debug the output of p4 -G."
  678. self.needsGit = False
  679. def run(self, args):
  680. j = 0
  681. for output in p4CmdList(args):
  682. print 'Element: %d' % j
  683. j += 1
  684. print output
  685. return True
  686. class P4RollBack(Command):
  687. def __init__(self):
  688. Command.__init__(self)
  689. self.options = [
  690. optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
  691. ]
  692. self.description = "A tool to debug the multi-branch import. Don't use :)"
  693. self.rollbackLocalBranches = False
  694. def run(self, args):
  695. if len(args) != 1:
  696. return False
  697. maxChange = int(args[0])
  698. if "p4ExitCode" in p4Cmd("changes -m 1"):
  699. die("Problems executing p4");
  700. if self.rollbackLocalBranches:
  701. refPrefix = "refs/heads/"
  702. lines = read_pipe_lines("git rev-parse --symbolic --branches")
  703. else:
  704. refPrefix = "refs/remotes/"
  705. lines = read_pipe_lines("git rev-parse --symbolic --remotes")
  706. for line in lines:
  707. if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
  708. line = line.strip()
  709. ref = refPrefix + line
  710. log = extractLogMessageFromGitCommit(ref)
  711. settings = extractSettingsGitLog(log)
  712. depotPaths = settings['depot-paths']
  713. change = settings['change']
  714. changed = False
  715. if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
  716. for p in depotPaths]))) == 0:
  717. print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
  718. system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
  719. continue
  720. while change and int(change) > maxChange:
  721. changed = True
  722. if self.verbose:
  723. print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
  724. system("git update-ref %s \"%s^\"" % (ref, ref))
  725. log = extractLogMessageFromGitCommit(ref)
  726. settings = extractSettingsGitLog(log)
  727. depotPaths = settings['depot-paths']
  728. change = settings['change']
  729. if changed:
  730. print "%s rewound to %s" % (ref, change)
  731. return True
  732. class P4Submit(Command, P4UserMap):
  733. conflict_behavior_choices = ("ask", "skip", "quit")
  734. def __init__(self):
  735. Command.__init__(self)
  736. P4UserMap.__init__(self)
  737. self.options = [
  738. optparse.make_option("--origin", dest="origin"),
  739. optparse.make_option("-M", dest="detectRenames", action="store_true"),
  740. # preserve the user, requires relevant p4 permissions
  741. optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),
  742. optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),
  743. optparse.make_option("--dry-run", "-n", dest="dry_run", action="store_true"),
  744. optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),
  745. optparse.make_option("--conflict", dest="conflict_behavior",
  746. choices=self.conflict_behavior_choices)
  747. ]
  748. self.description = "Submit changes from git to the perforce depot."
  749. self.usage += " [name of git branch to submit into perforce depot]"
  750. self.origin = ""
  751. self.detectRenames = False
  752. self.preserveUser = gitConfig("git-p4.preserveUser").lower() == "true"
  753. self.dry_run = False
  754. self.prepare_p4_only = False
  755. self.conflict_behavior = None
  756. self.isWindows = (platform.system() == "Windows")
  757. self.exportLabels = False
  758. self.p4HasMoveCommand = p4_has_move_command()
  759. def check(self):
  760. if len(p4CmdList("opened ...")) > 0:
  761. die("You have files opened with perforce! Close them before starting the sync.")
  762. def separate_jobs_from_description(self, message):
  763. """Extract and return a possible Jobs field in the commit
  764. message. It goes into a separate section in the p4 change
  765. specification.
  766. A jobs line starts with "Jobs:" and looks like a new field
  767. in a form. Values are white-space separated on the same
  768. line or on following lines that start with a tab.
  769. This does not parse and extract the full git commit message
  770. like a p4 form. It just sees the Jobs: line as a marker
  771. to pass everything from then on directly into the p4 form,
  772. but outside the description section.
  773. Return a tuple (stripped log message, jobs string)."""
  774. m = re.search(r'^Jobs:', message, re.MULTILINE)
  775. if m is None:
  776. return (message, None)
  777. jobtext = message[m.start():]
  778. stripped_message = message[:m.start()].rstrip()
  779. return (stripped_message, jobtext)
  780. def prepareLogMessage(self, template, message, jobs):
  781. """Edits the template returned from "p4 change -o" to insert
  782. the message in the Description field, and the jobs text in
  783. the Jobs field."""
  784. result = ""
  785. inDescriptionSection = False
  786. for line in template.split("\n"):
  787. if line.startswith("#"):
  788. result += line + "\n"
  789. continue
  790. if inDescriptionSection:
  791. if line.startswith("Files:") or line.startswith("Jobs:"):
  792. inDescriptionSection = False
  793. # insert Jobs section
  794. if jobs:
  795. result += jobs + "\n"
  796. else:
  797. continue
  798. else:
  799. if line.startswith("Description:"):
  800. inDescriptionSection = True
  801. line += "\n"
  802. for messageLine in message.split("\n"):
  803. line += "\t" + messageLine + "\n"
  804. result += line + "\n"
  805. return result
  806. def patchRCSKeywords(self, file, pattern):
  807. # Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern
  808. (handle, outFileName) = tempfile.mkstemp(dir='.')
  809. try:
  810. outFile = os.fdopen(handle, "w+")
  811. inFile = open(file, "r")
  812. regexp = re.compile(pattern, re.VERBOSE)
  813. for line in inFile.readlines():
  814. line = regexp.sub(r'$\1$', line)
  815. outFile.write(line)
  816. inFile.close()
  817. outFile.close()
  818. # Forcibly overwrite the original file
  819. os.unlink(file)
  820. shutil.move(outFileName, file)
  821. except:
  822. # cleanup our temporary file
  823. os.unlink(outFileName)
  824. print "Failed to strip RCS keywords in %s" % file
  825. raise
  826. print "Patched up RCS keywords in %s" % file
  827. def p4UserForCommit(self,id):
  828. # Return the tuple (perforce user,git email) for a given git commit id
  829. self.getUserMapFromPerforceServer()
  830. gitEmail = read_pipe("git log --max-count=1 --format='%%ae' %s" % id)
  831. gitEmail = gitEmail.strip()
  832. if not self.emails.has_key(gitEmail):
  833. return (None,gitEmail)
  834. else:
  835. return (self.emails[gitEmail],gitEmail)
  836. def checkValidP4Users(self,commits):
  837. # check if any git authors cannot be mapped to p4 users
  838. for id in commits:
  839. (user,email) = self.p4UserForCommit(id)
  840. if not user:
  841. msg = "Cannot find p4 user for email %s in commit %s." % (email, id)
  842. if gitConfig('git-p4.allowMissingP4Users').lower() == "true":
  843. print "%s" % msg
  844. else:
  845. die("Error: %s\nSet git-p4.allowMissingP4Users to true to allow this." % msg)
  846. def lastP4Changelist(self):
  847. # Get back the last changelist number submitted in this client spec. This
  848. # then gets used to patch up the username in the change. If the same
  849. # client spec is being used by multiple processes then this might go
  850. # wrong.
  851. results = p4CmdList("client -o") # find the current client
  852. client = None
  853. for r in results:
  854. if r.has_key('Client'):
  855. client = r['Client']
  856. break
  857. if not client:
  858. die("could not get client spec")
  859. results = p4CmdList(["changes", "-c", client, "-m", "1"])
  860. for r in results:
  861. if r.has_key('change'):
  862. return r['change']
  863. die("Could not get changelist number for last submit - cannot patch up user details")
  864. def modifyChangelistUser(self, changelist, newUser):
  865. # fixup the user field of a changelist after it has been submitted.
  866. changes = p4CmdList("change -o %s" % changelist)
  867. if len(changes) != 1:
  868. die("Bad output from p4 change modifying %s to user %s" %
  869. (changelist, newUser))
  870. c = changes[0]
  871. if c['User'] == newUser: return # nothing to do
  872. c['User'] = newUser
  873. input = marshal.dumps(c)
  874. result = p4CmdList("change -f -i", stdin=input)
  875. for r in result:
  876. if r.has_key('code'):
  877. if r['code'] == 'error':
  878. die("Could not modify user field of changelist %s to %s:%s" % (changelist, newUser, r['data']))
  879. if r.has_key('data'):
  880. print("Updated user field for changelist %s to %s" % (changelist, newUser))
  881. return
  882. die("Could not modify user field of changelist %s to %s" % (changelist, newUser))
  883. def canChangeChangelists(self):
  884. # check to see if we have p4 admin or super-user permissions, either of
  885. # which are required to modify changelists.
  886. results = p4CmdList(["protects", self.depotPath])
  887. for r in results:
  888. if r.has_key('perm'):
  889. if r['perm'] == 'admin':
  890. return 1
  891. if r['perm'] == 'super':
  892. return 1
  893. return 0
  894. def prepareSubmitTemplate(self):
  895. """Run "p4 change -o" to grab a change specification template.
  896. This does not use "p4 -G", as it is nice to keep the submission
  897. template in original order, since a human might edit it.
  898. Remove lines in the Files section that show changes to files
  899. outside the depot path we're committing into."""
  900. template = ""
  901. inFilesSection = False
  902. for line in p4_read_pipe_lines(['change', '-o']):
  903. if line.endswith("\r\n"):
  904. line = line[:-2] + "\n"
  905. if inFilesSection:
  906. if line.startswith("\t"):
  907. # path starts and ends with a tab
  908. path = line[1:]
  909. lastTab = path.rfind("\t")
  910. if lastTab != -1:
  911. path = path[:lastTab]
  912. if not p4PathStartsWith(path, self.depotPath):
  913. continue
  914. else:
  915. inFilesSection = False
  916. else:
  917. if line.startswith("Files:"):
  918. inFilesSection = True
  919. template += line
  920. return template
  921. def edit_template(self, template_file):
  922. """Invoke the editor to let the user change the submission
  923. message. Return true if okay to continue with the submit."""
  924. # if configured to skip the editing part, just submit
  925. if gitConfig("git-p4.skipSubmitEdit") == "true":
  926. return True
  927. # look at the modification time, to check later if the user saved
  928. # the file
  929. mtime = os.stat(template_file).st_mtime
  930. # invoke the editor
  931. if os.environ.has_key("P4EDITOR") and (os.environ.get("P4EDITOR") != ""):
  932. editor = os.environ.get("P4EDITOR")
  933. else:
  934. editor = read_pipe("git var GIT_EDITOR").strip()
  935. system(editor + " " + template_file)
  936. # If the file was not saved, prompt to see if this patch should
  937. # be skipped. But skip this verification step if configured so.
  938. if gitConfig("git-p4.skipSubmitEditCheck") == "true":
  939. return True
  940. # modification time updated means user saved the file
  941. if os.stat(template_file).st_mtime > mtime:
  942. return True
  943. while True:
  944. response = raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")
  945. if response == 'y':
  946. return True
  947. if response == 'n':
  948. return False
  949. def applyCommit(self, id):
  950. """Apply one commit, return True if it succeeded."""
  951. print "Applying", read_pipe(["git", "show", "-s",
  952. "--format=format:%h %s", id])
  953. (p4User, gitEmail) = self.p4UserForCommit(id)
  954. diff = read_pipe_lines("git diff-tree -r %s \"%s^\" \"%s\"" % (self.diffOpts, id, id))
  955. filesToAdd = set()
  956. filesToDelete = set()
  957. editedFiles = set()
  958. pureRenameCopy = set()
  959. filesToChangeExecBit = {}
  960. for line in diff:
  961. diff = parseDiffTreeEntry(line)
  962. modifier = diff['status']
  963. path = diff['src']
  964. if modifier == "M":
  965. p4_edit(path)
  966. if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
  967. filesToChangeExecBit[path] = diff['dst_mode']
  968. editedFiles.add(path)
  969. elif modifier == "A":
  970. filesToAdd.add(path)
  971. filesToChangeExecBit[path] = diff['dst_mode']
  972. if path in filesToDelete:
  973. filesToDelete.remove(path)
  974. elif modifier == "D":
  975. filesToDelete.add(path)
  976. if path in filesToAdd:
  977. filesToAdd.remove(path)
  978. elif modifier == "C":
  979. src, dest = diff['src'], diff['dst']
  980. p4_integrate(src, dest)
  981. pureRenameCopy.add(dest)
  982. if diff['src_sha1'] != diff['dst_sha1']:
  983. p4_edit(dest)
  984. pureRenameCopy.discard(dest)
  985. if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
  986. p4_edit(dest)
  987. pureRenameCopy.discard(dest)
  988. filesToChangeExecBit[dest] = diff['dst_mode']
  989. os.unlink(dest)
  990. editedFiles.add(dest)
  991. elif modifier == "R":
  992. src, dest = diff['src'], diff['dst']
  993. if self.p4HasMoveCommand:
  994. p4_edit(src) # src must be open before move
  995. p4_move(src, dest) # opens for (move/delete, move/add)
  996. else:
  997. p4_integrate(src, dest)
  998. if diff['src_sha1'] != diff['dst_sha1']:
  999. p4_edit(dest)
  1000. else:
  1001. pureRenameCopy.add(dest)
  1002. if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
  1003. if not self.p4HasMoveCommand:
  1004. p4_edit(dest) # with move: already open, writable
  1005. filesToChangeExecBit[dest] = diff['dst_mode']
  1006. if not self.p4HasMoveCommand:
  1007. os.unlink(dest)
  1008. filesToDelete.add(src)
  1009. editedFiles.add(dest)
  1010. else:
  1011. die("unknown modifier %s for %s" % (modifier, path))
  1012. diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
  1013. patchcmd = diffcmd + " | git apply "
  1014. tryPatchCmd = patchcmd + "--check -"
  1015. applyPatchCmd = patchcmd + "--check --apply -"
  1016. patch_succeeded = True
  1017. if os.system(tryPatchCmd) != 0:
  1018. fixed_rcs_keywords = False
  1019. patch_succeeded = False
  1020. print "Unfortunately applying the change failed!"
  1021. # Patch failed, maybe it's just RCS keyword woes. Look through
  1022. # the patch to see if that's possible.
  1023. if gitConfig("git-p4.attemptRCSCleanup","--bool") == "true":
  1024. file = None
  1025. pattern = None
  1026. kwfiles = {}
  1027. for file in editedFiles | filesToDelete:
  1028. # did this file's delta contain RCS keywords?
  1029. pattern = p4_keywords_regexp_for_file(file)
  1030. if pattern:
  1031. # this file is a possibility...look for RCS keywords.
  1032. regexp = re.compile(pattern, re.VERBOSE)
  1033. for line in read_pipe_lines(["git", "diff", "%s^..%s" % (id, id), file]):
  1034. if regexp.search(line):
  1035. if verbose:
  1036. print "got keyword match on %s in %s in %s" % (pattern, line, file)
  1037. kwfiles[file] = pattern
  1038. break
  1039. for file in kwfiles:
  1040. if verbose:
  1041. print "zapping %s with %s" % (line,pattern)
  1042. self.patchRCSKeywords(file, kwfiles[file])
  1043. fixed_rcs_keywords = True
  1044. if fixed_rcs_keywords:
  1045. print "Retrying the patch with RCS keywords cleaned up"
  1046. if os.system(tryPatchCmd) == 0:
  1047. patch_succeeded = True
  1048. if not patch_succeeded:
  1049. for f in editedFiles:
  1050. p4_revert(f)
  1051. return False
  1052. #
  1053. # Apply the patch for real, and do add/delete/+x handling.
  1054. #
  1055. system(applyPatchCmd)
  1056. for f in filesToAdd:
  1057. p4_add(f)
  1058. for f in filesToDelete:
  1059. p4_revert(f)
  1060. p4_delete(f)
  1061. # Set/clear executable bits
  1062. for f in filesToChangeExecBit.keys():
  1063. mode = filesToChangeExecBit[f]
  1064. setP4ExecBit(f, mode)
  1065. #
  1066. # Build p4 change description, starting with the contents
  1067. # of the git commit message.
  1068. #
  1069. logMessage = extractLogMessageFromGitCommit(id)
  1070. logMessage = logMessage.strip()
  1071. (logMessage, jobs) = self.separate_jobs_from_description(logMessage)
  1072. template = self.prepareSubmitTemplate()
  1073. submitTemplate = self.prepareLogMessage(template, logMessage, jobs)
  1074. if self.preserveUser:
  1075. submitTemplate += "\n######## Actual user %s, modified after commit\n" % p4User
  1076. if self.checkAuthorship and not self.p4UserIsMe(p4User):
  1077. submitTemplate += "######## git author %s does not match your p4 account.\n" % gitEmail
  1078. submitTemplate += "######## Use option --preserve-user to modify authorship.\n"
  1079. submitTemplate += "######## Variable git-p4.skipUserNameCheck hides this message.\n"
  1080. separatorLine = "######## everything below this line is just the diff #######\n"
  1081. # diff
  1082. if os.environ.has_key("P4DIFF"):
  1083. del(os.environ["P4DIFF"])
  1084. diff = ""
  1085. for editedFile in editedFiles:
  1086. diff += p4_read_pipe(['diff', '-du',
  1087. wildcard_encode(editedFile)])
  1088. # new file diff
  1089. newdiff = ""
  1090. for newFile in filesToAdd:
  1091. newdiff += "==== new file ====\n"
  1092. newdiff += "--- /dev/null\n"
  1093. newdiff += "+++ %s\n" % newFile
  1094. f = open(newFile, "r")
  1095. for line in f.readlines():
  1096. newdiff += "+" + line
  1097. f.close()
  1098. # change description file: submitTemplate, separatorLine, diff, newdiff
  1099. (handle, fileName) = tempfile.mkstemp()
  1100. tmpFile = os.fdopen(handle, "w+")
  1101. if self.isWindows:
  1102. submitTemplate = submitTemplate.replace("\n", "\r\n")
  1103. separatorLine = separatorLine.replace("\n", "\r\n")
  1104. newdiff = newdiff.replace("\n", "\r\n")
  1105. tmpFile.write(submitTemplate + separatorLine + diff + newdiff)
  1106. tmpFile.close()
  1107. if self.prepare_p4_only:
  1108. #
  1109. # Leave the p4 tree prepared, and the submit template around
  1110. # and let the user decide what to do next
  1111. #
  1112. print
  1113. print "P4 workspace prepared for submission."
  1114. print "To submit or revert, go to client workspace"
  1115. print " " + self.clientPath
  1116. print
  1117. print "To submit, use \"p4 submit\" to write a new description,"
  1118. print "or \"p4 submit -i %s\" to use the one prepared by" \
  1119. " \"git p4\"." % fileName
  1120. print "You can delete the file \"%s\" when finished." % fileName
  1121. if self.preserveUser and p4User and not self.p4UserIsMe(p4User):
  1122. print "To preserve change ownership by user %s, you must\n" \
  1123. "do \"p4 change -f <change>\" after submitting and\n" \
  1124. "edit the User field."
  1125. if pureRenameCopy:
  1126. print "After submitting, renamed files must be re-synced."
  1127. print "Invoke \"p4 sync -f\" on each of these files:"
  1128. for f in pureRenameCopy:
  1129. print " " + f
  1130. print
  1131. print "To revert the changes, use \"p4 revert ...\", and delete"
  1132. print "the submit template file \"%s\"" % fileName
  1133. if filesToAdd:
  1134. print "Since the commit adds new files, they must be deleted:"
  1135. for f in filesToAdd:
  1136. print " " + f
  1137. print
  1138. return True
  1139. #
  1140. # Let the user edit the change description, then submit it.
  1141. #
  1142. if self.edit_template(fileName):
  1143. # read the edited message and submit
  1144. ret = True
  1145. tmpFile = open(fileName, "rb")
  1146. message = tmpFile.read()
  1147. tmpFile.close()
  1148. submitTemplate = message[:message.index(separatorLine)]
  1149. if self.isWindows:
  1150. submitTemplate = submitTemplate.replace("\r\n", "\n")
  1151. p4_write_pipe(['submit', '-i'], submitTemplate)
  1152. if self.preserveUser:
  1153. if p4User:
  1154. # Get last changelist number. Cannot easily get it from
  1155. # the submit command output as the output is
  1156. # unmarshalled.
  1157. changelist = self.lastP4Changelist()
  1158. self.modifyChangelistUser(changelist, p4User)
  1159. # The rename/copy happened by applying a patch that created a
  1160. # new file. This leaves it writable, which confuses p4.
  1161. for f in pureRenameCopy:
  1162. p4_sync(f, "-f")
  1163. else:
  1164. # skip this patch
  1165. ret = False
  1166. print "Submission cancelled, undoing p4 changes."
  1167. for f in editedFiles:
  1168. p4_revert(f)
  1169. for f in filesToAdd:
  1170. p4_revert(f)
  1171. os.remove(f)
  1172. for f in filesToDelete:
  1173. p4_revert(f)
  1174. os.remove(fileName)
  1175. return ret
  1176. # Export git tags as p4 labels. Create a p4 label and then tag
  1177. # with that.
  1178. def exportGitTags(self, gitTags):
  1179. validLabelRegexp = gitConfig("git-p4.labelExportRegexp")
  1180. if len(validLabelRegexp) == 0:
  1181. validLabelRegexp = defaultLabelRegexp
  1182. m = re.compile(validLabelRegexp)
  1183. for name in gitTags:
  1184. if not m.match(name):
  1185. if verbose:
  1186. print "tag %s does not match regexp %s" % (name, validLabelRegexp)
  1187. continue
  1188. # Get the p4 commit this corresponds to
  1189. logMessage = extractLogMessageFromGitCommit(name)
  1190. values = extractSettingsGitLog(logMessage)
  1191. if not values.has_key('change'):
  1192. # a tag pointing to something not sent to p4; ignore
  1193. if verbose:
  1194. print "git tag %s does not give a p4 commit" % name
  1195. continue
  1196. else:
  1197. changelist = values['change']
  1198. # Get the tag details.
  1199. inHeader = True
  1200. isAnnotated = False
  1201. body = []
  1202. for l in read_pipe_lines(["git", "cat-file", "-p", name]):
  1203. l = l.strip()
  1204. if inHeader:
  1205. if re.match(r'tag\s+', l):
  1206. isAnnotated = True
  1207. elif re.match(r'\s*$', l):
  1208. inHeader = False
  1209. continue
  1210. else:
  1211. body.append(l)
  1212. if not isAnnotated:
  1213. body = ["lightweight tag imported by git p4\n"]
  1214. # Create the label - use the same view as the client spec we are using
  1215. clientSpec = getClientSpec()
  1216. labelTemplate = "Label: %s\n" % name
  1217. labelTemplate += "Description:\n"
  1218. for b in body:
  1219. labelTemplate += "\t" + b + "\n"
  1220. labelTemplate += "View:\n"
  1221. for mapping in clientSpec.mappings:
  1222. labelTemplate += "\t%s\n" % mapping.depot_side.path
  1223. if self.dry_run:
  1224. print "Would create p4 label %s for tag" % name
  1225. elif self.prepare_p4_only:
  1226. print "Not creating p4 label %s for tag due to option" \
  1227. " --prepare-p4-only" % name
  1228. else:
  1229. p4_write_pipe(["label", "-i"], labelTemplate)
  1230. # Use the label
  1231. p4_system(["tag", "-l", name] +
  1232. ["%s@%s" % (mapping.depot_side.path, changelist) for mapping in clientSpec.mappings])
  1233. if verbose:
  1234. print "created p4 label for tag %s" % name
  1235. def run(self, args):
  1236. if len(args) == 0:
  1237. self.master = currentGitBranch()
  1238. if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
  1239. die("Detecting current git branch failed!")
  1240. elif len(args) == 1:
  1241. self.master = args[0]
  1242. if not branchExists(self.master):
  1243. die("Branch %s does not exist" % self.master)
  1244. else:
  1245. return False
  1246. allowSubmit = gitConfig("git-p4.allowSubmit")
  1247. if len(allowSubmit) > 0 and not self.master in allowSubmit.split(","):
  1248. die("%s is not in git-p4.allowSubmit" % self.master)
  1249. [upstream, settings] = findUpstreamBranchPoint()
  1250. self.depotPath = settings['depot-paths'][0]
  1251. if len(self.origin) == 0:
  1252. self.origin = upstream
  1253. if self.preserveUser:
  1254. if not self.canChangeChangelists():
  1255. die("Cannot preserve user names without p4 super-user or admin permissions")
  1256. # if not set from the command line, try the config file
  1257. if self.conflict_behavior is None:
  1258. val = gitConfig("git-p4.conflict")
  1259. if val:
  1260. if val not in self.conflict_behavior_choices:
  1261. die("Invalid value '%s' for config git-p4.conflict" % val)
  1262. else:
  1263. val = "ask"
  1264. self.conflict_behavior = val
  1265. if self.verbose:
  1266. print "Origin branch is " + self.origin
  1267. if len(self.depotPath) == 0:
  1268. print "Internal error: cannot locate perforce depot path from existing branches"
  1269. sys.exit(128)
  1270. self.useClientSpec = False
  1271. if gitConfig("git-p4.useclientspec", "--bool") == "true":
  1272. self.useClientSpec = True
  1273. if self.useClientSpec:
  1274. self.clientSpecDirs = getClientSpec()
  1275. if self.useClientSpec:
  1276. # all files are relative to the client spec
  1277. self.clientPath = getClientRoot()
  1278. else:
  1279. self.clientPath = p4Where(self.depotPath)
  1280. if self.clientPath == "":
  1281. die("Error: Cannot locate perforce checkout of %s in client view" % self.depotPath)
  1282. print "Perforce checkout for depot path %s located at %s" % (self.depotPath, self.clientPath)
  1283. self.oldWorkingDirectory = os.getcwd()
  1284. # ensure the clientPath exists
  1285. new_client_dir = False
  1286. if not os.path.exists(self.clientPath):
  1287. new_client_dir = True
  1288. os.makedirs(self.clientPath)
  1289. chdir(self.clientPath)
  1290. if self.dry_run:
  1291. print "Would synchronize p4 checkout in %s" % self.clientPath
  1292. else:
  1293. print "Synchronizing p4 checkout..."
  1294. if new_client_dir:
  1295. # old one was destroyed, and maybe nobody told p4
  1296. p4_sync("...", "-f")
  1297. else:
  1298. p4_sync("...")
  1299. self.check()
  1300. commits = []
  1301. for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
  1302. commits.append(line.strip())
  1303. commits.reverse()
  1304. if self.preserveUser or (gitConfig("git-p4.skipUserNameCheck") == "true"):
  1305. self.checkAuthorship = False
  1306. else:
  1307. self.checkAuthorship = True
  1308. if self.preserveUser:
  1309. self.checkValidP4Users(commits)
  1310. #
  1311. # Build up a set of options to be passed to diff when
  1312. # submitting each commit to p4.
  1313. #
  1314. if self.detectRenames:
  1315. # command-line -M arg
  1316. self.diffOpts = "-M"
  1317. else:
  1318. # If not explicitly set check the config variable
  1319. detectRenames = gitConfig("git-p4.detectRenames")
  1320. if detectRenames.lower() == "false" or detectRenames == "":
  1321. self.diffOpts = ""
  1322. elif detectRenames.lower() == "true":
  1323. self.diffOpts = "-M"
  1324. else:
  1325. self.diffOpts = "-M%s" % detectRenames
  1326. # no command-line arg for -C or --find-copies-harder, just
  1327. # config variables
  1328. detectCopies = gitConfig("git-p4.detectCopies")
  1329. if detectCopies.lower() == "false" or detectCopies == "":
  1330. pass
  1331. elif detectCopies.lower() == "true":
  1332. self.diffOpts += " -C"
  1333. else:
  1334. self.diffOpts += " -C%s" % detectCopies
  1335. if gitConfig("git-p4.detectCopiesHarder", "--bool") == "true":
  1336. self.diffOpts += " --find-copies-harder"
  1337. #
  1338. # Apply the commits, one at a time. On failure, ask if should
  1339. # continue to try the rest of the patches, or quit.
  1340. #
  1341. if self.dry_run:
  1342. print "Would apply"
  1343. applied = []
  1344. last = len(commits) - 1
  1345. for i, commit in enumerate(commits):
  1346. if self.dry_run:
  1347. print " ", read_pipe(["git", "show", "-s",
  1348. "--format=format:%h %s", commit])
  1349. ok = True
  1350. else:
  1351. ok = self.applyCommit(commit)
  1352. if ok:
  1353. applied.append(commit)
  1354. else:
  1355. if self.prepare_p4_only and i < last:
  1356. print "Processing only the first commit due to option" \
  1357. " --prepare-p4-only"
  1358. break
  1359. if i < last:
  1360. quit = False
  1361. while True:
  1362. # prompt for what to do, or use the option/variable
  1363. if self.conflict_behavior == "ask":
  1364. print "What do you want to do?"
  1365. response = raw_input("[s]kip this commit but apply"
  1366. " the rest, or [q]uit? ")
  1367. if not response:
  1368. continue
  1369. elif self.conflict_behavior == "skip":
  1370. response = "s"
  1371. elif self.conflict_behavior == "quit":
  1372. response = "q"
  1373. else:
  1374. die("Unknown conflict_behavior '%s'" %
  1375. self.conflict_behavior)
  1376. if response[0] == "s":
  1377. print "Skipping this commit, but applying the rest"
  1378. break
  1379. if response[0] == "q":
  1380. print "Quitting"
  1381. quit = True
  1382. break
  1383. if quit:
  1384. break
  1385. chdir(self.oldWorkingDirectory)
  1386. if self.dry_run:
  1387. pass
  1388. elif self.prepare_p4_only:
  1389. pass
  1390. elif len(commits) == len(applied):
  1391. print "All commits applied!"
  1392. sync = P4Sync()
  1393. sync.run([])
  1394. rebase = P4Rebase()
  1395. rebase.rebase()
  1396. else:
  1397. if len(applied) == 0:
  1398. print "No commits applied."
  1399. else:
  1400. print "Applied only the commits marked with '*':"
  1401. for c in commits:
  1402. if c in applied:
  1403. star = "*"
  1404. else:
  1405. star = " "
  1406. print star, read_pipe(["git", "show", "-s",
  1407. "--format=format:%h %s", c])
  1408. print "You will have to do 'git p4 sync' and rebase."
  1409. if gitConfig("git-p4.exportLabels", "--bool") == "true":
  1410. self.exportLabels = True
  1411. if self.exportLabels:
  1412. p4Labels = getP4Labels(self.depotPath)
  1413. gitTags = getGitTags()
  1414. missingGitTags = gitTags - p4Labels
  1415. self.exportGitTags(missingGitTags)
  1416. # exit with error unless everything applied perfecly
  1417. if len(commits) != len(applied):
  1418. sys.exit(1)
  1419. return True
  1420. class View(object):
  1421. """Represent a p4 view ("p4 help views"), and map files in a
  1422. repo according to the view."""
  1423. class Path(object):
  1424. """A depot or client path, possibly containing wildcards.
  1425. The only one supported is ... at the end, currently.
  1426. Initialize with the full path, with //depot or //client."""
  1427. def __init__(self, path, is_depot):
  1428. self.path = path
  1429. self.is_depot = is_depot
  1430. self.find_wildcards()
  1431. # remember the prefix bit, useful for relative mappings
  1432. m = re.match("(//[^/]+/)", self.path)
  1433. if not m:
  1434. die("Path %s does not start with //prefix/" % self.path)
  1435. prefix = m.group(1)
  1436. if not self.is_depot:
  1437. # strip //client/ on client paths
  1438. self.path = self.path[len(prefix):]
  1439. def find_wildcards(self):
  1440. """Make sure wildcards are valid, and set up internal
  1441. variables."""
  1442. self.ends_triple_dot = False
  1443. # There are three wildcards allowed in p4 views
  1444. # (see "p4 help views"). This code knows how to
  1445. # handle "..." (only at the end), but cannot deal with
  1446. # "%%n" or "*". Only check the depot_side, as p4 should
  1447. # validate that the client_side matches too.
  1448. if re.search(r'%%[1-9]', self.path):
  1449. die("Can't handle %%n wildcards in view: %s" % self.path)
  1450. if self.path.find("*") >= 0:
  1451. die("Can't handle * wildcards in view: %s" % self.path)
  1452. triple_dot_index = self.path.find("...")
  1453. if triple_dot_index >= 0:
  1454. if triple_dot_index != len(self.path) - 3:
  1455. die("Can handle only single ... wildcard, at end: %s" %
  1456. self.path)
  1457. self.ends_triple_dot = True
  1458. def ensure_compatible(self, other_path):
  1459. """Make sure the wildcards agree."""
  1460. if self.ends_triple_dot != other_path.ends_triple_dot:
  1461. die("Both paths must end with ... if either does;\n" +
  1462. "paths: %s %s" % (self.path, other_path.path))
  1463. def match_wildcards(self, test_path):
  1464. """See if this test_path matches us, and fill in the value
  1465. of the wildcards if so. Returns a tuple of
  1466. (True|False, wildcards[]). For now, only the ... at end
  1467. is supported, so at most one wildcard."""
  1468. if self.ends_triple_dot:
  1469. dotless = self.path[:-3]
  1470. if test_path.startswith(dotless):
  1471. wildcard = test_path[len(dotless):]
  1472. return (True, [ wildcard ])
  1473. else:
  1474. if test_path == self.path:
  1475. return (True, [])
  1476. return (False, [])
  1477. def match(self, test_path):
  1478. """Just return if it matches; don't bother with the wildcards."""
  1479. b, _ = self.match_wildcards(test_path)
  1480. return b
  1481. def fill_in_wildcards(self, wildcards):
  1482. """Return the relative path, with the wildcards filled in
  1483. if there are any."""
  1484. if self.ends_triple_dot:
  1485. return self.path[:-3] + wildcards[0]
  1486. else:
  1487. return self.path
  1488. class Mapping(object):
  1489. def __init__(self, depot_side, client_side, overlay, exclude):
  1490. # depot_side is without the trailing /... if it had one
  1491. self.depot_side = View.Path(depot_side, is_depot=True)
  1492. self.client_side = View.Path(client_side, is_depot=False)
  1493. self.overlay = overlay # started with "+"
  1494. self.exclude = exclude # started with "-"
  1495. assert not (self.overlay and self.exclude)
  1496. self.depot_side.ensure_compatible(self.client_side)
  1497. def __str__(self):
  1498. c = " "
  1499. if self.overlay:
  1500. c = "+"
  1501. if self.exclude:
  1502. c = "-"
  1503. return "View.Mapping: %s%s -> %s" % \
  1504. (c, self.depot_side.path, self.client_side.path)
  1505. def map_depot_to_client(self, depot_path):
  1506. """Calculate the client path if using this mapping on the
  1507. given depot path; does not consider the effect of other
  1508. mappings in a view. Even excluded mappings are returned."""
  1509. matches, wildcards = self.depot_side.match_wildcards(depot_path)
  1510. if not matches:
  1511. return ""
  1512. client_path = self.client_side.fill_in_wildcards(wildcards)
  1513. return client_path
  1514. #
  1515. # View methods
  1516. #
  1517. def __init__(self):
  1518. self.mappings = []
  1519. def append(self, view_line):
  1520. """Parse a view line, splitting it into depot and client
  1521. sides. Append to self.mappings, preserving order."""
  1522. # Split the view line into exactly two words. P4 enforces
  1523. # structure on these lines that simplifies this quite a bit.
  1524. #
  1525. # Either or both words may be double-quoted.
  1526. # Single quotes do not matter.
  1527. # Double-quote marks cannot occur inside the words.
  1528. # A + or - prefix is also inside the quotes.
  1529. # There are no quotes unless they contain a space.
  1530. # The line is already white-space stripped.
  1531. # The two words are separated by a single space.
  1532. #
  1533. if view_line[0] == '"':
  1534. # First word is double quoted. Find its end.
  1535. close_quote_index = view_line.find('"', 1)
  1536. if close_quote_index <= 0:
  1537. die("No first-word closing quote found: %s" % view_line)
  1538. depot_side = view_line[1:close_quote_index]
  1539. # skip closing quote and space
  1540. rhs_index = close_quote_index + 1 + 1
  1541. else:
  1542. space_index = view_line.find(" ")
  1543. if space_index <= 0:
  1544. die("No word-splitting space found: %s" % view_line)
  1545. depot_side = view_line[0:space_index]
  1546. rhs_index = space_index + 1
  1547. if view_line[rhs_index] == '"':
  1548. # Second word is double quoted. Make sure there is a
  1549. # double quote at the end too.
  1550. if not view_line.endswith('"'):
  1551. die("View line with rhs quote should end with one: %s" %
  1552. view_line)
  1553. # skip the quotes
  1554. client_side = view_line[rhs_index+1:-1]
  1555. else:
  1556. client_side = view_line[rhs_index:]
  1557. # prefix + means overlay on previous mapping
  1558. overlay = False
  1559. if depot_side.startswith("+"):
  1560. overlay = True
  1561. depot_side = depot_side[1:]
  1562. # prefix - means exclude this path
  1563. exclude = False
  1564. if depot_side.startswith("-"):
  1565. exclude = True
  1566. depot_side = depot_side[1:]
  1567. m = View.Mapping(depot_side, client_side, overlay, exclude)
  1568. self.mappings.append(m)
  1569. def map_in_client(self, depot_path):
  1570. """Return the relative location in the client where this
  1571. depot file should live. Returns "" if the file should
  1572. not be mapped in the client."""
  1573. paths_filled = []
  1574. client_path = ""
  1575. # look at later entries first
  1576. for m in self.mappings[::-1]:
  1577. # see where will this path end up in the client
  1578. p = m.map_depot_to_client(depot_path)
  1579. if p == "":
  1580. # Depot path does not belong in client. Must remember
  1581. # this, as previous items should not cause files to
  1582. # exist in this path either. Remember that the list is
  1583. # being walked from the end, which has higher precedence.
  1584. # Overlap mappings do not exclude previous mappings.
  1585. if not m.overlay:
  1586. paths_filled.append(m.client_side)
  1587. else:
  1588. # This mapping matched; no need to search any further.
  1589. # But, the mapping could be rejected if the client path
  1590. # has already been claimed by an earlier mapping (i.e.
  1591. # one later in the list, which we are walking backwards).
  1592. already_mapped_in_client = False
  1593. for f in paths_filled:
  1594. # this is View.Path.match
  1595. if f.match(p):
  1596. already_mapped_in_client = True
  1597. break
  1598. if not already_mapped_in_client:
  1599. # Include this file, unless it is from a line that
  1600. # explicitly said to exclude it.
  1601. if not m.exclude:
  1602. client_path = p
  1603. # a match, even if rejected, always stops the search
  1604. break
  1605. return client_path
  1606. class P4Sync(Command, P4UserMap):
  1607. delete_actions = ( "delete", "move/delete", "purge" )
  1608. def __init__(self):
  1609. Command.__init__(self)
  1610. P4UserMap.__init__(self)
  1611. self.options = [
  1612. optparse.make_option("--branch", dest="branch"),
  1613. optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
  1614. optparse.make_option("--changesfile", dest="changesFile"),
  1615. optparse.make_option("--silent", dest="silent", action="store_true"),
  1616. optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
  1617. optparse.make_option("--import-labels", dest="importLabels", action="store_true"),
  1618. optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
  1619. help="Import into refs/heads/ , not refs/remotes"),
  1620. optparse.make_option("--max-changes", dest="maxChanges"),
  1621. optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
  1622. help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),
  1623. optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',
  1624. help="Only sync files that are included in the Perforce Client Spec")
  1625. ]
  1626. self.description = """Imports from Perforce into a git repository.\n
  1627. example:
  1628. //depot/my/project/ -- to import the current head
  1629. //depot/my/project/@all -- to import everything
  1630. //depot/my/project/@1,6 -- to import only from revision 1 to 6
  1631. (a ... is not needed in the path p4 specification, it's added implicitly)"""
  1632. self.usage += " //depot/path[@revRange]"
  1633. self.silent = False
  1634. self.createdBranches = set()
  1635. self.committedChanges = set()
  1636. self.branch = ""
  1637. self.detectBranches = False
  1638. self.detectLabels = False
  1639. self.importLabels = False
  1640. self.changesFile = ""
  1641. self.syncWithOrigin = True
  1642. self.importIntoRemotes = True
  1643. self.maxChanges = ""
  1644. self.isWindows = (platform.system() == "Windows")
  1645. self.keepRepoPath = False
  1646. self.depotPaths = None
  1647. self.p4BranchesInGit = []
  1648. self.cloneExclude = []
  1649. self.useClientSpec = False
  1650. self.useClientSpec_from_options = False
  1651. self.clientSpecDirs = None
  1652. self.tempBranches = []
  1653. self.tempBranchLocation = "git-p4-tmp"
  1654. if gitConfig("git-p4.syncFromOrigin") == "false":
  1655. self.syncWithOrigin = False
  1656. # Force a checkpoint in fast-import and wait for it to finish
  1657. def checkpoint(self):
  1658. self.gitStream.write("checkpoint\n\n")
  1659. self.gitStream.write("progress checkpoint\n\n")
  1660. out = self.gitOutput.readline()
  1661. if self.verbose:
  1662. print "checkpoint finished: " + out
  1663. def extractFilesFromCommit(self, commit):
  1664. self.cloneExclude = [re.sub(r"\.\.\.$", "", path)
  1665. for path in self.cloneExclude]
  1666. files = []
  1667. fnum = 0
  1668. while commit.has_key("depotFile%s" % fnum):
  1669. path = commit["depotFile%s" % fnum]
  1670. if [p for p in self.cloneExclude
  1671. if p4PathStartsWith(path, p)]:
  1672. found = False
  1673. else:
  1674. found = [p for p in self.depotPaths
  1675. if p4PathStartsWith(path, p)]
  1676. if not found:
  1677. fnum = fnum + 1
  1678. continue
  1679. file = {}
  1680. file["path"] = path
  1681. file["rev"] = commit["rev%s" % fnum]
  1682. file["action"] = commit["action%s" % fnum]
  1683. file["type"] = commit["type%s" % fnum]
  1684. files.append(file)
  1685. fnum = fnum + 1
  1686. return files
  1687. def stripRepoPath(self, path, prefixes):
  1688. """When streaming files, this is called to map a p4 depot path
  1689. to where it should go in git. The prefixes are either
  1690. self.depotPaths, or self.branchPrefixes in the case of
  1691. branch detection."""
  1692. if self.useClientSpec:
  1693. # branch detection moves files up a level (the branch name)
  1694. # from what client spec interpretation gives
  1695. path = self.clientSpecDirs.map_in_client(path)
  1696. if self.detectBranches:
  1697. for b in self.knownBranches:
  1698. if path.startswith(b + "/"):
  1699. path = path[len(b)+1:]
  1700. elif self.keepRepoPath:
  1701. # Preserve everything in relative path name except leading
  1702. # //depot/; just look at first prefix as they all should
  1703. # be in the same depot.
  1704. depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])
  1705. if p4PathStartsWith(path, depot):
  1706. path = path[len(depot):]
  1707. else:
  1708. for p in prefixes:
  1709. if p4PathStartsWith(path, p):
  1710. path = path[len(p):]
  1711. break
  1712. path = wildcard_decode(path)
  1713. return path
  1714. def splitFilesIntoBranches(self, commit):
  1715. """Look at each depotFile in the commit to figure out to what
  1716. branch it belongs."""
  1717. branches = {}
  1718. fnum = 0
  1719. while commit.has_key("depotFile%s" % fnum):
  1720. path = commit["depotFile%s" % fnum]
  1721. found = [p for p in self.depotPaths
  1722. if p4PathStartsWith(path, p)]
  1723. if not found:
  1724. fnum = fnum + 1
  1725. continue
  1726. file = {}
  1727. file["path"] = path
  1728. file["rev"] = commit["rev%s" % fnum]
  1729. file["action"] = commit["action%s" % fnum]
  1730. file["type"] = commit["type%s" % fnum]
  1731. fnum = fnum + 1
  1732. # start with the full relative path where this file would
  1733. # go in a p4 client
  1734. if self.useClientSpec:
  1735. relPath = self.clientSpecDirs.map_in_client(path)
  1736. else:
  1737. relPath = self.stripRepoPath(path, self.depotPaths)
  1738. for branch in self.knownBranches.keys():
  1739. # add a trailing slash so that a commit into qt/4.2foo
  1740. # doesn't end up in qt/4.2, e.g.
  1741. if relPath.startswith(branch + "/"):
  1742. if branch not in branches:
  1743. branches[branch] = []
  1744. branches[branch].append(file)
  1745. break
  1746. return branches
  1747. # output one file from the P4 stream
  1748. # - helper for streamP4Files
  1749. def streamOneP4File(self, file, contents):
  1750. relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)
  1751. if verbose:
  1752. sys.stderr.write("%s\n" % relPath)
  1753. (type_base, type_mods) = split_p4_type(file["type"])
  1754. git_mode = "100644"
  1755. if "x" in type_mods:
  1756. git_mode = "100755"
  1757. if type_base == "symlink":
  1758. git_mode = "120000"
  1759. # p4 print on a symlink contains "target\n"; remove the newline
  1760. data = ''.join(contents)
  1761. contents = [data[:-1]]
  1762. if type_base == "utf16":
  1763. # p4 delivers different text in the python output to -G
  1764. # than it does when using "print -o", or normal p4 client
  1765. # operations. utf16 is converted to ascii or utf8, perhaps.
  1766. # But ascii text saved as -t utf16 is completely mangled.
  1767. # Invoke print -o to get the real contents.
  1768. text = p4_read_pipe(['print', '-q', '-o', '-', file['depotFile']])
  1769. contents = [ text ]
  1770. if type_base == "apple":
  1771. # Apple filetype files will be streamed as a concatenation of
  1772. # its appledouble header and the contents. This is useless
  1773. # on both macs and non-macs. If using "print -q -o xx", it
  1774. # will create "xx" with the data, and "%xx" with the header.
  1775. # This is also not very useful.
  1776. #
  1777. # Ideally, someday, this script can learn how to generate
  1778. # appledouble files directly and import those to git, but
  1779. # non-mac machines can never find a use for apple filetype.
  1780. print "\nIgnoring apple filetype file %s" % file['depotFile']
  1781. return
  1782. # Perhaps windows wants unicode, utf16 newlines translated too;
  1783. # but this is not doing it.
  1784. if self.isWindows and type_base == "text":
  1785. mangled = []
  1786. for data in contents:
  1787. data = data.replace("\r\n", "\n")
  1788. mangled.append(data)
  1789. contents = mangled
  1790. # Note that we do not try to de-mangle keywords on utf16 files,
  1791. # even though in theory somebody may want that.
  1792. pattern = p4_keywords_regexp_for_type(type_base, type_mods)
  1793. if pattern:
  1794. regexp = re.compile(pattern, re.VERBOSE)
  1795. text = ''.join(contents)
  1796. text = regexp.sub(r'$\1$', text)
  1797. contents = [ text ]
  1798. self.gitStream.write("M %s inline %s\n" % (git_mode, relPath))
  1799. # total length...
  1800. length = 0
  1801. for d in contents:
  1802. length = length + len(d)
  1803. self.gitStream.write("data %d\n" % length)
  1804. for d in contents:
  1805. self.gitStream.write(d)
  1806. self.gitStream.write("\n")
  1807. def streamOneP4Deletion(self, file):
  1808. relPath = self.stripRepoPath(file['path'], self.branchPrefixes)
  1809. if verbose:
  1810. sys.stderr.write("delete %s\n" % relPath)
  1811. self.gitStream.write("D %s\n" % relPath)
  1812. # handle another chunk of streaming data
  1813. def streamP4FilesCb(self, marshalled):
  1814. # catch p4 errors and complain
  1815. err = None
  1816. if "code" in marshalled:
  1817. if marshalled["code"] == "error":
  1818. if "data" in marshalled:
  1819. err = marshalled["data"].rstrip()
  1820. if err:
  1821. f = None
  1822. if self.stream_have_file_info:
  1823. if "depotFile" in self.stream_file:
  1824. f = self.stream_file["depotFile"]
  1825. # force a failure in fast-import, else an empty
  1826. # commit will be made
  1827. self.gitStream.write("\n")
  1828. self.gitStream.write("die-now\n")
  1829. self.gitStream.close()
  1830. # ignore errors, but make sure it exits first
  1831. self.importProcess.wait()
  1832. if f:
  1833. die("Error from p4 print for %s: %s" % (f, err))
  1834. else:
  1835. die("Error from p4 print: %s" % err)
  1836. if marshalled.has_key('depotFile') and self.stream_have_file_info:
  1837. # start of a new file - output the old one first
  1838. self.streamOneP4File(self.stream_file, self.stream_contents)
  1839. self.stream_file = {}
  1840. self.stream_contents = []
  1841. self.stream_have_file_info = False
  1842. # pick up the new file information... for the
  1843. # 'data' field we need to append to our array
  1844. for k in marshalled.keys():
  1845. if k == 'data':
  1846. self.stream_contents.append(marshalled['data'])
  1847. else:
  1848. self.stream_file[k] = marshalled[k]
  1849. self.stream_have_file_info = True
  1850. # Stream directly from "p4 files" into "git fast-import"
  1851. def streamP4Files(self, files):
  1852. filesForCommit = []
  1853. filesToRead = []
  1854. filesToDelete = []
  1855. for f in files:
  1856. # if using a client spec, only add the files that have
  1857. # a path in the client
  1858. if self.clientSpecDirs:
  1859. if self.clientSpecDirs.map_in_client(f['path']) == "":
  1860. continue
  1861. filesForCommit.append(f)
  1862. if f['action'] in self.delete_actions:
  1863. filesToDelete.append(f)
  1864. else:
  1865. filesToRead.append(f)
  1866. # deleted files...
  1867. for f in filesToDelete:
  1868. self.streamOneP4Deletion(f)
  1869. if len(filesToRead) > 0:
  1870. self.stream_file = {}
  1871. self.stream_contents = []
  1872. self.stream_have_file_info = False
  1873. # curry self argument
  1874. def streamP4FilesCbSelf(entry):
  1875. self.streamP4FilesCb(entry)
  1876. fileArgs = ['%s#%s' % (f['path'], f['rev']) for f in filesToRead]
  1877. p4CmdList(["-x", "-", "print"],
  1878. stdin=fileArgs,
  1879. cb=streamP4FilesCbSelf)
  1880. # do the last chunk
  1881. if self.stream_file.has_key('depotFile'):
  1882. self.streamOneP4File(self.stream_file, self.stream_contents)
  1883. def make_email(self, userid):
  1884. if userid in self.users:
  1885. return self.users[userid]
  1886. else:
  1887. return "%s <a@b>" % userid
  1888. # Stream a p4 tag
  1889. def streamTag(self, gitStream, labelName, labelDetails, commit, epoch):
  1890. if verbose:
  1891. print "writing tag %s for commit %s" % (labelName, commit)
  1892. gitStream.write("tag %s\n" % labelName)
  1893. gitStream.write("from %s\n" % commit)
  1894. if labelDetails.has_key('Owner'):
  1895. owner = labelDetails["Owner"]
  1896. else:
  1897. owner = None
  1898. # Try to use the owner of the p4 label, or failing that,
  1899. # the current p4 user id.
  1900. if owner:
  1901. email = self.make_email(owner)
  1902. else:
  1903. email = self.make_email(self.p4UserId())
  1904. tagger = "%s %s %s" % (email, epoch, self.tz)
  1905. gitStream.write("tagger %s\n" % tagger)
  1906. print "labelDetails=",labelDetails
  1907. if labelDetails.has_key('Description'):
  1908. description = labelDetails['Description']
  1909. else:
  1910. description = 'Label from git p4'
  1911. gitStream.write("data %d\n" % len(description))
  1912. gitStream.write(description)
  1913. gitStream.write("\n")
  1914. def commit(self, details, files, branch, parent = ""):
  1915. epoch = details["time"]
  1916. author = details["user"]
  1917. if self.verbose:
  1918. print "commit into %s" % branch
  1919. # start with reading files; if that fails, we should not
  1920. # create a commit.
  1921. new_files = []
  1922. for f in files:
  1923. if [p for p in self.branchPrefixes if p4PathStartsWith(f['path'], p)]:
  1924. new_files.append (f)
  1925. else:
  1926. sys.stderr.write("Ignoring file outside of prefix: %s\n" % f['path'])
  1927. self.gitStream.write("commit %s\n" % branch)
  1928. # gitStream.write("mark :%s\n" % details["change"])
  1929. self.committedChanges.add(int(details["change"]))
  1930. committer = ""
  1931. if author not in self.users:
  1932. self.getUserMapFromPerforceServer()
  1933. committer = "%s %s %s" % (self.make_email(author), epoch, self.tz)
  1934. self.gitStream.write("committer %s\n" % committer)
  1935. self.gitStream.write("data <<EOT\n")
  1936. self.gitStream.write(details["desc"])
  1937. self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s" %
  1938. (','.join(self.branchPrefixes), details["change"]))
  1939. if len(details['options']) > 0:
  1940. self.gitStream.write(": options = %s" % details['options'])
  1941. self.gitStream.write("]\nEOT\n\n")
  1942. if len(parent) > 0:
  1943. if self.verbose:
  1944. print "parent %s" % parent
  1945. self.gitStream.write("from %s\n" % parent)
  1946. self.streamP4Files(new_files)
  1947. self.gitStream.write("\n")
  1948. change = int(details["change"])
  1949. if self.labels.has_key(change):
  1950. label = self.labels[change]
  1951. labelDetails = label[0]
  1952. labelRevisions = label[1]
  1953. if self.verbose:
  1954. print "Change %s is labelled %s" % (change, labelDetails)
  1955. files = p4CmdList(["files"] + ["%s...@%s" % (p, change)
  1956. for p in self.branchPrefixes])
  1957. if len(files) == len(labelRevisions):
  1958. cleanedFiles = {}
  1959. for info in files:
  1960. if info["action"] in self.delete_actions:
  1961. continue
  1962. cleanedFiles[info["depotFile"]] = info["rev"]
  1963. if cleanedFiles == labelRevisions:
  1964. self.streamTag(self.gitStream, 'tag_%s' % labelDetails['label'], labelDetails, branch, epoch)
  1965. else:
  1966. if not self.silent:
  1967. print ("Tag %s does not match with change %s: files do not match."
  1968. % (labelDetails["label"], change))
  1969. else:
  1970. if not self.silent:
  1971. print ("Tag %s does not match with change %s: file count is different."
  1972. % (labelDetails["label"], change))
  1973. # Build a dictionary of changelists and labels, for "detect-labels" option.
  1974. def getLabels(self):
  1975. self.labels = {}
  1976. l = p4CmdList(["labels"] + ["%s..." % p for p in self.depotPaths])
  1977. if len(l) > 0 and not self.silent:
  1978. print "Finding files belonging to labels in %s" % `self.depotPaths`
  1979. for output in l:
  1980. label = output["label"]
  1981. revisions = {}
  1982. newestChange = 0
  1983. if self.verbose:
  1984. print "Querying files for label %s" % label
  1985. for file in p4CmdList(["files"] +
  1986. ["%s...@%s" % (p, label)
  1987. for p in self.depotPaths]):
  1988. revisions[file["depotFile"]] = file["rev"]
  1989. change = int(file["change"])
  1990. if change > newestChange:
  1991. newestChange = change
  1992. self.labels[newestChange] = [output, revisions]
  1993. if self.verbose:
  1994. print "Label changes: %s" % self.labels.keys()
  1995. # Import p4 labels as git tags. A direct mapping does not
  1996. # exist, so assume that if all the files are at the same revision
  1997. # then we can use that, or it's something more complicated we should
  1998. # just ignore.
  1999. def importP4Labels(self, stream, p4Labels):
  2000. if verbose:
  2001. print "import p4 labels: " + ' '.join(p4Labels)
  2002. ignoredP4Labels = gitConfigList("git-p4.ignoredP4Labels")
  2003. validLabelRegexp = gitConfig("git-p4.labelImportRegexp")
  2004. if len(validLabelRegexp) == 0:
  2005. validLabelRegexp = defaultLabelRegexp
  2006. m = re.compile(validLabelRegexp)
  2007. for name in p4Labels:
  2008. commitFound = False
  2009. if not m.match(name):
  2010. if verbose:
  2011. print "label %s does not match regexp %s" % (name,validLabelRegexp)
  2012. continue
  2013. if name in ignoredP4Labels:
  2014. continue
  2015. labelDetails = p4CmdList(['label', "-o", name])[0]
  2016. # get the most recent changelist for each file in this label
  2017. change = p4Cmd(["changes", "-m", "1"] + ["%s...@%s" % (p, name)
  2018. for p in self.depotPaths])
  2019. if change.has_key('change'):
  2020. # find the corresponding git commit; take the oldest commit
  2021. changelist = int(change['change'])
  2022. gitCommit = read_pipe(["git", "rev-list", "--max-count=1",
  2023. "--reverse", ":/\[git-p4:.*change = %d\]" % changelist])
  2024. if len(gitCommit) == 0:
  2025. print "could not find git commit for changelist %d" % changelist
  2026. else:
  2027. gitCommit = gitCommit.strip()
  2028. commitFound = True
  2029. # Convert from p4 time format
  2030. try:
  2031. tmwhen = time.strptime(labelDetails['Update'], "%Y/%m/%d %H:%M:%S")
  2032. except ValueError:
  2033. print "Could not convert label time %s" % labelDetails['Update']
  2034. tmwhen = 1
  2035. when = int(time.mktime(tmwhen))
  2036. self.streamTag(stream, name, labelDetails, gitCommit, when)
  2037. if verbose:
  2038. print "p4 label %s mapped to git commit %s" % (name, gitCommit)
  2039. else:
  2040. if verbose:
  2041. print "Label %s has no changelists - possibly deleted?" % name
  2042. if not commitFound:
  2043. # We can't import this label; don't try again as it will get very
  2044. # expensive repeatedly fetching all the files for labels that will
  2045. # never be imported. If the label is moved in the future, the
  2046. # ignore will need to be removed manually.
  2047. system(["git", "config", "--add", "git-p4.ignoredP4Labels", name])
  2048. def guessProjectName(self):
  2049. for p in self.depotPaths:
  2050. if p.endswith("/"):
  2051. p = p[:-1]
  2052. p = p[p.strip().rfind("/") + 1:]
  2053. if not p.endswith("/"):
  2054. p += "/"
  2055. return p
  2056. def getBranchMapping(self):
  2057. lostAndFoundBranches = set()
  2058. user = gitConfig("git-p4.branchUser")
  2059. if len(user) > 0:
  2060. command = "branches -u %s" % user
  2061. else:
  2062. command = "branches"
  2063. for info in p4CmdList(command):
  2064. details = p4Cmd(["branch", "-o", info["branch"]])
  2065. viewIdx = 0
  2066. while details.has_key("View%s" % viewIdx):
  2067. paths = details["View%s" % viewIdx].split(" ")
  2068. viewIdx = viewIdx + 1
  2069. # require standard //depot/foo/... //depot/bar/... mapping
  2070. if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
  2071. continue
  2072. source = paths[0]
  2073. destination = paths[1]
  2074. ## HACK
  2075. if p4PathStartsWith(source, self.depotPaths[0]) and p4PathStartsWith(destination, self.depotPaths[0]):
  2076. source = source[len(self.depotPaths[0]):-4]
  2077. destination = destination[len(self.depotPaths[0]):-4]
  2078. if destination in self.knownBranches:
  2079. if not self.silent:
  2080. print "p4 branch %s defines a mapping from %s to %s" % (info["branch"], source, destination)
  2081. print "but there exists another mapping from %s to %s already!" % (self.knownBranches[destination], destination)
  2082. continue
  2083. self.knownBranches[destination] = source
  2084. lostAndFoundBranches.discard(destination)
  2085. if source not in self.knownBranches:
  2086. lostAndFoundBranches.add(source)
  2087. # Perforce does not strictly require branches to be defined, so we also
  2088. # check git config for a branch list.
  2089. #
  2090. # Example of branch definition in git config file:
  2091. # [git-p4]
  2092. # branchList=main:branchA
  2093. # branchList=main:branchB
  2094. # branchList=branchA:branchC
  2095. configBranches = gitConfigList("git-p4.branchList")
  2096. for branch in configBranches:
  2097. if branch:
  2098. (source, destination) = branch.split(":")
  2099. self.knownBranches[destination] = source
  2100. lostAndFoundBranches.discard(destination)
  2101. if source not in self.knownBranches:
  2102. lostAndFoundBranches.add(source)
  2103. for branch in lostAndFoundBranches:
  2104. self.knownBranches[branch] = branch
  2105. def getBranchMappingFromGitBranches(self):
  2106. branches = p4BranchesInGit(self.importIntoRemotes)
  2107. for branch in branches.keys():
  2108. if branch == "master":
  2109. branch = "main"
  2110. else:
  2111. branch = branch[len(self.projectName):]
  2112. self.knownBranches[branch] = branch
  2113. def listExistingP4GitBranches(self):
  2114. # branches holds mapping from name to commit
  2115. branches = p4BranchesInGit(self.importIntoRemotes)
  2116. self.p4BranchesInGit = branches.keys()
  2117. for branch in branches.keys():
  2118. self.initialParents[self.refPrefix + branch] = branches[branch]
  2119. def updateOptionDict(self, d):
  2120. option_keys = {}
  2121. if self.keepRepoPath:
  2122. option_keys['keepRepoPath'] = 1
  2123. d["options"] = ' '.join(sorted(option_keys.keys()))
  2124. def readOptions(self, d):
  2125. self.keepRepoPath = (d.has_key('options')
  2126. and ('keepRepoPath' in d['options']))
  2127. def gitRefForBranch(self, branch):
  2128. if branch == "main":
  2129. return self.refPrefix + "master"
  2130. if len(branch) <= 0:
  2131. return branch
  2132. return self.refPrefix + self.projectName + branch
  2133. def gitCommitByP4Change(self, ref, change):
  2134. if self.verbose:
  2135. print "looking in ref " + ref + " for change %s using bisect..." % change
  2136. earliestCommit = ""
  2137. latestCommit = parseRevision(ref)
  2138. while True:
  2139. if self.verbose:
  2140. print "trying: earliest %s latest %s" % (earliestCommit, latestCommit)
  2141. next = read_pipe("git rev-list --bisect %s %s" % (latestCommit, earliestCommit)).strip()
  2142. if len(next) == 0:
  2143. if self.verbose:
  2144. print "argh"
  2145. return ""
  2146. log = extractLogMessageFromGitCommit(next)
  2147. settings = extractSettingsGitLog(log)
  2148. currentChange = int(settings['change'])
  2149. if self.verbose:
  2150. print "current change %s" % currentChange
  2151. if currentChange == change:
  2152. if self.verbose:
  2153. print "found %s" % next
  2154. return next
  2155. if currentChange < change:
  2156. earliestCommit = "^%s" % next
  2157. else:
  2158. latestCommit = "%s" % next
  2159. return ""
  2160. def importNewBranch(self, branch, maxChange):
  2161. # make fast-import flush all changes to disk and update the refs using the checkpoint
  2162. # command so that we can try to find the branch parent in the git history
  2163. self.gitStream.write("checkpoint\n\n");
  2164. self.gitStream.flush();
  2165. branchPrefix = self.depotPaths[0] + branch + "/"
  2166. range = "@1,%s" % maxChange
  2167. #print "prefix" + branchPrefix
  2168. changes = p4ChangesForPaths([branchPrefix], range)
  2169. if len(changes) <= 0:
  2170. return False
  2171. firstChange = changes[0]
  2172. #print "first change in branch: %s" % firstChange
  2173. sourceBranch = self.knownBranches[branch]
  2174. sourceDepotPath = self.depotPaths[0] + sourceBranch
  2175. sourceRef = self.gitRefForBranch(sourceBranch)
  2176. #print "source " + sourceBranch
  2177. branchParentChange = int(p4Cmd(["changes", "-m", "1", "%s...@1,%s" % (sourceDepotPath, firstChange)])["change"])
  2178. #print "branch parent: %s" % branchParentChange
  2179. gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)
  2180. if len(gitParent) > 0:
  2181. self.initialParents[self.gitRefForBranch(branch)] = gitParent
  2182. #print "parent git commit: %s" % gitParent
  2183. self.importChanges(changes)
  2184. return True
  2185. def searchParent(self, parent, branch, target):
  2186. parentFound = False
  2187. for blob in read_pipe_lines(["git", "rev-list", "--reverse", "--no-merges", parent]):
  2188. blob = blob.strip()
  2189. if len(read_pipe(["git", "diff-tree", blob, target])) == 0:
  2190. parentFound = True
  2191. if self.verbose:
  2192. print "Found parent of %s in commit %s" % (branch, blob)
  2193. break
  2194. if parentFound:
  2195. return blob
  2196. else:
  2197. return None
  2198. def importChanges(self, changes):
  2199. cnt = 1
  2200. for change in changes:
  2201. description = p4_describe(change)
  2202. self.updateOptionDict(description)
  2203. if not self.silent:
  2204. sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
  2205. sys.stdout.flush()
  2206. cnt = cnt + 1
  2207. try:
  2208. if self.detectBranches:
  2209. branches = self.splitFilesIntoBranches(description)
  2210. for branch in branches.keys():
  2211. ## HACK --hwn
  2212. branchPrefix = self.depotPaths[0] + branch + "/"
  2213. self.branchPrefixes = [ branchPrefix ]
  2214. parent = ""
  2215. filesForCommit = branches[branch]
  2216. if self.verbose:
  2217. print "branch is %s" % branch
  2218. self.updatedBranches.add(branch)
  2219. if branch not in self.createdBranches:
  2220. self.createdBranches.add(branch)
  2221. parent = self.knownBranches[branch]
  2222. if parent == branch:
  2223. parent = ""
  2224. else:
  2225. fullBranch = self.projectName + branch
  2226. if fullBranch not in self.p4BranchesInGit:
  2227. if not self.silent:
  2228. print("\n Importing new branch %s" % fullBranch);
  2229. if self.importNewBranch(branch, change - 1):
  2230. parent = ""
  2231. self.p4BranchesInGit.append(fullBranch)
  2232. if not self.silent:
  2233. print("\n Resuming with change %s" % change);
  2234. if self.verbose:
  2235. print "parent determined through known branches: %s" % parent
  2236. branch = self.gitRefForBranch(branch)
  2237. parent = self.gitRefForBranch(parent)
  2238. if self.verbose:
  2239. print "looking for initial parent for %s; current parent is %s" % (branch, parent)
  2240. if len(parent) == 0 and branch in self.initialParents:
  2241. parent = self.initialParents[branch]
  2242. del self.initialParents[branch]
  2243. blob = None
  2244. if len(parent) > 0:
  2245. tempBranch = os.path.join(self.tempBranchLocation, "%d" % (change))
  2246. if self.verbose:
  2247. print "Creating temporary branch: " + tempBranch
  2248. self.commit(description, filesForCommit, tempBranch)
  2249. self.tempBranches.append(tempBranch)
  2250. self.checkpoint()
  2251. blob = self.searchParent(parent, branch, tempBranch)
  2252. if blob:
  2253. self.commit(description, filesForCommit, branch, blob)
  2254. else:
  2255. if self.verbose:
  2256. print "Parent of %s not found. Committing into head of %s" % (branch, parent)
  2257. self.commit(description, filesForCommit, branch, parent)
  2258. else:
  2259. files = self.extractFilesFromCommit(description)
  2260. self.commit(description, files, self.branch,
  2261. self.initialParent)
  2262. self.initialParent = ""
  2263. except IOError:
  2264. print self.gitError.read()
  2265. sys.exit(1)
  2266. def importHeadRevision(self, revision):
  2267. print "Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), revision, self.branch)
  2268. details = {}
  2269. details["user"] = "git perforce import user"
  2270. details["desc"] = ("Initial import of %s from the state at revision %s\n"
  2271. % (' '.join(self.depotPaths), revision))
  2272. details["change"] = revision
  2273. newestRevision = 0
  2274. fileCnt = 0
  2275. fileArgs = ["%s...%s" % (p,revision) for p in self.depotPaths]
  2276. for info in p4CmdList(["files"] + fileArgs):
  2277. if 'code' in info and info['code'] == 'error':
  2278. sys.stderr.write("p4 returned an error: %s\n"
  2279. % info['data'])
  2280. if info['data'].find("must refer to client") >= 0:
  2281. sys.stderr.write("This particular p4 error is misleading.\n")
  2282. sys.stderr.write("Perhaps the depot path was misspelled.\n");
  2283. sys.stderr.write("Depot path: %s\n" % " ".join(self.depotPaths))
  2284. sys.exit(1)
  2285. if 'p4ExitCode' in info:
  2286. sys.stderr.write("p4 exitcode: %s\n" % info['p4ExitCode'])
  2287. sys.exit(1)
  2288. change = int(info["change"])
  2289. if change > newestRevision:
  2290. newestRevision = change
  2291. if info["action"] in self.delete_actions:
  2292. # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
  2293. #fileCnt = fileCnt + 1
  2294. continue
  2295. for prop in ["depotFile", "rev", "action", "type" ]:
  2296. details["%s%s" % (prop, fileCnt)] = info[prop]
  2297. fileCnt = fileCnt + 1
  2298. details["change"] = newestRevision
  2299. # Use time from top-most change so that all git p4 clones of
  2300. # the same p4 repo have the same commit SHA1s.
  2301. res = p4_describe(newestRevision)
  2302. details["time"] = res["time"]
  2303. self.updateOptionDict(details)
  2304. try:
  2305. self.commit(details, self.extractFilesFromCommit(details), self.branch)
  2306. except IOError:
  2307. print "IO error with git fast-import. Is your git version recent enough?"
  2308. print self.gitError.read()
  2309. def run(self, args):
  2310. self.depotPaths = []
  2311. self.changeRange = ""
  2312. self.initialParent = ""
  2313. self.previousDepotPaths = []
  2314. # map from branch depot path to parent branch
  2315. self.knownBranches = {}
  2316. self.initialParents = {}
  2317. self.hasOrigin = originP4BranchesExist()
  2318. if not self.syncWithOrigin:
  2319. self.hasOrigin = False
  2320. if self.importIntoRemotes:
  2321. self.refPrefix = "refs/remotes/p4/"
  2322. else:
  2323. self.refPrefix = "refs/heads/p4/"
  2324. if self.syncWithOrigin and self.hasOrigin:
  2325. if not self.silent:
  2326. print "Syncing with origin first by calling git fetch origin"
  2327. system("git fetch origin")
  2328. if len(self.branch) == 0:
  2329. self.branch = self.refPrefix + "master"
  2330. if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
  2331. system("git update-ref %s refs/heads/p4" % self.branch)
  2332. system("git branch -D p4");
  2333. # create it /after/ importing, when master exists
  2334. if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes and gitBranchExists(self.branch):
  2335. system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
  2336. # accept either the command-line option, or the configuration variable
  2337. if self.useClientSpec:
  2338. # will use this after clone to set the variable
  2339. self.useClientSpec_from_options = True
  2340. else:
  2341. if gitConfig("git-p4.useclientspec", "--bool") == "true":
  2342. self.useClientSpec = True
  2343. if self.useClientSpec:
  2344. self.clientSpecDirs = getClientSpec()
  2345. # TODO: should always look at previous commits,
  2346. # merge with previous imports, if possible.
  2347. if args == []:
  2348. if self.hasOrigin:
  2349. createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)
  2350. self.listExistingP4GitBranches()
  2351. if len(self.p4BranchesInGit) > 1:
  2352. if not self.silent:
  2353. print "Importing from/into multiple branches"
  2354. self.detectBranches = True
  2355. if self.verbose:
  2356. print "branches: %s" % self.p4BranchesInGit
  2357. p4Change = 0
  2358. for branch in self.p4BranchesInGit:
  2359. logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
  2360. settings = extractSettingsGitLog(logMsg)
  2361. self.readOptions(settings)
  2362. if (settings.has_key('depot-paths')
  2363. and settings.has_key ('change')):
  2364. change = int(settings['change']) + 1
  2365. p4Change = max(p4Change, change)
  2366. depotPaths = sorted(settings['depot-paths'])
  2367. if self.previousDepotPaths == []:
  2368. self.previousDepotPaths = depotPaths
  2369. else:
  2370. paths = []
  2371. for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
  2372. prev_list = prev.split("/")
  2373. cur_list = cur.split("/")
  2374. for i in range(0, min(len(cur_list), len(prev_list))):
  2375. if cur_list[i] <> prev_list[i]:
  2376. i = i - 1
  2377. break
  2378. paths.append ("/".join(cur_list[:i + 1]))
  2379. self.previousDepotPaths = paths
  2380. if p4Change > 0:
  2381. self.depotPaths = sorted(self.previousDepotPaths)
  2382. self.changeRange = "@%s,#head" % p4Change
  2383. if not self.detectBranches:
  2384. self.initialParent = parseRevision(self.branch)
  2385. if not self.silent and not self.detectBranches:
  2386. print "Performing incremental import into %s git branch" % self.branch
  2387. if not self.branch.startswith("refs/"):
  2388. self.branch = "refs/heads/" + self.branch
  2389. if len(args) == 0 and self.depotPaths:
  2390. if not self.silent:
  2391. print "Depot paths: %s" % ' '.join(self.depotPaths)
  2392. else:
  2393. if self.depotPaths and self.depotPaths != args:
  2394. print ("previous import used depot path %s and now %s was specified. "
  2395. "This doesn't work!" % (' '.join (self.depotPaths),
  2396. ' '.join (args)))
  2397. sys.exit(1)
  2398. self.depotPaths = sorted(args)
  2399. revision = ""
  2400. self.users = {}
  2401. # Make sure no revision specifiers are used when --changesfile
  2402. # is specified.
  2403. bad_changesfile = False
  2404. if len(self.changesFile) > 0:
  2405. for p in self.depotPaths:
  2406. if p.find("@") >= 0 or p.find("#") >= 0:
  2407. bad_changesfile = True
  2408. break
  2409. if bad_changesfile:
  2410. die("Option --changesfile is incompatible with revision specifiers")
  2411. newPaths = []
  2412. for p in self.depotPaths:
  2413. if p.find("@") != -1:
  2414. atIdx = p.index("@")
  2415. self.changeRange = p[atIdx:]
  2416. if self.changeRange == "@all":
  2417. self.changeRange = ""
  2418. elif ',' not in self.changeRange:
  2419. revision = self.changeRange
  2420. self.changeRange = ""
  2421. p = p[:atIdx]
  2422. elif p.find("#") != -1:
  2423. hashIdx = p.index("#")
  2424. revision = p[hashIdx:]
  2425. p = p[:hashIdx]
  2426. elif self.previousDepotPaths == []:
  2427. # pay attention to changesfile, if given, else import
  2428. # the entire p4 tree at the head revision
  2429. if len(self.changesFile) == 0:
  2430. revision = "#head"
  2431. p = re.sub ("\.\.\.$", "", p)
  2432. if not p.endswith("/"):
  2433. p += "/"
  2434. newPaths.append(p)
  2435. self.depotPaths = newPaths
  2436. # --detect-branches may change this for each branch
  2437. self.branchPrefixes = self.depotPaths
  2438. self.loadUserMapFromCache()
  2439. self.labels = {}
  2440. if self.detectLabels:
  2441. self.getLabels();
  2442. if self.detectBranches:
  2443. ## FIXME - what's a P4 projectName ?
  2444. self.projectName = self.guessProjectName()
  2445. if self.hasOrigin:
  2446. self.getBranchMappingFromGitBranches()
  2447. else:
  2448. self.getBranchMapping()
  2449. if self.verbose:
  2450. print "p4-git branches: %s" % self.p4BranchesInGit
  2451. print "initial parents: %s" % self.initialParents
  2452. for b in self.p4BranchesInGit:
  2453. if b != "master":
  2454. ## FIXME
  2455. b = b[len(self.projectName):]
  2456. self.createdBranches.add(b)
  2457. self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
  2458. self.importProcess = subprocess.Popen(["git", "fast-import"],
  2459. stdin=subprocess.PIPE,
  2460. stdout=subprocess.PIPE,
  2461. stderr=subprocess.PIPE);
  2462. self.gitOutput = self.importProcess.stdout
  2463. self.gitStream = self.importProcess.stdin
  2464. self.gitError = self.importProcess.stderr
  2465. if revision:
  2466. self.importHeadRevision(revision)
  2467. else:
  2468. changes = []
  2469. if len(self.changesFile) > 0:
  2470. output = open(self.changesFile).readlines()
  2471. changeSet = set()
  2472. for line in output:
  2473. changeSet.add(int(line))
  2474. for change in changeSet:
  2475. changes.append(change)
  2476. changes.sort()
  2477. else:
  2478. # catch "git p4 sync" with no new branches, in a repo that
  2479. # does not have any existing p4 branches
  2480. if len(args) == 0 and not self.p4BranchesInGit:
  2481. die("No remote p4 branches. Perhaps you never did \"git p4 clone\" in here.");
  2482. if self.verbose:
  2483. print "Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
  2484. self.changeRange)
  2485. changes = p4ChangesForPaths(self.depotPaths, self.changeRange)
  2486. if len(self.maxChanges) > 0:
  2487. changes = changes[:min(int(self.maxChanges), len(changes))]
  2488. if len(changes) == 0:
  2489. if not self.silent:
  2490. print "No changes to import!"
  2491. else:
  2492. if not self.silent and not self.detectBranches:
  2493. print "Import destination: %s" % self.branch
  2494. self.updatedBranches = set()
  2495. self.importChanges(changes)
  2496. if not self.silent:
  2497. print ""
  2498. if len(self.updatedBranches) > 0:
  2499. sys.stdout.write("Updated branches: ")
  2500. for b in self.updatedBranches:
  2501. sys.stdout.write("%s " % b)
  2502. sys.stdout.write("\n")
  2503. if gitConfig("git-p4.importLabels", "--bool") == "true":
  2504. self.importLabels = True
  2505. if self.importLabels:
  2506. p4Labels = getP4Labels(self.depotPaths)
  2507. gitTags = getGitTags()
  2508. missingP4Labels = p4Labels - gitTags
  2509. self.importP4Labels(self.gitStream, missingP4Labels)
  2510. self.gitStream.close()
  2511. if self.importProcess.wait() != 0:
  2512. die("fast-import failed: %s" % self.gitError.read())
  2513. self.gitOutput.close()
  2514. self.gitError.close()
  2515. # Cleanup temporary branches created during import
  2516. if self.tempBranches != []:
  2517. for branch in self.tempBranches:
  2518. read_pipe("git update-ref -d %s" % branch)
  2519. os.rmdir(os.path.join(os.environ.get("GIT_DIR", ".git"), self.tempBranchLocation))
  2520. return True
  2521. class P4Rebase(Command):
  2522. def __init__(self):
  2523. Command.__init__(self)
  2524. self.options = [
  2525. optparse.make_option("--import-labels", dest="importLabels", action="store_true"),
  2526. ]
  2527. self.importLabels = False
  2528. self.description = ("Fetches the latest revision from perforce and "
  2529. + "rebases the current work (branch) against it")
  2530. def run(self, args):
  2531. sync = P4Sync()
  2532. sync.importLabels = self.importLabels
  2533. sync.run([])
  2534. return self.rebase()
  2535. def rebase(self):
  2536. if os.system("git update-index --refresh") != 0:
  2537. die("Some files in your working directory are modified and different than what is in your index. You can use git update-index <filename> to bring the index up-to-date or stash away all your changes with git stash.");
  2538. if len(read_pipe("git diff-index HEAD --")) > 0:
  2539. die("You have uncommited changes. Please commit them before rebasing or stash them away with git stash.");
  2540. [upstream, settings] = findUpstreamBranchPoint()
  2541. if len(upstream) == 0:
  2542. die("Cannot find upstream branchpoint for rebase")
  2543. # the branchpoint may be p4/foo~3, so strip off the parent
  2544. upstream = re.sub("~[0-9]+$", "", upstream)
  2545. print "Rebasing the current branch onto %s" % upstream
  2546. oldHead = read_pipe("git rev-parse HEAD").strip()
  2547. system("git rebase %s" % upstream)
  2548. system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
  2549. return True
  2550. class P4Clone(P4Sync):
  2551. def __init__(self):
  2552. P4Sync.__init__(self)
  2553. self.description = "Creates a new git repository and imports from Perforce into it"
  2554. self.usage = "usage: %prog [options] //depot/path[@revRange]"
  2555. self.options += [
  2556. optparse.make_option("--destination", dest="cloneDestination",
  2557. action='store', default=None,
  2558. help="where to leave result of the clone"),
  2559. optparse.make_option("-/", dest="cloneExclude",
  2560. action="append", type="string",
  2561. help="exclude depot path"),
  2562. optparse.make_option("--bare", dest="cloneBare",
  2563. action="store_true", default=False),
  2564. ]
  2565. self.cloneDestination = None
  2566. self.needsGit = False
  2567. self.cloneBare = False
  2568. # This is required for the "append" cloneExclude action
  2569. def ensure_value(self, attr, value):
  2570. if not hasattr(self, attr) or getattr(self, attr) is None:
  2571. setattr(self, attr, value)
  2572. return getattr(self, attr)
  2573. def defaultDestination(self, args):
  2574. ## TODO: use common prefix of args?
  2575. depotPath = args[0]
  2576. depotDir = re.sub("(@[^@]*)$", "", depotPath)
  2577. depotDir = re.sub("(#[^#]*)$", "", depotDir)
  2578. depotDir = re.sub(r"\.\.\.$", "", depotDir)
  2579. depotDir = re.sub(r"/$", "", depotDir)
  2580. return os.path.split(depotDir)[1]
  2581. def run(self, args):
  2582. if len(args) < 1:
  2583. return False
  2584. if self.keepRepoPath and not self.cloneDestination:
  2585. sys.stderr.write("Must specify destination for --keep-path\n")
  2586. sys.exit(1)
  2587. depotPaths = args
  2588. if not self.cloneDestination and len(depotPaths) > 1:
  2589. self.cloneDestination = depotPaths[-1]
  2590. depotPaths = depotPaths[:-1]
  2591. self.cloneExclude = ["/"+p for p in self.cloneExclude]
  2592. for p in depotPaths:
  2593. if not p.startswith("//"):
  2594. return False
  2595. if not self.cloneDestination:
  2596. self.cloneDestination = self.defaultDestination(args)
  2597. print "Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination)
  2598. if not os.path.exists(self.cloneDestination):
  2599. os.makedirs(self.cloneDestination)
  2600. chdir(self.cloneDestination)
  2601. init_cmd = [ "git", "init" ]
  2602. if self.cloneBare:
  2603. init_cmd.append("--bare")
  2604. subprocess.check_call(init_cmd)
  2605. if not P4Sync.run(self, depotPaths):
  2606. return False
  2607. if self.branch != "master":
  2608. if self.importIntoRemotes:
  2609. masterbranch = "refs/remotes/p4/master"
  2610. else:
  2611. masterbranch = "refs/heads/p4/master"
  2612. if gitBranchExists(masterbranch):
  2613. system("git branch master %s" % masterbranch)
  2614. if not self.cloneBare:
  2615. system("git checkout -f")
  2616. else:
  2617. print "Could not detect main branch. No checkout/master branch created."
  2618. # auto-set this variable if invoked with --use-client-spec
  2619. if self.useClientSpec_from_options:
  2620. system("git config --bool git-p4.useclientspec true")
  2621. return True
  2622. class P4Branches(Command):
  2623. def __init__(self):
  2624. Command.__init__(self)
  2625. self.options = [ ]
  2626. self.description = ("Shows the git branches that hold imports and their "
  2627. + "corresponding perforce depot paths")
  2628. self.verbose = False
  2629. def run(self, args):
  2630. if originP4BranchesExist():
  2631. createOrUpdateBranchesFromOrigin()
  2632. cmdline = "git rev-parse --symbolic "
  2633. cmdline += " --remotes"
  2634. for line in read_pipe_lines(cmdline):
  2635. line = line.strip()
  2636. if not line.startswith('p4/') or line == "p4/HEAD":
  2637. continue
  2638. branch = line
  2639. log = extractLogMessageFromGitCommit("refs/remotes/%s" % branch)
  2640. settings = extractSettingsGitLog(log)
  2641. print "%s <= %s (%s)" % (branch, ",".join(settings["depot-paths"]), settings["change"])
  2642. return True
  2643. class HelpFormatter(optparse.IndentedHelpFormatter):
  2644. def __init__(self):
  2645. optparse.IndentedHelpFormatter.__init__(self)
  2646. def format_description(self, description):
  2647. if description:
  2648. return description + "\n"
  2649. else:
  2650. return ""
  2651. def printUsage(commands):
  2652. print "usage: %s <command> [options]" % sys.argv[0]
  2653. print ""
  2654. print "valid commands: %s" % ", ".join(commands)
  2655. print ""
  2656. print "Try %s <command> --help for command specific help." % sys.argv[0]
  2657. print ""
  2658. commands = {
  2659. "debug" : P4Debug,
  2660. "submit" : P4Submit,
  2661. "commit" : P4Submit,
  2662. "sync" : P4Sync,
  2663. "rebase" : P4Rebase,
  2664. "clone" : P4Clone,
  2665. "rollback" : P4RollBack,
  2666. "branches" : P4Branches
  2667. }
  2668. def main():
  2669. if len(sys.argv[1:]) == 0:
  2670. printUsage(commands.keys())
  2671. sys.exit(2)
  2672. cmdName = sys.argv[1]
  2673. try:
  2674. klass = commands[cmdName]
  2675. cmd = klass()
  2676. except KeyError:
  2677. print "unknown command %s" % cmdName
  2678. print ""
  2679. printUsage(commands.keys())
  2680. sys.exit(2)
  2681. options = cmd.options
  2682. cmd.gitdir = os.environ.get("GIT_DIR", None)
  2683. args = sys.argv[2:]
  2684. options.append(optparse.make_option("--verbose", "-v", dest="verbose", action="store_true"))
  2685. if cmd.needsGit:
  2686. options.append(optparse.make_option("--git-dir", dest="gitdir"))
  2687. parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
  2688. options,
  2689. description = cmd.description,
  2690. formatter = HelpFormatter())
  2691. (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
  2692. global verbose
  2693. verbose = cmd.verbose
  2694. if cmd.needsGit:
  2695. if cmd.gitdir == None:
  2696. cmd.gitdir = os.path.abspath(".git")
  2697. if not isValidGitDir(cmd.gitdir):
  2698. cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
  2699. if os.path.exists(cmd.gitdir):
  2700. cdup = read_pipe("git rev-parse --show-cdup").strip()
  2701. if len(cdup) > 0:
  2702. chdir(cdup);
  2703. if not isValidGitDir(cmd.gitdir):
  2704. if isValidGitDir(cmd.gitdir + "/.git"):
  2705. cmd.gitdir += "/.git"
  2706. else:
  2707. die("fatal: cannot locate git repository at %s" % cmd.gitdir)
  2708. os.environ["GIT_DIR"] = cmd.gitdir
  2709. if not cmd.run(args):
  2710. parser.print_help()
  2711. sys.exit(2)
  2712. if __name__ == '__main__':
  2713. main()