PageRenderTime 68ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/git-p4.py

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