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

/git-p4.py

https://bitbucket.org/bluezoo/git
Python | 3242 lines | 3134 code | 61 blank | 47 comment | 125 complexity | 9c3354574a939b9049b165a69b54a968 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, Apache-2.0, BSD-2-Clause

Large files files are truncated, but you can click here to view the full file

  1. #!/usr/bin/env python
  2. #
  3. # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
  4. #
  5. # Author: Simon Hausmann <simon@lst.de>
  6. # Copyright: 2007 Simon Hausmann <simon@lst.de>
  7. # 2007 Trolltech ASA
  8. # License: MIT <http://www.opensource.org/licenses/mit-license.php>
  9. #
  10. import optparse, sys, os, marshal, subprocess, shelve
  11. import tempfile, getopt, os.path, time, platform
  12. import re, shutil
  13. verbose = False
  14. # Only labels/tags matching this will be imported/exported
  15. defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$'
  16. def p4_build_cmd(cmd):
  17. """Build a suitable p4 command line.
  18. This consolidates building and returning a p4 command line into one
  19. location. It means that hooking into the environment, or other configuration
  20. can be done more easily.
  21. """
  22. real_cmd = ["p4"]
  23. user = gitConfig("git-p4.user")
  24. if len(user) > 0:
  25. real_cmd += ["-u",user]
  26. password = gitConfig("git-p4.password")
  27. if len(password) > 0:
  28. real_cmd += ["-P", password]
  29. port = gitConfig("git-p4.port")
  30. if len(port) > 0:
  31. real_cmd += ["-p", port]
  32. host = gitConfig("git-p4.host")
  33. if len(host) > 0:
  34. real_cmd += ["-H", host]
  35. client = gitConfig("git-p4.client")
  36. if len(client) > 0:
  37. real_cmd += ["-c", client]
  38. if isinstance(cmd,basestring):
  39. real_cmd = ' '.join(real_cmd) + ' ' + cmd
  40. else:
  41. real_cmd += cmd
  42. return real_cmd
  43. def chdir(dir):
  44. # P4 uses the PWD environment variable rather than getcwd(). Since we're
  45. # not using the shell, we have to set it ourselves. This path could
  46. # be relative, so go there first, then figure out where we ended up.
  47. os.chdir(dir)
  48. os.environ['PWD'] = os.getcwd()
  49. def die(msg):
  50. if verbose:
  51. raise Exception(msg)
  52. else:
  53. sys.stderr.write(msg + "\n")
  54. sys.exit(1)
  55. def write_pipe(c, stdin):
  56. if verbose:
  57. sys.stderr.write('Writing pipe: %s\n' % str(c))
  58. expand = isinstance(c,basestring)
  59. p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand)
  60. pipe = p.stdin
  61. val = pipe.write(stdin)
  62. pipe.close()
  63. if p.wait():
  64. die('Command failed: %s' % str(c))
  65. return val
  66. def p4_write_pipe(c, stdin):
  67. real_cmd = p4_build_cmd(c)
  68. return write_pipe(real_cmd, stdin)
  69. def read_pipe(c, ignore_error=False):
  70. if verbose:
  71. sys.stderr.write('Reading pipe: %s\n' % str(c))
  72. expand = isinstance(c,basestring)
  73. p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)
  74. pipe = p.stdout
  75. val = pipe.read()
  76. if p.wait() and not ignore_error:
  77. die('Command failed: %s' % str(c))
  78. return val
  79. def p4_read_pipe(c, ignore_error=False):
  80. real_cmd = p4_build_cmd(c)
  81. return read_pipe(real_cmd, ignore_error)
  82. def read_pipe_lines(c):
  83. if verbose:
  84. sys.stderr.write('Reading pipe: %s\n' % str(c))
  85. expand = isinstance(c, basestring)
  86. p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)
  87. pipe = p.stdout
  88. val = pipe.readlines()
  89. if pipe.close() or p.wait():
  90. die('Command failed: %s' % str(c))
  91. return val
  92. def p4_read_pipe_lines(c):
  93. """Specifically invoke p4 on the command supplied. """
  94. real_cmd = p4_build_cmd(c)
  95. return read_pipe_lines(real_cmd)
  96. def p4_has_command(cmd):
  97. """Ask p4 for help on this command. If it returns an error, the
  98. command does not exist in this version of p4."""
  99. real_cmd = p4_build_cmd(["help", cmd])
  100. p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE,
  101. stderr=subprocess.PIPE)
  102. p.communicate()
  103. return p.returncode == 0
  104. def p4_has_move_command():
  105. """See if the move command exists, that it supports -k, and that
  106. it has not been administratively disabled. The arguments
  107. must be correct, but the filenames do not have to exist. Use
  108. ones with wildcards so even if they exist, it will fail."""
  109. if not p4_has_command("move"):
  110. return False
  111. cmd = p4_build_cmd(["move", "-k", "@from", "@to"])
  112. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  113. (out, err) = p.communicate()
  114. # return code will be 1 in either case
  115. if err.find("Invalid option") >= 0:
  116. return False
  117. if err.find("disabled") >= 0:
  118. return False
  119. # assume it failed because @... was invalid changelist
  120. return True
  121. def system(cmd):
  122. expand = isinstance(cmd,basestring)
  123. if verbose:
  124. sys.stderr.write("executing %s\n" % str(cmd))
  125. subprocess.check_call(cmd, shell=expand)
  126. def p4_system(cmd):
  127. """Specifically invoke p4 as the system command. """
  128. real_cmd = p4_build_cmd(cmd)
  129. expand = isinstance(real_cmd, basestring)
  130. subprocess.check_call(real_cmd, shell=expand)
  131. def p4_integrate(src, dest):
  132. p4_system(["integrate", "-Dt", wildcard_encode(src), wildcard_encode(dest)])
  133. def p4_sync(f, *options):
  134. p4_system(["sync"] + list(options) + [wildcard_encode(f)])
  135. def p4_add(f):
  136. # forcibly add file names with wildcards
  137. if wildcard_present(f):
  138. p4_system(["add", "-f", f])
  139. else:
  140. p4_system(["add", f])
  141. def p4_delete(f):
  142. p4_system(["delete", wildcard_encode(f)])
  143. def p4_edit(f):
  144. p4_system(["edit", wildcard_encode(f)])
  145. def p4_revert(f):
  146. p4_system(["revert", wildcard_encode(f)])
  147. def p4_reopen(type, f):
  148. p4_system(["reopen", "-t", type, wildcard_encode(f)])
  149. def p4_move(src, dest):
  150. p4_system(["move", "-k", wildcard_encode(src), wildcard_encode(dest)])
  151. def p4_describe(change):
  152. """Make sure it returns a valid result by checking for
  153. the presence of field "time". Return a dict of the
  154. results."""
  155. ds = p4CmdList(["describe", "-s", str(change)])
  156. if len(ds) != 1:
  157. die("p4 describe -s %d did not return 1 result: %s" % (change, str(ds)))
  158. d = ds[0]
  159. if "p4ExitCode" in d:
  160. die("p4 describe -s %d exited with %d: %s" % (change, d["p4ExitCode"],
  161. str(d)))
  162. if "code" in d:
  163. if d["code"] == "error":
  164. die("p4 describe -s %d returned error code: %s" % (change, str(d)))
  165. if "time" not in d:
  166. die("p4 describe -s %d returned no \"time\": %s" % (change, str(d)))
  167. return d
  168. #
  169. # Canonicalize the p4 type and return a tuple of the
  170. # base type, plus any modifiers. See "p4 help filetypes"
  171. # for a list and explanation.
  172. #
  173. def split_p4_type(p4type):
  174. p4_filetypes_historical = {
  175. "ctempobj": "binary+Sw",
  176. "ctext": "text+C",
  177. "cxtext": "text+Cx",
  178. "ktext": "text+k",
  179. "kxtext": "text+kx",
  180. "ltext": "text+F",
  181. "tempobj": "binary+FSw",
  182. "ubinary": "binary+F",
  183. "uresource": "resource+F",
  184. "uxbinary": "binary+Fx",
  185. "xbinary": "binary+x",
  186. "xltext": "text+Fx",
  187. "xtempobj": "binary+Swx",
  188. "xtext": "text+x",
  189. "xunicode": "unicode+x",
  190. "xutf16": "utf16+x",
  191. }
  192. if p4type in p4_filetypes_historical:
  193. p4type = p4_filetypes_historical[p4type]
  194. mods = ""
  195. s = p4type.split("+")
  196. base = s[0]
  197. mods = ""
  198. if len(s) > 1:
  199. mods = s[1]
  200. return (base, mods)
  201. #
  202. # return the raw p4 type of a file (text, text+ko, etc)
  203. #
  204. def p4_type(file):
  205. results = p4CmdList(["fstat", "-T", "headType", file])
  206. return results[0]['headType']
  207. #
  208. # Given a type base and modifier, return a regexp matching
  209. # the keywords that can be expanded in the file
  210. #
  211. def p4_keywords_regexp_for_type(base, type_mods):
  212. if base in ("text", "unicode", "binary"):
  213. kwords = None
  214. if "ko" in type_mods:
  215. kwords = 'Id|Header'
  216. elif "k" in type_mods:
  217. kwords = 'Id|Header|Author|Date|DateTime|Change|File|Revision'
  218. else:
  219. return None
  220. pattern = r"""
  221. \$ # Starts with a dollar, followed by...
  222. (%s) # one of the keywords, followed by...
  223. (:[^$\n]+)? # possibly an old expansion, followed by...
  224. \$ # another dollar
  225. """ % kwords
  226. return pattern
  227. else:
  228. return None
  229. #
  230. # Given a file, return a regexp matching the possible
  231. # RCS keywords that will be expanded, or None for files
  232. # with kw expansion turned off.
  233. #
  234. def p4_keywords_regexp_for_file(file):
  235. if not os.path.exists(file):
  236. return None
  237. else:
  238. (type_base, type_mods) = split_p4_type(p4_type(file))
  239. return p4_keywords_regexp_for_type(type_base, type_mods)
  240. def setP4ExecBit(file, mode):
  241. # Reopens an already open file and changes the execute bit to match
  242. # the execute bit setting in the passed in mode.
  243. p4Type = "+x"
  244. if not isModeExec(mode):
  245. p4Type = getP4OpenedType(file)
  246. p4Type = re.sub('^([cku]?)x(.*)', '\\1\\2', p4Type)
  247. p4Type = re.sub('(.*?\+.*?)x(.*?)', '\\1\\2', p4Type)
  248. if p4Type[-1] == "+":
  249. p4Type = p4Type[0:-1]
  250. p4_reopen(p4Type, file)
  251. def getP4OpenedType(file):
  252. # Returns the perforce file type for the given file.
  253. result = p4_read_pipe(["opened", wildcard_encode(file)])
  254. match = re.match(".*\((.+)\)\r?$", result)
  255. if match:
  256. return match.group(1)
  257. else:
  258. die("Could not determine file type for %s (result: '%s')" % (file, result))
  259. # Return the set of all p4 labels
  260. def getP4Labels(depotPaths):
  261. labels = set()
  262. if isinstance(depotPaths,basestring):
  263. depotPaths = [depotPaths]
  264. for l in p4CmdList(["labels"] + ["%s..." % p for p in depotPaths]):
  265. label = l['label']
  266. labels.add(label)
  267. return labels
  268. # Return the set of all git tags
  269. def getGitTags():
  270. gitTags = set()
  271. for line in read_pipe_lines(["git", "tag"]):
  272. tag = line.strip()
  273. gitTags.add(tag)
  274. return gitTags
  275. def diffTreePattern():
  276. # This is a simple generator for the diff tree regex pattern. This could be
  277. # a class variable if this and parseDiffTreeEntry were a part of a class.
  278. pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)')
  279. while True:
  280. yield pattern
  281. def parseDiffTreeEntry(entry):
  282. """Parses a single diff tree entry into its component elements.
  283. See git-diff-tree(1) manpage for details about the format of the diff
  284. output. This method returns a dictionary with the following elements:
  285. src_mode - The mode of the source file
  286. dst_mode - The mode of the destination file
  287. src_sha1 - The sha1 for the source file
  288. dst_sha1 - The sha1 fr the destination file
  289. status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc)
  290. status_score - The score for the status (applicable for 'C' and 'R'
  291. statuses). This is None if there is no score.
  292. src - The path for the source file.
  293. dst - The path for the destination file. This is only present for
  294. copy or renames. If it is not present, this is None.
  295. If the pattern is not matched, None is returned."""
  296. match = diffTreePattern().next().match(entry)
  297. if match:
  298. return {
  299. 'src_mode': match.group(1),
  300. 'dst_mode': match.group(2),
  301. 'src_sha1': match.group(3),
  302. 'dst_sha1': match.group(4),
  303. 'status': match.group(5),
  304. 'status_score': match.group(6),
  305. 'src': match.group(7),
  306. 'dst': match.group(10)
  307. }
  308. return None
  309. def isModeExec(mode):
  310. # Returns True if the given git mode represents an executable file,
  311. # otherwise False.
  312. return mode[-3:] == "755"
  313. def isModeExecChanged(src_mode, dst_mode):
  314. return isModeExec(src_mode) != isModeExec(dst_mode)
  315. def p4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None):
  316. if isinstance(cmd,basestring):
  317. cmd = "-G " + cmd
  318. expand = True
  319. else:
  320. cmd = ["-G"] + cmd
  321. expand = False
  322. cmd = p4_build_cmd(cmd)
  323. if verbose:
  324. sys.stderr.write("Opening pipe: %s\n" % str(cmd))
  325. # Use a temporary file to avoid deadlocks without
  326. # subprocess.communicate(), which would put another copy
  327. # of stdout into memory.
  328. stdin_file = None
  329. if stdin is not None:
  330. stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode)
  331. if isinstance(stdin,basestring):
  332. stdin_file.write(stdin)
  333. else:
  334. for i in stdin:
  335. stdin_file.write(i + '\n')
  336. stdin_file.flush()
  337. stdin_file.seek(0)
  338. p4 = subprocess.Popen(cmd,
  339. shell=expand,
  340. stdin=stdin_file,
  341. stdout=subprocess.PIPE)
  342. result = []
  343. try:
  344. while True:
  345. entry = marshal.load(p4.stdout)
  346. if cb is not None:
  347. cb(entry)
  348. else:
  349. result.append(entry)
  350. except EOFError:
  351. pass
  352. exitCode = p4.wait()
  353. if exitCode != 0:
  354. entry = {}
  355. entry["p4ExitCode"] = exitCode
  356. result.append(entry)
  357. return result
  358. def p4Cmd(cmd):
  359. list = p4CmdList(cmd)
  360. result = {}
  361. for entry in list:
  362. result.update(entry)
  363. return result;
  364. def p4Where(depotPath):
  365. if not depotPath.endswith("/"):
  366. depotPath += "/"
  367. depotPath = depotPath + "..."
  368. outputList = p4CmdList(["where", depotPath])
  369. output = None
  370. for entry in outputList:
  371. if "depotFile" in entry:
  372. if entry["depotFile"] == depotPath:
  373. output = entry
  374. break
  375. elif "data" in entry:
  376. data = entry.get("data")
  377. space = data.find(" ")
  378. if data[:space] == depotPath:
  379. output = entry
  380. break
  381. if output == None:
  382. return ""
  383. if output["code"] == "error":
  384. return ""
  385. clientPath = ""
  386. if "path" in output:
  387. clientPath = output.get("path")
  388. elif "data" in output:
  389. data = output.get("data")
  390. lastSpace = data.rfind(" ")
  391. clientPath = data[lastSpace + 1:]
  392. if clientPath.endswith("..."):
  393. clientPath = clientPath[:-3]
  394. return clientPath
  395. def currentGitBranch():
  396. return read_pipe("git name-rev HEAD").split(" ")[1].strip()
  397. def isValidGitDir(path):
  398. if (os.path.exists(path + "/HEAD")
  399. and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")):
  400. return True;
  401. return False
  402. def parseRevision(ref):
  403. return read_pipe("git rev-parse %s" % ref).strip()
  404. def branchExists(ref):
  405. rev = read_pipe(["git", "rev-parse", "-q", "--verify", ref],
  406. ignore_error=True)
  407. return len(rev) > 0
  408. def extractLogMessageFromGitCommit(commit):
  409. logMessage = ""
  410. ## fixme: title is first line of commit, not 1st paragraph.
  411. foundTitle = False
  412. for log in read_pipe_lines("git cat-file commit %s" % commit):
  413. if not foundTitle:
  414. if len(log) == 1:
  415. foundTitle = True
  416. continue
  417. logMessage += log
  418. return logMessage
  419. def extractSettingsGitLog(log):
  420. values = {}
  421. for line in log.split("\n"):
  422. line = line.strip()
  423. m = re.search (r"^ *\[git-p4: (.*)\]$", line)
  424. if not m:
  425. continue
  426. assignments = m.group(1).split (':')
  427. for a in assignments:
  428. vals = a.split ('=')
  429. key = vals[0].strip()
  430. val = ('='.join (vals[1:])).strip()
  431. if val.endswith ('\"') and val.startswith('"'):
  432. val = val[1:-1]
  433. values[key] = val
  434. paths = values.get("depot-paths")
  435. if not paths:
  436. paths = values.get("depot-path")
  437. if paths:
  438. values['depot-paths'] = paths.split(',')
  439. return values
  440. def gitBranchExists(branch):
  441. proc = subprocess.Popen(["git", "rev-parse", branch],
  442. stderr=subprocess.PIPE, stdout=subprocess.PIPE);
  443. return proc.wait() == 0;
  444. _gitConfig = {}
  445. def gitConfig(key, args = None): # set args to "--bool", for instance
  446. if not _gitConfig.has_key(key):
  447. argsFilter = ""
  448. if args != None:
  449. argsFilter = "%s " % args
  450. cmd = "git config %s%s" % (argsFilter, key)
  451. _gitConfig[key] = read_pipe(cmd, ignore_error=True).strip()
  452. return _gitConfig[key]
  453. def gitConfigList(key):
  454. if not _gitConfig.has_key(key):
  455. _gitConfig[key] = read_pipe("git config --get-all %s" % key, ignore_error=True).strip().split(os.linesep)
  456. return _gitConfig[key]
  457. def p4BranchesInGit(branchesAreInRemotes = True):
  458. branches = {}
  459. cmdline = "git rev-parse --symbolic "
  460. if branchesAreInRemotes:
  461. cmdline += " --remotes"
  462. else:
  463. cmdline += " --branches"
  464. for line in read_pipe_lines(cmdline):
  465. line = line.strip()
  466. ## only import to p4/
  467. if not line.startswith('p4/') or line == "p4/HEAD":
  468. continue
  469. branch = line
  470. # strip off p4
  471. branch = re.sub ("^p4/", "", line)
  472. branches[branch] = parseRevision(line)
  473. return branches
  474. def findUpstreamBranchPoint(head = "HEAD"):
  475. branches = p4BranchesInGit()
  476. # map from depot-path to branch name
  477. branchByDepotPath = {}
  478. for branch in branches.keys():
  479. tip = branches[branch]
  480. log = extractLogMessageFromGitCommit(tip)
  481. settings = extractSettingsGitLog(log)
  482. if settings.has_key("depot-paths"):
  483. paths = ",".join(settings["depot-paths"])
  484. branchByDepotPath[paths] = "remotes/p4/" + branch
  485. settings = None
  486. parent = 0
  487. while parent < 65535:
  488. commit = head + "~%s" % parent
  489. log = extractLogMessageFromGitCommit(commit)
  490. settings = extractSettingsGitLog(log)
  491. if settings.has_key("depot-paths"):
  492. paths = ",".join(settings["depot-paths"])
  493. if branchByDepotPath.has_key(paths):
  494. return [branchByDepotPath[paths], settings]
  495. parent = parent + 1
  496. return ["", settings]
  497. def createOrUpdateBranchesFromOrigin(localRefPrefix = "refs/remotes/p4/", silent=True):
  498. if not silent:
  499. print ("Creating/updating branch(es) in %s based on origin branch(es)"
  500. % localRefPrefix)
  501. originPrefix = "origin/p4/"
  502. for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
  503. line = line.strip()
  504. if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
  505. continue
  506. headName = line[len(originPrefix):]
  507. remoteHead = localRefPrefix + headName
  508. originHead = line
  509. original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
  510. if (not original.has_key('depot-paths')
  511. or not original.has_key('change')):
  512. continue
  513. update = False
  514. if not gitBranchExists(remoteHead):
  515. if verbose:
  516. print "creating %s" % remoteHead
  517. update = True
  518. else:
  519. settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
  520. if settings.has_key('change') > 0:
  521. if settings['depot-paths'] == original['depot-paths']:
  522. originP4Change = int(original['change'])
  523. p4Change = int(settings['change'])
  524. if originP4Change > p4Change:
  525. print ("%s (%s) is newer than %s (%s). "
  526. "Updating p4 branch from origin."
  527. % (originHead, originP4Change,
  528. remoteHead, p4Change))
  529. update = True
  530. else:
  531. print ("Ignoring: %s was imported from %s while "
  532. "%s was imported from %s"
  533. % (originHead, ','.join(original['depot-paths']),
  534. remoteHead, ','.join(settings['depot-paths'])))
  535. if update:
  536. system("git update-ref %s %s" % (remoteHead, originHead))
  537. def originP4BranchesExist():
  538. return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
  539. def p4ChangesForPaths(depotPaths, changeRange):
  540. assert depotPaths
  541. cmd = ['changes']
  542. for p in depotPaths:
  543. cmd += ["%s...%s" % (p, changeRange)]
  544. output = p4_read_pipe_lines(cmd)
  545. changes = {}
  546. for line in output:
  547. changeNum = int(line.split(" ")[1])
  548. changes[changeNum] = True
  549. changelist = changes.keys()
  550. changelist.sort()
  551. return changelist
  552. def p4PathStartsWith(path, prefix):
  553. # This method tries to remedy a potential mixed-case issue:
  554. #
  555. # If UserA adds //depot/DirA/file1
  556. # and UserB adds //depot/dira/file2
  557. #
  558. # we may or may not have a problem. If you have core.ignorecase=true,
  559. # we treat DirA and dira as the same directory
  560. ignorecase = gitConfig("core.ignorecase", "--bool") == "true"
  561. if ignorecase:
  562. return path.lower().startswith(prefix.lower())
  563. return path.startswith(prefix)
  564. def getClientSpec():
  565. """Look at the p4 client spec, create a View() object that contains
  566. all the mappings, and return it."""
  567. specList = p4CmdList("client -o")
  568. if len(specList) != 1:
  569. die('Output from "client -o" is %d lines, expecting 1' %
  570. len(specList))
  571. # dictionary of all client parameters
  572. entry = specList[0]
  573. # just the keys that start with "View"
  574. view_keys = [ k for k in entry.keys() if k.startswith("View") ]
  575. # hold this new View
  576. view = View()
  577. # append the lines, in order, to the view
  578. for view_num in range(len(view_keys)):
  579. k = "View%d" % view_num
  580. if k not in view_keys:
  581. die("Expected view key %s missing" % k)
  582. view.append(entry[k])
  583. return view
  584. def getClientRoot():
  585. """Grab the client directory."""
  586. output = p4CmdList("client -o")
  587. if len(output) != 1:
  588. die('Output from "client -o" is %d lines, expecting 1' % len(output))
  589. entry = output[0]
  590. if "Root" not in entry:
  591. die('Client has no "Root"')
  592. return entry["Root"]
  593. #
  594. # P4 wildcards are not allowed in filenames. P4 complains
  595. # if you simply add them, but you can force it with "-f", in
  596. # which case it translates them into %xx encoding internally.
  597. #
  598. def wildcard_decode(path):
  599. # Search for and fix just these four characters. Do % last so
  600. # that fixing it does not inadvertently create new %-escapes.
  601. # Cannot have * in a filename in windows; untested as to
  602. # what p4 would do in such a case.
  603. if not platform.system() == "Windows":
  604. path = path.replace("%2A", "*")
  605. path = path.replace("%23", "#") \
  606. .replace("%40", "@") \
  607. .replace("%25", "%")
  608. return path
  609. def wildcard_encode(path):
  610. # do % first to avoid double-encoding the %s introduced here
  611. path = path.replace("%", "%25") \
  612. .replace("*", "%2A") \
  613. .replace("#", "%23") \
  614. .replace("@", "%40")
  615. return path
  616. def wildcard_present(path):
  617. return path.translate(None, "*#@%") != path
  618. class Command:
  619. def __init__(self):
  620. self.usage = "usage: %prog [options]"
  621. self.needsGit = True
  622. self.verbose = False
  623. class P4UserMap:
  624. def __init__(self):
  625. self.userMapFromPerforceServer = False
  626. self.myP4UserId = None
  627. def p4UserId(self):
  628. if self.myP4UserId:
  629. return self.myP4UserId
  630. results = p4CmdList("user -o")
  631. for r in results:
  632. if r.has_key('User'):
  633. self.myP4UserId = r['User']
  634. return r['User']
  635. die("Could not find your p4 user id")
  636. def p4UserIsMe(self, p4User):
  637. # return True if the given p4 user is actually me
  638. me = self.p4UserId()
  639. if not p4User or p4User != me:
  640. return False
  641. else:
  642. return True
  643. def getUserCacheFilename(self):
  644. home = os.environ.get("HOME", os.environ.get("USERPROFILE"))
  645. return home + "/.gitp4-usercache.txt"
  646. def getUserMapFromPerforceServer(self):
  647. if self.userMapFromPerforceServer:
  648. return
  649. self.users = {}
  650. self.emails = {}
  651. for output in p4CmdList("users"):
  652. if not output.has_key("User"):
  653. continue
  654. self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
  655. self.emails[output["Email"]] = output["User"]
  656. s = ''
  657. for (key, val) in self.users.items():
  658. s += "%s\t%s\n" % (key.expandtabs(1), val.expandtabs(1))
  659. open(self.getUserCacheFilename(), "wb").write(s)
  660. self.userMapFromPerforceServer = True
  661. def loadUserMapFromCache(self):
  662. self.users = {}
  663. self.userMapFromPerforceServer = False
  664. try:
  665. cache = open(self.getUserCacheFilename(), "rb")
  666. lines = cache.readlines()
  667. cache.close()
  668. for line in lines:
  669. entry = line.strip().split("\t")
  670. self.users[entry[0]] = entry[1]
  671. except IOError:
  672. self.getUserMapFromPerforceServer()
  673. class P4Debug(Command):
  674. def __init__(self):
  675. Command.__init__(self)
  676. self.options = []
  677. self.description = "A tool to debug the output of p4 -G."
  678. self.needsGit = False
  679. def run(self, args):
  680. j = 0
  681. for output in p4CmdList(args):
  682. print 'Element: %d' % j
  683. j += 1
  684. print output
  685. return True
  686. class P4RollBack(Command):
  687. def __init__(self):
  688. Command.__init__(self)
  689. self.options = [
  690. optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
  691. ]
  692. self.description = "A tool to debug the multi-branch import. Don't use :)"
  693. self.rollbackLocalBranches = False
  694. def run(self, args):
  695. if len(args) != 1:
  696. return False
  697. maxChange = int(args[0])
  698. if "p4ExitCode" in p4Cmd("changes -m 1"):
  699. die("Problems executing p4");
  700. if self.rollbackLocalBranches:
  701. refPrefix = "refs/heads/"
  702. lines = read_pipe_lines("git rev-parse --symbolic --branches")
  703. else:
  704. refPrefix = "refs/remotes/"
  705. lines = read_pipe_lines("git rev-parse --symbolic --remotes")
  706. for line in lines:
  707. if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
  708. line = line.strip()
  709. ref = refPrefix + line
  710. log = extractLogMessageFromGitCommit(ref)
  711. settings = extractSettingsGitLog(log)
  712. depotPaths = settings['depot-paths']
  713. change = settings['change']
  714. changed = False
  715. if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
  716. for p in depotPaths]))) == 0:
  717. print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
  718. system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
  719. continue
  720. while change and int(change) > maxChange:
  721. changed = True
  722. if self.verbose:
  723. print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
  724. system("git update-ref %s \"%s^\"" % (ref, ref))
  725. log = extractLogMessageFromGitCommit(ref)
  726. settings = extractSettingsGitLog(log)
  727. depotPaths = settings['depot-paths']
  728. change = settings['change']
  729. if changed:
  730. print "%s rewound to %s" % (ref, change)
  731. return True
  732. class P4Submit(Command, P4UserMap):
  733. conflict_behavior_choices = ("ask", "skip", "quit")
  734. def __init__(self):
  735. Command.__init__(self)
  736. P4UserMap.__init__(self)
  737. self.options = [
  738. optparse.make_option("--origin", dest="origin"),
  739. optparse.make_option("-M", dest="detectRenames", action="store_true"),
  740. # preserve the user, requires relevant p4 permissions
  741. optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),
  742. optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),
  743. optparse.make_option("--dry-run", "-n", dest="dry_run", action="store_true"),
  744. optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),
  745. optparse.make_option("--conflict", dest="conflict_behavior",
  746. choices=self.conflict_behavior_choices)
  747. ]
  748. self.description = "Submit changes from git to the perforce depot."
  749. self.usage += " [name of git branch to submit into perforce depot]"
  750. self.origin = ""
  751. self.detectRenames = False
  752. self.preserveUser = gitConfig("git-p4.preserveUser").lower() == "true"
  753. self.dry_run = False
  754. self.prepare_p4_only = False
  755. self.conflict_behavior = None
  756. self.isWindows = (platform.system() == "Windows")
  757. self.exportLabels = False
  758. self.p4HasMoveCommand = p4_has_move_command()
  759. def check(self):
  760. if len(p4CmdList("opened ...")) > 0:
  761. die("You have files opened with perforce! Close them before starting the sync.")
  762. def separate_jobs_from_description(self, message):
  763. """Extract and return a possible Jobs field in the commit
  764. message. It goes into a separate section in the p4 change
  765. specification.
  766. A jobs line starts with "Jobs:" and looks like a new field
  767. in a form. Values are white-space separated on the same
  768. line or on following lines that start with a tab.
  769. This does not parse and extract the full git commit message
  770. like a p4 form. It just sees the Jobs: line as a marker
  771. to pass everything from then on directly into the p4 form,
  772. but outside the description section.
  773. Return a tuple (stripped log message, jobs string)."""
  774. m = re.search(r'^Jobs:', message, re.MULTILINE)
  775. if m is None:
  776. return (message, None)
  777. jobtext = message[m.start():]
  778. stripped_message = message[:m.start()].rstrip()
  779. return (stripped_message, jobtext)
  780. def prepareLogMessage(self, template, message, jobs):
  781. """Edits the template returned from "p4 change -o" to insert
  782. the message in the Description field, and the jobs text in
  783. the Jobs field."""
  784. result = ""
  785. inDescriptionSection = False
  786. for line in template.split("\n"):
  787. if line.startswith("#"):
  788. result += line + "\n"
  789. continue
  790. if inDescriptionSection:
  791. if line.startswith("Files:") or line.startswith("Jobs:"):
  792. inDescriptionSection = False
  793. # insert Jobs section
  794. if jobs:
  795. result += jobs + "\n"
  796. else:
  797. continue
  798. else:
  799. if line.startswith("Description:"):
  800. inDescriptionSection = True
  801. line += "\n"
  802. for messageLine in message.split("\n"):
  803. line += "\t" + messageLine + "\n"
  804. result += line + "\n"
  805. return result
  806. def patchRCSKeywords(self, file, pattern):
  807. # Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern
  808. (handle, outFileName) = tempfile.mkstemp(dir='.')
  809. try:
  810. outFile = os.fdopen(handle, "w+")
  811. inFile = open(file, "r")
  812. regexp = re.compile(pattern, re.VERBOSE)
  813. for line in inFile.readlines():
  814. line = regexp.sub(r'$\1$', line)
  815. outFile.write(line)
  816. inFile.close()
  817. outFile.close()
  818. # Forcibly overwrite the original file
  819. os.unlink(file)
  820. shutil.move(outFileName, file)
  821. except:
  822. # cleanup our temporary file
  823. os.unlink(outFileName)
  824. print "Failed to strip RCS keywords in %s" % file
  825. raise
  826. print "Patched up RCS keywords in %s" % file
  827. def p4UserForCommit(self,id):
  828. # Return the tuple (perforce user,git email) for a given git commit id
  829. self.getUserMapFromPerforceServer()
  830. gitEmail = read_pipe("git log --max-count=1 --format='%%ae' %s" % id)
  831. gitEmail = gitEmail.strip()
  832. if not self.emails.has_key(gitEmail):
  833. return (None,gitEmail)
  834. else:
  835. return (self.emails[gitEmail],gitEmail)
  836. def checkValidP4Users(self,commits):
  837. # check if any git authors cannot be mapped to p4 users
  838. for id in commits:
  839. (user,email) = self.p4UserForCommit(id)
  840. if not user:
  841. msg = "Cannot find p4 user for email %s in commit %s." % (email, id)
  842. if gitConfig('git-p4.allowMissingP4Users').lower() == "true":
  843. print "%s" % msg
  844. else:
  845. die("Error: %s\nSet git-p4.allowMissingP4Users to true to allow this." % msg)
  846. def lastP4Changelist(self):
  847. # Get back the last changelist number submitted in this client spec. This
  848. # then gets used to patch up the username in the change. If the same
  849. # client spec is being used by multiple processes then this might go
  850. # wrong.
  851. results = p4CmdList("client -o") # find the current client
  852. client = None
  853. for r in results:
  854. if r.has_key('Client'):
  855. client = r['Client']
  856. break
  857. if not client:
  858. die("could not get client spec")
  859. results = p4CmdList(["changes", "-c", client, "-m", "1"])
  860. for r in results:
  861. if r.has_key('change'):
  862. return r['change']
  863. die("Could not get changelist number for last submit - cannot patch up user details")
  864. def modifyChangelistUser(self, changelist, newUser):
  865. # fixup the user field of a changelist after it has been submitted.
  866. changes = p4CmdList("change -o %s" % changelist)
  867. if len(changes) != 1:
  868. die("Bad output from p4 change modifying %s to user %s" %
  869. (changelist, newUser))
  870. c = changes[0]
  871. if c['User'] == newUser: return # nothing to do
  872. c['User'] = newUser
  873. input = marshal.dumps(c)
  874. result = p4CmdList("change -f -i", stdin=input)
  875. for r in result:
  876. if r.has_key('code'):
  877. if r['code'] == 'error':
  878. die("Could not modify user field of changelist %s to %s:%s" % (changelist, newUser, r['data']))
  879. if r.has_key('data'):
  880. print("Updated user field for changelist %s to %s" % (changelist, newUser))
  881. return
  882. die("Could not modify user field of changelist %s to %s" % (changelist, newUser))
  883. def canChangeChangelists(self):
  884. # check to see if we have p4 admin or super-user permissions, either of
  885. # which are required to modify changelists.
  886. results = p4CmdList(["protects", self.depotPath])
  887. for r in results:
  888. if r.has_key('perm'):
  889. if r['perm'] == 'admin':
  890. return 1
  891. if r['perm'] == 'super':
  892. return 1
  893. return 0
  894. def prepareSubmitTemplate(self):
  895. """Run "p4 change -o" to grab a change specification template.
  896. This does not use "p4 -G", as it is nice to keep the submission
  897. template in original order, since a human might edit it.
  898. Remove lines in the Files section that show changes to files
  899. outside the depot path we're committing into."""
  900. template = ""
  901. inFilesSection = False
  902. for line in p4_read_pipe_lines(['change', '-o']):
  903. if line.endswith("\r\n"):
  904. line = line[:-2] + "\n"
  905. if inFilesSection:
  906. if line.startswith("\t"):
  907. # path starts and ends with a tab
  908. path = line[1:]
  909. lastTab = path.rfind("\t")
  910. if lastTab != -1:
  911. path = path[:lastTab]
  912. if not p4PathStartsWith(path, self.depotPath):
  913. continue
  914. else:
  915. inFilesSection = False
  916. else:
  917. if line.startswith("Files:"):
  918. inFilesSection = True
  919. template += line
  920. return template
  921. def edit_template(self, template_file):
  922. """Invoke the editor to let the user change the submission
  923. message. Return true if okay to continue with the submit."""
  924. # if configured to skip the editing part, just submit
  925. if gitConfig("git-p4.skipSubmitEdit") == "true":
  926. return True
  927. # look at the modification time, to check later if the user saved
  928. # the file
  929. mtime = os.stat(template_file).st_mtime
  930. # invoke the editor
  931. if os.environ.has_key("P4EDITOR") and (os.environ.get("P4EDITOR") != ""):
  932. editor = os.environ.get("P4EDITOR")
  933. else:
  934. editor = read_pipe("git var GIT_EDITOR").strip()
  935. system(editor + " " + template_file)
  936. # If the file was not saved, prompt to see if this patch should
  937. # be skipped. But skip this verification step if configured so.
  938. if gitConfig("git-p4.skipSubmitEditCheck") == "true":
  939. return True
  940. # modification time updated means user saved the file
  941. if os.stat(template_file).st_mtime > mtime:
  942. return True
  943. while True:
  944. response = raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")
  945. if response == 'y':
  946. return True
  947. if response == 'n':
  948. return False
  949. def applyCommit(self, id):
  950. """Apply one commit, return True if it succeeded."""
  951. print "Applying", read_pipe(["git", "show", "-s",
  952. "--format=format:%h %s", id])
  953. (p4User, gitEmail) = self.p4UserForCommit(id)
  954. diff = read_pipe_lines("git diff-tree -r %s \"%s^\" \"%s\"" % (self.diffOpts, id, id))
  955. filesToAdd = set()
  956. filesToDelete = set()
  957. editedFiles = set()
  958. pureRenameCopy = set()
  959. filesToChangeExecBit = {}
  960. for line in diff:
  961. diff = parseDiffTreeEntry(line)
  962. modifier = diff['status']
  963. path = diff['src']
  964. if modifier == "M":
  965. p4_edit(path)
  966. if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
  967. filesToChangeExecBit[path] = diff['dst_mode']
  968. editedFiles.add(path)
  969. elif modifier == "A":
  970. filesToAdd.add(path)
  971. filesToChangeExecBit[path] = diff['dst_mode']
  972. if path in filesToDelete:
  973. filesToDelete.remove(path)
  974. elif modifier == "D":
  975. filesToDelete.add(path)
  976. if path in filesToAdd:
  977. filesToAdd.remove(path)
  978. elif modifier == "C":
  979. src, dest = diff['src'], diff['dst']
  980. p4_integrate(src, dest)
  981. pureRenameCopy.add(dest)
  982. if diff['src_sha1'] != diff['dst_sha1']:
  983. p4_edit(dest)
  984. pureRenameCopy.discard(dest)
  985. if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
  986. p4_edit(dest)
  987. pureRenameCopy.discard(dest)
  988. filesToChangeExecBit[dest] = diff['dst_mode']
  989. os.unlink(dest)
  990. editedFiles.add(dest)
  991. elif modifier == "R":
  992. src, dest = diff['src'], diff['dst']
  993. if self.p4HasMoveCommand:
  994. p4_edit(src) # src must be open before move
  995. p4_move(src, dest) # opens for (move/delete, move/add)
  996. else:
  997. p4_integrate(src, dest)
  998. if diff['src_sha1'] != diff['dst_sha1']:
  999. p4_edit(dest)
  1000. else:
  1001. pureRenameCopy.add(dest)
  1002. if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
  1003. if not self.p4HasMoveCommand:
  1004. p4_edit(dest) # with move: already open, writable
  1005. filesToChangeExecBit[dest] = diff['dst_mode']
  1006. if not self.p4HasMoveCommand:
  1007. os.unlink(dest)
  1008. filesToDelete.add(src)
  1009. editedFiles.add(dest)
  1010. else:
  1011. die("unknown modifier %s for %s" % (modifier, path))
  1012. diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
  1013. patchcmd = diffcmd + " | git apply "
  1014. tryPatchCmd = patchcmd + "--check -"
  1015. applyPatchCmd = patchcmd + "--check --apply -"
  1016. patch_succeeded = True
  1017. if os.system(tryPatchCmd) != 0:
  1018. fixed_rcs_keywords = False
  1019. patch_succeeded = False
  1020. print "Unfortunately applying the change failed!"
  1021. # Patch failed, maybe it's just RCS keyword woes. Look through
  1022. # the patch to see if that's possible.
  1023. if gitConfig("git-p4.attemptRCSCleanup","--bool") == "true":
  1024. file = None
  1025. pattern = None
  1026. kwfiles = {}
  1027. for file in editedFiles | filesToDelete:
  1028. # did this file's delta contain RCS keywords?
  1029. pattern = p4_keywords_regexp_for_file(file)
  1030. if pattern:
  1031. # this file is a possibility...look for RCS keywords.
  1032. regexp = re.compile(pattern, re.VERBOSE)
  1033. for line in read_pipe_lines(["git", "diff", "%s^..%s" % (id, id), file]):
  1034. if regexp.search(line):
  1035. if verbose:
  1036. print "got keyword match on %s in %s in %s" % (pattern, line, file)
  1037. kwfiles[file] = pattern
  1038. break
  1039. for file in kwfiles:
  1040. if verbose:
  1041. print "zapping %s with %s" % (line,pattern)
  1042. self.patchRCSKeywords(file, kwfiles[file])
  1043. fixed_rcs_keywords = True
  1044. if fixed_rcs_keywords:
  1045. print "Retrying the patch with RCS keywords cleaned up"
  1046. if os.system(tryPatchCmd) == 0:
  1047. patch_succeeded = True
  1048. if not patch_succeeded:
  1049. for f in editedFiles:
  1050. p4_revert(f)
  1051. return False
  1052. #
  1053. # Apply the patch for real, and do add/delete/+x handling.
  1054. #
  1055. system(applyPatchCmd)
  1056. for f in filesToAdd:
  1057. p4_add(f)
  1058. for f in filesToDelete:
  1059. p4_revert(f)
  1060. p4_delete(f)
  1061. # Set/clear executable bits
  1062. for f in filesToChangeExecBit.keys():
  1063. mode = filesToChangeExecBit[f]
  1064. setP4ExecBit(f, mode)
  1065. #
  1066. # Build p4 change description, starting with the contents
  1067. # of the git commit message.
  1068. #
  1069. logMessage = extractLogMessageFromGitCommit(id)
  1070. logMessage = logMessage.strip()
  1071. (logMessage, jobs) = self.separate_jobs_from_description(logMessage)
  1072. template = self.prepareSubmitTemplate()
  1073. submitTemplate = self.prepareLogMessage(template, logMessage, jobs)
  1074. if self.preserveUser:
  1075. submitTemplate += "\n######## Actual user %s, modified after commit\n" % p4User
  1076. if self.checkAuthorship and not self.p4UserIsMe(p4User):
  1077. submitTemplate += "######## git author %s does not match your p4 account.\n" % gitEmail
  1078. submitTemplate += "######## Use option --preserve-user to modify authorship.\n"
  1079. submitTemplate += "######## Variable git-p4.skipUserNameCheck hides this message.\n"
  1080. separatorLine = "######## everything below this line is just the diff #######\n"
  1081. # diff
  1082. if os.environ.has_key("P4DIFF"):
  1083. del(os.environ["P4DIFF"])
  1084. diff = ""
  1085. for editedFile in editedFiles:
  1086. diff += p4_read_pipe(['diff', '-du',
  1087. wildcard_encode(editedFile)])
  1088. # new file diff
  1089. newdiff = ""
  1090. for newFile in filesToAdd:
  1091. newdiff += "==== new file ====\n"
  1092. newdiff += "--- /dev/null\n"
  1093. newdiff += "+++ %s\n" % newFile
  1094. f = open(newFile, "r")
  1095. for line in f.readlines():
  1096. newdiff += "+" + line
  1097. f.close()
  1098. # change description file: submitTemplate, separatorLine, diff, newdiff
  1099. (handle, fileName) = tempfile.mkstemp()
  1100. tmpFile = os.fdopen(handle, "w+")
  1101. if self.isWindows:
  1102. submitTemplate = submitTemplate.replace("\n", "\r\n")
  1103. separatorLine = separatorLine.replace("\n", "\r\n")
  1104. newdiff = newdiff.replace("\n", "\r\n")
  1105. tmpFile.write(submitTemplate + separatorLine + diff + newdiff)
  1106. tmpFile.close()
  1107. if self.prepare_p4_only:
  1108. #
  1109. # Leave the p4 tree prepared, and the submit template around
  1110. # and let the user decide what to do next
  1111. #
  1112. print
  1113. print "P4 workspace prepared for submission."
  1114. print "To submit or revert, go to client workspace"
  1115. print " " + self.clientPath
  1116. print
  1117. print "To submit, use \"p4 submit\" to write a new description,"
  1118. print "or \"p4 submit -i %s\" to use the one prepared by" \
  1119. " \"git p4\"." % fileName
  1120. print "You can delete the file \"%s\" when finished." % fileName
  1121. if self.preserveUser and p4User and not self.p4UserIsMe(p4User):
  1122. print "To preserve change ownership by user %s, you must\n" \
  1123. "do \"p4 change -f <change>\" after submitting and\n" \
  1124. "edit the User field."
  1125. if pureRenameCopy:
  1126. print "After submitting, renamed files must be re-synced."
  1127. print "Invoke \"p4 sync -f\" on each of these files:"
  1128. for f in pureRenameCopy:
  1129. print " " + f
  1130. print
  1131. print "To revert the changes, use \"p4 revert ...\", and delete"
  1132. print "the submit template file \"%s\"" % fileName
  1133. if filesToAdd:
  1134. print "Since the commit adds new files, they must be deleted:"
  1135. for f in filesToAdd:
  1136. print " " + f
  1137. print
  1138. return True
  1139. #
  1140. # Let the user edit the change description, then submit it.
  1141. #
  1142. if self.edit_template(fileName):
  1143. # read the edited message and submit
  1144. ret = True
  1145. tmpFile = open(fileName, "rb")
  1146. message = tmpFile.read()
  1147. tmpFile.close()
  1148. submitTemplate = message[:message.index(separatorLine)]
  1149. if self.isWindows:
  1150. submitTemplate = submitTemplate.replace("\r\n", "\n")
  1151. p4_write_pipe(['submit', '-i'], submitTemplate)
  1152. if self.preserveUser:
  1153. if p4User:
  1154. # Get last changelist number. Cannot easily get it from
  1155. # the submit command output as the output is
  1156. # unmarshalled.
  1157. changelist = self.lastP4Changelist()
  1158. self.modifyChangelistUser(changelist, p4User)
  1159. # The rename/copy happened by applying a patch that created a
  1160. # new file. This leaves it writable, which confuses p4.
  1161. for f in pureRenameCopy:
  1162. p4_sync(f, "-f")
  1163. else:
  1164. # skip this patch
  1165. ret = False
  1166. print "Submission cancelled, undoing p4 changes."
  1167. for f in editedFiles:
  1168. p4_revert(f)
  1169. for f in filesToAdd:
  1170. p4_revert(f)
  1171. os.remove(f)
  1172. for f in filesToDelete:
  1173. p4_revert(f)
  1174. os.remove(fileName)
  1175. return ret
  1176. # Export git tags as p4 labels. Create a p4 label and then tag
  1177. # with that.
  1178. def exportGitTags(self, gitTags):
  1179. validLabelRegexp = gitConfig("git-p4.labelExportRegexp")
  1180. if len(validLabelRegexp) == 0:
  1181. validLabelRegexp = defaultLabelRegexp
  1182. m = re.compile(validLabelRegexp)
  1183. for name in gitTags:
  1184. if not m.match(name):
  1185. if verbose:
  1186. print "tag %s does not match regexp %s" % (name, validLabelRegexp)
  1187. continue
  1188. # Get the p4 commit this corresponds to
  1189. logMessage = extractLogMessageFromGitCommit(name)
  1190. values = extractSettingsGitLog(logMessage)
  1191. if not values.has_key('change'):
  1192. # a tag pointing to something not sent to p4; ignore
  1193. if verbose:
  1194. print "git tag %s does not give a p4 commit" % name
  1195. continue
  1196. else:
  1197. changelist = values['change']
  1198. # Get the tag details.
  1199. inHeader = True
  1200. isAnnotated = False
  1201. body = []
  1202. for l in read_pipe_lines(["git", "cat-file", "-p", name]):
  1203. l = l.strip()
  1204. if inHeader:
  1205. if re.match(r'tag\s+', l):

Large files files are truncated, but you can click here to view the full file