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 11import sys 12if sys.hexversion <0x02040000: 13# The limiter is the subprocess module 14 sys.stderr.write("git-p4: requires Python 2.4 or later.\n") 15 sys.exit(1) 16 17import optparse, os, marshal, subprocess, shelve 18import tempfile, getopt, os.path, time, platform 19import re, shutil 20 21try: 22from subprocess import CalledProcessError 23exceptImportError: 24# from python2.7:subprocess.py 25# Exception classes used by this module. 26classCalledProcessError(Exception): 27"""This exception is raised when a process run by check_call() returns 28 a non-zero exit status. The exit status will be stored in the 29 returncode attribute.""" 30def__init__(self, returncode, cmd): 31 self.returncode = returncode 32 self.cmd = cmd 33def__str__(self): 34return"Command '%s' returned non-zero exit status%d"% (self.cmd, self.returncode) 35 36verbose =False 37 38# Only labels/tags matching this will be imported/exported 39defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$' 40 41defp4_build_cmd(cmd): 42"""Build a suitable p4 command line. 43 44 This consolidates building and returning a p4 command line into one 45 location. It means that hooking into the environment, or other configuration 46 can be done more easily. 47 """ 48 real_cmd = ["p4"] 49 50 user =gitConfig("git-p4.user") 51iflen(user) >0: 52 real_cmd += ["-u",user] 53 54 password =gitConfig("git-p4.password") 55iflen(password) >0: 56 real_cmd += ["-P", password] 57 58 port =gitConfig("git-p4.port") 59iflen(port) >0: 60 real_cmd += ["-p", port] 61 62 host =gitConfig("git-p4.host") 63iflen(host) >0: 64 real_cmd += ["-H", host] 65 66 client =gitConfig("git-p4.client") 67iflen(client) >0: 68 real_cmd += ["-c", client] 69 70 71ifisinstance(cmd,basestring): 72 real_cmd =' '.join(real_cmd) +' '+ cmd 73else: 74 real_cmd += cmd 75return real_cmd 76 77defchdir(dir): 78# P4 uses the PWD environment variable rather than getcwd(). Since we're 79# not using the shell, we have to set it ourselves. This path could 80# be relative, so go there first, then figure out where we ended up. 81 os.chdir(dir) 82 os.environ['PWD'] = os.getcwd() 83 84defdie(msg): 85if verbose: 86raiseException(msg) 87else: 88 sys.stderr.write(msg +"\n") 89 sys.exit(1) 90 91defwrite_pipe(c, stdin): 92if verbose: 93 sys.stderr.write('Writing pipe:%s\n'%str(c)) 94 95 expand =isinstance(c,basestring) 96 p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand) 97 pipe = p.stdin 98 val = pipe.write(stdin) 99 pipe.close() 100if p.wait(): 101die('Command failed:%s'%str(c)) 102 103return val 104 105defp4_write_pipe(c, stdin): 106 real_cmd =p4_build_cmd(c) 107returnwrite_pipe(real_cmd, stdin) 108 109defread_pipe(c, ignore_error=False): 110if verbose: 111 sys.stderr.write('Reading pipe:%s\n'%str(c)) 112 113 expand =isinstance(c,basestring) 114 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand) 115 pipe = p.stdout 116 val = pipe.read() 117if p.wait()and not ignore_error: 118die('Command failed:%s'%str(c)) 119 120return val 121 122defp4_read_pipe(c, ignore_error=False): 123 real_cmd =p4_build_cmd(c) 124returnread_pipe(real_cmd, ignore_error) 125 126defread_pipe_lines(c): 127if verbose: 128 sys.stderr.write('Reading pipe:%s\n'%str(c)) 129 130 expand =isinstance(c, basestring) 131 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand) 132 pipe = p.stdout 133 val = pipe.readlines() 134if pipe.close()or p.wait(): 135die('Command failed:%s'%str(c)) 136 137return val 138 139defp4_read_pipe_lines(c): 140"""Specifically invoke p4 on the command supplied. """ 141 real_cmd =p4_build_cmd(c) 142returnread_pipe_lines(real_cmd) 143 144defp4_has_command(cmd): 145"""Ask p4 for help on this command. If it returns an error, the 146 command does not exist in this version of p4.""" 147 real_cmd =p4_build_cmd(["help", cmd]) 148 p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE, 149 stderr=subprocess.PIPE) 150 p.communicate() 151return p.returncode ==0 152 153defp4_has_move_command(): 154"""See if the move command exists, that it supports -k, and that 155 it has not been administratively disabled. The arguments 156 must be correct, but the filenames do not have to exist. Use 157 ones with wildcards so even if they exist, it will fail.""" 158 159if notp4_has_command("move"): 160return False 161 cmd =p4_build_cmd(["move","-k","@from","@to"]) 162 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 163(out, err) = p.communicate() 164# return code will be 1 in either case 165if err.find("Invalid option") >=0: 166return False 167if err.find("disabled") >=0: 168return False 169# assume it failed because @... was invalid changelist 170return True 171 172defsystem(cmd): 173 expand =isinstance(cmd,basestring) 174if verbose: 175 sys.stderr.write("executing%s\n"%str(cmd)) 176 retcode = subprocess.call(cmd, shell=expand) 177if retcode: 178raiseCalledProcessError(retcode, cmd) 179 180defp4_system(cmd): 181"""Specifically invoke p4 as the system command. """ 182 real_cmd =p4_build_cmd(cmd) 183 expand =isinstance(real_cmd, basestring) 184 retcode = subprocess.call(real_cmd, shell=expand) 185if retcode: 186raiseCalledProcessError(retcode, real_cmd) 187 188defp4_integrate(src, dest): 189p4_system(["integrate","-Dt",wildcard_encode(src),wildcard_encode(dest)]) 190 191defp4_sync(f, *options): 192p4_system(["sync"] +list(options) + [wildcard_encode(f)]) 193 194defp4_add(f): 195# forcibly add file names with wildcards 196ifwildcard_present(f): 197p4_system(["add","-f", f]) 198else: 199p4_system(["add", f]) 200 201defp4_delete(f): 202p4_system(["delete",wildcard_encode(f)]) 203 204defp4_edit(f): 205p4_system(["edit",wildcard_encode(f)]) 206 207defp4_revert(f): 208p4_system(["revert",wildcard_encode(f)]) 209 210defp4_reopen(type, f): 211p4_system(["reopen","-t",type,wildcard_encode(f)]) 212 213defp4_move(src, dest): 214p4_system(["move","-k",wildcard_encode(src),wildcard_encode(dest)]) 215 216defp4_describe(change): 217"""Make sure it returns a valid result by checking for 218 the presence of field "time". Return a dict of the 219 results.""" 220 221 ds =p4CmdList(["describe","-s",str(change)]) 222iflen(ds) !=1: 223die("p4 describe -s%ddid not return 1 result:%s"% (change,str(ds))) 224 225 d = ds[0] 226 227if"p4ExitCode"in d: 228die("p4 describe -s%dexited with%d:%s"% (change, d["p4ExitCode"], 229str(d))) 230if"code"in d: 231if d["code"] =="error": 232die("p4 describe -s%dreturned error code:%s"% (change,str(d))) 233 234if"time"not in d: 235die("p4 describe -s%dreturned no\"time\":%s"% (change,str(d))) 236 237return d 238 239# 240# Canonicalize the p4 type and return a tuple of the 241# base type, plus any modifiers. See "p4 help filetypes" 242# for a list and explanation. 243# 244defsplit_p4_type(p4type): 245 246 p4_filetypes_historical = { 247"ctempobj":"binary+Sw", 248"ctext":"text+C", 249"cxtext":"text+Cx", 250"ktext":"text+k", 251"kxtext":"text+kx", 252"ltext":"text+F", 253"tempobj":"binary+FSw", 254"ubinary":"binary+F", 255"uresource":"resource+F", 256"uxbinary":"binary+Fx", 257"xbinary":"binary+x", 258"xltext":"text+Fx", 259"xtempobj":"binary+Swx", 260"xtext":"text+x", 261"xunicode":"unicode+x", 262"xutf16":"utf16+x", 263} 264if p4type in p4_filetypes_historical: 265 p4type = p4_filetypes_historical[p4type] 266 mods ="" 267 s = p4type.split("+") 268 base = s[0] 269 mods ="" 270iflen(s) >1: 271 mods = s[1] 272return(base, mods) 273 274# 275# return the raw p4 type of a file (text, text+ko, etc) 276# 277defp4_type(file): 278 results =p4CmdList(["fstat","-T","headType",file]) 279return results[0]['headType'] 280 281# 282# Given a type base and modifier, return a regexp matching 283# the keywords that can be expanded in the file 284# 285defp4_keywords_regexp_for_type(base, type_mods): 286if base in("text","unicode","binary"): 287 kwords =None 288if"ko"in type_mods: 289 kwords ='Id|Header' 290elif"k"in type_mods: 291 kwords ='Id|Header|Author|Date|DateTime|Change|File|Revision' 292else: 293return None 294 pattern = r""" 295 \$ # Starts with a dollar, followed by... 296 (%s) # one of the keywords, followed by... 297 (:[^$\n]+)? # possibly an old expansion, followed by... 298 \$ # another dollar 299 """% kwords 300return pattern 301else: 302return None 303 304# 305# Given a file, return a regexp matching the possible 306# RCS keywords that will be expanded, or None for files 307# with kw expansion turned off. 308# 309defp4_keywords_regexp_for_file(file): 310if not os.path.exists(file): 311return None 312else: 313(type_base, type_mods) =split_p4_type(p4_type(file)) 314returnp4_keywords_regexp_for_type(type_base, type_mods) 315 316defsetP4ExecBit(file, mode): 317# Reopens an already open file and changes the execute bit to match 318# the execute bit setting in the passed in mode. 319 320 p4Type ="+x" 321 322if notisModeExec(mode): 323 p4Type =getP4OpenedType(file) 324 p4Type = re.sub('^([cku]?)x(.*)','\\1\\2', p4Type) 325 p4Type = re.sub('(.*?\+.*?)x(.*?)','\\1\\2', p4Type) 326if p4Type[-1] =="+": 327 p4Type = p4Type[0:-1] 328 329p4_reopen(p4Type,file) 330 331defgetP4OpenedType(file): 332# Returns the perforce file type for the given file. 333 334 result =p4_read_pipe(["opened",wildcard_encode(file)]) 335 match = re.match(".*\((.+)\)\r?$", result) 336if match: 337return match.group(1) 338else: 339die("Could not determine file type for%s(result: '%s')"% (file, result)) 340 341# Return the set of all p4 labels 342defgetP4Labels(depotPaths): 343 labels =set() 344ifisinstance(depotPaths,basestring): 345 depotPaths = [depotPaths] 346 347for l inp4CmdList(["labels"] + ["%s..."% p for p in depotPaths]): 348 label = l['label'] 349 labels.add(label) 350 351return labels 352 353# Return the set of all git tags 354defgetGitTags(): 355 gitTags =set() 356for line inread_pipe_lines(["git","tag"]): 357 tag = line.strip() 358 gitTags.add(tag) 359return gitTags 360 361defdiffTreePattern(): 362# This is a simple generator for the diff tree regex pattern. This could be 363# a class variable if this and parseDiffTreeEntry were a part of a class. 364 pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)') 365while True: 366yield pattern 367 368defparseDiffTreeEntry(entry): 369"""Parses a single diff tree entry into its component elements. 370 371 See git-diff-tree(1) manpage for details about the format of the diff 372 output. This method returns a dictionary with the following elements: 373 374 src_mode - The mode of the source file 375 dst_mode - The mode of the destination file 376 src_sha1 - The sha1 for the source file 377 dst_sha1 - The sha1 fr the destination file 378 status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc) 379 status_score - The score for the status (applicable for 'C' and 'R' 380 statuses). This is None if there is no score. 381 src - The path for the source file. 382 dst - The path for the destination file. This is only present for 383 copy or renames. If it is not present, this is None. 384 385 If the pattern is not matched, None is returned.""" 386 387 match =diffTreePattern().next().match(entry) 388if match: 389return{ 390'src_mode': match.group(1), 391'dst_mode': match.group(2), 392'src_sha1': match.group(3), 393'dst_sha1': match.group(4), 394'status': match.group(5), 395'status_score': match.group(6), 396'src': match.group(7), 397'dst': match.group(10) 398} 399return None 400 401defisModeExec(mode): 402# Returns True if the given git mode represents an executable file, 403# otherwise False. 404return mode[-3:] =="755" 405 406defisModeExecChanged(src_mode, dst_mode): 407returnisModeExec(src_mode) !=isModeExec(dst_mode) 408 409defp4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None): 410 411ifisinstance(cmd,basestring): 412 cmd ="-G "+ cmd 413 expand =True 414else: 415 cmd = ["-G"] + cmd 416 expand =False 417 418 cmd =p4_build_cmd(cmd) 419if verbose: 420 sys.stderr.write("Opening pipe:%s\n"%str(cmd)) 421 422# Use a temporary file to avoid deadlocks without 423# subprocess.communicate(), which would put another copy 424# of stdout into memory. 425 stdin_file =None 426if stdin is not None: 427 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode) 428ifisinstance(stdin,basestring): 429 stdin_file.write(stdin) 430else: 431for i in stdin: 432 stdin_file.write(i +'\n') 433 stdin_file.flush() 434 stdin_file.seek(0) 435 436 p4 = subprocess.Popen(cmd, 437 shell=expand, 438 stdin=stdin_file, 439 stdout=subprocess.PIPE) 440 441 result = [] 442try: 443while True: 444 entry = marshal.load(p4.stdout) 445if cb is not None: 446cb(entry) 447else: 448 result.append(entry) 449exceptEOFError: 450pass 451 exitCode = p4.wait() 452if exitCode !=0: 453 entry = {} 454 entry["p4ExitCode"] = exitCode 455 result.append(entry) 456 457return result 458 459defp4Cmd(cmd): 460list=p4CmdList(cmd) 461 result = {} 462for entry inlist: 463 result.update(entry) 464return result; 465 466defp4Where(depotPath): 467if not depotPath.endswith("/"): 468 depotPath +="/" 469 depotPath = depotPath +"..." 470 outputList =p4CmdList(["where", depotPath]) 471 output =None 472for entry in outputList: 473if"depotFile"in entry: 474if entry["depotFile"] == depotPath: 475 output = entry 476break 477elif"data"in entry: 478 data = entry.get("data") 479 space = data.find(" ") 480if data[:space] == depotPath: 481 output = entry 482break 483if output ==None: 484return"" 485if output["code"] =="error": 486return"" 487 clientPath ="" 488if"path"in output: 489 clientPath = output.get("path") 490elif"data"in output: 491 data = output.get("data") 492 lastSpace = data.rfind(" ") 493 clientPath = data[lastSpace +1:] 494 495if clientPath.endswith("..."): 496 clientPath = clientPath[:-3] 497return clientPath 498 499defcurrentGitBranch(): 500returnread_pipe("git name-rev HEAD").split(" ")[1].strip() 501 502defisValidGitDir(path): 503if(os.path.exists(path +"/HEAD") 504and os.path.exists(path +"/refs")and os.path.exists(path +"/objects")): 505return True; 506return False 507 508defparseRevision(ref): 509returnread_pipe("git rev-parse%s"% ref).strip() 510 511defbranchExists(ref): 512 rev =read_pipe(["git","rev-parse","-q","--verify", ref], 513 ignore_error=True) 514returnlen(rev) >0 515 516defextractLogMessageFromGitCommit(commit): 517 logMessage ="" 518 519## fixme: title is first line of commit, not 1st paragraph. 520 foundTitle =False 521for log inread_pipe_lines("git cat-file commit%s"% commit): 522if not foundTitle: 523iflen(log) ==1: 524 foundTitle =True 525continue 526 527 logMessage += log 528return logMessage 529 530defextractSettingsGitLog(log): 531 values = {} 532for line in log.split("\n"): 533 line = line.strip() 534 m = re.search(r"^ *\[git-p4: (.*)\]$", line) 535if not m: 536continue 537 538 assignments = m.group(1).split(':') 539for a in assignments: 540 vals = a.split('=') 541 key = vals[0].strip() 542 val = ('='.join(vals[1:])).strip() 543if val.endswith('\"')and val.startswith('"'): 544 val = val[1:-1] 545 546 values[key] = val 547 548 paths = values.get("depot-paths") 549if not paths: 550 paths = values.get("depot-path") 551if paths: 552 values['depot-paths'] = paths.split(',') 553return values 554 555defgitBranchExists(branch): 556 proc = subprocess.Popen(["git","rev-parse", branch], 557 stderr=subprocess.PIPE, stdout=subprocess.PIPE); 558return proc.wait() ==0; 559 560_gitConfig = {} 561defgitConfig(key, args =None):# set args to "--bool", for instance 562if not _gitConfig.has_key(key): 563 argsFilter ="" 564if args !=None: 565 argsFilter ="%s"% args 566 cmd ="git config%s%s"% (argsFilter, key) 567 _gitConfig[key] =read_pipe(cmd, ignore_error=True).strip() 568return _gitConfig[key] 569 570defgitConfigList(key): 571if not _gitConfig.has_key(key): 572 _gitConfig[key] =read_pipe("git config --get-all%s"% key, ignore_error=True).strip().split(os.linesep) 573return _gitConfig[key] 574 575defp4BranchesInGit(branchesAreInRemotes=True): 576"""Find all the branches whose names start with "p4/", looking 577 in remotes or heads as specified by the argument. Return 578 a dictionary of{ branch: revision }for each one found. 579 The branch names are the short names, without any 580 "p4/" prefix.""" 581 582 branches = {} 583 584 cmdline ="git rev-parse --symbolic " 585if branchesAreInRemotes: 586 cmdline +="--remotes" 587else: 588 cmdline +="--branches" 589 590for line inread_pipe_lines(cmdline): 591 line = line.strip() 592 593# only import to p4/ 594if not line.startswith('p4/'): 595continue 596# special symbolic ref to p4/master 597if line =="p4/HEAD": 598continue 599 600# strip off p4/ prefix 601 branch = line[len("p4/"):] 602 603 branches[branch] =parseRevision(line) 604 605return branches 606 607defbranch_exists(branch): 608"""Make sure that the given ref name really exists.""" 609 610 cmd = ["git","rev-parse","--symbolic","--verify", branch ] 611 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 612 out, _ = p.communicate() 613if p.returncode: 614return False 615# expect exactly one line of output: the branch name 616return out.rstrip() == branch 617 618deffindUpstreamBranchPoint(head ="HEAD"): 619 branches =p4BranchesInGit() 620# map from depot-path to branch name 621 branchByDepotPath = {} 622for branch in branches.keys(): 623 tip = branches[branch] 624 log =extractLogMessageFromGitCommit(tip) 625 settings =extractSettingsGitLog(log) 626if settings.has_key("depot-paths"): 627 paths =",".join(settings["depot-paths"]) 628 branchByDepotPath[paths] ="remotes/p4/"+ branch 629 630 settings =None 631 parent =0 632while parent <65535: 633 commit = head +"~%s"% parent 634 log =extractLogMessageFromGitCommit(commit) 635 settings =extractSettingsGitLog(log) 636if settings.has_key("depot-paths"): 637 paths =",".join(settings["depot-paths"]) 638if branchByDepotPath.has_key(paths): 639return[branchByDepotPath[paths], settings] 640 641 parent = parent +1 642 643return["", settings] 644 645defcreateOrUpdateBranchesFromOrigin(localRefPrefix ="refs/remotes/p4/", silent=True): 646if not silent: 647print("Creating/updating branch(es) in%sbased on origin branch(es)" 648% localRefPrefix) 649 650 originPrefix ="origin/p4/" 651 652for line inread_pipe_lines("git rev-parse --symbolic --remotes"): 653 line = line.strip() 654if(not line.startswith(originPrefix))or line.endswith("HEAD"): 655continue 656 657 headName = line[len(originPrefix):] 658 remoteHead = localRefPrefix + headName 659 originHead = line 660 661 original =extractSettingsGitLog(extractLogMessageFromGitCommit(originHead)) 662if(not original.has_key('depot-paths') 663or not original.has_key('change')): 664continue 665 666 update =False 667if notgitBranchExists(remoteHead): 668if verbose: 669print"creating%s"% remoteHead 670 update =True 671else: 672 settings =extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead)) 673if settings.has_key('change') >0: 674if settings['depot-paths'] == original['depot-paths']: 675 originP4Change =int(original['change']) 676 p4Change =int(settings['change']) 677if originP4Change > p4Change: 678print("%s(%s) is newer than%s(%s). " 679"Updating p4 branch from origin." 680% (originHead, originP4Change, 681 remoteHead, p4Change)) 682 update =True 683else: 684print("Ignoring:%swas imported from%swhile " 685"%swas imported from%s" 686% (originHead,','.join(original['depot-paths']), 687 remoteHead,','.join(settings['depot-paths']))) 688 689if update: 690system("git update-ref%s %s"% (remoteHead, originHead)) 691 692deforiginP4BranchesExist(): 693returngitBranchExists("origin")orgitBranchExists("origin/p4")orgitBranchExists("origin/p4/master") 694 695defp4ChangesForPaths(depotPaths, changeRange): 696assert depotPaths 697 cmd = ['changes'] 698for p in depotPaths: 699 cmd += ["%s...%s"% (p, changeRange)] 700 output =p4_read_pipe_lines(cmd) 701 702 changes = {} 703for line in output: 704 changeNum =int(line.split(" ")[1]) 705 changes[changeNum] =True 706 707 changelist = changes.keys() 708 changelist.sort() 709return changelist 710 711defp4PathStartsWith(path, prefix): 712# This method tries to remedy a potential mixed-case issue: 713# 714# If UserA adds //depot/DirA/file1 715# and UserB adds //depot/dira/file2 716# 717# we may or may not have a problem. If you have core.ignorecase=true, 718# we treat DirA and dira as the same directory 719 ignorecase =gitConfig("core.ignorecase","--bool") =="true" 720if ignorecase: 721return path.lower().startswith(prefix.lower()) 722return path.startswith(prefix) 723 724defgetClientSpec(): 725"""Look at the p4 client spec, create a View() object that contains 726 all the mappings, and return it.""" 727 728 specList =p4CmdList("client -o") 729iflen(specList) !=1: 730die('Output from "client -o" is%dlines, expecting 1'% 731len(specList)) 732 733# dictionary of all client parameters 734 entry = specList[0] 735 736# just the keys that start with "View" 737 view_keys = [ k for k in entry.keys()if k.startswith("View") ] 738 739# hold this new View 740 view =View() 741 742# append the lines, in order, to the view 743for view_num inrange(len(view_keys)): 744 k ="View%d"% view_num 745if k not in view_keys: 746die("Expected view key%smissing"% k) 747 view.append(entry[k]) 748 749return view 750 751defgetClientRoot(): 752"""Grab the client directory.""" 753 754 output =p4CmdList("client -o") 755iflen(output) !=1: 756die('Output from "client -o" is%dlines, expecting 1'%len(output)) 757 758 entry = output[0] 759if"Root"not in entry: 760die('Client has no "Root"') 761 762return entry["Root"] 763 764# 765# P4 wildcards are not allowed in filenames. P4 complains 766# if you simply add them, but you can force it with "-f", in 767# which case it translates them into %xx encoding internally. 768# 769defwildcard_decode(path): 770# Search for and fix just these four characters. Do % last so 771# that fixing it does not inadvertently create new %-escapes. 772# Cannot have * in a filename in windows; untested as to 773# what p4 would do in such a case. 774if not platform.system() =="Windows": 775 path = path.replace("%2A","*") 776 path = path.replace("%23","#") \ 777.replace("%40","@") \ 778.replace("%25","%") 779return path 780 781defwildcard_encode(path): 782# do % first to avoid double-encoding the %s introduced here 783 path = path.replace("%","%25") \ 784.replace("*","%2A") \ 785.replace("#","%23") \ 786.replace("@","%40") 787return path 788 789defwildcard_present(path): 790 m = re.search("[*#@%]", path) 791return m is not None 792 793class Command: 794def__init__(self): 795 self.usage ="usage: %prog [options]" 796 self.needsGit =True 797 self.verbose =False 798 799class P4UserMap: 800def__init__(self): 801 self.userMapFromPerforceServer =False 802 self.myP4UserId =None 803 804defp4UserId(self): 805if self.myP4UserId: 806return self.myP4UserId 807 808 results =p4CmdList("user -o") 809for r in results: 810if r.has_key('User'): 811 self.myP4UserId = r['User'] 812return r['User'] 813die("Could not find your p4 user id") 814 815defp4UserIsMe(self, p4User): 816# return True if the given p4 user is actually me 817 me = self.p4UserId() 818if not p4User or p4User != me: 819return False 820else: 821return True 822 823defgetUserCacheFilename(self): 824 home = os.environ.get("HOME", os.environ.get("USERPROFILE")) 825return home +"/.gitp4-usercache.txt" 826 827defgetUserMapFromPerforceServer(self): 828if self.userMapFromPerforceServer: 829return 830 self.users = {} 831 self.emails = {} 832 833for output inp4CmdList("users"): 834if not output.has_key("User"): 835continue 836 self.users[output["User"]] = output["FullName"] +" <"+ output["Email"] +">" 837 self.emails[output["Email"]] = output["User"] 838 839 840 s ='' 841for(key, val)in self.users.items(): 842 s +="%s\t%s\n"% (key.expandtabs(1), val.expandtabs(1)) 843 844open(self.getUserCacheFilename(),"wb").write(s) 845 self.userMapFromPerforceServer =True 846 847defloadUserMapFromCache(self): 848 self.users = {} 849 self.userMapFromPerforceServer =False 850try: 851 cache =open(self.getUserCacheFilename(),"rb") 852 lines = cache.readlines() 853 cache.close() 854for line in lines: 855 entry = line.strip().split("\t") 856 self.users[entry[0]] = entry[1] 857exceptIOError: 858 self.getUserMapFromPerforceServer() 859 860classP4Debug(Command): 861def__init__(self): 862 Command.__init__(self) 863 self.options = [] 864 self.description ="A tool to debug the output of p4 -G." 865 self.needsGit =False 866 867defrun(self, args): 868 j =0 869for output inp4CmdList(args): 870print'Element:%d'% j 871 j +=1 872print output 873return True 874 875classP4RollBack(Command): 876def__init__(self): 877 Command.__init__(self) 878 self.options = [ 879 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true") 880] 881 self.description ="A tool to debug the multi-branch import. Don't use :)" 882 self.rollbackLocalBranches =False 883 884defrun(self, args): 885iflen(args) !=1: 886return False 887 maxChange =int(args[0]) 888 889if"p4ExitCode"inp4Cmd("changes -m 1"): 890die("Problems executing p4"); 891 892if self.rollbackLocalBranches: 893 refPrefix ="refs/heads/" 894 lines =read_pipe_lines("git rev-parse --symbolic --branches") 895else: 896 refPrefix ="refs/remotes/" 897 lines =read_pipe_lines("git rev-parse --symbolic --remotes") 898 899for line in lines: 900if self.rollbackLocalBranches or(line.startswith("p4/")and line !="p4/HEAD\n"): 901 line = line.strip() 902 ref = refPrefix + line 903 log =extractLogMessageFromGitCommit(ref) 904 settings =extractSettingsGitLog(log) 905 906 depotPaths = settings['depot-paths'] 907 change = settings['change'] 908 909 changed =False 910 911iflen(p4Cmd("changes -m 1 "+' '.join(['%s...@%s'% (p, maxChange) 912for p in depotPaths]))) ==0: 913print"Branch%sdid not exist at change%s, deleting."% (ref, maxChange) 914system("git update-ref -d%s`git rev-parse%s`"% (ref, ref)) 915continue 916 917while change andint(change) > maxChange: 918 changed =True 919if self.verbose: 920print"%sis at%s; rewinding towards%s"% (ref, change, maxChange) 921system("git update-ref%s\"%s^\""% (ref, ref)) 922 log =extractLogMessageFromGitCommit(ref) 923 settings =extractSettingsGitLog(log) 924 925 926 depotPaths = settings['depot-paths'] 927 change = settings['change'] 928 929if changed: 930print"%srewound to%s"% (ref, change) 931 932return True 933 934classP4Submit(Command, P4UserMap): 935 936 conflict_behavior_choices = ("ask","skip","quit") 937 938def__init__(self): 939 Command.__init__(self) 940 P4UserMap.__init__(self) 941 self.options = [ 942 optparse.make_option("--origin", dest="origin"), 943 optparse.make_option("-M", dest="detectRenames", action="store_true"), 944# preserve the user, requires relevant p4 permissions 945 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"), 946 optparse.make_option("--export-labels", dest="exportLabels", action="store_true"), 947 optparse.make_option("--dry-run","-n", dest="dry_run", action="store_true"), 948 optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"), 949 optparse.make_option("--conflict", dest="conflict_behavior", 950 choices=self.conflict_behavior_choices), 951 optparse.make_option("--branch", dest="branch"), 952] 953 self.description ="Submit changes from git to the perforce depot." 954 self.usage +=" [name of git branch to submit into perforce depot]" 955 self.origin ="" 956 self.detectRenames =False 957 self.preserveUser =gitConfig("git-p4.preserveUser").lower() =="true" 958 self.dry_run =False 959 self.prepare_p4_only =False 960 self.conflict_behavior =None 961 self.isWindows = (platform.system() =="Windows") 962 self.exportLabels =False 963 self.p4HasMoveCommand =p4_has_move_command() 964 self.branch =None 965 966defcheck(self): 967iflen(p4CmdList("opened ...")) >0: 968die("You have files opened with perforce! Close them before starting the sync.") 969 970defseparate_jobs_from_description(self, message): 971"""Extract and return a possible Jobs field in the commit 972 message. It goes into a separate section in the p4 change 973 specification. 974 975 A jobs line starts with "Jobs:" and looks like a new field 976 in a form. Values are white-space separated on the same 977 line or on following lines that start with a tab. 978 979 This does not parse and extract the full git commit message 980 like a p4 form. It just sees the Jobs: line as a marker 981 to pass everything from then on directly into the p4 form, 982 but outside the description section. 983 984 Return a tuple (stripped log message, jobs string).""" 985 986 m = re.search(r'^Jobs:', message, re.MULTILINE) 987if m is None: 988return(message,None) 989 990 jobtext = message[m.start():] 991 stripped_message = message[:m.start()].rstrip() 992return(stripped_message, jobtext) 993 994defprepareLogMessage(self, template, message, jobs): 995"""Edits the template returned from "p4 change -o" to insert 996 the message in the Description field, and the jobs text in 997 the Jobs field.""" 998 result ="" 9991000 inDescriptionSection =False10011002for line in template.split("\n"):1003if line.startswith("#"):1004 result += line +"\n"1005continue10061007if inDescriptionSection:1008if line.startswith("Files:")or line.startswith("Jobs:"):1009 inDescriptionSection =False1010# insert Jobs section1011if jobs:1012 result += jobs +"\n"1013else:1014continue1015else:1016if line.startswith("Description:"):1017 inDescriptionSection =True1018 line +="\n"1019for messageLine in message.split("\n"):1020 line +="\t"+ messageLine +"\n"10211022 result += line +"\n"10231024return result10251026defpatchRCSKeywords(self,file, pattern):1027# Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern1028(handle, outFileName) = tempfile.mkstemp(dir='.')1029try:1030 outFile = os.fdopen(handle,"w+")1031 inFile =open(file,"r")1032 regexp = re.compile(pattern, re.VERBOSE)1033for line in inFile.readlines():1034 line = regexp.sub(r'$\1$', line)1035 outFile.write(line)1036 inFile.close()1037 outFile.close()1038# Forcibly overwrite the original file1039 os.unlink(file)1040 shutil.move(outFileName,file)1041except:1042# cleanup our temporary file1043 os.unlink(outFileName)1044print"Failed to strip RCS keywords in%s"%file1045raise10461047print"Patched up RCS keywords in%s"%file10481049defp4UserForCommit(self,id):1050# Return the tuple (perforce user,git email) for a given git commit id1051 self.getUserMapFromPerforceServer()1052 gitEmail =read_pipe("git log --max-count=1 --format='%%ae'%s"%id)1053 gitEmail = gitEmail.strip()1054if not self.emails.has_key(gitEmail):1055return(None,gitEmail)1056else:1057return(self.emails[gitEmail],gitEmail)10581059defcheckValidP4Users(self,commits):1060# check if any git authors cannot be mapped to p4 users1061foridin commits:1062(user,email) = self.p4UserForCommit(id)1063if not user:1064 msg ="Cannot find p4 user for email%sin commit%s."% (email,id)1065ifgitConfig('git-p4.allowMissingP4Users').lower() =="true":1066print"%s"% msg1067else:1068die("Error:%s\nSet git-p4.allowMissingP4Users to true to allow this."% msg)10691070deflastP4Changelist(self):1071# Get back the last changelist number submitted in this client spec. This1072# then gets used to patch up the username in the change. If the same1073# client spec is being used by multiple processes then this might go1074# wrong.1075 results =p4CmdList("client -o")# find the current client1076 client =None1077for r in results:1078if r.has_key('Client'):1079 client = r['Client']1080break1081if not client:1082die("could not get client spec")1083 results =p4CmdList(["changes","-c", client,"-m","1"])1084for r in results:1085if r.has_key('change'):1086return r['change']1087die("Could not get changelist number for last submit - cannot patch up user details")10881089defmodifyChangelistUser(self, changelist, newUser):1090# fixup the user field of a changelist after it has been submitted.1091 changes =p4CmdList("change -o%s"% changelist)1092iflen(changes) !=1:1093die("Bad output from p4 change modifying%sto user%s"%1094(changelist, newUser))10951096 c = changes[0]1097if c['User'] == newUser:return# nothing to do1098 c['User'] = newUser1099input= marshal.dumps(c)11001101 result =p4CmdList("change -f -i", stdin=input)1102for r in result:1103if r.has_key('code'):1104if r['code'] =='error':1105die("Could not modify user field of changelist%sto%s:%s"% (changelist, newUser, r['data']))1106if r.has_key('data'):1107print("Updated user field for changelist%sto%s"% (changelist, newUser))1108return1109die("Could not modify user field of changelist%sto%s"% (changelist, newUser))11101111defcanChangeChangelists(self):1112# check to see if we have p4 admin or super-user permissions, either of1113# which are required to modify changelists.1114 results =p4CmdList(["protects", self.depotPath])1115for r in results:1116if r.has_key('perm'):1117if r['perm'] =='admin':1118return11119if r['perm'] =='super':1120return11121return011221123defprepareSubmitTemplate(self):1124"""Run "p4 change -o" to grab a change specification template.1125 This does not use "p4 -G", as it is nice to keep the submission1126 template in original order, since a human might edit it.11271128 Remove lines in the Files section that show changes to files1129 outside the depot path we're committing into."""11301131 template =""1132 inFilesSection =False1133for line inp4_read_pipe_lines(['change','-o']):1134if line.endswith("\r\n"):1135 line = line[:-2] +"\n"1136if inFilesSection:1137if line.startswith("\t"):1138# path starts and ends with a tab1139 path = line[1:]1140 lastTab = path.rfind("\t")1141if lastTab != -1:1142 path = path[:lastTab]1143if notp4PathStartsWith(path, self.depotPath):1144continue1145else:1146 inFilesSection =False1147else:1148if line.startswith("Files:"):1149 inFilesSection =True11501151 template += line11521153return template11541155defedit_template(self, template_file):1156"""Invoke the editor to let the user change the submission1157 message. Return true if okay to continue with the submit."""11581159# if configured to skip the editing part, just submit1160ifgitConfig("git-p4.skipSubmitEdit") =="true":1161return True11621163# look at the modification time, to check later if the user saved1164# the file1165 mtime = os.stat(template_file).st_mtime11661167# invoke the editor1168if os.environ.has_key("P4EDITOR")and(os.environ.get("P4EDITOR") !=""):1169 editor = os.environ.get("P4EDITOR")1170else:1171 editor =read_pipe("git var GIT_EDITOR").strip()1172system(editor +" "+ template_file)11731174# If the file was not saved, prompt to see if this patch should1175# be skipped. But skip this verification step if configured so.1176ifgitConfig("git-p4.skipSubmitEditCheck") =="true":1177return True11781179# modification time updated means user saved the file1180if os.stat(template_file).st_mtime > mtime:1181return True11821183while True:1184 response =raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")1185if response =='y':1186return True1187if response =='n':1188return False11891190defapplyCommit(self,id):1191"""Apply one commit, return True if it succeeded."""11921193print"Applying",read_pipe(["git","show","-s",1194"--format=format:%h%s",id])11951196(p4User, gitEmail) = self.p4UserForCommit(id)11971198 diff =read_pipe_lines("git diff-tree -r%s\"%s^\" \"%s\""% (self.diffOpts,id,id))1199 filesToAdd =set()1200 filesToDelete =set()1201 editedFiles =set()1202 pureRenameCopy =set()1203 filesToChangeExecBit = {}12041205for line in diff:1206 diff =parseDiffTreeEntry(line)1207 modifier = diff['status']1208 path = diff['src']1209if modifier =="M":1210p4_edit(path)1211ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1212 filesToChangeExecBit[path] = diff['dst_mode']1213 editedFiles.add(path)1214elif modifier =="A":1215 filesToAdd.add(path)1216 filesToChangeExecBit[path] = diff['dst_mode']1217if path in filesToDelete:1218 filesToDelete.remove(path)1219elif modifier =="D":1220 filesToDelete.add(path)1221if path in filesToAdd:1222 filesToAdd.remove(path)1223elif modifier =="C":1224 src, dest = diff['src'], diff['dst']1225p4_integrate(src, dest)1226 pureRenameCopy.add(dest)1227if diff['src_sha1'] != diff['dst_sha1']:1228p4_edit(dest)1229 pureRenameCopy.discard(dest)1230ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1231p4_edit(dest)1232 pureRenameCopy.discard(dest)1233 filesToChangeExecBit[dest] = diff['dst_mode']1234 os.unlink(dest)1235 editedFiles.add(dest)1236elif modifier =="R":1237 src, dest = diff['src'], diff['dst']1238if self.p4HasMoveCommand:1239p4_edit(src)# src must be open before move1240p4_move(src, dest)# opens for (move/delete, move/add)1241else:1242p4_integrate(src, dest)1243if diff['src_sha1'] != diff['dst_sha1']:1244p4_edit(dest)1245else:1246 pureRenameCopy.add(dest)1247ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1248if not self.p4HasMoveCommand:1249p4_edit(dest)# with move: already open, writable1250 filesToChangeExecBit[dest] = diff['dst_mode']1251if not self.p4HasMoveCommand:1252 os.unlink(dest)1253 filesToDelete.add(src)1254 editedFiles.add(dest)1255else:1256die("unknown modifier%sfor%s"% (modifier, path))12571258 diffcmd ="git format-patch -k --stdout\"%s^\"..\"%s\""% (id,id)1259 patchcmd = diffcmd +" | git apply "1260 tryPatchCmd = patchcmd +"--check -"1261 applyPatchCmd = patchcmd +"--check --apply -"1262 patch_succeeded =True12631264if os.system(tryPatchCmd) !=0:1265 fixed_rcs_keywords =False1266 patch_succeeded =False1267print"Unfortunately applying the change failed!"12681269# Patch failed, maybe it's just RCS keyword woes. Look through1270# the patch to see if that's possible.1271ifgitConfig("git-p4.attemptRCSCleanup","--bool") =="true":1272file=None1273 pattern =None1274 kwfiles = {}1275forfilein editedFiles | filesToDelete:1276# did this file's delta contain RCS keywords?1277 pattern =p4_keywords_regexp_for_file(file)12781279if pattern:1280# this file is a possibility...look for RCS keywords.1281 regexp = re.compile(pattern, re.VERBOSE)1282for line inread_pipe_lines(["git","diff","%s^..%s"% (id,id),file]):1283if regexp.search(line):1284if verbose:1285print"got keyword match on%sin%sin%s"% (pattern, line,file)1286 kwfiles[file] = pattern1287break12881289forfilein kwfiles:1290if verbose:1291print"zapping%swith%s"% (line,pattern)1292 self.patchRCSKeywords(file, kwfiles[file])1293 fixed_rcs_keywords =True12941295if fixed_rcs_keywords:1296print"Retrying the patch with RCS keywords cleaned up"1297if os.system(tryPatchCmd) ==0:1298 patch_succeeded =True12991300if not patch_succeeded:1301for f in editedFiles:1302p4_revert(f)1303return False13041305#1306# Apply the patch for real, and do add/delete/+x handling.1307#1308system(applyPatchCmd)13091310for f in filesToAdd:1311p4_add(f)1312for f in filesToDelete:1313p4_revert(f)1314p4_delete(f)13151316# Set/clear executable bits1317for f in filesToChangeExecBit.keys():1318 mode = filesToChangeExecBit[f]1319setP4ExecBit(f, mode)13201321#1322# Build p4 change description, starting with the contents1323# of the git commit message.1324#1325 logMessage =extractLogMessageFromGitCommit(id)1326 logMessage = logMessage.strip()1327(logMessage, jobs) = self.separate_jobs_from_description(logMessage)13281329 template = self.prepareSubmitTemplate()1330 submitTemplate = self.prepareLogMessage(template, logMessage, jobs)13311332if self.preserveUser:1333 submitTemplate +="\n######## Actual user%s, modified after commit\n"% p4User13341335if self.checkAuthorship and not self.p4UserIsMe(p4User):1336 submitTemplate +="######## git author%sdoes not match your p4 account.\n"% gitEmail1337 submitTemplate +="######## Use option --preserve-user to modify authorship.\n"1338 submitTemplate +="######## Variable git-p4.skipUserNameCheck hides this message.\n"13391340 separatorLine ="######## everything below this line is just the diff #######\n"13411342# diff1343if os.environ.has_key("P4DIFF"):1344del(os.environ["P4DIFF"])1345 diff =""1346for editedFile in editedFiles:1347 diff +=p4_read_pipe(['diff','-du',1348wildcard_encode(editedFile)])13491350# new file diff1351 newdiff =""1352for newFile in filesToAdd:1353 newdiff +="==== new file ====\n"1354 newdiff +="--- /dev/null\n"1355 newdiff +="+++%s\n"% newFile1356 f =open(newFile,"r")1357for line in f.readlines():1358 newdiff +="+"+ line1359 f.close()13601361# change description file: submitTemplate, separatorLine, diff, newdiff1362(handle, fileName) = tempfile.mkstemp()1363 tmpFile = os.fdopen(handle,"w+")1364if self.isWindows:1365 submitTemplate = submitTemplate.replace("\n","\r\n")1366 separatorLine = separatorLine.replace("\n","\r\n")1367 newdiff = newdiff.replace("\n","\r\n")1368 tmpFile.write(submitTemplate + separatorLine + diff + newdiff)1369 tmpFile.close()13701371if self.prepare_p4_only:1372#1373# Leave the p4 tree prepared, and the submit template around1374# and let the user decide what to do next1375#1376print1377print"P4 workspace prepared for submission."1378print"To submit or revert, go to client workspace"1379print" "+ self.clientPath1380print1381print"To submit, use\"p4 submit\"to write a new description,"1382print"or\"p4 submit -i%s\"to use the one prepared by" \1383"\"git p4\"."% fileName1384print"You can delete the file\"%s\"when finished."% fileName13851386if self.preserveUser and p4User and not self.p4UserIsMe(p4User):1387print"To preserve change ownership by user%s, you must\n" \1388"do\"p4 change -f <change>\"after submitting and\n" \1389"edit the User field."1390if pureRenameCopy:1391print"After submitting, renamed files must be re-synced."1392print"Invoke\"p4 sync -f\"on each of these files:"1393for f in pureRenameCopy:1394print" "+ f13951396print1397print"To revert the changes, use\"p4 revert ...\", and delete"1398print"the submit template file\"%s\""% fileName1399if filesToAdd:1400print"Since the commit adds new files, they must be deleted:"1401for f in filesToAdd:1402print" "+ f1403print1404return True14051406#1407# Let the user edit the change description, then submit it.1408#1409if self.edit_template(fileName):1410# read the edited message and submit1411 ret =True1412 tmpFile =open(fileName,"rb")1413 message = tmpFile.read()1414 tmpFile.close()1415 submitTemplate = message[:message.index(separatorLine)]1416if self.isWindows:1417 submitTemplate = submitTemplate.replace("\r\n","\n")1418p4_write_pipe(['submit','-i'], submitTemplate)14191420if self.preserveUser:1421if p4User:1422# Get last changelist number. Cannot easily get it from1423# the submit command output as the output is1424# unmarshalled.1425 changelist = self.lastP4Changelist()1426 self.modifyChangelistUser(changelist, p4User)14271428# The rename/copy happened by applying a patch that created a1429# new file. This leaves it writable, which confuses p4.1430for f in pureRenameCopy:1431p4_sync(f,"-f")14321433else:1434# skip this patch1435 ret =False1436print"Submission cancelled, undoing p4 changes."1437for f in editedFiles:1438p4_revert(f)1439for f in filesToAdd:1440p4_revert(f)1441 os.remove(f)1442for f in filesToDelete:1443p4_revert(f)14441445 os.remove(fileName)1446return ret14471448# Export git tags as p4 labels. Create a p4 label and then tag1449# with that.1450defexportGitTags(self, gitTags):1451 validLabelRegexp =gitConfig("git-p4.labelExportRegexp")1452iflen(validLabelRegexp) ==0:1453 validLabelRegexp = defaultLabelRegexp1454 m = re.compile(validLabelRegexp)14551456for name in gitTags:14571458if not m.match(name):1459if verbose:1460print"tag%sdoes not match regexp%s"% (name, validLabelRegexp)1461continue14621463# Get the p4 commit this corresponds to1464 logMessage =extractLogMessageFromGitCommit(name)1465 values =extractSettingsGitLog(logMessage)14661467if not values.has_key('change'):1468# a tag pointing to something not sent to p4; ignore1469if verbose:1470print"git tag%sdoes not give a p4 commit"% name1471continue1472else:1473 changelist = values['change']14741475# Get the tag details.1476 inHeader =True1477 isAnnotated =False1478 body = []1479for l inread_pipe_lines(["git","cat-file","-p", name]):1480 l = l.strip()1481if inHeader:1482if re.match(r'tag\s+', l):1483 isAnnotated =True1484elif re.match(r'\s*$', l):1485 inHeader =False1486continue1487else:1488 body.append(l)14891490if not isAnnotated:1491 body = ["lightweight tag imported by git p4\n"]14921493# Create the label - use the same view as the client spec we are using1494 clientSpec =getClientSpec()14951496 labelTemplate ="Label:%s\n"% name1497 labelTemplate +="Description:\n"1498for b in body:1499 labelTemplate +="\t"+ b +"\n"1500 labelTemplate +="View:\n"1501for mapping in clientSpec.mappings:1502 labelTemplate +="\t%s\n"% mapping.depot_side.path15031504if self.dry_run:1505print"Would create p4 label%sfor tag"% name1506elif self.prepare_p4_only:1507print"Not creating p4 label%sfor tag due to option" \1508" --prepare-p4-only"% name1509else:1510p4_write_pipe(["label","-i"], labelTemplate)15111512# Use the label1513p4_system(["tag","-l", name] +1514["%s@%s"% (mapping.depot_side.path, changelist)for mapping in clientSpec.mappings])15151516if verbose:1517print"created p4 label for tag%s"% name15181519defrun(self, args):1520iflen(args) ==0:1521 self.master =currentGitBranch()1522iflen(self.master) ==0or notgitBranchExists("refs/heads/%s"% self.master):1523die("Detecting current git branch failed!")1524eliflen(args) ==1:1525 self.master = args[0]1526if notbranchExists(self.master):1527die("Branch%sdoes not exist"% self.master)1528else:1529return False15301531 allowSubmit =gitConfig("git-p4.allowSubmit")1532iflen(allowSubmit) >0and not self.master in allowSubmit.split(","):1533die("%sis not in git-p4.allowSubmit"% self.master)15341535[upstream, settings] =findUpstreamBranchPoint()1536 self.depotPath = settings['depot-paths'][0]1537iflen(self.origin) ==0:1538 self.origin = upstream15391540if self.preserveUser:1541if not self.canChangeChangelists():1542die("Cannot preserve user names without p4 super-user or admin permissions")15431544# if not set from the command line, try the config file1545if self.conflict_behavior is None:1546 val =gitConfig("git-p4.conflict")1547if val:1548if val not in self.conflict_behavior_choices:1549die("Invalid value '%s' for config git-p4.conflict"% val)1550else:1551 val ="ask"1552 self.conflict_behavior = val15531554if self.verbose:1555print"Origin branch is "+ self.origin15561557iflen(self.depotPath) ==0:1558print"Internal error: cannot locate perforce depot path from existing branches"1559 sys.exit(128)15601561 self.useClientSpec =False1562ifgitConfig("git-p4.useclientspec","--bool") =="true":1563 self.useClientSpec =True1564if self.useClientSpec:1565 self.clientSpecDirs =getClientSpec()15661567if self.useClientSpec:1568# all files are relative to the client spec1569 self.clientPath =getClientRoot()1570else:1571 self.clientPath =p4Where(self.depotPath)15721573if self.clientPath =="":1574die("Error: Cannot locate perforce checkout of%sin client view"% self.depotPath)15751576print"Perforce checkout for depot path%slocated at%s"% (self.depotPath, self.clientPath)1577 self.oldWorkingDirectory = os.getcwd()15781579# ensure the clientPath exists1580 new_client_dir =False1581if not os.path.exists(self.clientPath):1582 new_client_dir =True1583 os.makedirs(self.clientPath)15841585chdir(self.clientPath)1586if self.dry_run:1587print"Would synchronize p4 checkout in%s"% self.clientPath1588else:1589print"Synchronizing p4 checkout..."1590if new_client_dir:1591# old one was destroyed, and maybe nobody told p41592p4_sync("...","-f")1593else:1594p4_sync("...")1595 self.check()15961597 commits = []1598for line inread_pipe_lines("git rev-list --no-merges%s..%s"% (self.origin, self.master)):1599 commits.append(line.strip())1600 commits.reverse()16011602if self.preserveUser or(gitConfig("git-p4.skipUserNameCheck") =="true"):1603 self.checkAuthorship =False1604else:1605 self.checkAuthorship =True16061607if self.preserveUser:1608 self.checkValidP4Users(commits)16091610#1611# Build up a set of options to be passed to diff when1612# submitting each commit to p4.1613#1614if self.detectRenames:1615# command-line -M arg1616 self.diffOpts ="-M"1617else:1618# If not explicitly set check the config variable1619 detectRenames =gitConfig("git-p4.detectRenames")16201621if detectRenames.lower() =="false"or detectRenames =="":1622 self.diffOpts =""1623elif detectRenames.lower() =="true":1624 self.diffOpts ="-M"1625else:1626 self.diffOpts ="-M%s"% detectRenames16271628# no command-line arg for -C or --find-copies-harder, just1629# config variables1630 detectCopies =gitConfig("git-p4.detectCopies")1631if detectCopies.lower() =="false"or detectCopies =="":1632pass1633elif detectCopies.lower() =="true":1634 self.diffOpts +=" -C"1635else:1636 self.diffOpts +=" -C%s"% detectCopies16371638ifgitConfig("git-p4.detectCopiesHarder","--bool") =="true":1639 self.diffOpts +=" --find-copies-harder"16401641#1642# Apply the commits, one at a time. On failure, ask if should1643# continue to try the rest of the patches, or quit.1644#1645if self.dry_run:1646print"Would apply"1647 applied = []1648 last =len(commits) -11649for i, commit inenumerate(commits):1650if self.dry_run:1651print" ",read_pipe(["git","show","-s",1652"--format=format:%h%s", commit])1653 ok =True1654else:1655 ok = self.applyCommit(commit)1656if ok:1657 applied.append(commit)1658else:1659if self.prepare_p4_only and i < last:1660print"Processing only the first commit due to option" \1661" --prepare-p4-only"1662break1663if i < last:1664 quit =False1665while True:1666# prompt for what to do, or use the option/variable1667if self.conflict_behavior =="ask":1668print"What do you want to do?"1669 response =raw_input("[s]kip this commit but apply"1670" the rest, or [q]uit? ")1671if not response:1672continue1673elif self.conflict_behavior =="skip":1674 response ="s"1675elif self.conflict_behavior =="quit":1676 response ="q"1677else:1678die("Unknown conflict_behavior '%s'"%1679 self.conflict_behavior)16801681if response[0] =="s":1682print"Skipping this commit, but applying the rest"1683break1684if response[0] =="q":1685print"Quitting"1686 quit =True1687break1688if quit:1689break16901691chdir(self.oldWorkingDirectory)16921693if self.dry_run:1694pass1695elif self.prepare_p4_only:1696pass1697eliflen(commits) ==len(applied):1698print"All commits applied!"16991700 sync =P4Sync()1701if self.branch:1702 sync.branch = self.branch1703 sync.run([])17041705 rebase =P4Rebase()1706 rebase.rebase()17071708else:1709iflen(applied) ==0:1710print"No commits applied."1711else:1712print"Applied only the commits marked with '*':"1713for c in commits:1714if c in applied:1715 star ="*"1716else:1717 star =" "1718print star,read_pipe(["git","show","-s",1719"--format=format:%h%s", c])1720print"You will have to do 'git p4 sync' and rebase."17211722ifgitConfig("git-p4.exportLabels","--bool") =="true":1723 self.exportLabels =True17241725if self.exportLabels:1726 p4Labels =getP4Labels(self.depotPath)1727 gitTags =getGitTags()17281729 missingGitTags = gitTags - p4Labels1730 self.exportGitTags(missingGitTags)17311732# exit with error unless everything applied perfecly1733iflen(commits) !=len(applied):1734 sys.exit(1)17351736return True17371738classView(object):1739"""Represent a p4 view ("p4 help views"), and map files in a1740 repo according to the view."""17411742classPath(object):1743"""A depot or client path, possibly containing wildcards.1744 The only one supported is ... at the end, currently.1745 Initialize with the full path, with //depot or //client."""17461747def__init__(self, path, is_depot):1748 self.path = path1749 self.is_depot = is_depot1750 self.find_wildcards()1751# remember the prefix bit, useful for relative mappings1752 m = re.match("(//[^/]+/)", self.path)1753if not m:1754die("Path%sdoes not start with //prefix/"% self.path)1755 prefix = m.group(1)1756if not self.is_depot:1757# strip //client/ on client paths1758 self.path = self.path[len(prefix):]17591760deffind_wildcards(self):1761"""Make sure wildcards are valid, and set up internal1762 variables."""17631764 self.ends_triple_dot =False1765# There are three wildcards allowed in p4 views1766# (see "p4 help views"). This code knows how to1767# handle "..." (only at the end), but cannot deal with1768# "%%n" or "*". Only check the depot_side, as p4 should1769# validate that the client_side matches too.1770if re.search(r'%%[1-9]', self.path):1771die("Can't handle%%n wildcards in view:%s"% self.path)1772if self.path.find("*") >=0:1773die("Can't handle * wildcards in view:%s"% self.path)1774 triple_dot_index = self.path.find("...")1775if triple_dot_index >=0:1776if triple_dot_index !=len(self.path) -3:1777die("Can handle only single ... wildcard, at end:%s"%1778 self.path)1779 self.ends_triple_dot =True17801781defensure_compatible(self, other_path):1782"""Make sure the wildcards agree."""1783if self.ends_triple_dot != other_path.ends_triple_dot:1784die("Both paths must end with ... if either does;\n"+1785"paths:%s %s"% (self.path, other_path.path))17861787defmatch_wildcards(self, test_path):1788"""See if this test_path matches us, and fill in the value1789 of the wildcards if so. Returns a tuple of1790 (True|False, wildcards[]). For now, only the ... at end1791 is supported, so at most one wildcard."""1792if self.ends_triple_dot:1793 dotless = self.path[:-3]1794if test_path.startswith(dotless):1795 wildcard = test_path[len(dotless):]1796return(True, [ wildcard ])1797else:1798if test_path == self.path:1799return(True, [])1800return(False, [])18011802defmatch(self, test_path):1803"""Just return if it matches; don't bother with the wildcards."""1804 b, _ = self.match_wildcards(test_path)1805return b18061807deffill_in_wildcards(self, wildcards):1808"""Return the relative path, with the wildcards filled in1809 if there are any."""1810if self.ends_triple_dot:1811return self.path[:-3] + wildcards[0]1812else:1813return self.path18141815classMapping(object):1816def__init__(self, depot_side, client_side, overlay, exclude):1817# depot_side is without the trailing /... if it had one1818 self.depot_side = View.Path(depot_side, is_depot=True)1819 self.client_side = View.Path(client_side, is_depot=False)1820 self.overlay = overlay # started with "+"1821 self.exclude = exclude # started with "-"1822assert not(self.overlay and self.exclude)1823 self.depot_side.ensure_compatible(self.client_side)18241825def__str__(self):1826 c =" "1827if self.overlay:1828 c ="+"1829if self.exclude:1830 c ="-"1831return"View.Mapping:%s%s->%s"% \1832(c, self.depot_side.path, self.client_side.path)18331834defmap_depot_to_client(self, depot_path):1835"""Calculate the client path if using this mapping on the1836 given depot path; does not consider the effect of other1837 mappings in a view. Even excluded mappings are returned."""1838 matches, wildcards = self.depot_side.match_wildcards(depot_path)1839if not matches:1840return""1841 client_path = self.client_side.fill_in_wildcards(wildcards)1842return client_path18431844#1845# View methods1846#1847def__init__(self):1848 self.mappings = []18491850defappend(self, view_line):1851"""Parse a view line, splitting it into depot and client1852 sides. Append to self.mappings, preserving order."""18531854# Split the view line into exactly two words. P4 enforces1855# structure on these lines that simplifies this quite a bit.1856#1857# Either or both words may be double-quoted.1858# Single quotes do not matter.1859# Double-quote marks cannot occur inside the words.1860# A + or - prefix is also inside the quotes.1861# There are no quotes unless they contain a space.1862# The line is already white-space stripped.1863# The two words are separated by a single space.1864#1865if view_line[0] =='"':1866# First word is double quoted. Find its end.1867 close_quote_index = view_line.find('"',1)1868if close_quote_index <=0:1869die("No first-word closing quote found:%s"% view_line)1870 depot_side = view_line[1:close_quote_index]1871# skip closing quote and space1872 rhs_index = close_quote_index +1+11873else:1874 space_index = view_line.find(" ")1875if space_index <=0:1876die("No word-splitting space found:%s"% view_line)1877 depot_side = view_line[0:space_index]1878 rhs_index = space_index +118791880if view_line[rhs_index] =='"':1881# Second word is double quoted. Make sure there is a1882# double quote at the end too.1883if not view_line.endswith('"'):1884die("View line with rhs quote should end with one:%s"%1885 view_line)1886# skip the quotes1887 client_side = view_line[rhs_index+1:-1]1888else:1889 client_side = view_line[rhs_index:]18901891# prefix + means overlay on previous mapping1892 overlay =False1893if depot_side.startswith("+"):1894 overlay =True1895 depot_side = depot_side[1:]18961897# prefix - means exclude this path1898 exclude =False1899if depot_side.startswith("-"):1900 exclude =True1901 depot_side = depot_side[1:]19021903 m = View.Mapping(depot_side, client_side, overlay, exclude)1904 self.mappings.append(m)19051906defmap_in_client(self, depot_path):1907"""Return the relative location in the client where this1908 depot file should live. Returns "" if the file should1909 not be mapped in the client."""19101911 paths_filled = []1912 client_path =""19131914# look at later entries first1915for m in self.mappings[::-1]:19161917# see where will this path end up in the client1918 p = m.map_depot_to_client(depot_path)19191920if p =="":1921# Depot path does not belong in client. Must remember1922# this, as previous items should not cause files to1923# exist in this path either. Remember that the list is1924# being walked from the end, which has higher precedence.1925# Overlap mappings do not exclude previous mappings.1926if not m.overlay:1927 paths_filled.append(m.client_side)19281929else:1930# This mapping matched; no need to search any further.1931# But, the mapping could be rejected if the client path1932# has already been claimed by an earlier mapping (i.e.1933# one later in the list, which we are walking backwards).1934 already_mapped_in_client =False1935for f in paths_filled:1936# this is View.Path.match1937if f.match(p):1938 already_mapped_in_client =True1939break1940if not already_mapped_in_client:1941# Include this file, unless it is from a line that1942# explicitly said to exclude it.1943if not m.exclude:1944 client_path = p19451946# a match, even if rejected, always stops the search1947break19481949return client_path19501951classP4Sync(Command, P4UserMap):1952 delete_actions = ("delete","move/delete","purge")19531954def__init__(self):1955 Command.__init__(self)1956 P4UserMap.__init__(self)1957 self.options = [1958 optparse.make_option("--branch", dest="branch"),1959 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),1960 optparse.make_option("--changesfile", dest="changesFile"),1961 optparse.make_option("--silent", dest="silent", action="store_true"),1962 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),1963 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),1964 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",1965help="Import into refs/heads/ , not refs/remotes"),1966 optparse.make_option("--max-changes", dest="maxChanges"),1967 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',1968help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),1969 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',1970help="Only sync files that are included in the Perforce Client Spec")1971]1972 self.description ="""Imports from Perforce into a git repository.\n1973 example:1974 //depot/my/project/ -- to import the current head1975 //depot/my/project/@all -- to import everything1976 //depot/my/project/@1,6 -- to import only from revision 1 to 619771978 (a ... is not needed in the path p4 specification, it's added implicitly)"""19791980 self.usage +=" //depot/path[@revRange]"1981 self.silent =False1982 self.createdBranches =set()1983 self.committedChanges =set()1984 self.branch =""1985 self.detectBranches =False1986 self.detectLabels =False1987 self.importLabels =False1988 self.changesFile =""1989 self.syncWithOrigin =True1990 self.importIntoRemotes =True1991 self.maxChanges =""1992 self.isWindows = (platform.system() =="Windows")1993 self.keepRepoPath =False1994 self.depotPaths =None1995 self.p4BranchesInGit = []1996 self.cloneExclude = []1997 self.useClientSpec =False1998 self.useClientSpec_from_options =False1999 self.clientSpecDirs =None2000 self.tempBranches = []2001 self.tempBranchLocation ="git-p4-tmp"20022003ifgitConfig("git-p4.syncFromOrigin") =="false":2004 self.syncWithOrigin =False20052006# Force a checkpoint in fast-import and wait for it to finish2007defcheckpoint(self):2008 self.gitStream.write("checkpoint\n\n")2009 self.gitStream.write("progress checkpoint\n\n")2010 out = self.gitOutput.readline()2011if self.verbose:2012print"checkpoint finished: "+ out20132014defextractFilesFromCommit(self, commit):2015 self.cloneExclude = [re.sub(r"\.\.\.$","", path)2016for path in self.cloneExclude]2017 files = []2018 fnum =02019while commit.has_key("depotFile%s"% fnum):2020 path = commit["depotFile%s"% fnum]20212022if[p for p in self.cloneExclude2023ifp4PathStartsWith(path, p)]:2024 found =False2025else:2026 found = [p for p in self.depotPaths2027ifp4PathStartsWith(path, p)]2028if not found:2029 fnum = fnum +12030continue20312032file= {}2033file["path"] = path2034file["rev"] = commit["rev%s"% fnum]2035file["action"] = commit["action%s"% fnum]2036file["type"] = commit["type%s"% fnum]2037 files.append(file)2038 fnum = fnum +12039return files20402041defstripRepoPath(self, path, prefixes):2042"""When streaming files, this is called to map a p4 depot path2043 to where it should go in git. The prefixes are either2044 self.depotPaths, or self.branchPrefixes in the case of2045 branch detection."""20462047if self.useClientSpec:2048# branch detection moves files up a level (the branch name)2049# from what client spec interpretation gives2050 path = self.clientSpecDirs.map_in_client(path)2051if self.detectBranches:2052for b in self.knownBranches:2053if path.startswith(b +"/"):2054 path = path[len(b)+1:]20552056elif self.keepRepoPath:2057# Preserve everything in relative path name except leading2058# //depot/; just look at first prefix as they all should2059# be in the same depot.2060 depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])2061ifp4PathStartsWith(path, depot):2062 path = path[len(depot):]20632064else:2065for p in prefixes:2066ifp4PathStartsWith(path, p):2067 path = path[len(p):]2068break20692070 path =wildcard_decode(path)2071return path20722073defsplitFilesIntoBranches(self, commit):2074"""Look at each depotFile in the commit to figure out to what2075 branch it belongs."""20762077 branches = {}2078 fnum =02079while commit.has_key("depotFile%s"% fnum):2080 path = commit["depotFile%s"% fnum]2081 found = [p for p in self.depotPaths2082ifp4PathStartsWith(path, p)]2083if not found:2084 fnum = fnum +12085continue20862087file= {}2088file["path"] = path2089file["rev"] = commit["rev%s"% fnum]2090file["action"] = commit["action%s"% fnum]2091file["type"] = commit["type%s"% fnum]2092 fnum = fnum +120932094# start with the full relative path where this file would2095# go in a p4 client2096if self.useClientSpec:2097 relPath = self.clientSpecDirs.map_in_client(path)2098else:2099 relPath = self.stripRepoPath(path, self.depotPaths)21002101for branch in self.knownBranches.keys():2102# add a trailing slash so that a commit into qt/4.2foo2103# doesn't end up in qt/4.2, e.g.2104if relPath.startswith(branch +"/"):2105if branch not in branches:2106 branches[branch] = []2107 branches[branch].append(file)2108break21092110return branches21112112# output one file from the P4 stream2113# - helper for streamP4Files21142115defstreamOneP4File(self,file, contents):2116 relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)2117if verbose:2118 sys.stderr.write("%s\n"% relPath)21192120(type_base, type_mods) =split_p4_type(file["type"])21212122 git_mode ="100644"2123if"x"in type_mods:2124 git_mode ="100755"2125if type_base =="symlink":2126 git_mode ="120000"2127# p4 print on a symlink contains "target\n"; remove the newline2128 data =''.join(contents)2129 contents = [data[:-1]]21302131if type_base =="utf16":2132# p4 delivers different text in the python output to -G2133# than it does when using "print -o", or normal p4 client2134# operations. utf16 is converted to ascii or utf8, perhaps.2135# But ascii text saved as -t utf16 is completely mangled.2136# Invoke print -o to get the real contents.2137 text =p4_read_pipe(['print','-q','-o','-',file['depotFile']])2138 contents = [ text ]21392140if type_base =="apple":2141# Apple filetype files will be streamed as a concatenation of2142# its appledouble header and the contents. This is useless2143# on both macs and non-macs. If using "print -q -o xx", it2144# will create "xx" with the data, and "%xx" with the header.2145# This is also not very useful.2146#2147# Ideally, someday, this script can learn how to generate2148# appledouble files directly and import those to git, but2149# non-mac machines can never find a use for apple filetype.2150print"\nIgnoring apple filetype file%s"%file['depotFile']2151return21522153# Perhaps windows wants unicode, utf16 newlines translated too;2154# but this is not doing it.2155if self.isWindows and type_base =="text":2156 mangled = []2157for data in contents:2158 data = data.replace("\r\n","\n")2159 mangled.append(data)2160 contents = mangled21612162# Note that we do not try to de-mangle keywords on utf16 files,2163# even though in theory somebody may want that.2164 pattern =p4_keywords_regexp_for_type(type_base, type_mods)2165if pattern:2166 regexp = re.compile(pattern, re.VERBOSE)2167 text =''.join(contents)2168 text = regexp.sub(r'$\1$', text)2169 contents = [ text ]21702171 self.gitStream.write("M%sinline%s\n"% (git_mode, relPath))21722173# total length...2174 length =02175for d in contents:2176 length = length +len(d)21772178 self.gitStream.write("data%d\n"% length)2179for d in contents:2180 self.gitStream.write(d)2181 self.gitStream.write("\n")21822183defstreamOneP4Deletion(self,file):2184 relPath = self.stripRepoPath(file['path'], self.branchPrefixes)2185if verbose:2186 sys.stderr.write("delete%s\n"% relPath)2187 self.gitStream.write("D%s\n"% relPath)21882189# handle another chunk of streaming data2190defstreamP4FilesCb(self, marshalled):21912192# catch p4 errors and complain2193 err =None2194if"code"in marshalled:2195if marshalled["code"] =="error":2196if"data"in marshalled:2197 err = marshalled["data"].rstrip()2198if err:2199 f =None2200if self.stream_have_file_info:2201if"depotFile"in self.stream_file:2202 f = self.stream_file["depotFile"]2203# force a failure in fast-import, else an empty2204# commit will be made2205 self.gitStream.write("\n")2206 self.gitStream.write("die-now\n")2207 self.gitStream.close()2208# ignore errors, but make sure it exits first2209 self.importProcess.wait()2210if f:2211die("Error from p4 print for%s:%s"% (f, err))2212else:2213die("Error from p4 print:%s"% err)22142215if marshalled.has_key('depotFile')and self.stream_have_file_info:2216# start of a new file - output the old one first2217 self.streamOneP4File(self.stream_file, self.stream_contents)2218 self.stream_file = {}2219 self.stream_contents = []2220 self.stream_have_file_info =False22212222# pick up the new file information... for the2223# 'data' field we need to append to our array2224for k in marshalled.keys():2225if k =='data':2226 self.stream_contents.append(marshalled['data'])2227else:2228 self.stream_file[k] = marshalled[k]22292230 self.stream_have_file_info =True22312232# Stream directly from "p4 files" into "git fast-import"2233defstreamP4Files(self, files):2234 filesForCommit = []2235 filesToRead = []2236 filesToDelete = []22372238for f in files:2239# if using a client spec, only add the files that have2240# a path in the client2241if self.clientSpecDirs:2242if self.clientSpecDirs.map_in_client(f['path']) =="":2243continue22442245 filesForCommit.append(f)2246if f['action']in self.delete_actions:2247 filesToDelete.append(f)2248else:2249 filesToRead.append(f)22502251# deleted files...2252for f in filesToDelete:2253 self.streamOneP4Deletion(f)22542255iflen(filesToRead) >0:2256 self.stream_file = {}2257 self.stream_contents = []2258 self.stream_have_file_info =False22592260# curry self argument2261defstreamP4FilesCbSelf(entry):2262 self.streamP4FilesCb(entry)22632264 fileArgs = ['%s#%s'% (f['path'], f['rev'])for f in filesToRead]22652266p4CmdList(["-x","-","print"],2267 stdin=fileArgs,2268 cb=streamP4FilesCbSelf)22692270# do the last chunk2271if self.stream_file.has_key('depotFile'):2272 self.streamOneP4File(self.stream_file, self.stream_contents)22732274defmake_email(self, userid):2275if userid in self.users:2276return self.users[userid]2277else:2278return"%s<a@b>"% userid22792280# Stream a p4 tag2281defstreamTag(self, gitStream, labelName, labelDetails, commit, epoch):2282if verbose:2283print"writing tag%sfor commit%s"% (labelName, commit)2284 gitStream.write("tag%s\n"% labelName)2285 gitStream.write("from%s\n"% commit)22862287if labelDetails.has_key('Owner'):2288 owner = labelDetails["Owner"]2289else:2290 owner =None22912292# Try to use the owner of the p4 label, or failing that,2293# the current p4 user id.2294if owner:2295 email = self.make_email(owner)2296else:2297 email = self.make_email(self.p4UserId())2298 tagger ="%s %s %s"% (email, epoch, self.tz)22992300 gitStream.write("tagger%s\n"% tagger)23012302print"labelDetails=",labelDetails2303if labelDetails.has_key('Description'):2304 description = labelDetails['Description']2305else:2306 description ='Label from git p4'23072308 gitStream.write("data%d\n"%len(description))2309 gitStream.write(description)2310 gitStream.write("\n")23112312defcommit(self, details, files, branch, parent =""):2313 epoch = details["time"]2314 author = details["user"]23152316if self.verbose:2317print"commit into%s"% branch23182319# start with reading files; if that fails, we should not2320# create a commit.2321 new_files = []2322for f in files:2323if[p for p in self.branchPrefixes ifp4PathStartsWith(f['path'], p)]:2324 new_files.append(f)2325else:2326 sys.stderr.write("Ignoring file outside of prefix:%s\n"% f['path'])23272328 self.gitStream.write("commit%s\n"% branch)2329# gitStream.write("mark :%s\n" % details["change"])2330 self.committedChanges.add(int(details["change"]))2331 committer =""2332if author not in self.users:2333 self.getUserMapFromPerforceServer()2334 committer ="%s %s %s"% (self.make_email(author), epoch, self.tz)23352336 self.gitStream.write("committer%s\n"% committer)23372338 self.gitStream.write("data <<EOT\n")2339 self.gitStream.write(details["desc"])2340 self.gitStream.write("\n[git-p4: depot-paths =\"%s\": change =%s"%2341(','.join(self.branchPrefixes), details["change"]))2342iflen(details['options']) >0:2343 self.gitStream.write(": options =%s"% details['options'])2344 self.gitStream.write("]\nEOT\n\n")23452346iflen(parent) >0:2347if self.verbose:2348print"parent%s"% parent2349 self.gitStream.write("from%s\n"% parent)23502351 self.streamP4Files(new_files)2352 self.gitStream.write("\n")23532354 change =int(details["change"])23552356if self.labels.has_key(change):2357 label = self.labels[change]2358 labelDetails = label[0]2359 labelRevisions = label[1]2360if self.verbose:2361print"Change%sis labelled%s"% (change, labelDetails)23622363 files =p4CmdList(["files"] + ["%s...@%s"% (p, change)2364for p in self.branchPrefixes])23652366iflen(files) ==len(labelRevisions):23672368 cleanedFiles = {}2369for info in files:2370if info["action"]in self.delete_actions:2371continue2372 cleanedFiles[info["depotFile"]] = info["rev"]23732374if cleanedFiles == labelRevisions:2375 self.streamTag(self.gitStream,'tag_%s'% labelDetails['label'], labelDetails, branch, epoch)23762377else:2378if not self.silent:2379print("Tag%sdoes not match with change%s: files do not match."2380% (labelDetails["label"], change))23812382else:2383if not self.silent:2384print("Tag%sdoes not match with change%s: file count is different."2385% (labelDetails["label"], change))23862387# Build a dictionary of changelists and labels, for "detect-labels" option.2388defgetLabels(self):2389 self.labels = {}23902391 l =p4CmdList(["labels"] + ["%s..."% p for p in self.depotPaths])2392iflen(l) >0and not self.silent:2393print"Finding files belonging to labels in%s"% `self.depotPaths`23942395for output in l:2396 label = output["label"]2397 revisions = {}2398 newestChange =02399if self.verbose:2400print"Querying files for label%s"% label2401forfileinp4CmdList(["files"] +2402["%s...@%s"% (p, label)2403for p in self.depotPaths]):2404 revisions[file["depotFile"]] =file["rev"]2405 change =int(file["change"])2406if change > newestChange:2407 newestChange = change24082409 self.labels[newestChange] = [output, revisions]24102411if self.verbose:2412print"Label changes:%s"% self.labels.keys()24132414# Import p4 labels as git tags. A direct mapping does not2415# exist, so assume that if all the files are at the same revision2416# then we can use that, or it's something more complicated we should2417# just ignore.2418defimportP4Labels(self, stream, p4Labels):2419if verbose:2420print"import p4 labels: "+' '.join(p4Labels)24212422 ignoredP4Labels =gitConfigList("git-p4.ignoredP4Labels")2423 validLabelRegexp =gitConfig("git-p4.labelImportRegexp")2424iflen(validLabelRegexp) ==0:2425 validLabelRegexp = defaultLabelRegexp2426 m = re.compile(validLabelRegexp)24272428for name in p4Labels:2429 commitFound =False24302431if not m.match(name):2432if verbose:2433print"label%sdoes not match regexp%s"% (name,validLabelRegexp)2434continue24352436if name in ignoredP4Labels:2437continue24382439 labelDetails =p4CmdList(['label',"-o", name])[0]24402441# get the most recent changelist for each file in this label2442 change =p4Cmd(["changes","-m","1"] + ["%s...@%s"% (p, name)2443for p in self.depotPaths])24442445if change.has_key('change'):2446# find the corresponding git commit; take the oldest commit2447 changelist =int(change['change'])2448 gitCommit =read_pipe(["git","rev-list","--max-count=1",2449"--reverse",":/\[git-p4:.*change =%d\]"% changelist])2450iflen(gitCommit) ==0:2451print"could not find git commit for changelist%d"% changelist2452else:2453 gitCommit = gitCommit.strip()2454 commitFound =True2455# Convert from p4 time format2456try:2457 tmwhen = time.strptime(labelDetails['Update'],"%Y/%m/%d%H:%M:%S")2458exceptValueError:2459print"Could not convert label time%s"% labelDetails['Update']2460 tmwhen =124612462 when =int(time.mktime(tmwhen))2463 self.streamTag(stream, name, labelDetails, gitCommit, when)2464if verbose:2465print"p4 label%smapped to git commit%s"% (name, gitCommit)2466else:2467if verbose:2468print"Label%shas no changelists - possibly deleted?"% name24692470if not commitFound:2471# We can't import this label; don't try again as it will get very2472# expensive repeatedly fetching all the files for labels that will2473# never be imported. If the label is moved in the future, the2474# ignore will need to be removed manually.2475system(["git","config","--add","git-p4.ignoredP4Labels", name])24762477defguessProjectName(self):2478for p in self.depotPaths:2479if p.endswith("/"):2480 p = p[:-1]2481 p = p[p.strip().rfind("/") +1:]2482if not p.endswith("/"):2483 p +="/"2484return p24852486defgetBranchMapping(self):2487 lostAndFoundBranches =set()24882489 user =gitConfig("git-p4.branchUser")2490iflen(user) >0:2491 command ="branches -u%s"% user2492else:2493 command ="branches"24942495for info inp4CmdList(command):2496 details =p4Cmd(["branch","-o", info["branch"]])2497 viewIdx =02498while details.has_key("View%s"% viewIdx):2499 paths = details["View%s"% viewIdx].split(" ")2500 viewIdx = viewIdx +12501# require standard //depot/foo/... //depot/bar/... mapping2502iflen(paths) !=2or not paths[0].endswith("/...")or not paths[1].endswith("/..."):2503continue2504 source = paths[0]2505 destination = paths[1]2506## HACK2507ifp4PathStartsWith(source, self.depotPaths[0])andp4PathStartsWith(destination, self.depotPaths[0]):2508 source = source[len(self.depotPaths[0]):-4]2509 destination = destination[len(self.depotPaths[0]):-4]25102511if destination in self.knownBranches:2512if not self.silent:2513print"p4 branch%sdefines a mapping from%sto%s"% (info["branch"], source, destination)2514print"but there exists another mapping from%sto%salready!"% (self.knownBranches[destination], destination)2515continue25162517 self.knownBranches[destination] = source25182519 lostAndFoundBranches.discard(destination)25202521if source not in self.knownBranches:2522 lostAndFoundBranches.add(source)25232524# Perforce does not strictly require branches to be defined, so we also2525# check git config for a branch list.2526#2527# Example of branch definition in git config file:2528# [git-p4]2529# branchList=main:branchA2530# branchList=main:branchB2531# branchList=branchA:branchC2532 configBranches =gitConfigList("git-p4.branchList")2533for branch in configBranches:2534if branch:2535(source, destination) = branch.split(":")2536 self.knownBranches[destination] = source25372538 lostAndFoundBranches.discard(destination)25392540if source not in self.knownBranches:2541 lostAndFoundBranches.add(source)254225432544for branch in lostAndFoundBranches:2545 self.knownBranches[branch] = branch25462547defgetBranchMappingFromGitBranches(self):2548 branches =p4BranchesInGit(self.importIntoRemotes)2549for branch in branches.keys():2550if branch =="master":2551 branch ="main"2552else:2553 branch = branch[len(self.projectName):]2554 self.knownBranches[branch] = branch25552556defupdateOptionDict(self, d):2557 option_keys = {}2558if self.keepRepoPath:2559 option_keys['keepRepoPath'] =125602561 d["options"] =' '.join(sorted(option_keys.keys()))25622563defreadOptions(self, d):2564 self.keepRepoPath = (d.has_key('options')2565and('keepRepoPath'in d['options']))25662567defgitRefForBranch(self, branch):2568if branch =="main":2569return self.refPrefix +"master"25702571iflen(branch) <=0:2572return branch25732574return self.refPrefix + self.projectName + branch25752576defgitCommitByP4Change(self, ref, change):2577if self.verbose:2578print"looking in ref "+ ref +" for change%susing bisect..."% change25792580 earliestCommit =""2581 latestCommit =parseRevision(ref)25822583while True:2584if self.verbose:2585print"trying: earliest%slatest%s"% (earliestCommit, latestCommit)2586 next =read_pipe("git rev-list --bisect%s %s"% (latestCommit, earliestCommit)).strip()2587iflen(next) ==0:2588if self.verbose:2589print"argh"2590return""2591 log =extractLogMessageFromGitCommit(next)2592 settings =extractSettingsGitLog(log)2593 currentChange =int(settings['change'])2594if self.verbose:2595print"current change%s"% currentChange25962597if currentChange == change:2598if self.verbose:2599print"found%s"% next2600return next26012602if currentChange < change:2603 earliestCommit ="^%s"% next2604else:2605 latestCommit ="%s"% next26062607return""26082609defimportNewBranch(self, branch, maxChange):2610# make fast-import flush all changes to disk and update the refs using the checkpoint2611# command so that we can try to find the branch parent in the git history2612 self.gitStream.write("checkpoint\n\n");2613 self.gitStream.flush();2614 branchPrefix = self.depotPaths[0] + branch +"/"2615range="@1,%s"% maxChange2616#print "prefix" + branchPrefix2617 changes =p4ChangesForPaths([branchPrefix],range)2618iflen(changes) <=0:2619return False2620 firstChange = changes[0]2621#print "first change in branch: %s" % firstChange2622 sourceBranch = self.knownBranches[branch]2623 sourceDepotPath = self.depotPaths[0] + sourceBranch2624 sourceRef = self.gitRefForBranch(sourceBranch)2625#print "source " + sourceBranch26262627 branchParentChange =int(p4Cmd(["changes","-m","1","%s...@1,%s"% (sourceDepotPath, firstChange)])["change"])2628#print "branch parent: %s" % branchParentChange2629 gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)2630iflen(gitParent) >0:2631 self.initialParents[self.gitRefForBranch(branch)] = gitParent2632#print "parent git commit: %s" % gitParent26332634 self.importChanges(changes)2635return True26362637defsearchParent(self, parent, branch, target):2638 parentFound =False2639for blob inread_pipe_lines(["git","rev-list","--reverse","--no-merges", parent]):2640 blob = blob.strip()2641iflen(read_pipe(["git","diff-tree", blob, target])) ==0:2642 parentFound =True2643if self.verbose:2644print"Found parent of%sin commit%s"% (branch, blob)2645break2646if parentFound:2647return blob2648else:2649return None26502651defimportChanges(self, changes):2652 cnt =12653for change in changes:2654 description =p4_describe(change)2655 self.updateOptionDict(description)26562657if not self.silent:2658 sys.stdout.write("\rImporting revision%s(%s%%)"% (change, cnt *100/len(changes)))2659 sys.stdout.flush()2660 cnt = cnt +126612662try:2663if self.detectBranches:2664 branches = self.splitFilesIntoBranches(description)2665for branch in branches.keys():2666## HACK --hwn2667 branchPrefix = self.depotPaths[0] + branch +"/"2668 self.branchPrefixes = [ branchPrefix ]26692670 parent =""26712672 filesForCommit = branches[branch]26732674if self.verbose:2675print"branch is%s"% branch26762677 self.updatedBranches.add(branch)26782679if branch not in self.createdBranches:2680 self.createdBranches.add(branch)2681 parent = self.knownBranches[branch]2682if parent == branch:2683 parent =""2684else:2685 fullBranch = self.projectName + branch2686if fullBranch not in self.p4BranchesInGit:2687if not self.silent:2688print("\nImporting new branch%s"% fullBranch);2689if self.importNewBranch(branch, change -1):2690 parent =""2691 self.p4BranchesInGit.append(fullBranch)2692if not self.silent:2693print("\nResuming with change%s"% change);26942695if self.verbose:2696print"parent determined through known branches:%s"% parent26972698 branch = self.gitRefForBranch(branch)2699 parent = self.gitRefForBranch(parent)27002701if self.verbose:2702print"looking for initial parent for%s; current parent is%s"% (branch, parent)27032704iflen(parent) ==0and branch in self.initialParents:2705 parent = self.initialParents[branch]2706del self.initialParents[branch]27072708 blob =None2709iflen(parent) >0:2710 tempBranch = os.path.join(self.tempBranchLocation,"%d"% (change))2711if self.verbose:2712print"Creating temporary branch: "+ tempBranch2713 self.commit(description, filesForCommit, tempBranch)2714 self.tempBranches.append(tempBranch)2715 self.checkpoint()2716 blob = self.searchParent(parent, branch, tempBranch)2717if blob:2718 self.commit(description, filesForCommit, branch, blob)2719else:2720if self.verbose:2721print"Parent of%snot found. Committing into head of%s"% (branch, parent)2722 self.commit(description, filesForCommit, branch, parent)2723else:2724 files = self.extractFilesFromCommit(description)2725 self.commit(description, files, self.branch,2726 self.initialParent)2727# only needed once, to connect to the previous commit2728 self.initialParent =""2729exceptIOError:2730print self.gitError.read()2731 sys.exit(1)27322733defimportHeadRevision(self, revision):2734print"Doing initial import of%sfrom revision%sinto%s"% (' '.join(self.depotPaths), revision, self.branch)27352736 details = {}2737 details["user"] ="git perforce import user"2738 details["desc"] = ("Initial import of%sfrom the state at revision%s\n"2739% (' '.join(self.depotPaths), revision))2740 details["change"] = revision2741 newestRevision =027422743 fileCnt =02744 fileArgs = ["%s...%s"% (p,revision)for p in self.depotPaths]27452746for info inp4CmdList(["files"] + fileArgs):27472748if'code'in info and info['code'] =='error':2749 sys.stderr.write("p4 returned an error:%s\n"2750% info['data'])2751if info['data'].find("must refer to client") >=0:2752 sys.stderr.write("This particular p4 error is misleading.\n")2753 sys.stderr.write("Perhaps the depot path was misspelled.\n");2754 sys.stderr.write("Depot path:%s\n"%" ".join(self.depotPaths))2755 sys.exit(1)2756if'p4ExitCode'in info:2757 sys.stderr.write("p4 exitcode:%s\n"% info['p4ExitCode'])2758 sys.exit(1)275927602761 change =int(info["change"])2762if change > newestRevision:2763 newestRevision = change27642765if info["action"]in self.delete_actions:2766# don't increase the file cnt, otherwise details["depotFile123"] will have gaps!2767#fileCnt = fileCnt + 12768continue27692770for prop in["depotFile","rev","action","type"]:2771 details["%s%s"% (prop, fileCnt)] = info[prop]27722773 fileCnt = fileCnt +127742775 details["change"] = newestRevision27762777# Use time from top-most change so that all git p4 clones of2778# the same p4 repo have the same commit SHA1s.2779 res =p4_describe(newestRevision)2780 details["time"] = res["time"]27812782 self.updateOptionDict(details)2783try:2784 self.commit(details, self.extractFilesFromCommit(details), self.branch)2785exceptIOError:2786print"IO error with git fast-import. Is your git version recent enough?"2787print self.gitError.read()278827892790defrun(self, args):2791 self.depotPaths = []2792 self.changeRange =""2793 self.previousDepotPaths = []2794 self.hasOrigin =False27952796# map from branch depot path to parent branch2797 self.knownBranches = {}2798 self.initialParents = {}27992800if self.importIntoRemotes:2801 self.refPrefix ="refs/remotes/p4/"2802else:2803 self.refPrefix ="refs/heads/p4/"28042805if self.syncWithOrigin:2806 self.hasOrigin =originP4BranchesExist()2807if self.hasOrigin:2808if not self.silent:2809print'Syncing with origin first, using "git fetch origin"'2810system("git fetch origin")28112812 branch_arg_given =bool(self.branch)2813iflen(self.branch) ==0:2814 self.branch = self.refPrefix +"master"2815ifgitBranchExists("refs/heads/p4")and self.importIntoRemotes:2816system("git update-ref%srefs/heads/p4"% self.branch)2817system("git branch -D p4")28182819# accept either the command-line option, or the configuration variable2820if self.useClientSpec:2821# will use this after clone to set the variable2822 self.useClientSpec_from_options =True2823else:2824ifgitConfig("git-p4.useclientspec","--bool") =="true":2825 self.useClientSpec =True2826if self.useClientSpec:2827 self.clientSpecDirs =getClientSpec()28282829# TODO: should always look at previous commits,2830# merge with previous imports, if possible.2831if args == []:2832if self.hasOrigin:2833createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)28342835# branches holds mapping from branch name to sha12836 branches =p4BranchesInGit(self.importIntoRemotes)28372838# restrict to just this one, disabling detect-branches2839if branch_arg_given:2840 short = self.branch.split("/")[-1]2841if short in branches:2842 self.p4BranchesInGit = [ short ]2843else:2844 self.p4BranchesInGit = branches.keys()28452846iflen(self.p4BranchesInGit) >1:2847if not self.silent:2848print"Importing from/into multiple branches"2849 self.detectBranches =True2850for branch in branches.keys():2851 self.initialParents[self.refPrefix + branch] = \2852 branches[branch]28532854if self.verbose:2855print"branches:%s"% self.p4BranchesInGit28562857 p4Change =02858for branch in self.p4BranchesInGit:2859 logMsg =extractLogMessageFromGitCommit(self.refPrefix + branch)28602861 settings =extractSettingsGitLog(logMsg)28622863 self.readOptions(settings)2864if(settings.has_key('depot-paths')2865and settings.has_key('change')):2866 change =int(settings['change']) +12867 p4Change =max(p4Change, change)28682869 depotPaths =sorted(settings['depot-paths'])2870if self.previousDepotPaths == []:2871 self.previousDepotPaths = depotPaths2872else:2873 paths = []2874for(prev, cur)inzip(self.previousDepotPaths, depotPaths):2875 prev_list = prev.split("/")2876 cur_list = cur.split("/")2877for i inrange(0,min(len(cur_list),len(prev_list))):2878if cur_list[i] <> prev_list[i]:2879 i = i -12880break28812882 paths.append("/".join(cur_list[:i +1]))28832884 self.previousDepotPaths = paths28852886if p4Change >0:2887 self.depotPaths =sorted(self.previousDepotPaths)2888 self.changeRange ="@%s,#head"% p4Change2889if not self.silent and not self.detectBranches:2890print"Performing incremental import into%sgit branch"% self.branch28912892# accept multiple ref name abbreviations:2893# refs/foo/bar/branch -> use it exactly2894# p4/branch -> prepend refs/remotes/ or refs/heads/2895# branch -> prepend refs/remotes/p4/ or refs/heads/p4/2896if not self.branch.startswith("refs/"):2897if self.importIntoRemotes:2898 prepend ="refs/remotes/"2899else:2900 prepend ="refs/heads/"2901if not self.branch.startswith("p4/"):2902 prepend +="p4/"2903 self.branch = prepend + self.branch29042905iflen(args) ==0and self.depotPaths:2906if not self.silent:2907print"Depot paths:%s"%' '.join(self.depotPaths)2908else:2909if self.depotPaths and self.depotPaths != args:2910print("previous import used depot path%sand now%swas specified. "2911"This doesn't work!"% (' '.join(self.depotPaths),2912' '.join(args)))2913 sys.exit(1)29142915 self.depotPaths =sorted(args)29162917 revision =""2918 self.users = {}29192920# Make sure no revision specifiers are used when --changesfile2921# is specified.2922 bad_changesfile =False2923iflen(self.changesFile) >0:2924for p in self.depotPaths:2925if p.find("@") >=0or p.find("#") >=0:2926 bad_changesfile =True2927break2928if bad_changesfile:2929die("Option --changesfile is incompatible with revision specifiers")29302931 newPaths = []2932for p in self.depotPaths:2933if p.find("@") != -1:2934 atIdx = p.index("@")2935 self.changeRange = p[atIdx:]2936if self.changeRange =="@all":2937 self.changeRange =""2938elif','not in self.changeRange:2939 revision = self.changeRange2940 self.changeRange =""2941 p = p[:atIdx]2942elif p.find("#") != -1:2943 hashIdx = p.index("#")2944 revision = p[hashIdx:]2945 p = p[:hashIdx]2946elif self.previousDepotPaths == []:2947# pay attention to changesfile, if given, else import2948# the entire p4 tree at the head revision2949iflen(self.changesFile) ==0:2950 revision ="#head"29512952 p = re.sub("\.\.\.$","", p)2953if not p.endswith("/"):2954 p +="/"29552956 newPaths.append(p)29572958 self.depotPaths = newPaths29592960# --detect-branches may change this for each branch2961 self.branchPrefixes = self.depotPaths29622963 self.loadUserMapFromCache()2964 self.labels = {}2965if self.detectLabels:2966 self.getLabels();29672968if self.detectBranches:2969## FIXME - what's a P4 projectName ?2970 self.projectName = self.guessProjectName()29712972if self.hasOrigin:2973 self.getBranchMappingFromGitBranches()2974else:2975 self.getBranchMapping()2976if self.verbose:2977print"p4-git branches:%s"% self.p4BranchesInGit2978print"initial parents:%s"% self.initialParents2979for b in self.p4BranchesInGit:2980if b !="master":29812982## FIXME2983 b = b[len(self.projectName):]2984 self.createdBranches.add(b)29852986 self.tz ="%+03d%02d"% (- time.timezone /3600, ((- time.timezone %3600) /60))29872988 self.importProcess = subprocess.Popen(["git","fast-import"],2989 stdin=subprocess.PIPE,2990 stdout=subprocess.PIPE,2991 stderr=subprocess.PIPE);2992 self.gitOutput = self.importProcess.stdout2993 self.gitStream = self.importProcess.stdin2994 self.gitError = self.importProcess.stderr29952996if revision:2997 self.importHeadRevision(revision)2998else:2999 changes = []30003001iflen(self.changesFile) >0:3002 output =open(self.changesFile).readlines()3003 changeSet =set()3004for line in output:3005 changeSet.add(int(line))30063007for change in changeSet:3008 changes.append(change)30093010 changes.sort()3011else:3012# catch "git p4 sync" with no new branches, in a repo that3013# does not have any existing p4 branches3014iflen(args) ==0:3015if not self.p4BranchesInGit:3016die("No remote p4 branches. Perhaps you never did\"git p4 clone\"in here.")30173018# The default branch is master, unless --branch is used to3019# specify something else. Make sure it exists, or complain3020# nicely about how to use --branch.3021if not self.detectBranches:3022if notbranch_exists(self.branch):3023if branch_arg_given:3024die("Error: branch%sdoes not exist."% self.branch)3025else:3026die("Error: no branch%s; perhaps specify one with --branch."%3027 self.branch)30283029if self.verbose:3030print"Getting p4 changes for%s...%s"% (', '.join(self.depotPaths),3031 self.changeRange)3032 changes =p4ChangesForPaths(self.depotPaths, self.changeRange)30333034iflen(self.maxChanges) >0:3035 changes = changes[:min(int(self.maxChanges),len(changes))]30363037iflen(changes) ==0:3038if not self.silent:3039print"No changes to import!"3040else:3041if not self.silent and not self.detectBranches:3042print"Import destination:%s"% self.branch30433044 self.updatedBranches =set()30453046if not self.detectBranches:3047if args:3048# start a new branch3049 self.initialParent =""3050else:3051# build on a previous revision3052 self.initialParent =parseRevision(self.branch)30533054 self.importChanges(changes)30553056if not self.silent:3057print""3058iflen(self.updatedBranches) >0:3059 sys.stdout.write("Updated branches: ")3060for b in self.updatedBranches:3061 sys.stdout.write("%s"% b)3062 sys.stdout.write("\n")30633064ifgitConfig("git-p4.importLabels","--bool") =="true":3065 self.importLabels =True30663067if self.importLabels:3068 p4Labels =getP4Labels(self.depotPaths)3069 gitTags =getGitTags()30703071 missingP4Labels = p4Labels - gitTags3072 self.importP4Labels(self.gitStream, missingP4Labels)30733074 self.gitStream.close()3075if self.importProcess.wait() !=0:3076die("fast-import failed:%s"% self.gitError.read())3077 self.gitOutput.close()3078 self.gitError.close()30793080# Cleanup temporary branches created during import3081if self.tempBranches != []:3082for branch in self.tempBranches:3083read_pipe("git update-ref -d%s"% branch)3084 os.rmdir(os.path.join(os.environ.get("GIT_DIR",".git"), self.tempBranchLocation))30853086# Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow3087# a convenient shortcut refname "p4".3088if self.importIntoRemotes:3089 head_ref = self.refPrefix +"HEAD"3090if notgitBranchExists(head_ref)andgitBranchExists(self.branch):3091system(["git","symbolic-ref", head_ref, self.branch])30923093return True30943095classP4Rebase(Command):3096def__init__(self):3097 Command.__init__(self)3098 self.options = [3099 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),3100]3101 self.importLabels =False3102 self.description = ("Fetches the latest revision from perforce and "3103+"rebases the current work (branch) against it")31043105defrun(self, args):3106 sync =P4Sync()3107 sync.importLabels = self.importLabels3108 sync.run([])31093110return self.rebase()31113112defrebase(self):3113if os.system("git update-index --refresh") !=0:3114die("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.");3115iflen(read_pipe("git diff-index HEAD --")) >0:3116die("You have uncommited changes. Please commit them before rebasing or stash them away with git stash.");31173118[upstream, settings] =findUpstreamBranchPoint()3119iflen(upstream) ==0:3120die("Cannot find upstream branchpoint for rebase")31213122# the branchpoint may be p4/foo~3, so strip off the parent3123 upstream = re.sub("~[0-9]+$","", upstream)31243125print"Rebasing the current branch onto%s"% upstream3126 oldHead =read_pipe("git rev-parse HEAD").strip()3127system("git rebase%s"% upstream)3128system("git diff-tree --stat --summary -M%sHEAD"% oldHead)3129return True31303131classP4Clone(P4Sync):3132def__init__(self):3133 P4Sync.__init__(self)3134 self.description ="Creates a new git repository and imports from Perforce into it"3135 self.usage ="usage: %prog [options] //depot/path[@revRange]"3136 self.options += [3137 optparse.make_option("--destination", dest="cloneDestination",3138 action='store', default=None,3139help="where to leave result of the clone"),3140 optparse.make_option("-/", dest="cloneExclude",3141 action="append",type="string",3142help="exclude depot path"),3143 optparse.make_option("--bare", dest="cloneBare",3144 action="store_true", default=False),3145]3146 self.cloneDestination =None3147 self.needsGit =False3148 self.cloneBare =False31493150# This is required for the "append" cloneExclude action3151defensure_value(self, attr, value):3152if nothasattr(self, attr)orgetattr(self, attr)is None:3153setattr(self, attr, value)3154returngetattr(self, attr)31553156defdefaultDestination(self, args):3157## TODO: use common prefix of args?3158 depotPath = args[0]3159 depotDir = re.sub("(@[^@]*)$","", depotPath)3160 depotDir = re.sub("(#[^#]*)$","", depotDir)3161 depotDir = re.sub(r"\.\.\.$","", depotDir)3162 depotDir = re.sub(r"/$","", depotDir)3163return os.path.split(depotDir)[1]31643165defrun(self, args):3166iflen(args) <1:3167return False31683169if self.keepRepoPath and not self.cloneDestination:3170 sys.stderr.write("Must specify destination for --keep-path\n")3171 sys.exit(1)31723173 depotPaths = args31743175if not self.cloneDestination andlen(depotPaths) >1:3176 self.cloneDestination = depotPaths[-1]3177 depotPaths = depotPaths[:-1]31783179 self.cloneExclude = ["/"+p for p in self.cloneExclude]3180for p in depotPaths:3181if not p.startswith("//"):3182return False31833184if not self.cloneDestination:3185 self.cloneDestination = self.defaultDestination(args)31863187print"Importing from%sinto%s"% (', '.join(depotPaths), self.cloneDestination)31883189if not os.path.exists(self.cloneDestination):3190 os.makedirs(self.cloneDestination)3191chdir(self.cloneDestination)31923193 init_cmd = ["git","init"]3194if self.cloneBare:3195 init_cmd.append("--bare")3196 retcode = subprocess.call(init_cmd)3197if retcode:3198raiseCalledProcessError(retcode, init_cmd)31993200if not P4Sync.run(self, depotPaths):3201return False32023203# create a master branch and check out a work tree3204ifgitBranchExists(self.branch):3205system(["git","branch","master", self.branch ])3206if not self.cloneBare:3207system(["git","checkout","-f"])3208else:3209print'Not checking out any branch, use ' \3210'"git checkout -q -b master <branch>"'32113212# auto-set this variable if invoked with --use-client-spec3213if self.useClientSpec_from_options:3214system("git config --bool git-p4.useclientspec true")32153216return True32173218classP4Branches(Command):3219def__init__(self):3220 Command.__init__(self)3221 self.options = [ ]3222 self.description = ("Shows the git branches that hold imports and their "3223+"corresponding perforce depot paths")3224 self.verbose =False32253226defrun(self, args):3227iforiginP4BranchesExist():3228createOrUpdateBranchesFromOrigin()32293230 cmdline ="git rev-parse --symbolic "3231 cmdline +=" --remotes"32323233for line inread_pipe_lines(cmdline):3234 line = line.strip()32353236if not line.startswith('p4/')or line =="p4/HEAD":3237continue3238 branch = line32393240 log =extractLogMessageFromGitCommit("refs/remotes/%s"% branch)3241 settings =extractSettingsGitLog(log)32423243print"%s<=%s(%s)"% (branch,",".join(settings["depot-paths"]), settings["change"])3244return True32453246classHelpFormatter(optparse.IndentedHelpFormatter):3247def__init__(self):3248 optparse.IndentedHelpFormatter.__init__(self)32493250defformat_description(self, description):3251if description:3252return description +"\n"3253else:3254return""32553256defprintUsage(commands):3257print"usage:%s<command> [options]"% sys.argv[0]3258print""3259print"valid commands:%s"%", ".join(commands)3260print""3261print"Try%s<command> --help for command specific help."% sys.argv[0]3262print""32633264commands = {3265"debug": P4Debug,3266"submit": P4Submit,3267"commit": P4Submit,3268"sync": P4Sync,3269"rebase": P4Rebase,3270"clone": P4Clone,3271"rollback": P4RollBack,3272"branches": P4Branches3273}327432753276defmain():3277iflen(sys.argv[1:]) ==0:3278printUsage(commands.keys())3279 sys.exit(2)32803281 cmdName = sys.argv[1]3282try:3283 klass = commands[cmdName]3284 cmd =klass()3285exceptKeyError:3286print"unknown command%s"% cmdName3287print""3288printUsage(commands.keys())3289 sys.exit(2)32903291 options = cmd.options3292 cmd.gitdir = os.environ.get("GIT_DIR",None)32933294 args = sys.argv[2:]32953296 options.append(optparse.make_option("--verbose","-v", dest="verbose", action="store_true"))3297if cmd.needsGit:3298 options.append(optparse.make_option("--git-dir", dest="gitdir"))32993300 parser = optparse.OptionParser(cmd.usage.replace("%prog","%prog "+ cmdName),3301 options,3302 description = cmd.description,3303 formatter =HelpFormatter())33043305(cmd, args) = parser.parse_args(sys.argv[2:], cmd);3306global verbose3307 verbose = cmd.verbose3308if cmd.needsGit:3309if cmd.gitdir ==None:3310 cmd.gitdir = os.path.abspath(".git")3311if notisValidGitDir(cmd.gitdir):3312 cmd.gitdir =read_pipe("git rev-parse --git-dir").strip()3313if os.path.exists(cmd.gitdir):3314 cdup =read_pipe("git rev-parse --show-cdup").strip()3315iflen(cdup) >0:3316chdir(cdup);33173318if notisValidGitDir(cmd.gitdir):3319ifisValidGitDir(cmd.gitdir +"/.git"):3320 cmd.gitdir +="/.git"3321else:3322die("fatal: cannot locate git repository at%s"% cmd.gitdir)33233324 os.environ["GIT_DIR"] = cmd.gitdir33253326if not cmd.run(args):3327 parser.print_help()3328 sys.exit(2)332933303331if __name__ =='__main__':3332main()