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 optparse, sys, os, marshal, subprocess, shelve 12import tempfile, getopt, os.path, time, platform 13import re 14 15verbose =False 16 17 18defp4_build_cmd(cmd): 19"""Build a suitable p4 command line. 20 21 This consolidates building and returning a p4 command line into one 22 location. It means that hooking into the environment, or other configuration 23 can be done more easily. 24 """ 25 real_cmd = ["p4"] 26 27 user =gitConfig("git-p4.user") 28iflen(user) >0: 29 real_cmd += ["-u",user] 30 31 password =gitConfig("git-p4.password") 32iflen(password) >0: 33 real_cmd += ["-P", password] 34 35 port =gitConfig("git-p4.port") 36iflen(port) >0: 37 real_cmd += ["-p", port] 38 39 host =gitConfig("git-p4.host") 40iflen(host) >0: 41 real_cmd += ["-h", host] 42 43 client =gitConfig("git-p4.client") 44iflen(client) >0: 45 real_cmd += ["-c", client] 46 47 48ifisinstance(cmd,basestring): 49 real_cmd =' '.join(real_cmd) +' '+ cmd 50else: 51 real_cmd += cmd 52return real_cmd 53 54defchdir(dir): 55# P4 uses the PWD environment variable rather than getcwd(). Since we're 56# not using the shell, we have to set it ourselves. This path could 57# be relative, so go there first, then figure out where we ended up. 58 os.chdir(dir) 59 os.environ['PWD'] = os.getcwd() 60 61defdie(msg): 62if verbose: 63raiseException(msg) 64else: 65 sys.stderr.write(msg +"\n") 66 sys.exit(1) 67 68defwrite_pipe(c, stdin): 69if verbose: 70 sys.stderr.write('Writing pipe:%s\n'%str(c)) 71 72 expand =isinstance(c,basestring) 73 p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand) 74 pipe = p.stdin 75 val = pipe.write(stdin) 76 pipe.close() 77if p.wait(): 78die('Command failed:%s'%str(c)) 79 80return val 81 82defp4_write_pipe(c, stdin): 83 real_cmd =p4_build_cmd(c) 84returnwrite_pipe(real_cmd, stdin) 85 86defread_pipe(c, ignore_error=False): 87if verbose: 88 sys.stderr.write('Reading pipe:%s\n'%str(c)) 89 90 expand =isinstance(c,basestring) 91 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand) 92 pipe = p.stdout 93 val = pipe.read() 94if p.wait()and not ignore_error: 95die('Command failed:%s'%str(c)) 96 97return val 98 99defp4_read_pipe(c, ignore_error=False): 100 real_cmd =p4_build_cmd(c) 101returnread_pipe(real_cmd, ignore_error) 102 103defread_pipe_lines(c): 104if verbose: 105 sys.stderr.write('Reading pipe:%s\n'%str(c)) 106 107 expand =isinstance(c, basestring) 108 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand) 109 pipe = p.stdout 110 val = pipe.readlines() 111if pipe.close()or p.wait(): 112die('Command failed:%s'%str(c)) 113 114return val 115 116defp4_read_pipe_lines(c): 117"""Specifically invoke p4 on the command supplied. """ 118 real_cmd =p4_build_cmd(c) 119returnread_pipe_lines(real_cmd) 120 121defsystem(cmd): 122 expand =isinstance(cmd,basestring) 123if verbose: 124 sys.stderr.write("executing%s\n"%str(cmd)) 125 subprocess.check_call(cmd, shell=expand) 126 127defp4_system(cmd): 128"""Specifically invoke p4 as the system command. """ 129 real_cmd =p4_build_cmd(cmd) 130 expand =isinstance(real_cmd, basestring) 131 subprocess.check_call(real_cmd, shell=expand) 132 133defp4_integrate(src, dest): 134p4_system(["integrate","-Dt", src, dest]) 135 136defp4_sync(path): 137p4_system(["sync", path]) 138 139defp4_add(f): 140p4_system(["add", f]) 141 142defp4_delete(f): 143p4_system(["delete", f]) 144 145defp4_edit(f): 146p4_system(["edit", f]) 147 148defp4_revert(f): 149p4_system(["revert", f]) 150 151defp4_reopen(type,file): 152p4_system(["reopen","-t",type,file]) 153 154# 155# Canonicalize the p4 type and return a tuple of the 156# base type, plus any modifiers. See "p4 help filetypes" 157# for a list and explanation. 158# 159defsplit_p4_type(p4type): 160 161 p4_filetypes_historical = { 162"ctempobj":"binary+Sw", 163"ctext":"text+C", 164"cxtext":"text+Cx", 165"ktext":"text+k", 166"kxtext":"text+kx", 167"ltext":"text+F", 168"tempobj":"binary+FSw", 169"ubinary":"binary+F", 170"uresource":"resource+F", 171"uxbinary":"binary+Fx", 172"xbinary":"binary+x", 173"xltext":"text+Fx", 174"xtempobj":"binary+Swx", 175"xtext":"text+x", 176"xunicode":"unicode+x", 177"xutf16":"utf16+x", 178} 179if p4type in p4_filetypes_historical: 180 p4type = p4_filetypes_historical[p4type] 181 mods ="" 182 s = p4type.split("+") 183 base = s[0] 184 mods ="" 185iflen(s) >1: 186 mods = s[1] 187return(base, mods) 188 189 190defsetP4ExecBit(file, mode): 191# Reopens an already open file and changes the execute bit to match 192# the execute bit setting in the passed in mode. 193 194 p4Type ="+x" 195 196if notisModeExec(mode): 197 p4Type =getP4OpenedType(file) 198 p4Type = re.sub('^([cku]?)x(.*)','\\1\\2', p4Type) 199 p4Type = re.sub('(.*?\+.*?)x(.*?)','\\1\\2', p4Type) 200if p4Type[-1] =="+": 201 p4Type = p4Type[0:-1] 202 203p4_reopen(p4Type,file) 204 205defgetP4OpenedType(file): 206# Returns the perforce file type for the given file. 207 208 result =p4_read_pipe(["opened",file]) 209 match = re.match(".*\((.+)\)\r?$", result) 210if match: 211return match.group(1) 212else: 213die("Could not determine file type for%s(result: '%s')"% (file, result)) 214 215defdiffTreePattern(): 216# This is a simple generator for the diff tree regex pattern. This could be 217# a class variable if this and parseDiffTreeEntry were a part of a class. 218 pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)') 219while True: 220yield pattern 221 222defparseDiffTreeEntry(entry): 223"""Parses a single diff tree entry into its component elements. 224 225 See git-diff-tree(1) manpage for details about the format of the diff 226 output. This method returns a dictionary with the following elements: 227 228 src_mode - The mode of the source file 229 dst_mode - The mode of the destination file 230 src_sha1 - The sha1 for the source file 231 dst_sha1 - The sha1 fr the destination file 232 status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc) 233 status_score - The score for the status (applicable for 'C' and 'R' 234 statuses). This is None if there is no score. 235 src - The path for the source file. 236 dst - The path for the destination file. This is only present for 237 copy or renames. If it is not present, this is None. 238 239 If the pattern is not matched, None is returned.""" 240 241 match =diffTreePattern().next().match(entry) 242if match: 243return{ 244'src_mode': match.group(1), 245'dst_mode': match.group(2), 246'src_sha1': match.group(3), 247'dst_sha1': match.group(4), 248'status': match.group(5), 249'status_score': match.group(6), 250'src': match.group(7), 251'dst': match.group(10) 252} 253return None 254 255defisModeExec(mode): 256# Returns True if the given git mode represents an executable file, 257# otherwise False. 258return mode[-3:] =="755" 259 260defisModeExecChanged(src_mode, dst_mode): 261returnisModeExec(src_mode) !=isModeExec(dst_mode) 262 263defp4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None): 264 265ifisinstance(cmd,basestring): 266 cmd ="-G "+ cmd 267 expand =True 268else: 269 cmd = ["-G"] + cmd 270 expand =False 271 272 cmd =p4_build_cmd(cmd) 273if verbose: 274 sys.stderr.write("Opening pipe:%s\n"%str(cmd)) 275 276# Use a temporary file to avoid deadlocks without 277# subprocess.communicate(), which would put another copy 278# of stdout into memory. 279 stdin_file =None 280if stdin is not None: 281 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode) 282ifisinstance(stdin,basestring): 283 stdin_file.write(stdin) 284else: 285for i in stdin: 286 stdin_file.write(i +'\n') 287 stdin_file.flush() 288 stdin_file.seek(0) 289 290 p4 = subprocess.Popen(cmd, 291 shell=expand, 292 stdin=stdin_file, 293 stdout=subprocess.PIPE) 294 295 result = [] 296try: 297while True: 298 entry = marshal.load(p4.stdout) 299if cb is not None: 300cb(entry) 301else: 302 result.append(entry) 303exceptEOFError: 304pass 305 exitCode = p4.wait() 306if exitCode !=0: 307 entry = {} 308 entry["p4ExitCode"] = exitCode 309 result.append(entry) 310 311return result 312 313defp4Cmd(cmd): 314list=p4CmdList(cmd) 315 result = {} 316for entry inlist: 317 result.update(entry) 318return result; 319 320defp4Where(depotPath): 321if not depotPath.endswith("/"): 322 depotPath +="/" 323 depotPath = depotPath +"..." 324 outputList =p4CmdList(["where", depotPath]) 325 output =None 326for entry in outputList: 327if"depotFile"in entry: 328if entry["depotFile"] == depotPath: 329 output = entry 330break 331elif"data"in entry: 332 data = entry.get("data") 333 space = data.find(" ") 334if data[:space] == depotPath: 335 output = entry 336break 337if output ==None: 338return"" 339if output["code"] =="error": 340return"" 341 clientPath ="" 342if"path"in output: 343 clientPath = output.get("path") 344elif"data"in output: 345 data = output.get("data") 346 lastSpace = data.rfind(" ") 347 clientPath = data[lastSpace +1:] 348 349if clientPath.endswith("..."): 350 clientPath = clientPath[:-3] 351return clientPath 352 353defcurrentGitBranch(): 354returnread_pipe("git name-rev HEAD").split(" ")[1].strip() 355 356defisValidGitDir(path): 357if(os.path.exists(path +"/HEAD") 358and os.path.exists(path +"/refs")and os.path.exists(path +"/objects")): 359return True; 360return False 361 362defparseRevision(ref): 363returnread_pipe("git rev-parse%s"% ref).strip() 364 365defbranchExists(ref): 366 rev =read_pipe(["git","rev-parse","-q","--verify", ref], 367 ignore_error=True) 368returnlen(rev) >0 369 370defextractLogMessageFromGitCommit(commit): 371 logMessage ="" 372 373## fixme: title is first line of commit, not 1st paragraph. 374 foundTitle =False 375for log inread_pipe_lines("git cat-file commit%s"% commit): 376if not foundTitle: 377iflen(log) ==1: 378 foundTitle =True 379continue 380 381 logMessage += log 382return logMessage 383 384defextractSettingsGitLog(log): 385 values = {} 386for line in log.split("\n"): 387 line = line.strip() 388 m = re.search(r"^ *\[git-p4: (.*)\]$", line) 389if not m: 390continue 391 392 assignments = m.group(1).split(':') 393for a in assignments: 394 vals = a.split('=') 395 key = vals[0].strip() 396 val = ('='.join(vals[1:])).strip() 397if val.endswith('\"')and val.startswith('"'): 398 val = val[1:-1] 399 400 values[key] = val 401 402 paths = values.get("depot-paths") 403if not paths: 404 paths = values.get("depot-path") 405if paths: 406 values['depot-paths'] = paths.split(',') 407return values 408 409defgitBranchExists(branch): 410 proc = subprocess.Popen(["git","rev-parse", branch], 411 stderr=subprocess.PIPE, stdout=subprocess.PIPE); 412return proc.wait() ==0; 413 414_gitConfig = {} 415defgitConfig(key, args =None):# set args to "--bool", for instance 416if not _gitConfig.has_key(key): 417 argsFilter ="" 418if args !=None: 419 argsFilter ="%s"% args 420 cmd ="git config%s%s"% (argsFilter, key) 421 _gitConfig[key] =read_pipe(cmd, ignore_error=True).strip() 422return _gitConfig[key] 423 424defgitConfigList(key): 425if not _gitConfig.has_key(key): 426 _gitConfig[key] =read_pipe("git config --get-all%s"% key, ignore_error=True).strip().split(os.linesep) 427return _gitConfig[key] 428 429defp4BranchesInGit(branchesAreInRemotes =True): 430 branches = {} 431 432 cmdline ="git rev-parse --symbolic " 433if branchesAreInRemotes: 434 cmdline +=" --remotes" 435else: 436 cmdline +=" --branches" 437 438for line inread_pipe_lines(cmdline): 439 line = line.strip() 440 441## only import to p4/ 442if not line.startswith('p4/')or line =="p4/HEAD": 443continue 444 branch = line 445 446# strip off p4 447 branch = re.sub("^p4/","", line) 448 449 branches[branch] =parseRevision(line) 450return branches 451 452deffindUpstreamBranchPoint(head ="HEAD"): 453 branches =p4BranchesInGit() 454# map from depot-path to branch name 455 branchByDepotPath = {} 456for branch in branches.keys(): 457 tip = branches[branch] 458 log =extractLogMessageFromGitCommit(tip) 459 settings =extractSettingsGitLog(log) 460if settings.has_key("depot-paths"): 461 paths =",".join(settings["depot-paths"]) 462 branchByDepotPath[paths] ="remotes/p4/"+ branch 463 464 settings =None 465 parent =0 466while parent <65535: 467 commit = head +"~%s"% parent 468 log =extractLogMessageFromGitCommit(commit) 469 settings =extractSettingsGitLog(log) 470if settings.has_key("depot-paths"): 471 paths =",".join(settings["depot-paths"]) 472if branchByDepotPath.has_key(paths): 473return[branchByDepotPath[paths], settings] 474 475 parent = parent +1 476 477return["", settings] 478 479defcreateOrUpdateBranchesFromOrigin(localRefPrefix ="refs/remotes/p4/", silent=True): 480if not silent: 481print("Creating/updating branch(es) in%sbased on origin branch(es)" 482% localRefPrefix) 483 484 originPrefix ="origin/p4/" 485 486for line inread_pipe_lines("git rev-parse --symbolic --remotes"): 487 line = line.strip() 488if(not line.startswith(originPrefix))or line.endswith("HEAD"): 489continue 490 491 headName = line[len(originPrefix):] 492 remoteHead = localRefPrefix + headName 493 originHead = line 494 495 original =extractSettingsGitLog(extractLogMessageFromGitCommit(originHead)) 496if(not original.has_key('depot-paths') 497or not original.has_key('change')): 498continue 499 500 update =False 501if notgitBranchExists(remoteHead): 502if verbose: 503print"creating%s"% remoteHead 504 update =True 505else: 506 settings =extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead)) 507if settings.has_key('change') >0: 508if settings['depot-paths'] == original['depot-paths']: 509 originP4Change =int(original['change']) 510 p4Change =int(settings['change']) 511if originP4Change > p4Change: 512print("%s(%s) is newer than%s(%s). " 513"Updating p4 branch from origin." 514% (originHead, originP4Change, 515 remoteHead, p4Change)) 516 update =True 517else: 518print("Ignoring:%swas imported from%swhile " 519"%swas imported from%s" 520% (originHead,','.join(original['depot-paths']), 521 remoteHead,','.join(settings['depot-paths']))) 522 523if update: 524system("git update-ref%s %s"% (remoteHead, originHead)) 525 526deforiginP4BranchesExist(): 527returngitBranchExists("origin")orgitBranchExists("origin/p4")orgitBranchExists("origin/p4/master") 528 529defp4ChangesForPaths(depotPaths, changeRange): 530assert depotPaths 531 cmd = ['changes'] 532for p in depotPaths: 533 cmd += ["%s...%s"% (p, changeRange)] 534 output =p4_read_pipe_lines(cmd) 535 536 changes = {} 537for line in output: 538 changeNum =int(line.split(" ")[1]) 539 changes[changeNum] =True 540 541 changelist = changes.keys() 542 changelist.sort() 543return changelist 544 545defp4PathStartsWith(path, prefix): 546# This method tries to remedy a potential mixed-case issue: 547# 548# If UserA adds //depot/DirA/file1 549# and UserB adds //depot/dira/file2 550# 551# we may or may not have a problem. If you have core.ignorecase=true, 552# we treat DirA and dira as the same directory 553 ignorecase =gitConfig("core.ignorecase","--bool") =="true" 554if ignorecase: 555return path.lower().startswith(prefix.lower()) 556return path.startswith(prefix) 557 558class Command: 559def__init__(self): 560 self.usage ="usage: %prog [options]" 561 self.needsGit =True 562 563class P4UserMap: 564def__init__(self): 565 self.userMapFromPerforceServer =False 566 567defgetUserCacheFilename(self): 568 home = os.environ.get("HOME", os.environ.get("USERPROFILE")) 569return home +"/.gitp4-usercache.txt" 570 571defgetUserMapFromPerforceServer(self): 572if self.userMapFromPerforceServer: 573return 574 self.users = {} 575 self.emails = {} 576 577for output inp4CmdList("users"): 578if not output.has_key("User"): 579continue 580 self.users[output["User"]] = output["FullName"] +" <"+ output["Email"] +">" 581 self.emails[output["Email"]] = output["User"] 582 583 584 s ='' 585for(key, val)in self.users.items(): 586 s +="%s\t%s\n"% (key.expandtabs(1), val.expandtabs(1)) 587 588open(self.getUserCacheFilename(),"wb").write(s) 589 self.userMapFromPerforceServer =True 590 591defloadUserMapFromCache(self): 592 self.users = {} 593 self.userMapFromPerforceServer =False 594try: 595 cache =open(self.getUserCacheFilename(),"rb") 596 lines = cache.readlines() 597 cache.close() 598for line in lines: 599 entry = line.strip().split("\t") 600 self.users[entry[0]] = entry[1] 601exceptIOError: 602 self.getUserMapFromPerforceServer() 603 604classP4Debug(Command): 605def__init__(self): 606 Command.__init__(self) 607 self.options = [ 608 optparse.make_option("--verbose", dest="verbose", action="store_true", 609 default=False), 610] 611 self.description ="A tool to debug the output of p4 -G." 612 self.needsGit =False 613 self.verbose =False 614 615defrun(self, args): 616 j =0 617for output inp4CmdList(args): 618print'Element:%d'% j 619 j +=1 620print output 621return True 622 623classP4RollBack(Command): 624def__init__(self): 625 Command.__init__(self) 626 self.options = [ 627 optparse.make_option("--verbose", dest="verbose", action="store_true"), 628 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true") 629] 630 self.description ="A tool to debug the multi-branch import. Don't use :)" 631 self.verbose =False 632 self.rollbackLocalBranches =False 633 634defrun(self, args): 635iflen(args) !=1: 636return False 637 maxChange =int(args[0]) 638 639if"p4ExitCode"inp4Cmd("changes -m 1"): 640die("Problems executing p4"); 641 642if self.rollbackLocalBranches: 643 refPrefix ="refs/heads/" 644 lines =read_pipe_lines("git rev-parse --symbolic --branches") 645else: 646 refPrefix ="refs/remotes/" 647 lines =read_pipe_lines("git rev-parse --symbolic --remotes") 648 649for line in lines: 650if self.rollbackLocalBranches or(line.startswith("p4/")and line !="p4/HEAD\n"): 651 line = line.strip() 652 ref = refPrefix + line 653 log =extractLogMessageFromGitCommit(ref) 654 settings =extractSettingsGitLog(log) 655 656 depotPaths = settings['depot-paths'] 657 change = settings['change'] 658 659 changed =False 660 661iflen(p4Cmd("changes -m 1 "+' '.join(['%s...@%s'% (p, maxChange) 662for p in depotPaths]))) ==0: 663print"Branch%sdid not exist at change%s, deleting."% (ref, maxChange) 664system("git update-ref -d%s`git rev-parse%s`"% (ref, ref)) 665continue 666 667while change andint(change) > maxChange: 668 changed =True 669if self.verbose: 670print"%sis at%s; rewinding towards%s"% (ref, change, maxChange) 671system("git update-ref%s\"%s^\""% (ref, ref)) 672 log =extractLogMessageFromGitCommit(ref) 673 settings =extractSettingsGitLog(log) 674 675 676 depotPaths = settings['depot-paths'] 677 change = settings['change'] 678 679if changed: 680print"%srewound to%s"% (ref, change) 681 682return True 683 684classP4Submit(Command, P4UserMap): 685def__init__(self): 686 Command.__init__(self) 687 P4UserMap.__init__(self) 688 self.options = [ 689 optparse.make_option("--verbose", dest="verbose", action="store_true"), 690 optparse.make_option("--origin", dest="origin"), 691 optparse.make_option("-M", dest="detectRenames", action="store_true"), 692# preserve the user, requires relevant p4 permissions 693 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"), 694] 695 self.description ="Submit changes from git to the perforce depot." 696 self.usage +=" [name of git branch to submit into perforce depot]" 697 self.interactive =True 698 self.origin ="" 699 self.detectRenames =False 700 self.verbose =False 701 self.preserveUser =gitConfig("git-p4.preserveUser").lower() =="true" 702 self.isWindows = (platform.system() =="Windows") 703 self.myP4UserId =None 704 705defcheck(self): 706iflen(p4CmdList("opened ...")) >0: 707die("You have files opened with perforce! Close them before starting the sync.") 708 709# replaces everything between 'Description:' and the next P4 submit template field with the 710# commit message 711defprepareLogMessage(self, template, message): 712 result ="" 713 714 inDescriptionSection =False 715 716for line in template.split("\n"): 717if line.startswith("#"): 718 result += line +"\n" 719continue 720 721if inDescriptionSection: 722if line.startswith("Files:")or line.startswith("Jobs:"): 723 inDescriptionSection =False 724else: 725continue 726else: 727if line.startswith("Description:"): 728 inDescriptionSection =True 729 line +="\n" 730for messageLine in message.split("\n"): 731 line +="\t"+ messageLine +"\n" 732 733 result += line +"\n" 734 735return result 736 737defp4UserForCommit(self,id): 738# Return the tuple (perforce user,git email) for a given git commit id 739 self.getUserMapFromPerforceServer() 740 gitEmail =read_pipe("git log --max-count=1 --format='%%ae'%s"%id) 741 gitEmail = gitEmail.strip() 742if not self.emails.has_key(gitEmail): 743return(None,gitEmail) 744else: 745return(self.emails[gitEmail],gitEmail) 746 747defcheckValidP4Users(self,commits): 748# check if any git authors cannot be mapped to p4 users 749foridin commits: 750(user,email) = self.p4UserForCommit(id) 751if not user: 752 msg ="Cannot find p4 user for email%sin commit%s."% (email,id) 753ifgitConfig('git-p4.allowMissingP4Users').lower() =="true": 754print"%s"% msg 755else: 756die("Error:%s\nSet git-p4.allowMissingP4Users to true to allow this."% msg) 757 758deflastP4Changelist(self): 759# Get back the last changelist number submitted in this client spec. This 760# then gets used to patch up the username in the change. If the same 761# client spec is being used by multiple processes then this might go 762# wrong. 763 results =p4CmdList("client -o")# find the current client 764 client =None 765for r in results: 766if r.has_key('Client'): 767 client = r['Client'] 768break 769if not client: 770die("could not get client spec") 771 results =p4CmdList(["changes","-c", client,"-m","1"]) 772for r in results: 773if r.has_key('change'): 774return r['change'] 775die("Could not get changelist number for last submit - cannot patch up user details") 776 777defmodifyChangelistUser(self, changelist, newUser): 778# fixup the user field of a changelist after it has been submitted. 779 changes =p4CmdList("change -o%s"% changelist) 780iflen(changes) !=1: 781die("Bad output from p4 change modifying%sto user%s"% 782(changelist, newUser)) 783 784 c = changes[0] 785if c['User'] == newUser:return# nothing to do 786 c['User'] = newUser 787input= marshal.dumps(c) 788 789 result =p4CmdList("change -f -i", stdin=input) 790for r in result: 791if r.has_key('code'): 792if r['code'] =='error': 793die("Could not modify user field of changelist%sto%s:%s"% (changelist, newUser, r['data'])) 794if r.has_key('data'): 795print("Updated user field for changelist%sto%s"% (changelist, newUser)) 796return 797die("Could not modify user field of changelist%sto%s"% (changelist, newUser)) 798 799defcanChangeChangelists(self): 800# check to see if we have p4 admin or super-user permissions, either of 801# which are required to modify changelists. 802 results =p4CmdList("protects%s"% self.depotPath) 803for r in results: 804if r.has_key('perm'): 805if r['perm'] =='admin': 806return1 807if r['perm'] =='super': 808return1 809return0 810 811defp4UserId(self): 812if self.myP4UserId: 813return self.myP4UserId 814 815 results =p4CmdList("user -o") 816for r in results: 817if r.has_key('User'): 818 self.myP4UserId = r['User'] 819return r['User'] 820die("Could not find your p4 user id") 821 822defp4UserIsMe(self, p4User): 823# return True if the given p4 user is actually me 824 me = self.p4UserId() 825if not p4User or p4User != me: 826return False 827else: 828return True 829 830defprepareSubmitTemplate(self): 831# remove lines in the Files section that show changes to files outside the depot path we're committing into 832 template ="" 833 inFilesSection =False 834for line inp4_read_pipe_lines(['change','-o']): 835if line.endswith("\r\n"): 836 line = line[:-2] +"\n" 837if inFilesSection: 838if line.startswith("\t"): 839# path starts and ends with a tab 840 path = line[1:] 841 lastTab = path.rfind("\t") 842if lastTab != -1: 843 path = path[:lastTab] 844if notp4PathStartsWith(path, self.depotPath): 845continue 846else: 847 inFilesSection =False 848else: 849if line.startswith("Files:"): 850 inFilesSection =True 851 852 template += line 853 854return template 855 856defedit_template(self, template_file): 857"""Invoke the editor to let the user change the submission 858 message. Return true if okay to continue with the submit.""" 859 860# if configured to skip the editing part, just submit 861ifgitConfig("git-p4.skipSubmitEdit") =="true": 862return True 863 864# look at the modification time, to check later if the user saved 865# the file 866 mtime = os.stat(template_file).st_mtime 867 868# invoke the editor 869if os.environ.has_key("P4EDITOR"): 870 editor = os.environ.get("P4EDITOR") 871else: 872 editor =read_pipe("git var GIT_EDITOR").strip() 873system(editor +" "+ template_file) 874 875# If the file was not saved, prompt to see if this patch should 876# be skipped. But skip this verification step if configured so. 877ifgitConfig("git-p4.skipSubmitEditCheck") =="true": 878return True 879 880# modification time updated means user saved the file 881if os.stat(template_file).st_mtime > mtime: 882return True 883 884while True: 885 response =raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ") 886if response =='y': 887return True 888if response =='n': 889return False 890 891defapplyCommit(self,id): 892print"Applying%s"% (read_pipe("git log --max-count=1 --pretty=oneline%s"%id)) 893 894(p4User, gitEmail) = self.p4UserForCommit(id) 895 896if not self.detectRenames: 897# If not explicitly set check the config variable 898 self.detectRenames =gitConfig("git-p4.detectRenames") 899 900if self.detectRenames.lower() =="false"or self.detectRenames =="": 901 diffOpts ="" 902elif self.detectRenames.lower() =="true": 903 diffOpts ="-M" 904else: 905 diffOpts ="-M%s"% self.detectRenames 906 907 detectCopies =gitConfig("git-p4.detectCopies") 908if detectCopies.lower() =="true": 909 diffOpts +=" -C" 910elif detectCopies !=""and detectCopies.lower() !="false": 911 diffOpts +=" -C%s"% detectCopies 912 913ifgitConfig("git-p4.detectCopiesHarder","--bool") =="true": 914 diffOpts +=" --find-copies-harder" 915 916 diff =read_pipe_lines("git diff-tree -r%s\"%s^\" \"%s\""% (diffOpts,id,id)) 917 filesToAdd =set() 918 filesToDelete =set() 919 editedFiles =set() 920 filesToChangeExecBit = {} 921for line in diff: 922 diff =parseDiffTreeEntry(line) 923 modifier = diff['status'] 924 path = diff['src'] 925if modifier =="M": 926p4_edit(path) 927ifisModeExecChanged(diff['src_mode'], diff['dst_mode']): 928 filesToChangeExecBit[path] = diff['dst_mode'] 929 editedFiles.add(path) 930elif modifier =="A": 931 filesToAdd.add(path) 932 filesToChangeExecBit[path] = diff['dst_mode'] 933if path in filesToDelete: 934 filesToDelete.remove(path) 935elif modifier =="D": 936 filesToDelete.add(path) 937if path in filesToAdd: 938 filesToAdd.remove(path) 939elif modifier =="C": 940 src, dest = diff['src'], diff['dst'] 941p4_integrate(src, dest) 942if diff['src_sha1'] != diff['dst_sha1']: 943p4_edit(dest) 944ifisModeExecChanged(diff['src_mode'], diff['dst_mode']): 945p4_edit(dest) 946 filesToChangeExecBit[dest] = diff['dst_mode'] 947 os.unlink(dest) 948 editedFiles.add(dest) 949elif modifier =="R": 950 src, dest = diff['src'], diff['dst'] 951p4_integrate(src, dest) 952if diff['src_sha1'] != diff['dst_sha1']: 953p4_edit(dest) 954ifisModeExecChanged(diff['src_mode'], diff['dst_mode']): 955p4_edit(dest) 956 filesToChangeExecBit[dest] = diff['dst_mode'] 957 os.unlink(dest) 958 editedFiles.add(dest) 959 filesToDelete.add(src) 960else: 961die("unknown modifier%sfor%s"% (modifier, path)) 962 963 diffcmd ="git format-patch -k --stdout\"%s^\"..\"%s\""% (id,id) 964 patchcmd = diffcmd +" | git apply " 965 tryPatchCmd = patchcmd +"--check -" 966 applyPatchCmd = patchcmd +"--check --apply -" 967 968if os.system(tryPatchCmd) !=0: 969print"Unfortunately applying the change failed!" 970print"What do you want to do?" 971 response ="x" 972while response !="s"and response !="a"and response !="w": 973 response =raw_input("[s]kip this patch / [a]pply the patch forcibly " 974"and with .rej files / [w]rite the patch to a file (patch.txt) ") 975if response =="s": 976print"Skipping! Good luck with the next patches..." 977for f in editedFiles: 978p4_revert(f) 979for f in filesToAdd: 980 os.remove(f) 981return 982elif response =="a": 983 os.system(applyPatchCmd) 984iflen(filesToAdd) >0: 985print"You may also want to call p4 add on the following files:" 986print" ".join(filesToAdd) 987iflen(filesToDelete): 988print"The following files should be scheduled for deletion with p4 delete:" 989print" ".join(filesToDelete) 990die("Please resolve and submit the conflict manually and " 991+"continue afterwards with git-p4 submit --continue") 992elif response =="w": 993system(diffcmd +" > patch.txt") 994print"Patch saved to patch.txt in%s!"% self.clientPath 995die("Please resolve and submit the conflict manually and " 996"continue afterwards with git-p4 submit --continue") 997 998system(applyPatchCmd) 9991000for f in filesToAdd:1001p4_add(f)1002for f in filesToDelete:1003p4_revert(f)1004p4_delete(f)10051006# Set/clear executable bits1007for f in filesToChangeExecBit.keys():1008 mode = filesToChangeExecBit[f]1009setP4ExecBit(f, mode)10101011 logMessage =extractLogMessageFromGitCommit(id)1012 logMessage = logMessage.strip()10131014 template = self.prepareSubmitTemplate()10151016if self.interactive:1017 submitTemplate = self.prepareLogMessage(template, logMessage)10181019if self.preserveUser:1020 submitTemplate = submitTemplate + ("\n######## Actual user%s, modified after commit\n"% p4User)10211022if os.environ.has_key("P4DIFF"):1023del(os.environ["P4DIFF"])1024 diff =""1025for editedFile in editedFiles:1026 diff +=p4_read_pipe(['diff','-du', editedFile])10271028 newdiff =""1029for newFile in filesToAdd:1030 newdiff +="==== new file ====\n"1031 newdiff +="--- /dev/null\n"1032 newdiff +="+++%s\n"% newFile1033 f =open(newFile,"r")1034for line in f.readlines():1035 newdiff +="+"+ line1036 f.close()10371038if self.checkAuthorship and not self.p4UserIsMe(p4User):1039 submitTemplate +="######## git author%sdoes not match your p4 account.\n"% gitEmail1040 submitTemplate +="######## Use git-p4 option --preserve-user to modify authorship\n"1041 submitTemplate +="######## Use git-p4 config git-p4.skipUserNameCheck hides this message.\n"10421043 separatorLine ="######## everything below this line is just the diff #######\n"10441045(handle, fileName) = tempfile.mkstemp()1046 tmpFile = os.fdopen(handle,"w+")1047if self.isWindows:1048 submitTemplate = submitTemplate.replace("\n","\r\n")1049 separatorLine = separatorLine.replace("\n","\r\n")1050 newdiff = newdiff.replace("\n","\r\n")1051 tmpFile.write(submitTemplate + separatorLine + diff + newdiff)1052 tmpFile.close()10531054if self.edit_template(fileName):1055# read the edited message and submit1056 tmpFile =open(fileName,"rb")1057 message = tmpFile.read()1058 tmpFile.close()1059 submitTemplate = message[:message.index(separatorLine)]1060if self.isWindows:1061 submitTemplate = submitTemplate.replace("\r\n","\n")1062p4_write_pipe(['submit','-i'], submitTemplate)10631064if self.preserveUser:1065if p4User:1066# Get last changelist number. Cannot easily get it from1067# the submit command output as the output is1068# unmarshalled.1069 changelist = self.lastP4Changelist()1070 self.modifyChangelistUser(changelist, p4User)1071else:1072# skip this patch1073print"Submission cancelled, undoing p4 changes."1074for f in editedFiles:1075p4_revert(f)1076for f in filesToAdd:1077p4_revert(f)1078 os.remove(f)10791080 os.remove(fileName)1081else:1082 fileName ="submit.txt"1083file=open(fileName,"w+")1084file.write(self.prepareLogMessage(template, logMessage))1085file.close()1086print("Perforce submit template written as%s. "1087+"Please review/edit and then use p4 submit -i <%sto submit directly!"1088% (fileName, fileName))10891090defrun(self, args):1091iflen(args) ==0:1092 self.master =currentGitBranch()1093iflen(self.master) ==0or notgitBranchExists("refs/heads/%s"% self.master):1094die("Detecting current git branch failed!")1095eliflen(args) ==1:1096 self.master = args[0]1097if notbranchExists(self.master):1098die("Branch%sdoes not exist"% self.master)1099else:1100return False11011102 allowSubmit =gitConfig("git-p4.allowSubmit")1103iflen(allowSubmit) >0and not self.master in allowSubmit.split(","):1104die("%sis not in git-p4.allowSubmit"% self.master)11051106[upstream, settings] =findUpstreamBranchPoint()1107 self.depotPath = settings['depot-paths'][0]1108iflen(self.origin) ==0:1109 self.origin = upstream11101111if self.preserveUser:1112if not self.canChangeChangelists():1113die("Cannot preserve user names without p4 super-user or admin permissions")11141115if self.verbose:1116print"Origin branch is "+ self.origin11171118iflen(self.depotPath) ==0:1119print"Internal error: cannot locate perforce depot path from existing branches"1120 sys.exit(128)11211122 self.clientPath =p4Where(self.depotPath)11231124iflen(self.clientPath) ==0:1125print"Error: Cannot locate perforce checkout of%sin client view"% self.depotPath1126 sys.exit(128)11271128print"Perforce checkout for depot path%slocated at%s"% (self.depotPath, self.clientPath)1129 self.oldWorkingDirectory = os.getcwd()11301131# ensure the clientPath exists1132if not os.path.exists(self.clientPath):1133 os.makedirs(self.clientPath)11341135chdir(self.clientPath)1136print"Synchronizing p4 checkout..."1137p4_sync("...")1138 self.check()11391140 commits = []1141for line inread_pipe_lines("git rev-list --no-merges%s..%s"% (self.origin, self.master)):1142 commits.append(line.strip())1143 commits.reverse()11441145if self.preserveUser or(gitConfig("git-p4.skipUserNameCheck") =="true"):1146 self.checkAuthorship =False1147else:1148 self.checkAuthorship =True11491150if self.preserveUser:1151 self.checkValidP4Users(commits)11521153whilelen(commits) >0:1154 commit = commits[0]1155 commits = commits[1:]1156 self.applyCommit(commit)1157if not self.interactive:1158break11591160iflen(commits) ==0:1161print"All changes applied!"1162chdir(self.oldWorkingDirectory)11631164 sync =P4Sync()1165 sync.run([])11661167 rebase =P4Rebase()1168 rebase.rebase()11691170return True11711172classView(object):1173"""Represent a p4 view ("p4 help views"), and map files in a1174 repo according to the view."""11751176classPath(object):1177"""A depot or client path, possibly containing wildcards.1178 The only one supported is ... at the end, currently.1179 Initialize with the full path, with //depot or //client."""11801181def__init__(self, path, is_depot):1182 self.path = path1183 self.is_depot = is_depot1184 self.find_wildcards()1185# remember the prefix bit, useful for relative mappings1186 m = re.match("(//[^/]+/)", self.path)1187if not m:1188die("Path%sdoes not start with //prefix/"% self.path)1189 prefix = m.group(1)1190if not self.is_depot:1191# strip //client/ on client paths1192 self.path = self.path[len(prefix):]11931194deffind_wildcards(self):1195"""Make sure wildcards are valid, and set up internal1196 variables."""11971198 self.ends_triple_dot =False1199# There are three wildcards allowed in p4 views1200# (see "p4 help views"). This code knows how to1201# handle "..." (only at the end), but cannot deal with1202# "%%n" or "*". Only check the depot_side, as p4 should1203# validate that the client_side matches too.1204if re.search(r'%%[1-9]', self.path):1205die("Can't handle%%n wildcards in view:%s"% self.path)1206if self.path.find("*") >=0:1207die("Can't handle * wildcards in view:%s"% self.path)1208 triple_dot_index = self.path.find("...")1209if triple_dot_index >=0:1210if triple_dot_index !=len(self.path) -3:1211die("Can handle only single ... wildcard, at end:%s"%1212 self.path)1213 self.ends_triple_dot =True12141215defensure_compatible(self, other_path):1216"""Make sure the wildcards agree."""1217if self.ends_triple_dot != other_path.ends_triple_dot:1218die("Both paths must end with ... if either does;\n"+1219"paths:%s %s"% (self.path, other_path.path))12201221defmatch_wildcards(self, test_path):1222"""See if this test_path matches us, and fill in the value1223 of the wildcards if so. Returns a tuple of1224 (True|False, wildcards[]). For now, only the ... at end1225 is supported, so at most one wildcard."""1226if self.ends_triple_dot:1227 dotless = self.path[:-3]1228if test_path.startswith(dotless):1229 wildcard = test_path[len(dotless):]1230return(True, [ wildcard ])1231else:1232if test_path == self.path:1233return(True, [])1234return(False, [])12351236defmatch(self, test_path):1237"""Just return if it matches; don't bother with the wildcards."""1238 b, _ = self.match_wildcards(test_path)1239return b12401241deffill_in_wildcards(self, wildcards):1242"""Return the relative path, with the wildcards filled in1243 if there are any."""1244if self.ends_triple_dot:1245return self.path[:-3] + wildcards[0]1246else:1247return self.path12481249classMapping(object):1250def__init__(self, depot_side, client_side, overlay, exclude):1251# depot_side is without the trailing /... if it had one1252 self.depot_side = View.Path(depot_side, is_depot=True)1253 self.client_side = View.Path(client_side, is_depot=False)1254 self.overlay = overlay # started with "+"1255 self.exclude = exclude # started with "-"1256assert not(self.overlay and self.exclude)1257 self.depot_side.ensure_compatible(self.client_side)12581259def__str__(self):1260 c =" "1261if self.overlay:1262 c ="+"1263if self.exclude:1264 c ="-"1265return"View.Mapping:%s%s->%s"% \1266(c, self.depot_side.path, self.client_side.path)12671268defmap_depot_to_client(self, depot_path):1269"""Calculate the client path if using this mapping on the1270 given depot path; does not consider the effect of other1271 mappings in a view. Even excluded mappings are returned."""1272 matches, wildcards = self.depot_side.match_wildcards(depot_path)1273if not matches:1274return""1275 client_path = self.client_side.fill_in_wildcards(wildcards)1276return client_path12771278#1279# View methods1280#1281def__init__(self):1282 self.mappings = []12831284defappend(self, view_line):1285"""Parse a view line, splitting it into depot and client1286 sides. Append to self.mappings, preserving order."""12871288# Split the view line into exactly two words. P4 enforces1289# structure on these lines that simplifies this quite a bit.1290#1291# Either or both words may be double-quoted.1292# Single quotes do not matter.1293# Double-quote marks cannot occur inside the words.1294# A + or - prefix is also inside the quotes.1295# There are no quotes unless they contain a space.1296# The line is already white-space stripped.1297# The two words are separated by a single space.1298#1299if view_line[0] =='"':1300# First word is double quoted. Find its end.1301 close_quote_index = view_line.find('"',1)1302if close_quote_index <=0:1303die("No first-word closing quote found:%s"% view_line)1304 depot_side = view_line[1:close_quote_index]1305# skip closing quote and space1306 rhs_index = close_quote_index +1+11307else:1308 space_index = view_line.find(" ")1309if space_index <=0:1310die("No word-splitting space found:%s"% view_line)1311 depot_side = view_line[0:space_index]1312 rhs_index = space_index +113131314if view_line[rhs_index] =='"':1315# Second word is double quoted. Make sure there is a1316# double quote at the end too.1317if not view_line.endswith('"'):1318die("View line with rhs quote should end with one:%s"%1319 view_line)1320# skip the quotes1321 client_side = view_line[rhs_index+1:-1]1322else:1323 client_side = view_line[rhs_index:]13241325# prefix + means overlay on previous mapping1326 overlay =False1327if depot_side.startswith("+"):1328 overlay =True1329 depot_side = depot_side[1:]13301331# prefix - means exclude this path1332 exclude =False1333if depot_side.startswith("-"):1334 exclude =True1335 depot_side = depot_side[1:]13361337 m = View.Mapping(depot_side, client_side, overlay, exclude)1338 self.mappings.append(m)13391340defmap_in_client(self, depot_path):1341"""Return the relative location in the client where this1342 depot file should live. Returns "" if the file should1343 not be mapped in the client."""13441345 paths_filled = []1346 client_path =""13471348# look at later entries first1349for m in self.mappings[::-1]:13501351# see where will this path end up in the client1352 p = m.map_depot_to_client(depot_path)13531354if p =="":1355# Depot path does not belong in client. Must remember1356# this, as previous items should not cause files to1357# exist in this path either. Remember that the list is1358# being walked from the end, which has higher precedence.1359# Overlap mappings do not exclude previous mappings.1360if not m.overlay:1361 paths_filled.append(m.client_side)13621363else:1364# This mapping matched; no need to search any further.1365# But, the mapping could be rejected if the client path1366# has already been claimed by an earlier mapping (i.e.1367# one later in the list, which we are walking backwards).1368 already_mapped_in_client =False1369for f in paths_filled:1370# this is View.Path.match1371if f.match(p):1372 already_mapped_in_client =True1373break1374if not already_mapped_in_client:1375# Include this file, unless it is from a line that1376# explicitly said to exclude it.1377if not m.exclude:1378 client_path = p13791380# a match, even if rejected, always stops the search1381break13821383return client_path13841385classP4Sync(Command, P4UserMap):1386 delete_actions = ("delete","move/delete","purge")13871388def__init__(self):1389 Command.__init__(self)1390 P4UserMap.__init__(self)1391 self.options = [1392 optparse.make_option("--branch", dest="branch"),1393 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),1394 optparse.make_option("--changesfile", dest="changesFile"),1395 optparse.make_option("--silent", dest="silent", action="store_true"),1396 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),1397 optparse.make_option("--verbose", dest="verbose", action="store_true"),1398 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",1399help="Import into refs/heads/ , not refs/remotes"),1400 optparse.make_option("--max-changes", dest="maxChanges"),1401 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',1402help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),1403 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',1404help="Only sync files that are included in the Perforce Client Spec")1405]1406 self.description ="""Imports from Perforce into a git repository.\n1407 example:1408 //depot/my/project/ -- to import the current head1409 //depot/my/project/@all -- to import everything1410 //depot/my/project/@1,6 -- to import only from revision 1 to 614111412 (a ... is not needed in the path p4 specification, it's added implicitly)"""14131414 self.usage +=" //depot/path[@revRange]"1415 self.silent =False1416 self.createdBranches =set()1417 self.committedChanges =set()1418 self.branch =""1419 self.detectBranches =False1420 self.detectLabels =False1421 self.changesFile =""1422 self.syncWithOrigin =True1423 self.verbose =False1424 self.importIntoRemotes =True1425 self.maxChanges =""1426 self.isWindows = (platform.system() =="Windows")1427 self.keepRepoPath =False1428 self.depotPaths =None1429 self.p4BranchesInGit = []1430 self.cloneExclude = []1431 self.useClientSpec =False1432 self.clientSpecDirs =None14331434ifgitConfig("git-p4.syncFromOrigin") =="false":1435 self.syncWithOrigin =False14361437#1438# P4 wildcards are not allowed in filenames. P4 complains1439# if you simply add them, but you can force it with "-f", in1440# which case it translates them into %xx encoding internally.1441# Search for and fix just these four characters. Do % last so1442# that fixing it does not inadvertently create new %-escapes.1443#1444defwildcard_decode(self, path):1445# Cannot have * in a filename in windows; untested as to1446# what p4 would do in such a case.1447if not self.isWindows:1448 path = path.replace("%2A","*")1449 path = path.replace("%23","#") \1450.replace("%40","@") \1451.replace("%25","%")1452return path14531454defextractFilesFromCommit(self, commit):1455 self.cloneExclude = [re.sub(r"\.\.\.$","", path)1456for path in self.cloneExclude]1457 files = []1458 fnum =01459while commit.has_key("depotFile%s"% fnum):1460 path = commit["depotFile%s"% fnum]14611462if[p for p in self.cloneExclude1463ifp4PathStartsWith(path, p)]:1464 found =False1465else:1466 found = [p for p in self.depotPaths1467ifp4PathStartsWith(path, p)]1468if not found:1469 fnum = fnum +11470continue14711472file= {}1473file["path"] = path1474file["rev"] = commit["rev%s"% fnum]1475file["action"] = commit["action%s"% fnum]1476file["type"] = commit["type%s"% fnum]1477 files.append(file)1478 fnum = fnum +11479return files14801481defstripRepoPath(self, path, prefixes):1482if self.useClientSpec:1483return self.clientSpecDirs.map_in_client(path)14841485if self.keepRepoPath:1486 prefixes = [re.sub("^(//[^/]+/).*", r'\1', prefixes[0])]14871488for p in prefixes:1489ifp4PathStartsWith(path, p):1490 path = path[len(p):]14911492return path14931494defsplitFilesIntoBranches(self, commit):1495 branches = {}1496 fnum =01497while commit.has_key("depotFile%s"% fnum):1498 path = commit["depotFile%s"% fnum]1499 found = [p for p in self.depotPaths1500ifp4PathStartsWith(path, p)]1501if not found:1502 fnum = fnum +11503continue15041505file= {}1506file["path"] = path1507file["rev"] = commit["rev%s"% fnum]1508file["action"] = commit["action%s"% fnum]1509file["type"] = commit["type%s"% fnum]1510 fnum = fnum +115111512 relPath = self.stripRepoPath(path, self.depotPaths)15131514for branch in self.knownBranches.keys():15151516# add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.21517if relPath.startswith(branch +"/"):1518if branch not in branches:1519 branches[branch] = []1520 branches[branch].append(file)1521break15221523return branches15241525# output one file from the P4 stream1526# - helper for streamP4Files15271528defstreamOneP4File(self,file, contents):1529 relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)1530 relPath = self.wildcard_decode(relPath)1531if verbose:1532 sys.stderr.write("%s\n"% relPath)15331534(type_base, type_mods) =split_p4_type(file["type"])15351536 git_mode ="100644"1537if"x"in type_mods:1538 git_mode ="100755"1539if type_base =="symlink":1540 git_mode ="120000"1541# p4 print on a symlink contains "target\n"; remove the newline1542 data =''.join(contents)1543 contents = [data[:-1]]15441545if type_base =="utf16":1546# p4 delivers different text in the python output to -G1547# than it does when using "print -o", or normal p4 client1548# operations. utf16 is converted to ascii or utf8, perhaps.1549# But ascii text saved as -t utf16 is completely mangled.1550# Invoke print -o to get the real contents.1551 text =p4_read_pipe(['print','-q','-o','-',file['depotFile']])1552 contents = [ text ]15531554if type_base =="apple":1555# Apple filetype files will be streamed as a concatenation of1556# its appledouble header and the contents. This is useless1557# on both macs and non-macs. If using "print -q -o xx", it1558# will create "xx" with the data, and "%xx" with the header.1559# This is also not very useful.1560#1561# Ideally, someday, this script can learn how to generate1562# appledouble files directly and import those to git, but1563# non-mac machines can never find a use for apple filetype.1564print"\nIgnoring apple filetype file%s"%file['depotFile']1565return15661567# Perhaps windows wants unicode, utf16 newlines translated too;1568# but this is not doing it.1569if self.isWindows and type_base =="text":1570 mangled = []1571for data in contents:1572 data = data.replace("\r\n","\n")1573 mangled.append(data)1574 contents = mangled15751576# Note that we do not try to de-mangle keywords on utf16 files,1577# even though in theory somebody may want that.1578if type_base in("text","unicode","binary"):1579if"ko"in type_mods:1580 text =''.join(contents)1581 text = re.sub(r'\$(Id|Header):[^$]*\$', r'$\1$', text)1582 contents = [ text ]1583elif"k"in type_mods:1584 text =''.join(contents)1585 text = re.sub(r'\$(Id|Header|Author|Date|DateTime|Change|File|Revision):[^$]*\$', r'$\1$', text)1586 contents = [ text ]15871588 self.gitStream.write("M%sinline%s\n"% (git_mode, relPath))15891590# total length...1591 length =01592for d in contents:1593 length = length +len(d)15941595 self.gitStream.write("data%d\n"% length)1596for d in contents:1597 self.gitStream.write(d)1598 self.gitStream.write("\n")15991600defstreamOneP4Deletion(self,file):1601 relPath = self.stripRepoPath(file['path'], self.branchPrefixes)1602if verbose:1603 sys.stderr.write("delete%s\n"% relPath)1604 self.gitStream.write("D%s\n"% relPath)16051606# handle another chunk of streaming data1607defstreamP4FilesCb(self, marshalled):16081609if marshalled.has_key('depotFile')and self.stream_have_file_info:1610# start of a new file - output the old one first1611 self.streamOneP4File(self.stream_file, self.stream_contents)1612 self.stream_file = {}1613 self.stream_contents = []1614 self.stream_have_file_info =False16151616# pick up the new file information... for the1617# 'data' field we need to append to our array1618for k in marshalled.keys():1619if k =='data':1620 self.stream_contents.append(marshalled['data'])1621else:1622 self.stream_file[k] = marshalled[k]16231624 self.stream_have_file_info =True16251626# Stream directly from "p4 files" into "git fast-import"1627defstreamP4Files(self, files):1628 filesForCommit = []1629 filesToRead = []1630 filesToDelete = []16311632for f in files:1633# if using a client spec, only add the files that have1634# a path in the client1635if self.clientSpecDirs:1636if self.clientSpecDirs.map_in_client(f['path']) =="":1637continue16381639 filesForCommit.append(f)1640if f['action']in self.delete_actions:1641 filesToDelete.append(f)1642else:1643 filesToRead.append(f)16441645# deleted files...1646for f in filesToDelete:1647 self.streamOneP4Deletion(f)16481649iflen(filesToRead) >0:1650 self.stream_file = {}1651 self.stream_contents = []1652 self.stream_have_file_info =False16531654# curry self argument1655defstreamP4FilesCbSelf(entry):1656 self.streamP4FilesCb(entry)16571658 fileArgs = ['%s#%s'% (f['path'], f['rev'])for f in filesToRead]16591660p4CmdList(["-x","-","print"],1661 stdin=fileArgs,1662 cb=streamP4FilesCbSelf)16631664# do the last chunk1665if self.stream_file.has_key('depotFile'):1666 self.streamOneP4File(self.stream_file, self.stream_contents)16671668defcommit(self, details, files, branch, branchPrefixes, parent =""):1669 epoch = details["time"]1670 author = details["user"]1671 self.branchPrefixes = branchPrefixes16721673if self.verbose:1674print"commit into%s"% branch16751676# start with reading files; if that fails, we should not1677# create a commit.1678 new_files = []1679for f in files:1680if[p for p in branchPrefixes ifp4PathStartsWith(f['path'], p)]:1681 new_files.append(f)1682else:1683 sys.stderr.write("Ignoring file outside of prefix:%s\n"% f['path'])16841685 self.gitStream.write("commit%s\n"% branch)1686# gitStream.write("mark :%s\n" % details["change"])1687 self.committedChanges.add(int(details["change"]))1688 committer =""1689if author not in self.users:1690 self.getUserMapFromPerforceServer()1691if author in self.users:1692 committer ="%s %s %s"% (self.users[author], epoch, self.tz)1693else:1694 committer ="%s<a@b>%s %s"% (author, epoch, self.tz)16951696 self.gitStream.write("committer%s\n"% committer)16971698 self.gitStream.write("data <<EOT\n")1699 self.gitStream.write(details["desc"])1700 self.gitStream.write("\n[git-p4: depot-paths =\"%s\": change =%s"1701% (','.join(branchPrefixes), details["change"]))1702iflen(details['options']) >0:1703 self.gitStream.write(": options =%s"% details['options'])1704 self.gitStream.write("]\nEOT\n\n")17051706iflen(parent) >0:1707if self.verbose:1708print"parent%s"% parent1709 self.gitStream.write("from%s\n"% parent)17101711 self.streamP4Files(new_files)1712 self.gitStream.write("\n")17131714 change =int(details["change"])17151716if self.labels.has_key(change):1717 label = self.labels[change]1718 labelDetails = label[0]1719 labelRevisions = label[1]1720if self.verbose:1721print"Change%sis labelled%s"% (change, labelDetails)17221723 files =p4CmdList(["files"] + ["%s...@%s"% (p, change)1724for p in branchPrefixes])17251726iflen(files) ==len(labelRevisions):17271728 cleanedFiles = {}1729for info in files:1730if info["action"]in self.delete_actions:1731continue1732 cleanedFiles[info["depotFile"]] = info["rev"]17331734if cleanedFiles == labelRevisions:1735 self.gitStream.write("tag tag_%s\n"% labelDetails["label"])1736 self.gitStream.write("from%s\n"% branch)17371738 owner = labelDetails["Owner"]1739 tagger =""1740if author in self.users:1741 tagger ="%s %s %s"% (self.users[owner], epoch, self.tz)1742else:1743 tagger ="%s<a@b>%s %s"% (owner, epoch, self.tz)1744 self.gitStream.write("tagger%s\n"% tagger)1745 self.gitStream.write("data <<EOT\n")1746 self.gitStream.write(labelDetails["Description"])1747 self.gitStream.write("EOT\n\n")17481749else:1750if not self.silent:1751print("Tag%sdoes not match with change%s: files do not match."1752% (labelDetails["label"], change))17531754else:1755if not self.silent:1756print("Tag%sdoes not match with change%s: file count is different."1757% (labelDetails["label"], change))17581759defgetLabels(self):1760 self.labels = {}17611762 l =p4CmdList("labels%s..."%' '.join(self.depotPaths))1763iflen(l) >0and not self.silent:1764print"Finding files belonging to labels in%s"% `self.depotPaths`17651766for output in l:1767 label = output["label"]1768 revisions = {}1769 newestChange =01770if self.verbose:1771print"Querying files for label%s"% label1772forfileinp4CmdList(["files"] +1773["%s...@%s"% (p, label)1774for p in self.depotPaths]):1775 revisions[file["depotFile"]] =file["rev"]1776 change =int(file["change"])1777if change > newestChange:1778 newestChange = change17791780 self.labels[newestChange] = [output, revisions]17811782if self.verbose:1783print"Label changes:%s"% self.labels.keys()17841785defguessProjectName(self):1786for p in self.depotPaths:1787if p.endswith("/"):1788 p = p[:-1]1789 p = p[p.strip().rfind("/") +1:]1790if not p.endswith("/"):1791 p +="/"1792return p17931794defgetBranchMapping(self):1795 lostAndFoundBranches =set()17961797 user =gitConfig("git-p4.branchUser")1798iflen(user) >0:1799 command ="branches -u%s"% user1800else:1801 command ="branches"18021803for info inp4CmdList(command):1804 details =p4Cmd("branch -o%s"% info["branch"])1805 viewIdx =01806while details.has_key("View%s"% viewIdx):1807 paths = details["View%s"% viewIdx].split(" ")1808 viewIdx = viewIdx +11809# require standard //depot/foo/... //depot/bar/... mapping1810iflen(paths) !=2or not paths[0].endswith("/...")or not paths[1].endswith("/..."):1811continue1812 source = paths[0]1813 destination = paths[1]1814## HACK1815ifp4PathStartsWith(source, self.depotPaths[0])andp4PathStartsWith(destination, self.depotPaths[0]):1816 source = source[len(self.depotPaths[0]):-4]1817 destination = destination[len(self.depotPaths[0]):-4]18181819if destination in self.knownBranches:1820if not self.silent:1821print"p4 branch%sdefines a mapping from%sto%s"% (info["branch"], source, destination)1822print"but there exists another mapping from%sto%salready!"% (self.knownBranches[destination], destination)1823continue18241825 self.knownBranches[destination] = source18261827 lostAndFoundBranches.discard(destination)18281829if source not in self.knownBranches:1830 lostAndFoundBranches.add(source)18311832# Perforce does not strictly require branches to be defined, so we also1833# check git config for a branch list.1834#1835# Example of branch definition in git config file:1836# [git-p4]1837# branchList=main:branchA1838# branchList=main:branchB1839# branchList=branchA:branchC1840 configBranches =gitConfigList("git-p4.branchList")1841for branch in configBranches:1842if branch:1843(source, destination) = branch.split(":")1844 self.knownBranches[destination] = source18451846 lostAndFoundBranches.discard(destination)18471848if source not in self.knownBranches:1849 lostAndFoundBranches.add(source)185018511852for branch in lostAndFoundBranches:1853 self.knownBranches[branch] = branch18541855defgetBranchMappingFromGitBranches(self):1856 branches =p4BranchesInGit(self.importIntoRemotes)1857for branch in branches.keys():1858if branch =="master":1859 branch ="main"1860else:1861 branch = branch[len(self.projectName):]1862 self.knownBranches[branch] = branch18631864deflistExistingP4GitBranches(self):1865# branches holds mapping from name to commit1866 branches =p4BranchesInGit(self.importIntoRemotes)1867 self.p4BranchesInGit = branches.keys()1868for branch in branches.keys():1869 self.initialParents[self.refPrefix + branch] = branches[branch]18701871defupdateOptionDict(self, d):1872 option_keys = {}1873if self.keepRepoPath:1874 option_keys['keepRepoPath'] =118751876 d["options"] =' '.join(sorted(option_keys.keys()))18771878defreadOptions(self, d):1879 self.keepRepoPath = (d.has_key('options')1880and('keepRepoPath'in d['options']))18811882defgitRefForBranch(self, branch):1883if branch =="main":1884return self.refPrefix +"master"18851886iflen(branch) <=0:1887return branch18881889return self.refPrefix + self.projectName + branch18901891defgitCommitByP4Change(self, ref, change):1892if self.verbose:1893print"looking in ref "+ ref +" for change%susing bisect..."% change18941895 earliestCommit =""1896 latestCommit =parseRevision(ref)18971898while True:1899if self.verbose:1900print"trying: earliest%slatest%s"% (earliestCommit, latestCommit)1901 next =read_pipe("git rev-list --bisect%s %s"% (latestCommit, earliestCommit)).strip()1902iflen(next) ==0:1903if self.verbose:1904print"argh"1905return""1906 log =extractLogMessageFromGitCommit(next)1907 settings =extractSettingsGitLog(log)1908 currentChange =int(settings['change'])1909if self.verbose:1910print"current change%s"% currentChange19111912if currentChange == change:1913if self.verbose:1914print"found%s"% next1915return next19161917if currentChange < change:1918 earliestCommit ="^%s"% next1919else:1920 latestCommit ="%s"% next19211922return""19231924defimportNewBranch(self, branch, maxChange):1925# make fast-import flush all changes to disk and update the refs using the checkpoint1926# command so that we can try to find the branch parent in the git history1927 self.gitStream.write("checkpoint\n\n");1928 self.gitStream.flush();1929 branchPrefix = self.depotPaths[0] + branch +"/"1930range="@1,%s"% maxChange1931#print "prefix" + branchPrefix1932 changes =p4ChangesForPaths([branchPrefix],range)1933iflen(changes) <=0:1934return False1935 firstChange = changes[0]1936#print "first change in branch: %s" % firstChange1937 sourceBranch = self.knownBranches[branch]1938 sourceDepotPath = self.depotPaths[0] + sourceBranch1939 sourceRef = self.gitRefForBranch(sourceBranch)1940#print "source " + sourceBranch19411942 branchParentChange =int(p4Cmd("changes -m 1%s...@1,%s"% (sourceDepotPath, firstChange))["change"])1943#print "branch parent: %s" % branchParentChange1944 gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)1945iflen(gitParent) >0:1946 self.initialParents[self.gitRefForBranch(branch)] = gitParent1947#print "parent git commit: %s" % gitParent19481949 self.importChanges(changes)1950return True19511952defimportChanges(self, changes):1953 cnt =11954for change in changes:1955 description =p4Cmd("describe%s"% change)1956 self.updateOptionDict(description)19571958if not self.silent:1959 sys.stdout.write("\rImporting revision%s(%s%%)"% (change, cnt *100/len(changes)))1960 sys.stdout.flush()1961 cnt = cnt +119621963try:1964if self.detectBranches:1965 branches = self.splitFilesIntoBranches(description)1966for branch in branches.keys():1967## HACK --hwn1968 branchPrefix = self.depotPaths[0] + branch +"/"19691970 parent =""19711972 filesForCommit = branches[branch]19731974if self.verbose:1975print"branch is%s"% branch19761977 self.updatedBranches.add(branch)19781979if branch not in self.createdBranches:1980 self.createdBranches.add(branch)1981 parent = self.knownBranches[branch]1982if parent == branch:1983 parent =""1984else:1985 fullBranch = self.projectName + branch1986if fullBranch not in self.p4BranchesInGit:1987if not self.silent:1988print("\nImporting new branch%s"% fullBranch);1989if self.importNewBranch(branch, change -1):1990 parent =""1991 self.p4BranchesInGit.append(fullBranch)1992if not self.silent:1993print("\nResuming with change%s"% change);19941995if self.verbose:1996print"parent determined through known branches:%s"% parent19971998 branch = self.gitRefForBranch(branch)1999 parent = self.gitRefForBranch(parent)20002001if self.verbose:2002print"looking for initial parent for%s; current parent is%s"% (branch, parent)20032004iflen(parent) ==0and branch in self.initialParents:2005 parent = self.initialParents[branch]2006del self.initialParents[branch]20072008 self.commit(description, filesForCommit, branch, [branchPrefix], parent)2009else:2010 files = self.extractFilesFromCommit(description)2011 self.commit(description, files, self.branch, self.depotPaths,2012 self.initialParent)2013 self.initialParent =""2014exceptIOError:2015print self.gitError.read()2016 sys.exit(1)20172018defimportHeadRevision(self, revision):2019print"Doing initial import of%sfrom revision%sinto%s"% (' '.join(self.depotPaths), revision, self.branch)20202021 details = {}2022 details["user"] ="git perforce import user"2023 details["desc"] = ("Initial import of%sfrom the state at revision%s\n"2024% (' '.join(self.depotPaths), revision))2025 details["change"] = revision2026 newestRevision =020272028 fileCnt =02029 fileArgs = ["%s...%s"% (p,revision)for p in self.depotPaths]20302031for info inp4CmdList(["files"] + fileArgs):20322033if'code'in info and info['code'] =='error':2034 sys.stderr.write("p4 returned an error:%s\n"2035% info['data'])2036if info['data'].find("must refer to client") >=0:2037 sys.stderr.write("This particular p4 error is misleading.\n")2038 sys.stderr.write("Perhaps the depot path was misspelled.\n");2039 sys.stderr.write("Depot path:%s\n"%" ".join(self.depotPaths))2040 sys.exit(1)2041if'p4ExitCode'in info:2042 sys.stderr.write("p4 exitcode:%s\n"% info['p4ExitCode'])2043 sys.exit(1)204420452046 change =int(info["change"])2047if change > newestRevision:2048 newestRevision = change20492050if info["action"]in self.delete_actions:2051# don't increase the file cnt, otherwise details["depotFile123"] will have gaps!2052#fileCnt = fileCnt + 12053continue20542055for prop in["depotFile","rev","action","type"]:2056 details["%s%s"% (prop, fileCnt)] = info[prop]20572058 fileCnt = fileCnt +120592060 details["change"] = newestRevision20612062# Use time from top-most change so that all git-p4 clones of2063# the same p4 repo have the same commit SHA1s.2064 res =p4CmdList("describe -s%d"% newestRevision)2065 newestTime =None2066for r in res:2067if r.has_key('time'):2068 newestTime =int(r['time'])2069if newestTime is None:2070die("\"describe -s\"on newest change%ddid not give a time")2071 details["time"] = newestTime20722073 self.updateOptionDict(details)2074try:2075 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths)2076exceptIOError:2077print"IO error with git fast-import. Is your git version recent enough?"2078print self.gitError.read()207920802081defgetClientSpec(self):2082 specList =p4CmdList("client -o")2083iflen(specList) !=1:2084die('Output from "client -o" is%dlines, expecting 1'%2085len(specList))20862087# dictionary of all client parameters2088 entry = specList[0]20892090# just the keys that start with "View"2091 view_keys = [ k for k in entry.keys()if k.startswith("View") ]20922093# hold this new View2094 view =View()20952096# append the lines, in order, to the view2097for view_num inrange(len(view_keys)):2098 k ="View%d"% view_num2099if k not in view_keys:2100die("Expected view key%smissing"% k)2101 view.append(entry[k])21022103 self.clientSpecDirs = view2104if self.verbose:2105for i, m inenumerate(self.clientSpecDirs.mappings):2106print"clientSpecDirs%d:%s"% (i,str(m))21072108defrun(self, args):2109 self.depotPaths = []2110 self.changeRange =""2111 self.initialParent =""2112 self.previousDepotPaths = []21132114# map from branch depot path to parent branch2115 self.knownBranches = {}2116 self.initialParents = {}2117 self.hasOrigin =originP4BranchesExist()2118if not self.syncWithOrigin:2119 self.hasOrigin =False21202121if self.importIntoRemotes:2122 self.refPrefix ="refs/remotes/p4/"2123else:2124 self.refPrefix ="refs/heads/p4/"21252126if self.syncWithOrigin and self.hasOrigin:2127if not self.silent:2128print"Syncing with origin first by calling git fetch origin"2129system("git fetch origin")21302131iflen(self.branch) ==0:2132 self.branch = self.refPrefix +"master"2133ifgitBranchExists("refs/heads/p4")and self.importIntoRemotes:2134system("git update-ref%srefs/heads/p4"% self.branch)2135system("git branch -D p4");2136# create it /after/ importing, when master exists2137if notgitBranchExists(self.refPrefix +"HEAD")and self.importIntoRemotes andgitBranchExists(self.branch):2138system("git symbolic-ref%sHEAD%s"% (self.refPrefix, self.branch))21392140if not self.useClientSpec:2141ifgitConfig("git-p4.useclientspec","--bool") =="true":2142 self.useClientSpec =True2143if self.useClientSpec:2144 self.getClientSpec()21452146# TODO: should always look at previous commits,2147# merge with previous imports, if possible.2148if args == []:2149if self.hasOrigin:2150createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)2151 self.listExistingP4GitBranches()21522153iflen(self.p4BranchesInGit) >1:2154if not self.silent:2155print"Importing from/into multiple branches"2156 self.detectBranches =True21572158if self.verbose:2159print"branches:%s"% self.p4BranchesInGit21602161 p4Change =02162for branch in self.p4BranchesInGit:2163 logMsg =extractLogMessageFromGitCommit(self.refPrefix + branch)21642165 settings =extractSettingsGitLog(logMsg)21662167 self.readOptions(settings)2168if(settings.has_key('depot-paths')2169and settings.has_key('change')):2170 change =int(settings['change']) +12171 p4Change =max(p4Change, change)21722173 depotPaths =sorted(settings['depot-paths'])2174if self.previousDepotPaths == []:2175 self.previousDepotPaths = depotPaths2176else:2177 paths = []2178for(prev, cur)inzip(self.previousDepotPaths, depotPaths):2179 prev_list = prev.split("/")2180 cur_list = cur.split("/")2181for i inrange(0,min(len(cur_list),len(prev_list))):2182if cur_list[i] <> prev_list[i]:2183 i = i -12184break21852186 paths.append("/".join(cur_list[:i +1]))21872188 self.previousDepotPaths = paths21892190if p4Change >0:2191 self.depotPaths =sorted(self.previousDepotPaths)2192 self.changeRange ="@%s,#head"% p4Change2193if not self.detectBranches:2194 self.initialParent =parseRevision(self.branch)2195if not self.silent and not self.detectBranches:2196print"Performing incremental import into%sgit branch"% self.branch21972198if not self.branch.startswith("refs/"):2199 self.branch ="refs/heads/"+ self.branch22002201iflen(args) ==0and self.depotPaths:2202if not self.silent:2203print"Depot paths:%s"%' '.join(self.depotPaths)2204else:2205if self.depotPaths and self.depotPaths != args:2206print("previous import used depot path%sand now%swas specified. "2207"This doesn't work!"% (' '.join(self.depotPaths),2208' '.join(args)))2209 sys.exit(1)22102211 self.depotPaths =sorted(args)22122213 revision =""2214 self.users = {}22152216# Make sure no revision specifiers are used when --changesfile2217# is specified.2218 bad_changesfile =False2219iflen(self.changesFile) >0:2220for p in self.depotPaths:2221if p.find("@") >=0or p.find("#") >=0:2222 bad_changesfile =True2223break2224if bad_changesfile:2225die("Option --changesfile is incompatible with revision specifiers")22262227 newPaths = []2228for p in self.depotPaths:2229if p.find("@") != -1:2230 atIdx = p.index("@")2231 self.changeRange = p[atIdx:]2232if self.changeRange =="@all":2233 self.changeRange =""2234elif','not in self.changeRange:2235 revision = self.changeRange2236 self.changeRange =""2237 p = p[:atIdx]2238elif p.find("#") != -1:2239 hashIdx = p.index("#")2240 revision = p[hashIdx:]2241 p = p[:hashIdx]2242elif self.previousDepotPaths == []:2243# pay attention to changesfile, if given, else import2244# the entire p4 tree at the head revision2245iflen(self.changesFile) ==0:2246 revision ="#head"22472248 p = re.sub("\.\.\.$","", p)2249if not p.endswith("/"):2250 p +="/"22512252 newPaths.append(p)22532254 self.depotPaths = newPaths225522562257 self.loadUserMapFromCache()2258 self.labels = {}2259if self.detectLabels:2260 self.getLabels();22612262if self.detectBranches:2263## FIXME - what's a P4 projectName ?2264 self.projectName = self.guessProjectName()22652266if self.hasOrigin:2267 self.getBranchMappingFromGitBranches()2268else:2269 self.getBranchMapping()2270if self.verbose:2271print"p4-git branches:%s"% self.p4BranchesInGit2272print"initial parents:%s"% self.initialParents2273for b in self.p4BranchesInGit:2274if b !="master":22752276## FIXME2277 b = b[len(self.projectName):]2278 self.createdBranches.add(b)22792280 self.tz ="%+03d%02d"% (- time.timezone /3600, ((- time.timezone %3600) /60))22812282 importProcess = subprocess.Popen(["git","fast-import"],2283 stdin=subprocess.PIPE, stdout=subprocess.PIPE,2284 stderr=subprocess.PIPE);2285 self.gitOutput = importProcess.stdout2286 self.gitStream = importProcess.stdin2287 self.gitError = importProcess.stderr22882289if revision:2290 self.importHeadRevision(revision)2291else:2292 changes = []22932294iflen(self.changesFile) >0:2295 output =open(self.changesFile).readlines()2296 changeSet =set()2297for line in output:2298 changeSet.add(int(line))22992300for change in changeSet:2301 changes.append(change)23022303 changes.sort()2304else:2305# catch "git-p4 sync" with no new branches, in a repo that2306# does not have any existing git-p4 branches2307iflen(args) ==0and not self.p4BranchesInGit:2308die("No remote p4 branches. Perhaps you never did\"git p4 clone\"in here.");2309if self.verbose:2310print"Getting p4 changes for%s...%s"% (', '.join(self.depotPaths),2311 self.changeRange)2312 changes =p4ChangesForPaths(self.depotPaths, self.changeRange)23132314iflen(self.maxChanges) >0:2315 changes = changes[:min(int(self.maxChanges),len(changes))]23162317iflen(changes) ==0:2318if not self.silent:2319print"No changes to import!"2320return True23212322if not self.silent and not self.detectBranches:2323print"Import destination:%s"% self.branch23242325 self.updatedBranches =set()23262327 self.importChanges(changes)23282329if not self.silent:2330print""2331iflen(self.updatedBranches) >0:2332 sys.stdout.write("Updated branches: ")2333for b in self.updatedBranches:2334 sys.stdout.write("%s"% b)2335 sys.stdout.write("\n")23362337 self.gitStream.close()2338if importProcess.wait() !=0:2339die("fast-import failed:%s"% self.gitError.read())2340 self.gitOutput.close()2341 self.gitError.close()23422343return True23442345classP4Rebase(Command):2346def__init__(self):2347 Command.__init__(self)2348 self.options = [ ]2349 self.description = ("Fetches the latest revision from perforce and "2350+"rebases the current work (branch) against it")2351 self.verbose =False23522353defrun(self, args):2354 sync =P4Sync()2355 sync.run([])23562357return self.rebase()23582359defrebase(self):2360if os.system("git update-index --refresh") !=0:2361die("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.");2362iflen(read_pipe("git diff-index HEAD --")) >0:2363die("You have uncommited changes. Please commit them before rebasing or stash them away with git stash.");23642365[upstream, settings] =findUpstreamBranchPoint()2366iflen(upstream) ==0:2367die("Cannot find upstream branchpoint for rebase")23682369# the branchpoint may be p4/foo~3, so strip off the parent2370 upstream = re.sub("~[0-9]+$","", upstream)23712372print"Rebasing the current branch onto%s"% upstream2373 oldHead =read_pipe("git rev-parse HEAD").strip()2374system("git rebase%s"% upstream)2375system("git diff-tree --stat --summary -M%sHEAD"% oldHead)2376return True23772378classP4Clone(P4Sync):2379def__init__(self):2380 P4Sync.__init__(self)2381 self.description ="Creates a new git repository and imports from Perforce into it"2382 self.usage ="usage: %prog [options] //depot/path[@revRange]"2383 self.options += [2384 optparse.make_option("--destination", dest="cloneDestination",2385 action='store', default=None,2386help="where to leave result of the clone"),2387 optparse.make_option("-/", dest="cloneExclude",2388 action="append",type="string",2389help="exclude depot path"),2390 optparse.make_option("--bare", dest="cloneBare",2391 action="store_true", default=False),2392]2393 self.cloneDestination =None2394 self.needsGit =False2395 self.cloneBare =False23962397# This is required for the "append" cloneExclude action2398defensure_value(self, attr, value):2399if nothasattr(self, attr)orgetattr(self, attr)is None:2400setattr(self, attr, value)2401returngetattr(self, attr)24022403defdefaultDestination(self, args):2404## TODO: use common prefix of args?2405 depotPath = args[0]2406 depotDir = re.sub("(@[^@]*)$","", depotPath)2407 depotDir = re.sub("(#[^#]*)$","", depotDir)2408 depotDir = re.sub(r"\.\.\.$","", depotDir)2409 depotDir = re.sub(r"/$","", depotDir)2410return os.path.split(depotDir)[1]24112412defrun(self, args):2413iflen(args) <1:2414return False24152416if self.keepRepoPath and not self.cloneDestination:2417 sys.stderr.write("Must specify destination for --keep-path\n")2418 sys.exit(1)24192420 depotPaths = args24212422if not self.cloneDestination andlen(depotPaths) >1:2423 self.cloneDestination = depotPaths[-1]2424 depotPaths = depotPaths[:-1]24252426 self.cloneExclude = ["/"+p for p in self.cloneExclude]2427for p in depotPaths:2428if not p.startswith("//"):2429return False24302431if not self.cloneDestination:2432 self.cloneDestination = self.defaultDestination(args)24332434print"Importing from%sinto%s"% (', '.join(depotPaths), self.cloneDestination)24352436if not os.path.exists(self.cloneDestination):2437 os.makedirs(self.cloneDestination)2438chdir(self.cloneDestination)24392440 init_cmd = ["git","init"]2441if self.cloneBare:2442 init_cmd.append("--bare")2443 subprocess.check_call(init_cmd)24442445if not P4Sync.run(self, depotPaths):2446return False2447if self.branch !="master":2448if self.importIntoRemotes:2449 masterbranch ="refs/remotes/p4/master"2450else:2451 masterbranch ="refs/heads/p4/master"2452ifgitBranchExists(masterbranch):2453system("git branch master%s"% masterbranch)2454if not self.cloneBare:2455system("git checkout -f")2456else:2457print"Could not detect main branch. No checkout/master branch created."24582459return True24602461classP4Branches(Command):2462def__init__(self):2463 Command.__init__(self)2464 self.options = [ ]2465 self.description = ("Shows the git branches that hold imports and their "2466+"corresponding perforce depot paths")2467 self.verbose =False24682469defrun(self, args):2470iforiginP4BranchesExist():2471createOrUpdateBranchesFromOrigin()24722473 cmdline ="git rev-parse --symbolic "2474 cmdline +=" --remotes"24752476for line inread_pipe_lines(cmdline):2477 line = line.strip()24782479if not line.startswith('p4/')or line =="p4/HEAD":2480continue2481 branch = line24822483 log =extractLogMessageFromGitCommit("refs/remotes/%s"% branch)2484 settings =extractSettingsGitLog(log)24852486print"%s<=%s(%s)"% (branch,",".join(settings["depot-paths"]), settings["change"])2487return True24882489classHelpFormatter(optparse.IndentedHelpFormatter):2490def__init__(self):2491 optparse.IndentedHelpFormatter.__init__(self)24922493defformat_description(self, description):2494if description:2495return description +"\n"2496else:2497return""24982499defprintUsage(commands):2500print"usage:%s<command> [options]"% sys.argv[0]2501print""2502print"valid commands:%s"%", ".join(commands)2503print""2504print"Try%s<command> --help for command specific help."% sys.argv[0]2505print""25062507commands = {2508"debug": P4Debug,2509"submit": P4Submit,2510"commit": P4Submit,2511"sync": P4Sync,2512"rebase": P4Rebase,2513"clone": P4Clone,2514"rollback": P4RollBack,2515"branches": P4Branches2516}251725182519defmain():2520iflen(sys.argv[1:]) ==0:2521printUsage(commands.keys())2522 sys.exit(2)25232524 cmd =""2525 cmdName = sys.argv[1]2526try:2527 klass = commands[cmdName]2528 cmd =klass()2529exceptKeyError:2530print"unknown command%s"% cmdName2531print""2532printUsage(commands.keys())2533 sys.exit(2)25342535 options = cmd.options2536 cmd.gitdir = os.environ.get("GIT_DIR",None)25372538 args = sys.argv[2:]25392540iflen(options) >0:2541if cmd.needsGit:2542 options.append(optparse.make_option("--git-dir", dest="gitdir"))25432544 parser = optparse.OptionParser(cmd.usage.replace("%prog","%prog "+ cmdName),2545 options,2546 description = cmd.description,2547 formatter =HelpFormatter())25482549(cmd, args) = parser.parse_args(sys.argv[2:], cmd);2550global verbose2551 verbose = cmd.verbose2552if cmd.needsGit:2553if cmd.gitdir ==None:2554 cmd.gitdir = os.path.abspath(".git")2555if notisValidGitDir(cmd.gitdir):2556 cmd.gitdir =read_pipe("git rev-parse --git-dir").strip()2557if os.path.exists(cmd.gitdir):2558 cdup =read_pipe("git rev-parse --show-cdup").strip()2559iflen(cdup) >0:2560chdir(cdup);25612562if notisValidGitDir(cmd.gitdir):2563ifisValidGitDir(cmd.gitdir +"/.git"):2564 cmd.gitdir +="/.git"2565else:2566die("fatal: cannot locate git repository at%s"% cmd.gitdir)25672568 os.environ["GIT_DIR"] = cmd.gitdir25692570if not cmd.run(args):2571 parser.print_help()2572 sys.exit(2)257325742575if __name__ =='__main__':2576main()