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, shutil 14 15try: 16from subprocess import CalledProcessError 17exceptImportError: 18# from python2.7:subprocess.py 19# Exception classes used by this module. 20classCalledProcessError(Exception): 21"""This exception is raised when a process run by check_call() returns 22 a non-zero exit status. The exit status will be stored in the 23 returncode attribute.""" 24def__init__(self, returncode, cmd): 25 self.returncode = returncode 26 self.cmd = cmd 27def__str__(self): 28return"Command '%s' returned non-zero exit status%d"% (self.cmd, self.returncode) 29 30verbose =False 31 32# Only labels/tags matching this will be imported/exported 33defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$' 34 35defp4_build_cmd(cmd): 36"""Build a suitable p4 command line. 37 38 This consolidates building and returning a p4 command line into one 39 location. It means that hooking into the environment, or other configuration 40 can be done more easily. 41 """ 42 real_cmd = ["p4"] 43 44 user =gitConfig("git-p4.user") 45iflen(user) >0: 46 real_cmd += ["-u",user] 47 48 password =gitConfig("git-p4.password") 49iflen(password) >0: 50 real_cmd += ["-P", password] 51 52 port =gitConfig("git-p4.port") 53iflen(port) >0: 54 real_cmd += ["-p", port] 55 56 host =gitConfig("git-p4.host") 57iflen(host) >0: 58 real_cmd += ["-H", host] 59 60 client =gitConfig("git-p4.client") 61iflen(client) >0: 62 real_cmd += ["-c", client] 63 64 65ifisinstance(cmd,basestring): 66 real_cmd =' '.join(real_cmd) +' '+ cmd 67else: 68 real_cmd += cmd 69return real_cmd 70 71defchdir(dir): 72# P4 uses the PWD environment variable rather than getcwd(). Since we're 73# not using the shell, we have to set it ourselves. This path could 74# be relative, so go there first, then figure out where we ended up. 75 os.chdir(dir) 76 os.environ['PWD'] = os.getcwd() 77 78defdie(msg): 79if verbose: 80raiseException(msg) 81else: 82 sys.stderr.write(msg +"\n") 83 sys.exit(1) 84 85defwrite_pipe(c, stdin): 86if verbose: 87 sys.stderr.write('Writing pipe:%s\n'%str(c)) 88 89 expand =isinstance(c,basestring) 90 p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand) 91 pipe = p.stdin 92 val = pipe.write(stdin) 93 pipe.close() 94if p.wait(): 95die('Command failed:%s'%str(c)) 96 97return val 98 99defp4_write_pipe(c, stdin): 100 real_cmd =p4_build_cmd(c) 101returnwrite_pipe(real_cmd, stdin) 102 103defread_pipe(c, ignore_error=False): 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.read() 111if p.wait()and not ignore_error: 112die('Command failed:%s'%str(c)) 113 114return val 115 116defp4_read_pipe(c, ignore_error=False): 117 real_cmd =p4_build_cmd(c) 118returnread_pipe(real_cmd, ignore_error) 119 120defread_pipe_lines(c): 121if verbose: 122 sys.stderr.write('Reading pipe:%s\n'%str(c)) 123 124 expand =isinstance(c, basestring) 125 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand) 126 pipe = p.stdout 127 val = pipe.readlines() 128if pipe.close()or p.wait(): 129die('Command failed:%s'%str(c)) 130 131return val 132 133defp4_read_pipe_lines(c): 134"""Specifically invoke p4 on the command supplied. """ 135 real_cmd =p4_build_cmd(c) 136returnread_pipe_lines(real_cmd) 137 138defp4_has_command(cmd): 139"""Ask p4 for help on this command. If it returns an error, the 140 command does not exist in this version of p4.""" 141 real_cmd =p4_build_cmd(["help", cmd]) 142 p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE, 143 stderr=subprocess.PIPE) 144 p.communicate() 145return p.returncode ==0 146 147defp4_has_move_command(): 148"""See if the move command exists, that it supports -k, and that 149 it has not been administratively disabled. The arguments 150 must be correct, but the filenames do not have to exist. Use 151 ones with wildcards so even if they exist, it will fail.""" 152 153if notp4_has_command("move"): 154return False 155 cmd =p4_build_cmd(["move","-k","@from","@to"]) 156 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 157(out, err) = p.communicate() 158# return code will be 1 in either case 159if err.find("Invalid option") >=0: 160return False 161if err.find("disabled") >=0: 162return False 163# assume it failed because @... was invalid changelist 164return True 165 166defsystem(cmd): 167 expand =isinstance(cmd,basestring) 168if verbose: 169 sys.stderr.write("executing%s\n"%str(cmd)) 170 retcode = subprocess.call(cmd, shell=expand) 171if retcode: 172raiseCalledProcessError(retcode, cmd) 173 174defp4_system(cmd): 175"""Specifically invoke p4 as the system command. """ 176 real_cmd =p4_build_cmd(cmd) 177 expand =isinstance(real_cmd, basestring) 178 retcode = subprocess.call(real_cmd, shell=expand) 179if retcode: 180raiseCalledProcessError(retcode, real_cmd) 181 182defp4_integrate(src, dest): 183p4_system(["integrate","-Dt",wildcard_encode(src),wildcard_encode(dest)]) 184 185defp4_sync(f, *options): 186p4_system(["sync"] +list(options) + [wildcard_encode(f)]) 187 188defp4_add(f): 189# forcibly add file names with wildcards 190ifwildcard_present(f): 191p4_system(["add","-f", f]) 192else: 193p4_system(["add", f]) 194 195defp4_delete(f): 196p4_system(["delete",wildcard_encode(f)]) 197 198defp4_edit(f): 199p4_system(["edit",wildcard_encode(f)]) 200 201defp4_revert(f): 202p4_system(["revert",wildcard_encode(f)]) 203 204defp4_reopen(type, f): 205p4_system(["reopen","-t",type,wildcard_encode(f)]) 206 207defp4_move(src, dest): 208p4_system(["move","-k",wildcard_encode(src),wildcard_encode(dest)]) 209 210defp4_describe(change): 211"""Make sure it returns a valid result by checking for 212 the presence of field "time". Return a dict of the 213 results.""" 214 215 ds =p4CmdList(["describe","-s",str(change)]) 216iflen(ds) !=1: 217die("p4 describe -s%ddid not return 1 result:%s"% (change,str(ds))) 218 219 d = ds[0] 220 221if"p4ExitCode"in d: 222die("p4 describe -s%dexited with%d:%s"% (change, d["p4ExitCode"], 223str(d))) 224if"code"in d: 225if d["code"] =="error": 226die("p4 describe -s%dreturned error code:%s"% (change,str(d))) 227 228if"time"not in d: 229die("p4 describe -s%dreturned no\"time\":%s"% (change,str(d))) 230 231return d 232 233# 234# Canonicalize the p4 type and return a tuple of the 235# base type, plus any modifiers. See "p4 help filetypes" 236# for a list and explanation. 237# 238defsplit_p4_type(p4type): 239 240 p4_filetypes_historical = { 241"ctempobj":"binary+Sw", 242"ctext":"text+C", 243"cxtext":"text+Cx", 244"ktext":"text+k", 245"kxtext":"text+kx", 246"ltext":"text+F", 247"tempobj":"binary+FSw", 248"ubinary":"binary+F", 249"uresource":"resource+F", 250"uxbinary":"binary+Fx", 251"xbinary":"binary+x", 252"xltext":"text+Fx", 253"xtempobj":"binary+Swx", 254"xtext":"text+x", 255"xunicode":"unicode+x", 256"xutf16":"utf16+x", 257} 258if p4type in p4_filetypes_historical: 259 p4type = p4_filetypes_historical[p4type] 260 mods ="" 261 s = p4type.split("+") 262 base = s[0] 263 mods ="" 264iflen(s) >1: 265 mods = s[1] 266return(base, mods) 267 268# 269# return the raw p4 type of a file (text, text+ko, etc) 270# 271defp4_type(file): 272 results =p4CmdList(["fstat","-T","headType",file]) 273return results[0]['headType'] 274 275# 276# Given a type base and modifier, return a regexp matching 277# the keywords that can be expanded in the file 278# 279defp4_keywords_regexp_for_type(base, type_mods): 280if base in("text","unicode","binary"): 281 kwords =None 282if"ko"in type_mods: 283 kwords ='Id|Header' 284elif"k"in type_mods: 285 kwords ='Id|Header|Author|Date|DateTime|Change|File|Revision' 286else: 287return None 288 pattern = r""" 289 \$ # Starts with a dollar, followed by... 290 (%s) # one of the keywords, followed by... 291 (:[^$\n]+)? # possibly an old expansion, followed by... 292 \$ # another dollar 293 """% kwords 294return pattern 295else: 296return None 297 298# 299# Given a file, return a regexp matching the possible 300# RCS keywords that will be expanded, or None for files 301# with kw expansion turned off. 302# 303defp4_keywords_regexp_for_file(file): 304if not os.path.exists(file): 305return None 306else: 307(type_base, type_mods) =split_p4_type(p4_type(file)) 308returnp4_keywords_regexp_for_type(type_base, type_mods) 309 310defsetP4ExecBit(file, mode): 311# Reopens an already open file and changes the execute bit to match 312# the execute bit setting in the passed in mode. 313 314 p4Type ="+x" 315 316if notisModeExec(mode): 317 p4Type =getP4OpenedType(file) 318 p4Type = re.sub('^([cku]?)x(.*)','\\1\\2', p4Type) 319 p4Type = re.sub('(.*?\+.*?)x(.*?)','\\1\\2', p4Type) 320if p4Type[-1] =="+": 321 p4Type = p4Type[0:-1] 322 323p4_reopen(p4Type,file) 324 325defgetP4OpenedType(file): 326# Returns the perforce file type for the given file. 327 328 result =p4_read_pipe(["opened",wildcard_encode(file)]) 329 match = re.match(".*\((.+)\)\r?$", result) 330if match: 331return match.group(1) 332else: 333die("Could not determine file type for%s(result: '%s')"% (file, result)) 334 335# Return the set of all p4 labels 336defgetP4Labels(depotPaths): 337 labels =set() 338ifisinstance(depotPaths,basestring): 339 depotPaths = [depotPaths] 340 341for l inp4CmdList(["labels"] + ["%s..."% p for p in depotPaths]): 342 label = l['label'] 343 labels.add(label) 344 345return labels 346 347# Return the set of all git tags 348defgetGitTags(): 349 gitTags =set() 350for line inread_pipe_lines(["git","tag"]): 351 tag = line.strip() 352 gitTags.add(tag) 353return gitTags 354 355defdiffTreePattern(): 356# This is a simple generator for the diff tree regex pattern. This could be 357# a class variable if this and parseDiffTreeEntry were a part of a class. 358 pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)') 359while True: 360yield pattern 361 362defparseDiffTreeEntry(entry): 363"""Parses a single diff tree entry into its component elements. 364 365 See git-diff-tree(1) manpage for details about the format of the diff 366 output. This method returns a dictionary with the following elements: 367 368 src_mode - The mode of the source file 369 dst_mode - The mode of the destination file 370 src_sha1 - The sha1 for the source file 371 dst_sha1 - The sha1 fr the destination file 372 status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc) 373 status_score - The score for the status (applicable for 'C' and 'R' 374 statuses). This is None if there is no score. 375 src - The path for the source file. 376 dst - The path for the destination file. This is only present for 377 copy or renames. If it is not present, this is None. 378 379 If the pattern is not matched, None is returned.""" 380 381 match =diffTreePattern().next().match(entry) 382if match: 383return{ 384'src_mode': match.group(1), 385'dst_mode': match.group(2), 386'src_sha1': match.group(3), 387'dst_sha1': match.group(4), 388'status': match.group(5), 389'status_score': match.group(6), 390'src': match.group(7), 391'dst': match.group(10) 392} 393return None 394 395defisModeExec(mode): 396# Returns True if the given git mode represents an executable file, 397# otherwise False. 398return mode[-3:] =="755" 399 400defisModeExecChanged(src_mode, dst_mode): 401returnisModeExec(src_mode) !=isModeExec(dst_mode) 402 403defp4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None): 404 405ifisinstance(cmd,basestring): 406 cmd ="-G "+ cmd 407 expand =True 408else: 409 cmd = ["-G"] + cmd 410 expand =False 411 412 cmd =p4_build_cmd(cmd) 413if verbose: 414 sys.stderr.write("Opening pipe:%s\n"%str(cmd)) 415 416# Use a temporary file to avoid deadlocks without 417# subprocess.communicate(), which would put another copy 418# of stdout into memory. 419 stdin_file =None 420if stdin is not None: 421 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode) 422ifisinstance(stdin,basestring): 423 stdin_file.write(stdin) 424else: 425for i in stdin: 426 stdin_file.write(i +'\n') 427 stdin_file.flush() 428 stdin_file.seek(0) 429 430 p4 = subprocess.Popen(cmd, 431 shell=expand, 432 stdin=stdin_file, 433 stdout=subprocess.PIPE) 434 435 result = [] 436try: 437while True: 438 entry = marshal.load(p4.stdout) 439if cb is not None: 440cb(entry) 441else: 442 result.append(entry) 443exceptEOFError: 444pass 445 exitCode = p4.wait() 446if exitCode !=0: 447 entry = {} 448 entry["p4ExitCode"] = exitCode 449 result.append(entry) 450 451return result 452 453defp4Cmd(cmd): 454list=p4CmdList(cmd) 455 result = {} 456for entry inlist: 457 result.update(entry) 458return result; 459 460defp4Where(depotPath): 461if not depotPath.endswith("/"): 462 depotPath +="/" 463 depotPath = depotPath +"..." 464 outputList =p4CmdList(["where", depotPath]) 465 output =None 466for entry in outputList: 467if"depotFile"in entry: 468if entry["depotFile"] == depotPath: 469 output = entry 470break 471elif"data"in entry: 472 data = entry.get("data") 473 space = data.find(" ") 474if data[:space] == depotPath: 475 output = entry 476break 477if output ==None: 478return"" 479if output["code"] =="error": 480return"" 481 clientPath ="" 482if"path"in output: 483 clientPath = output.get("path") 484elif"data"in output: 485 data = output.get("data") 486 lastSpace = data.rfind(" ") 487 clientPath = data[lastSpace +1:] 488 489if clientPath.endswith("..."): 490 clientPath = clientPath[:-3] 491return clientPath 492 493defcurrentGitBranch(): 494returnread_pipe("git name-rev HEAD").split(" ")[1].strip() 495 496defisValidGitDir(path): 497if(os.path.exists(path +"/HEAD") 498and os.path.exists(path +"/refs")and os.path.exists(path +"/objects")): 499return True; 500return False 501 502defparseRevision(ref): 503returnread_pipe("git rev-parse%s"% ref).strip() 504 505defbranchExists(ref): 506 rev =read_pipe(["git","rev-parse","-q","--verify", ref], 507 ignore_error=True) 508returnlen(rev) >0 509 510defextractLogMessageFromGitCommit(commit): 511 logMessage ="" 512 513## fixme: title is first line of commit, not 1st paragraph. 514 foundTitle =False 515for log inread_pipe_lines("git cat-file commit%s"% commit): 516if not foundTitle: 517iflen(log) ==1: 518 foundTitle =True 519continue 520 521 logMessage += log 522return logMessage 523 524defextractSettingsGitLog(log): 525 values = {} 526for line in log.split("\n"): 527 line = line.strip() 528 m = re.search(r"^ *\[git-p4: (.*)\]$", line) 529if not m: 530continue 531 532 assignments = m.group(1).split(':') 533for a in assignments: 534 vals = a.split('=') 535 key = vals[0].strip() 536 val = ('='.join(vals[1:])).strip() 537if val.endswith('\"')and val.startswith('"'): 538 val = val[1:-1] 539 540 values[key] = val 541 542 paths = values.get("depot-paths") 543if not paths: 544 paths = values.get("depot-path") 545if paths: 546 values['depot-paths'] = paths.split(',') 547return values 548 549defgitBranchExists(branch): 550 proc = subprocess.Popen(["git","rev-parse", branch], 551 stderr=subprocess.PIPE, stdout=subprocess.PIPE); 552return proc.wait() ==0; 553 554_gitConfig = {} 555defgitConfig(key, args =None):# set args to "--bool", for instance 556if not _gitConfig.has_key(key): 557 argsFilter ="" 558if args !=None: 559 argsFilter ="%s"% args 560 cmd ="git config%s%s"% (argsFilter, key) 561 _gitConfig[key] =read_pipe(cmd, ignore_error=True).strip() 562return _gitConfig[key] 563 564defgitConfigList(key): 565if not _gitConfig.has_key(key): 566 _gitConfig[key] =read_pipe("git config --get-all%s"% key, ignore_error=True).strip().split(os.linesep) 567return _gitConfig[key] 568 569defp4BranchesInGit(branchesAreInRemotes =True): 570 branches = {} 571 572 cmdline ="git rev-parse --symbolic " 573if branchesAreInRemotes: 574 cmdline +=" --remotes" 575else: 576 cmdline +=" --branches" 577 578for line inread_pipe_lines(cmdline): 579 line = line.strip() 580 581## only import to p4/ 582if not line.startswith('p4/')or line =="p4/HEAD": 583continue 584 branch = line 585 586# strip off p4 587 branch = re.sub("^p4/","", line) 588 589 branches[branch] =parseRevision(line) 590return branches 591 592deffindUpstreamBranchPoint(head ="HEAD"): 593 branches =p4BranchesInGit() 594# map from depot-path to branch name 595 branchByDepotPath = {} 596for branch in branches.keys(): 597 tip = branches[branch] 598 log =extractLogMessageFromGitCommit(tip) 599 settings =extractSettingsGitLog(log) 600if settings.has_key("depot-paths"): 601 paths =",".join(settings["depot-paths"]) 602 branchByDepotPath[paths] ="remotes/p4/"+ branch 603 604 settings =None 605 parent =0 606while parent <65535: 607 commit = head +"~%s"% parent 608 log =extractLogMessageFromGitCommit(commit) 609 settings =extractSettingsGitLog(log) 610if settings.has_key("depot-paths"): 611 paths =",".join(settings["depot-paths"]) 612if branchByDepotPath.has_key(paths): 613return[branchByDepotPath[paths], settings] 614 615 parent = parent +1 616 617return["", settings] 618 619defcreateOrUpdateBranchesFromOrigin(localRefPrefix ="refs/remotes/p4/", silent=True): 620if not silent: 621print("Creating/updating branch(es) in%sbased on origin branch(es)" 622% localRefPrefix) 623 624 originPrefix ="origin/p4/" 625 626for line inread_pipe_lines("git rev-parse --symbolic --remotes"): 627 line = line.strip() 628if(not line.startswith(originPrefix))or line.endswith("HEAD"): 629continue 630 631 headName = line[len(originPrefix):] 632 remoteHead = localRefPrefix + headName 633 originHead = line 634 635 original =extractSettingsGitLog(extractLogMessageFromGitCommit(originHead)) 636if(not original.has_key('depot-paths') 637or not original.has_key('change')): 638continue 639 640 update =False 641if notgitBranchExists(remoteHead): 642if verbose: 643print"creating%s"% remoteHead 644 update =True 645else: 646 settings =extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead)) 647if settings.has_key('change') >0: 648if settings['depot-paths'] == original['depot-paths']: 649 originP4Change =int(original['change']) 650 p4Change =int(settings['change']) 651if originP4Change > p4Change: 652print("%s(%s) is newer than%s(%s). " 653"Updating p4 branch from origin." 654% (originHead, originP4Change, 655 remoteHead, p4Change)) 656 update =True 657else: 658print("Ignoring:%swas imported from%swhile " 659"%swas imported from%s" 660% (originHead,','.join(original['depot-paths']), 661 remoteHead,','.join(settings['depot-paths']))) 662 663if update: 664system("git update-ref%s %s"% (remoteHead, originHead)) 665 666deforiginP4BranchesExist(): 667returngitBranchExists("origin")orgitBranchExists("origin/p4")orgitBranchExists("origin/p4/master") 668 669defp4ChangesForPaths(depotPaths, changeRange): 670assert depotPaths 671 cmd = ['changes'] 672for p in depotPaths: 673 cmd += ["%s...%s"% (p, changeRange)] 674 output =p4_read_pipe_lines(cmd) 675 676 changes = {} 677for line in output: 678 changeNum =int(line.split(" ")[1]) 679 changes[changeNum] =True 680 681 changelist = changes.keys() 682 changelist.sort() 683return changelist 684 685defp4PathStartsWith(path, prefix): 686# This method tries to remedy a potential mixed-case issue: 687# 688# If UserA adds //depot/DirA/file1 689# and UserB adds //depot/dira/file2 690# 691# we may or may not have a problem. If you have core.ignorecase=true, 692# we treat DirA and dira as the same directory 693 ignorecase =gitConfig("core.ignorecase","--bool") =="true" 694if ignorecase: 695return path.lower().startswith(prefix.lower()) 696return path.startswith(prefix) 697 698defgetClientSpec(): 699"""Look at the p4 client spec, create a View() object that contains 700 all the mappings, and return it.""" 701 702 specList =p4CmdList("client -o") 703iflen(specList) !=1: 704die('Output from "client -o" is%dlines, expecting 1'% 705len(specList)) 706 707# dictionary of all client parameters 708 entry = specList[0] 709 710# just the keys that start with "View" 711 view_keys = [ k for k in entry.keys()if k.startswith("View") ] 712 713# hold this new View 714 view =View() 715 716# append the lines, in order, to the view 717for view_num inrange(len(view_keys)): 718 k ="View%d"% view_num 719if k not in view_keys: 720die("Expected view key%smissing"% k) 721 view.append(entry[k]) 722 723return view 724 725defgetClientRoot(): 726"""Grab the client directory.""" 727 728 output =p4CmdList("client -o") 729iflen(output) !=1: 730die('Output from "client -o" is%dlines, expecting 1'%len(output)) 731 732 entry = output[0] 733if"Root"not in entry: 734die('Client has no "Root"') 735 736return entry["Root"] 737 738# 739# P4 wildcards are not allowed in filenames. P4 complains 740# if you simply add them, but you can force it with "-f", in 741# which case it translates them into %xx encoding internally. 742# 743defwildcard_decode(path): 744# Search for and fix just these four characters. Do % last so 745# that fixing it does not inadvertently create new %-escapes. 746# Cannot have * in a filename in windows; untested as to 747# what p4 would do in such a case. 748if not platform.system() =="Windows": 749 path = path.replace("%2A","*") 750 path = path.replace("%23","#") \ 751.replace("%40","@") \ 752.replace("%25","%") 753return path 754 755defwildcard_encode(path): 756# do % first to avoid double-encoding the %s introduced here 757 path = path.replace("%","%25") \ 758.replace("*","%2A") \ 759.replace("#","%23") \ 760.replace("@","%40") 761return path 762 763defwildcard_present(path): 764 m = re.search("[*#@%]", path) 765return m is not None 766 767class Command: 768def__init__(self): 769 self.usage ="usage: %prog [options]" 770 self.needsGit =True 771 self.verbose =False 772 773class P4UserMap: 774def__init__(self): 775 self.userMapFromPerforceServer =False 776 self.myP4UserId =None 777 778defp4UserId(self): 779if self.myP4UserId: 780return self.myP4UserId 781 782 results =p4CmdList("user -o") 783for r in results: 784if r.has_key('User'): 785 self.myP4UserId = r['User'] 786return r['User'] 787die("Could not find your p4 user id") 788 789defp4UserIsMe(self, p4User): 790# return True if the given p4 user is actually me 791 me = self.p4UserId() 792if not p4User or p4User != me: 793return False 794else: 795return True 796 797defgetUserCacheFilename(self): 798 home = os.environ.get("HOME", os.environ.get("USERPROFILE")) 799return home +"/.gitp4-usercache.txt" 800 801defgetUserMapFromPerforceServer(self): 802if self.userMapFromPerforceServer: 803return 804 self.users = {} 805 self.emails = {} 806 807for output inp4CmdList("users"): 808if not output.has_key("User"): 809continue 810 self.users[output["User"]] = output["FullName"] +" <"+ output["Email"] +">" 811 self.emails[output["Email"]] = output["User"] 812 813 814 s ='' 815for(key, val)in self.users.items(): 816 s +="%s\t%s\n"% (key.expandtabs(1), val.expandtabs(1)) 817 818open(self.getUserCacheFilename(),"wb").write(s) 819 self.userMapFromPerforceServer =True 820 821defloadUserMapFromCache(self): 822 self.users = {} 823 self.userMapFromPerforceServer =False 824try: 825 cache =open(self.getUserCacheFilename(),"rb") 826 lines = cache.readlines() 827 cache.close() 828for line in lines: 829 entry = line.strip().split("\t") 830 self.users[entry[0]] = entry[1] 831exceptIOError: 832 self.getUserMapFromPerforceServer() 833 834classP4Debug(Command): 835def__init__(self): 836 Command.__init__(self) 837 self.options = [] 838 self.description ="A tool to debug the output of p4 -G." 839 self.needsGit =False 840 841defrun(self, args): 842 j =0 843for output inp4CmdList(args): 844print'Element:%d'% j 845 j +=1 846print output 847return True 848 849classP4RollBack(Command): 850def__init__(self): 851 Command.__init__(self) 852 self.options = [ 853 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true") 854] 855 self.description ="A tool to debug the multi-branch import. Don't use :)" 856 self.rollbackLocalBranches =False 857 858defrun(self, args): 859iflen(args) !=1: 860return False 861 maxChange =int(args[0]) 862 863if"p4ExitCode"inp4Cmd("changes -m 1"): 864die("Problems executing p4"); 865 866if self.rollbackLocalBranches: 867 refPrefix ="refs/heads/" 868 lines =read_pipe_lines("git rev-parse --symbolic --branches") 869else: 870 refPrefix ="refs/remotes/" 871 lines =read_pipe_lines("git rev-parse --symbolic --remotes") 872 873for line in lines: 874if self.rollbackLocalBranches or(line.startswith("p4/")and line !="p4/HEAD\n"): 875 line = line.strip() 876 ref = refPrefix + line 877 log =extractLogMessageFromGitCommit(ref) 878 settings =extractSettingsGitLog(log) 879 880 depotPaths = settings['depot-paths'] 881 change = settings['change'] 882 883 changed =False 884 885iflen(p4Cmd("changes -m 1 "+' '.join(['%s...@%s'% (p, maxChange) 886for p in depotPaths]))) ==0: 887print"Branch%sdid not exist at change%s, deleting."% (ref, maxChange) 888system("git update-ref -d%s`git rev-parse%s`"% (ref, ref)) 889continue 890 891while change andint(change) > maxChange: 892 changed =True 893if self.verbose: 894print"%sis at%s; rewinding towards%s"% (ref, change, maxChange) 895system("git update-ref%s\"%s^\""% (ref, ref)) 896 log =extractLogMessageFromGitCommit(ref) 897 settings =extractSettingsGitLog(log) 898 899 900 depotPaths = settings['depot-paths'] 901 change = settings['change'] 902 903if changed: 904print"%srewound to%s"% (ref, change) 905 906return True 907 908classP4Submit(Command, P4UserMap): 909 910 conflict_behavior_choices = ("ask","skip","quit") 911 912def__init__(self): 913 Command.__init__(self) 914 P4UserMap.__init__(self) 915 self.options = [ 916 optparse.make_option("--origin", dest="origin"), 917 optparse.make_option("-M", dest="detectRenames", action="store_true"), 918# preserve the user, requires relevant p4 permissions 919 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"), 920 optparse.make_option("--export-labels", dest="exportLabels", action="store_true"), 921 optparse.make_option("--dry-run","-n", dest="dry_run", action="store_true"), 922 optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"), 923 optparse.make_option("--conflict", dest="conflict_behavior", 924 choices=self.conflict_behavior_choices) 925] 926 self.description ="Submit changes from git to the perforce depot." 927 self.usage +=" [name of git branch to submit into perforce depot]" 928 self.origin ="" 929 self.detectRenames =False 930 self.preserveUser =gitConfig("git-p4.preserveUser").lower() =="true" 931 self.dry_run =False 932 self.prepare_p4_only =False 933 self.conflict_behavior =None 934 self.isWindows = (platform.system() =="Windows") 935 self.exportLabels =False 936 self.p4HasMoveCommand =p4_has_move_command() 937 938defcheck(self): 939iflen(p4CmdList("opened ...")) >0: 940die("You have files opened with perforce! Close them before starting the sync.") 941 942defseparate_jobs_from_description(self, message): 943"""Extract and return a possible Jobs field in the commit 944 message. It goes into a separate section in the p4 change 945 specification. 946 947 A jobs line starts with "Jobs:" and looks like a new field 948 in a form. Values are white-space separated on the same 949 line or on following lines that start with a tab. 950 951 This does not parse and extract the full git commit message 952 like a p4 form. It just sees the Jobs: line as a marker 953 to pass everything from then on directly into the p4 form, 954 but outside the description section. 955 956 Return a tuple (stripped log message, jobs string).""" 957 958 m = re.search(r'^Jobs:', message, re.MULTILINE) 959if m is None: 960return(message,None) 961 962 jobtext = message[m.start():] 963 stripped_message = message[:m.start()].rstrip() 964return(stripped_message, jobtext) 965 966defprepareLogMessage(self, template, message, jobs): 967"""Edits the template returned from "p4 change -o" to insert 968 the message in the Description field, and the jobs text in 969 the Jobs field.""" 970 result ="" 971 972 inDescriptionSection =False 973 974for line in template.split("\n"): 975if line.startswith("#"): 976 result += line +"\n" 977continue 978 979if inDescriptionSection: 980if line.startswith("Files:")or line.startswith("Jobs:"): 981 inDescriptionSection =False 982# insert Jobs section 983if jobs: 984 result += jobs +"\n" 985else: 986continue 987else: 988if line.startswith("Description:"): 989 inDescriptionSection =True 990 line +="\n" 991for messageLine in message.split("\n"): 992 line +="\t"+ messageLine +"\n" 993 994 result += line +"\n" 995 996return result 997 998defpatchRCSKeywords(self,file, pattern): 999# Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern1000(handle, outFileName) = tempfile.mkstemp(dir='.')1001try:1002 outFile = os.fdopen(handle,"w+")1003 inFile =open(file,"r")1004 regexp = re.compile(pattern, re.VERBOSE)1005for line in inFile.readlines():1006 line = regexp.sub(r'$\1$', line)1007 outFile.write(line)1008 inFile.close()1009 outFile.close()1010# Forcibly overwrite the original file1011 os.unlink(file)1012 shutil.move(outFileName,file)1013except:1014# cleanup our temporary file1015 os.unlink(outFileName)1016print"Failed to strip RCS keywords in%s"%file1017raise10181019print"Patched up RCS keywords in%s"%file10201021defp4UserForCommit(self,id):1022# Return the tuple (perforce user,git email) for a given git commit id1023 self.getUserMapFromPerforceServer()1024 gitEmail =read_pipe("git log --max-count=1 --format='%%ae'%s"%id)1025 gitEmail = gitEmail.strip()1026if not self.emails.has_key(gitEmail):1027return(None,gitEmail)1028else:1029return(self.emails[gitEmail],gitEmail)10301031defcheckValidP4Users(self,commits):1032# check if any git authors cannot be mapped to p4 users1033foridin commits:1034(user,email) = self.p4UserForCommit(id)1035if not user:1036 msg ="Cannot find p4 user for email%sin commit%s."% (email,id)1037ifgitConfig('git-p4.allowMissingP4Users').lower() =="true":1038print"%s"% msg1039else:1040die("Error:%s\nSet git-p4.allowMissingP4Users to true to allow this."% msg)10411042deflastP4Changelist(self):1043# Get back the last changelist number submitted in this client spec. This1044# then gets used to patch up the username in the change. If the same1045# client spec is being used by multiple processes then this might go1046# wrong.1047 results =p4CmdList("client -o")# find the current client1048 client =None1049for r in results:1050if r.has_key('Client'):1051 client = r['Client']1052break1053if not client:1054die("could not get client spec")1055 results =p4CmdList(["changes","-c", client,"-m","1"])1056for r in results:1057if r.has_key('change'):1058return r['change']1059die("Could not get changelist number for last submit - cannot patch up user details")10601061defmodifyChangelistUser(self, changelist, newUser):1062# fixup the user field of a changelist after it has been submitted.1063 changes =p4CmdList("change -o%s"% changelist)1064iflen(changes) !=1:1065die("Bad output from p4 change modifying%sto user%s"%1066(changelist, newUser))10671068 c = changes[0]1069if c['User'] == newUser:return# nothing to do1070 c['User'] = newUser1071input= marshal.dumps(c)10721073 result =p4CmdList("change -f -i", stdin=input)1074for r in result:1075if r.has_key('code'):1076if r['code'] =='error':1077die("Could not modify user field of changelist%sto%s:%s"% (changelist, newUser, r['data']))1078if r.has_key('data'):1079print("Updated user field for changelist%sto%s"% (changelist, newUser))1080return1081die("Could not modify user field of changelist%sto%s"% (changelist, newUser))10821083defcanChangeChangelists(self):1084# check to see if we have p4 admin or super-user permissions, either of1085# which are required to modify changelists.1086 results =p4CmdList(["protects", self.depotPath])1087for r in results:1088if r.has_key('perm'):1089if r['perm'] =='admin':1090return11091if r['perm'] =='super':1092return11093return010941095defprepareSubmitTemplate(self):1096"""Run "p4 change -o" to grab a change specification template.1097 This does not use "p4 -G", as it is nice to keep the submission1098 template in original order, since a human might edit it.10991100 Remove lines in the Files section that show changes to files1101 outside the depot path we're committing into."""11021103 template =""1104 inFilesSection =False1105for line inp4_read_pipe_lines(['change','-o']):1106if line.endswith("\r\n"):1107 line = line[:-2] +"\n"1108if inFilesSection:1109if line.startswith("\t"):1110# path starts and ends with a tab1111 path = line[1:]1112 lastTab = path.rfind("\t")1113if lastTab != -1:1114 path = path[:lastTab]1115if notp4PathStartsWith(path, self.depotPath):1116continue1117else:1118 inFilesSection =False1119else:1120if line.startswith("Files:"):1121 inFilesSection =True11221123 template += line11241125return template11261127defedit_template(self, template_file):1128"""Invoke the editor to let the user change the submission1129 message. Return true if okay to continue with the submit."""11301131# if configured to skip the editing part, just submit1132ifgitConfig("git-p4.skipSubmitEdit") =="true":1133return True11341135# look at the modification time, to check later if the user saved1136# the file1137 mtime = os.stat(template_file).st_mtime11381139# invoke the editor1140if os.environ.has_key("P4EDITOR")and(os.environ.get("P4EDITOR") !=""):1141 editor = os.environ.get("P4EDITOR")1142else:1143 editor =read_pipe("git var GIT_EDITOR").strip()1144system(editor +" "+ template_file)11451146# If the file was not saved, prompt to see if this patch should1147# be skipped. But skip this verification step if configured so.1148ifgitConfig("git-p4.skipSubmitEditCheck") =="true":1149return True11501151# modification time updated means user saved the file1152if os.stat(template_file).st_mtime > mtime:1153return True11541155while True:1156 response =raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")1157if response =='y':1158return True1159if response =='n':1160return False11611162defapplyCommit(self,id):1163"""Apply one commit, return True if it succeeded."""11641165print"Applying",read_pipe(["git","show","-s",1166"--format=format:%h%s",id])11671168(p4User, gitEmail) = self.p4UserForCommit(id)11691170 diff =read_pipe_lines("git diff-tree -r%s\"%s^\" \"%s\""% (self.diffOpts,id,id))1171 filesToAdd =set()1172 filesToDelete =set()1173 editedFiles =set()1174 pureRenameCopy =set()1175 filesToChangeExecBit = {}11761177for line in diff:1178 diff =parseDiffTreeEntry(line)1179 modifier = diff['status']1180 path = diff['src']1181if modifier =="M":1182p4_edit(path)1183ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1184 filesToChangeExecBit[path] = diff['dst_mode']1185 editedFiles.add(path)1186elif modifier =="A":1187 filesToAdd.add(path)1188 filesToChangeExecBit[path] = diff['dst_mode']1189if path in filesToDelete:1190 filesToDelete.remove(path)1191elif modifier =="D":1192 filesToDelete.add(path)1193if path in filesToAdd:1194 filesToAdd.remove(path)1195elif modifier =="C":1196 src, dest = diff['src'], diff['dst']1197p4_integrate(src, dest)1198 pureRenameCopy.add(dest)1199if diff['src_sha1'] != diff['dst_sha1']:1200p4_edit(dest)1201 pureRenameCopy.discard(dest)1202ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1203p4_edit(dest)1204 pureRenameCopy.discard(dest)1205 filesToChangeExecBit[dest] = diff['dst_mode']1206 os.unlink(dest)1207 editedFiles.add(dest)1208elif modifier =="R":1209 src, dest = diff['src'], diff['dst']1210if self.p4HasMoveCommand:1211p4_edit(src)# src must be open before move1212p4_move(src, dest)# opens for (move/delete, move/add)1213else:1214p4_integrate(src, dest)1215if diff['src_sha1'] != diff['dst_sha1']:1216p4_edit(dest)1217else:1218 pureRenameCopy.add(dest)1219ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1220if not self.p4HasMoveCommand:1221p4_edit(dest)# with move: already open, writable1222 filesToChangeExecBit[dest] = diff['dst_mode']1223if not self.p4HasMoveCommand:1224 os.unlink(dest)1225 filesToDelete.add(src)1226 editedFiles.add(dest)1227else:1228die("unknown modifier%sfor%s"% (modifier, path))12291230 diffcmd ="git format-patch -k --stdout\"%s^\"..\"%s\""% (id,id)1231 patchcmd = diffcmd +" | git apply "1232 tryPatchCmd = patchcmd +"--check -"1233 applyPatchCmd = patchcmd +"--check --apply -"1234 patch_succeeded =True12351236if os.system(tryPatchCmd) !=0:1237 fixed_rcs_keywords =False1238 patch_succeeded =False1239print"Unfortunately applying the change failed!"12401241# Patch failed, maybe it's just RCS keyword woes. Look through1242# the patch to see if that's possible.1243ifgitConfig("git-p4.attemptRCSCleanup","--bool") =="true":1244file=None1245 pattern =None1246 kwfiles = {}1247forfilein editedFiles | filesToDelete:1248# did this file's delta contain RCS keywords?1249 pattern =p4_keywords_regexp_for_file(file)12501251if pattern:1252# this file is a possibility...look for RCS keywords.1253 regexp = re.compile(pattern, re.VERBOSE)1254for line inread_pipe_lines(["git","diff","%s^..%s"% (id,id),file]):1255if regexp.search(line):1256if verbose:1257print"got keyword match on%sin%sin%s"% (pattern, line,file)1258 kwfiles[file] = pattern1259break12601261forfilein kwfiles:1262if verbose:1263print"zapping%swith%s"% (line,pattern)1264 self.patchRCSKeywords(file, kwfiles[file])1265 fixed_rcs_keywords =True12661267if fixed_rcs_keywords:1268print"Retrying the patch with RCS keywords cleaned up"1269if os.system(tryPatchCmd) ==0:1270 patch_succeeded =True12711272if not patch_succeeded:1273for f in editedFiles:1274p4_revert(f)1275return False12761277#1278# Apply the patch for real, and do add/delete/+x handling.1279#1280system(applyPatchCmd)12811282for f in filesToAdd:1283p4_add(f)1284for f in filesToDelete:1285p4_revert(f)1286p4_delete(f)12871288# Set/clear executable bits1289for f in filesToChangeExecBit.keys():1290 mode = filesToChangeExecBit[f]1291setP4ExecBit(f, mode)12921293#1294# Build p4 change description, starting with the contents1295# of the git commit message.1296#1297 logMessage =extractLogMessageFromGitCommit(id)1298 logMessage = logMessage.strip()1299(logMessage, jobs) = self.separate_jobs_from_description(logMessage)13001301 template = self.prepareSubmitTemplate()1302 submitTemplate = self.prepareLogMessage(template, logMessage, jobs)13031304if self.preserveUser:1305 submitTemplate +="\n######## Actual user%s, modified after commit\n"% p4User13061307if self.checkAuthorship and not self.p4UserIsMe(p4User):1308 submitTemplate +="######## git author%sdoes not match your p4 account.\n"% gitEmail1309 submitTemplate +="######## Use option --preserve-user to modify authorship.\n"1310 submitTemplate +="######## Variable git-p4.skipUserNameCheck hides this message.\n"13111312 separatorLine ="######## everything below this line is just the diff #######\n"13131314# diff1315if os.environ.has_key("P4DIFF"):1316del(os.environ["P4DIFF"])1317 diff =""1318for editedFile in editedFiles:1319 diff +=p4_read_pipe(['diff','-du',1320wildcard_encode(editedFile)])13211322# new file diff1323 newdiff =""1324for newFile in filesToAdd:1325 newdiff +="==== new file ====\n"1326 newdiff +="--- /dev/null\n"1327 newdiff +="+++%s\n"% newFile1328 f =open(newFile,"r")1329for line in f.readlines():1330 newdiff +="+"+ line1331 f.close()13321333# change description file: submitTemplate, separatorLine, diff, newdiff1334(handle, fileName) = tempfile.mkstemp()1335 tmpFile = os.fdopen(handle,"w+")1336if self.isWindows:1337 submitTemplate = submitTemplate.replace("\n","\r\n")1338 separatorLine = separatorLine.replace("\n","\r\n")1339 newdiff = newdiff.replace("\n","\r\n")1340 tmpFile.write(submitTemplate + separatorLine + diff + newdiff)1341 tmpFile.close()13421343if self.prepare_p4_only:1344#1345# Leave the p4 tree prepared, and the submit template around1346# and let the user decide what to do next1347#1348print1349print"P4 workspace prepared for submission."1350print"To submit or revert, go to client workspace"1351print" "+ self.clientPath1352print1353print"To submit, use\"p4 submit\"to write a new description,"1354print"or\"p4 submit -i%s\"to use the one prepared by" \1355"\"git p4\"."% fileName1356print"You can delete the file\"%s\"when finished."% fileName13571358if self.preserveUser and p4User and not self.p4UserIsMe(p4User):1359print"To preserve change ownership by user%s, you must\n" \1360"do\"p4 change -f <change>\"after submitting and\n" \1361"edit the User field."1362if pureRenameCopy:1363print"After submitting, renamed files must be re-synced."1364print"Invoke\"p4 sync -f\"on each of these files:"1365for f in pureRenameCopy:1366print" "+ f13671368print1369print"To revert the changes, use\"p4 revert ...\", and delete"1370print"the submit template file\"%s\""% fileName1371if filesToAdd:1372print"Since the commit adds new files, they must be deleted:"1373for f in filesToAdd:1374print" "+ f1375print1376return True13771378#1379# Let the user edit the change description, then submit it.1380#1381if self.edit_template(fileName):1382# read the edited message and submit1383 ret =True1384 tmpFile =open(fileName,"rb")1385 message = tmpFile.read()1386 tmpFile.close()1387 submitTemplate = message[:message.index(separatorLine)]1388if self.isWindows:1389 submitTemplate = submitTemplate.replace("\r\n","\n")1390p4_write_pipe(['submit','-i'], submitTemplate)13911392if self.preserveUser:1393if p4User:1394# Get last changelist number. Cannot easily get it from1395# the submit command output as the output is1396# unmarshalled.1397 changelist = self.lastP4Changelist()1398 self.modifyChangelistUser(changelist, p4User)13991400# The rename/copy happened by applying a patch that created a1401# new file. This leaves it writable, which confuses p4.1402for f in pureRenameCopy:1403p4_sync(f,"-f")14041405else:1406# skip this patch1407 ret =False1408print"Submission cancelled, undoing p4 changes."1409for f in editedFiles:1410p4_revert(f)1411for f in filesToAdd:1412p4_revert(f)1413 os.remove(f)1414for f in filesToDelete:1415p4_revert(f)14161417 os.remove(fileName)1418return ret14191420# Export git tags as p4 labels. Create a p4 label and then tag1421# with that.1422defexportGitTags(self, gitTags):1423 validLabelRegexp =gitConfig("git-p4.labelExportRegexp")1424iflen(validLabelRegexp) ==0:1425 validLabelRegexp = defaultLabelRegexp1426 m = re.compile(validLabelRegexp)14271428for name in gitTags:14291430if not m.match(name):1431if verbose:1432print"tag%sdoes not match regexp%s"% (name, validLabelRegexp)1433continue14341435# Get the p4 commit this corresponds to1436 logMessage =extractLogMessageFromGitCommit(name)1437 values =extractSettingsGitLog(logMessage)14381439if not values.has_key('change'):1440# a tag pointing to something not sent to p4; ignore1441if verbose:1442print"git tag%sdoes not give a p4 commit"% name1443continue1444else:1445 changelist = values['change']14461447# Get the tag details.1448 inHeader =True1449 isAnnotated =False1450 body = []1451for l inread_pipe_lines(["git","cat-file","-p", name]):1452 l = l.strip()1453if inHeader:1454if re.match(r'tag\s+', l):1455 isAnnotated =True1456elif re.match(r'\s*$', l):1457 inHeader =False1458continue1459else:1460 body.append(l)14611462if not isAnnotated:1463 body = ["lightweight tag imported by git p4\n"]14641465# Create the label - use the same view as the client spec we are using1466 clientSpec =getClientSpec()14671468 labelTemplate ="Label:%s\n"% name1469 labelTemplate +="Description:\n"1470for b in body:1471 labelTemplate +="\t"+ b +"\n"1472 labelTemplate +="View:\n"1473for mapping in clientSpec.mappings:1474 labelTemplate +="\t%s\n"% mapping.depot_side.path14751476if self.dry_run:1477print"Would create p4 label%sfor tag"% name1478elif self.prepare_p4_only:1479print"Not creating p4 label%sfor tag due to option" \1480" --prepare-p4-only"% name1481else:1482p4_write_pipe(["label","-i"], labelTemplate)14831484# Use the label1485p4_system(["tag","-l", name] +1486["%s@%s"% (mapping.depot_side.path, changelist)for mapping in clientSpec.mappings])14871488if verbose:1489print"created p4 label for tag%s"% name14901491defrun(self, args):1492iflen(args) ==0:1493 self.master =currentGitBranch()1494iflen(self.master) ==0or notgitBranchExists("refs/heads/%s"% self.master):1495die("Detecting current git branch failed!")1496eliflen(args) ==1:1497 self.master = args[0]1498if notbranchExists(self.master):1499die("Branch%sdoes not exist"% self.master)1500else:1501return False15021503 allowSubmit =gitConfig("git-p4.allowSubmit")1504iflen(allowSubmit) >0and not self.master in allowSubmit.split(","):1505die("%sis not in git-p4.allowSubmit"% self.master)15061507[upstream, settings] =findUpstreamBranchPoint()1508 self.depotPath = settings['depot-paths'][0]1509iflen(self.origin) ==0:1510 self.origin = upstream15111512if self.preserveUser:1513if not self.canChangeChangelists():1514die("Cannot preserve user names without p4 super-user or admin permissions")15151516# if not set from the command line, try the config file1517if self.conflict_behavior is None:1518 val =gitConfig("git-p4.conflict")1519if val:1520if val not in self.conflict_behavior_choices:1521die("Invalid value '%s' for config git-p4.conflict"% val)1522else:1523 val ="ask"1524 self.conflict_behavior = val15251526if self.verbose:1527print"Origin branch is "+ self.origin15281529iflen(self.depotPath) ==0:1530print"Internal error: cannot locate perforce depot path from existing branches"1531 sys.exit(128)15321533 self.useClientSpec =False1534ifgitConfig("git-p4.useclientspec","--bool") =="true":1535 self.useClientSpec =True1536if self.useClientSpec:1537 self.clientSpecDirs =getClientSpec()15381539if self.useClientSpec:1540# all files are relative to the client spec1541 self.clientPath =getClientRoot()1542else:1543 self.clientPath =p4Where(self.depotPath)15441545if self.clientPath =="":1546die("Error: Cannot locate perforce checkout of%sin client view"% self.depotPath)15471548print"Perforce checkout for depot path%slocated at%s"% (self.depotPath, self.clientPath)1549 self.oldWorkingDirectory = os.getcwd()15501551# ensure the clientPath exists1552 new_client_dir =False1553if not os.path.exists(self.clientPath):1554 new_client_dir =True1555 os.makedirs(self.clientPath)15561557chdir(self.clientPath)1558if self.dry_run:1559print"Would synchronize p4 checkout in%s"% self.clientPath1560else:1561print"Synchronizing p4 checkout..."1562if new_client_dir:1563# old one was destroyed, and maybe nobody told p41564p4_sync("...","-f")1565else:1566p4_sync("...")1567 self.check()15681569 commits = []1570for line inread_pipe_lines("git rev-list --no-merges%s..%s"% (self.origin, self.master)):1571 commits.append(line.strip())1572 commits.reverse()15731574if self.preserveUser or(gitConfig("git-p4.skipUserNameCheck") =="true"):1575 self.checkAuthorship =False1576else:1577 self.checkAuthorship =True15781579if self.preserveUser:1580 self.checkValidP4Users(commits)15811582#1583# Build up a set of options to be passed to diff when1584# submitting each commit to p4.1585#1586if self.detectRenames:1587# command-line -M arg1588 self.diffOpts ="-M"1589else:1590# If not explicitly set check the config variable1591 detectRenames =gitConfig("git-p4.detectRenames")15921593if detectRenames.lower() =="false"or detectRenames =="":1594 self.diffOpts =""1595elif detectRenames.lower() =="true":1596 self.diffOpts ="-M"1597else:1598 self.diffOpts ="-M%s"% detectRenames15991600# no command-line arg for -C or --find-copies-harder, just1601# config variables1602 detectCopies =gitConfig("git-p4.detectCopies")1603if detectCopies.lower() =="false"or detectCopies =="":1604pass1605elif detectCopies.lower() =="true":1606 self.diffOpts +=" -C"1607else:1608 self.diffOpts +=" -C%s"% detectCopies16091610ifgitConfig("git-p4.detectCopiesHarder","--bool") =="true":1611 self.diffOpts +=" --find-copies-harder"16121613#1614# Apply the commits, one at a time. On failure, ask if should1615# continue to try the rest of the patches, or quit.1616#1617if self.dry_run:1618print"Would apply"1619 applied = []1620 last =len(commits) -11621for i, commit inenumerate(commits):1622if self.dry_run:1623print" ",read_pipe(["git","show","-s",1624"--format=format:%h%s", commit])1625 ok =True1626else:1627 ok = self.applyCommit(commit)1628if ok:1629 applied.append(commit)1630else:1631if self.prepare_p4_only and i < last:1632print"Processing only the first commit due to option" \1633" --prepare-p4-only"1634break1635if i < last:1636 quit =False1637while True:1638# prompt for what to do, or use the option/variable1639if self.conflict_behavior =="ask":1640print"What do you want to do?"1641 response =raw_input("[s]kip this commit but apply"1642" the rest, or [q]uit? ")1643if not response:1644continue1645elif self.conflict_behavior =="skip":1646 response ="s"1647elif self.conflict_behavior =="quit":1648 response ="q"1649else:1650die("Unknown conflict_behavior '%s'"%1651 self.conflict_behavior)16521653if response[0] =="s":1654print"Skipping this commit, but applying the rest"1655break1656if response[0] =="q":1657print"Quitting"1658 quit =True1659break1660if quit:1661break16621663chdir(self.oldWorkingDirectory)16641665if self.dry_run:1666pass1667elif self.prepare_p4_only:1668pass1669eliflen(commits) ==len(applied):1670print"All commits applied!"16711672 sync =P4Sync()1673 sync.run([])16741675 rebase =P4Rebase()1676 rebase.rebase()16771678else:1679iflen(applied) ==0:1680print"No commits applied."1681else:1682print"Applied only the commits marked with '*':"1683for c in commits:1684if c in applied:1685 star ="*"1686else:1687 star =" "1688print star,read_pipe(["git","show","-s",1689"--format=format:%h%s", c])1690print"You will have to do 'git p4 sync' and rebase."16911692ifgitConfig("git-p4.exportLabels","--bool") =="true":1693 self.exportLabels =True16941695if self.exportLabels:1696 p4Labels =getP4Labels(self.depotPath)1697 gitTags =getGitTags()16981699 missingGitTags = gitTags - p4Labels1700 self.exportGitTags(missingGitTags)17011702# exit with error unless everything applied perfecly1703iflen(commits) !=len(applied):1704 sys.exit(1)17051706return True17071708classView(object):1709"""Represent a p4 view ("p4 help views"), and map files in a1710 repo according to the view."""17111712classPath(object):1713"""A depot or client path, possibly containing wildcards.1714 The only one supported is ... at the end, currently.1715 Initialize with the full path, with //depot or //client."""17161717def__init__(self, path, is_depot):1718 self.path = path1719 self.is_depot = is_depot1720 self.find_wildcards()1721# remember the prefix bit, useful for relative mappings1722 m = re.match("(//[^/]+/)", self.path)1723if not m:1724die("Path%sdoes not start with //prefix/"% self.path)1725 prefix = m.group(1)1726if not self.is_depot:1727# strip //client/ on client paths1728 self.path = self.path[len(prefix):]17291730deffind_wildcards(self):1731"""Make sure wildcards are valid, and set up internal1732 variables."""17331734 self.ends_triple_dot =False1735# There are three wildcards allowed in p4 views1736# (see "p4 help views"). This code knows how to1737# handle "..." (only at the end), but cannot deal with1738# "%%n" or "*". Only check the depot_side, as p4 should1739# validate that the client_side matches too.1740if re.search(r'%%[1-9]', self.path):1741die("Can't handle%%n wildcards in view:%s"% self.path)1742if self.path.find("*") >=0:1743die("Can't handle * wildcards in view:%s"% self.path)1744 triple_dot_index = self.path.find("...")1745if triple_dot_index >=0:1746if triple_dot_index !=len(self.path) -3:1747die("Can handle only single ... wildcard, at end:%s"%1748 self.path)1749 self.ends_triple_dot =True17501751defensure_compatible(self, other_path):1752"""Make sure the wildcards agree."""1753if self.ends_triple_dot != other_path.ends_triple_dot:1754die("Both paths must end with ... if either does;\n"+1755"paths:%s %s"% (self.path, other_path.path))17561757defmatch_wildcards(self, test_path):1758"""See if this test_path matches us, and fill in the value1759 of the wildcards if so. Returns a tuple of1760 (True|False, wildcards[]). For now, only the ... at end1761 is supported, so at most one wildcard."""1762if self.ends_triple_dot:1763 dotless = self.path[:-3]1764if test_path.startswith(dotless):1765 wildcard = test_path[len(dotless):]1766return(True, [ wildcard ])1767else:1768if test_path == self.path:1769return(True, [])1770return(False, [])17711772defmatch(self, test_path):1773"""Just return if it matches; don't bother with the wildcards."""1774 b, _ = self.match_wildcards(test_path)1775return b17761777deffill_in_wildcards(self, wildcards):1778"""Return the relative path, with the wildcards filled in1779 if there are any."""1780if self.ends_triple_dot:1781return self.path[:-3] + wildcards[0]1782else:1783return self.path17841785classMapping(object):1786def__init__(self, depot_side, client_side, overlay, exclude):1787# depot_side is without the trailing /... if it had one1788 self.depot_side = View.Path(depot_side, is_depot=True)1789 self.client_side = View.Path(client_side, is_depot=False)1790 self.overlay = overlay # started with "+"1791 self.exclude = exclude # started with "-"1792assert not(self.overlay and self.exclude)1793 self.depot_side.ensure_compatible(self.client_side)17941795def__str__(self):1796 c =" "1797if self.overlay:1798 c ="+"1799if self.exclude:1800 c ="-"1801return"View.Mapping:%s%s->%s"% \1802(c, self.depot_side.path, self.client_side.path)18031804defmap_depot_to_client(self, depot_path):1805"""Calculate the client path if using this mapping on the1806 given depot path; does not consider the effect of other1807 mappings in a view. Even excluded mappings are returned."""1808 matches, wildcards = self.depot_side.match_wildcards(depot_path)1809if not matches:1810return""1811 client_path = self.client_side.fill_in_wildcards(wildcards)1812return client_path18131814#1815# View methods1816#1817def__init__(self):1818 self.mappings = []18191820defappend(self, view_line):1821"""Parse a view line, splitting it into depot and client1822 sides. Append to self.mappings, preserving order."""18231824# Split the view line into exactly two words. P4 enforces1825# structure on these lines that simplifies this quite a bit.1826#1827# Either or both words may be double-quoted.1828# Single quotes do not matter.1829# Double-quote marks cannot occur inside the words.1830# A + or - prefix is also inside the quotes.1831# There are no quotes unless they contain a space.1832# The line is already white-space stripped.1833# The two words are separated by a single space.1834#1835if view_line[0] =='"':1836# First word is double quoted. Find its end.1837 close_quote_index = view_line.find('"',1)1838if close_quote_index <=0:1839die("No first-word closing quote found:%s"% view_line)1840 depot_side = view_line[1:close_quote_index]1841# skip closing quote and space1842 rhs_index = close_quote_index +1+11843else:1844 space_index = view_line.find(" ")1845if space_index <=0:1846die("No word-splitting space found:%s"% view_line)1847 depot_side = view_line[0:space_index]1848 rhs_index = space_index +118491850if view_line[rhs_index] =='"':1851# Second word is double quoted. Make sure there is a1852# double quote at the end too.1853if not view_line.endswith('"'):1854die("View line with rhs quote should end with one:%s"%1855 view_line)1856# skip the quotes1857 client_side = view_line[rhs_index+1:-1]1858else:1859 client_side = view_line[rhs_index:]18601861# prefix + means overlay on previous mapping1862 overlay =False1863if depot_side.startswith("+"):1864 overlay =True1865 depot_side = depot_side[1:]18661867# prefix - means exclude this path1868 exclude =False1869if depot_side.startswith("-"):1870 exclude =True1871 depot_side = depot_side[1:]18721873 m = View.Mapping(depot_side, client_side, overlay, exclude)1874 self.mappings.append(m)18751876defmap_in_client(self, depot_path):1877"""Return the relative location in the client where this1878 depot file should live. Returns "" if the file should1879 not be mapped in the client."""18801881 paths_filled = []1882 client_path =""18831884# look at later entries first1885for m in self.mappings[::-1]:18861887# see where will this path end up in the client1888 p = m.map_depot_to_client(depot_path)18891890if p =="":1891# Depot path does not belong in client. Must remember1892# this, as previous items should not cause files to1893# exist in this path either. Remember that the list is1894# being walked from the end, which has higher precedence.1895# Overlap mappings do not exclude previous mappings.1896if not m.overlay:1897 paths_filled.append(m.client_side)18981899else:1900# This mapping matched; no need to search any further.1901# But, the mapping could be rejected if the client path1902# has already been claimed by an earlier mapping (i.e.1903# one later in the list, which we are walking backwards).1904 already_mapped_in_client =False1905for f in paths_filled:1906# this is View.Path.match1907if f.match(p):1908 already_mapped_in_client =True1909break1910if not already_mapped_in_client:1911# Include this file, unless it is from a line that1912# explicitly said to exclude it.1913if not m.exclude:1914 client_path = p19151916# a match, even if rejected, always stops the search1917break19181919return client_path19201921classP4Sync(Command, P4UserMap):1922 delete_actions = ("delete","move/delete","purge")19231924def__init__(self):1925 Command.__init__(self)1926 P4UserMap.__init__(self)1927 self.options = [1928 optparse.make_option("--branch", dest="branch"),1929 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),1930 optparse.make_option("--changesfile", dest="changesFile"),1931 optparse.make_option("--silent", dest="silent", action="store_true"),1932 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),1933 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),1934 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",1935help="Import into refs/heads/ , not refs/remotes"),1936 optparse.make_option("--max-changes", dest="maxChanges"),1937 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',1938help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),1939 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',1940help="Only sync files that are included in the Perforce Client Spec")1941]1942 self.description ="""Imports from Perforce into a git repository.\n1943 example:1944 //depot/my/project/ -- to import the current head1945 //depot/my/project/@all -- to import everything1946 //depot/my/project/@1,6 -- to import only from revision 1 to 619471948 (a ... is not needed in the path p4 specification, it's added implicitly)"""19491950 self.usage +=" //depot/path[@revRange]"1951 self.silent =False1952 self.createdBranches =set()1953 self.committedChanges =set()1954 self.branch =""1955 self.detectBranches =False1956 self.detectLabels =False1957 self.importLabels =False1958 self.changesFile =""1959 self.syncWithOrigin =True1960 self.importIntoRemotes =True1961 self.maxChanges =""1962 self.isWindows = (platform.system() =="Windows")1963 self.keepRepoPath =False1964 self.depotPaths =None1965 self.p4BranchesInGit = []1966 self.cloneExclude = []1967 self.useClientSpec =False1968 self.useClientSpec_from_options =False1969 self.clientSpecDirs =None1970 self.tempBranches = []1971 self.tempBranchLocation ="git-p4-tmp"19721973ifgitConfig("git-p4.syncFromOrigin") =="false":1974 self.syncWithOrigin =False19751976# Force a checkpoint in fast-import and wait for it to finish1977defcheckpoint(self):1978 self.gitStream.write("checkpoint\n\n")1979 self.gitStream.write("progress checkpoint\n\n")1980 out = self.gitOutput.readline()1981if self.verbose:1982print"checkpoint finished: "+ out19831984defextractFilesFromCommit(self, commit):1985 self.cloneExclude = [re.sub(r"\.\.\.$","", path)1986for path in self.cloneExclude]1987 files = []1988 fnum =01989while commit.has_key("depotFile%s"% fnum):1990 path = commit["depotFile%s"% fnum]19911992if[p for p in self.cloneExclude1993ifp4PathStartsWith(path, p)]:1994 found =False1995else:1996 found = [p for p in self.depotPaths1997ifp4PathStartsWith(path, p)]1998if not found:1999 fnum = fnum +12000continue20012002file= {}2003file["path"] = path2004file["rev"] = commit["rev%s"% fnum]2005file["action"] = commit["action%s"% fnum]2006file["type"] = commit["type%s"% fnum]2007 files.append(file)2008 fnum = fnum +12009return files20102011defstripRepoPath(self, path, prefixes):2012"""When streaming files, this is called to map a p4 depot path2013 to where it should go in git. The prefixes are either2014 self.depotPaths, or self.branchPrefixes in the case of2015 branch detection."""20162017if self.useClientSpec:2018# branch detection moves files up a level (the branch name)2019# from what client spec interpretation gives2020 path = self.clientSpecDirs.map_in_client(path)2021if self.detectBranches:2022for b in self.knownBranches:2023if path.startswith(b +"/"):2024 path = path[len(b)+1:]20252026elif self.keepRepoPath:2027# Preserve everything in relative path name except leading2028# //depot/; just look at first prefix as they all should2029# be in the same depot.2030 depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])2031ifp4PathStartsWith(path, depot):2032 path = path[len(depot):]20332034else:2035for p in prefixes:2036ifp4PathStartsWith(path, p):2037 path = path[len(p):]2038break20392040 path =wildcard_decode(path)2041return path20422043defsplitFilesIntoBranches(self, commit):2044"""Look at each depotFile in the commit to figure out to what2045 branch it belongs."""20462047 branches = {}2048 fnum =02049while commit.has_key("depotFile%s"% fnum):2050 path = commit["depotFile%s"% fnum]2051 found = [p for p in self.depotPaths2052ifp4PathStartsWith(path, p)]2053if not found:2054 fnum = fnum +12055continue20562057file= {}2058file["path"] = path2059file["rev"] = commit["rev%s"% fnum]2060file["action"] = commit["action%s"% fnum]2061file["type"] = commit["type%s"% fnum]2062 fnum = fnum +120632064# start with the full relative path where this file would2065# go in a p4 client2066if self.useClientSpec:2067 relPath = self.clientSpecDirs.map_in_client(path)2068else:2069 relPath = self.stripRepoPath(path, self.depotPaths)20702071for branch in self.knownBranches.keys():2072# add a trailing slash so that a commit into qt/4.2foo2073# doesn't end up in qt/4.2, e.g.2074if relPath.startswith(branch +"/"):2075if branch not in branches:2076 branches[branch] = []2077 branches[branch].append(file)2078break20792080return branches20812082# output one file from the P4 stream2083# - helper for streamP4Files20842085defstreamOneP4File(self,file, contents):2086 relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)2087if verbose:2088 sys.stderr.write("%s\n"% relPath)20892090(type_base, type_mods) =split_p4_type(file["type"])20912092 git_mode ="100644"2093if"x"in type_mods:2094 git_mode ="100755"2095if type_base =="symlink":2096 git_mode ="120000"2097# p4 print on a symlink contains "target\n"; remove the newline2098 data =''.join(contents)2099 contents = [data[:-1]]21002101if type_base =="utf16":2102# p4 delivers different text in the python output to -G2103# than it does when using "print -o", or normal p4 client2104# operations. utf16 is converted to ascii or utf8, perhaps.2105# But ascii text saved as -t utf16 is completely mangled.2106# Invoke print -o to get the real contents.2107 text =p4_read_pipe(['print','-q','-o','-',file['depotFile']])2108 contents = [ text ]21092110if type_base =="apple":2111# Apple filetype files will be streamed as a concatenation of2112# its appledouble header and the contents. This is useless2113# on both macs and non-macs. If using "print -q -o xx", it2114# will create "xx" with the data, and "%xx" with the header.2115# This is also not very useful.2116#2117# Ideally, someday, this script can learn how to generate2118# appledouble files directly and import those to git, but2119# non-mac machines can never find a use for apple filetype.2120print"\nIgnoring apple filetype file%s"%file['depotFile']2121return21222123# Perhaps windows wants unicode, utf16 newlines translated too;2124# but this is not doing it.2125if self.isWindows and type_base =="text":2126 mangled = []2127for data in contents:2128 data = data.replace("\r\n","\n")2129 mangled.append(data)2130 contents = mangled21312132# Note that we do not try to de-mangle keywords on utf16 files,2133# even though in theory somebody may want that.2134 pattern =p4_keywords_regexp_for_type(type_base, type_mods)2135if pattern:2136 regexp = re.compile(pattern, re.VERBOSE)2137 text =''.join(contents)2138 text = regexp.sub(r'$\1$', text)2139 contents = [ text ]21402141 self.gitStream.write("M%sinline%s\n"% (git_mode, relPath))21422143# total length...2144 length =02145for d in contents:2146 length = length +len(d)21472148 self.gitStream.write("data%d\n"% length)2149for d in contents:2150 self.gitStream.write(d)2151 self.gitStream.write("\n")21522153defstreamOneP4Deletion(self,file):2154 relPath = self.stripRepoPath(file['path'], self.branchPrefixes)2155if verbose:2156 sys.stderr.write("delete%s\n"% relPath)2157 self.gitStream.write("D%s\n"% relPath)21582159# handle another chunk of streaming data2160defstreamP4FilesCb(self, marshalled):21612162# catch p4 errors and complain2163 err =None2164if"code"in marshalled:2165if marshalled["code"] =="error":2166if"data"in marshalled:2167 err = marshalled["data"].rstrip()2168if err:2169 f =None2170if self.stream_have_file_info:2171if"depotFile"in self.stream_file:2172 f = self.stream_file["depotFile"]2173# force a failure in fast-import, else an empty2174# commit will be made2175 self.gitStream.write("\n")2176 self.gitStream.write("die-now\n")2177 self.gitStream.close()2178# ignore errors, but make sure it exits first2179 self.importProcess.wait()2180if f:2181die("Error from p4 print for%s:%s"% (f, err))2182else:2183die("Error from p4 print:%s"% err)21842185if marshalled.has_key('depotFile')and self.stream_have_file_info:2186# start of a new file - output the old one first2187 self.streamOneP4File(self.stream_file, self.stream_contents)2188 self.stream_file = {}2189 self.stream_contents = []2190 self.stream_have_file_info =False21912192# pick up the new file information... for the2193# 'data' field we need to append to our array2194for k in marshalled.keys():2195if k =='data':2196 self.stream_contents.append(marshalled['data'])2197else:2198 self.stream_file[k] = marshalled[k]21992200 self.stream_have_file_info =True22012202# Stream directly from "p4 files" into "git fast-import"2203defstreamP4Files(self, files):2204 filesForCommit = []2205 filesToRead = []2206 filesToDelete = []22072208for f in files:2209# if using a client spec, only add the files that have2210# a path in the client2211if self.clientSpecDirs:2212if self.clientSpecDirs.map_in_client(f['path']) =="":2213continue22142215 filesForCommit.append(f)2216if f['action']in self.delete_actions:2217 filesToDelete.append(f)2218else:2219 filesToRead.append(f)22202221# deleted files...2222for f in filesToDelete:2223 self.streamOneP4Deletion(f)22242225iflen(filesToRead) >0:2226 self.stream_file = {}2227 self.stream_contents = []2228 self.stream_have_file_info =False22292230# curry self argument2231defstreamP4FilesCbSelf(entry):2232 self.streamP4FilesCb(entry)22332234 fileArgs = ['%s#%s'% (f['path'], f['rev'])for f in filesToRead]22352236p4CmdList(["-x","-","print"],2237 stdin=fileArgs,2238 cb=streamP4FilesCbSelf)22392240# do the last chunk2241if self.stream_file.has_key('depotFile'):2242 self.streamOneP4File(self.stream_file, self.stream_contents)22432244defmake_email(self, userid):2245if userid in self.users:2246return self.users[userid]2247else:2248return"%s<a@b>"% userid22492250# Stream a p4 tag2251defstreamTag(self, gitStream, labelName, labelDetails, commit, epoch):2252if verbose:2253print"writing tag%sfor commit%s"% (labelName, commit)2254 gitStream.write("tag%s\n"% labelName)2255 gitStream.write("from%s\n"% commit)22562257if labelDetails.has_key('Owner'):2258 owner = labelDetails["Owner"]2259else:2260 owner =None22612262# Try to use the owner of the p4 label, or failing that,2263# the current p4 user id.2264if owner:2265 email = self.make_email(owner)2266else:2267 email = self.make_email(self.p4UserId())2268 tagger ="%s %s %s"% (email, epoch, self.tz)22692270 gitStream.write("tagger%s\n"% tagger)22712272print"labelDetails=",labelDetails2273if labelDetails.has_key('Description'):2274 description = labelDetails['Description']2275else:2276 description ='Label from git p4'22772278 gitStream.write("data%d\n"%len(description))2279 gitStream.write(description)2280 gitStream.write("\n")22812282defcommit(self, details, files, branch, parent =""):2283 epoch = details["time"]2284 author = details["user"]22852286if self.verbose:2287print"commit into%s"% branch22882289# start with reading files; if that fails, we should not2290# create a commit.2291 new_files = []2292for f in files:2293if[p for p in self.branchPrefixes ifp4PathStartsWith(f['path'], p)]:2294 new_files.append(f)2295else:2296 sys.stderr.write("Ignoring file outside of prefix:%s\n"% f['path'])22972298 self.gitStream.write("commit%s\n"% branch)2299# gitStream.write("mark :%s\n" % details["change"])2300 self.committedChanges.add(int(details["change"]))2301 committer =""2302if author not in self.users:2303 self.getUserMapFromPerforceServer()2304 committer ="%s %s %s"% (self.make_email(author), epoch, self.tz)23052306 self.gitStream.write("committer%s\n"% committer)23072308 self.gitStream.write("data <<EOT\n")2309 self.gitStream.write(details["desc"])2310 self.gitStream.write("\n[git-p4: depot-paths =\"%s\": change =%s"%2311(','.join(self.branchPrefixes), details["change"]))2312iflen(details['options']) >0:2313 self.gitStream.write(": options =%s"% details['options'])2314 self.gitStream.write("]\nEOT\n\n")23152316iflen(parent) >0:2317if self.verbose:2318print"parent%s"% parent2319 self.gitStream.write("from%s\n"% parent)23202321 self.streamP4Files(new_files)2322 self.gitStream.write("\n")23232324 change =int(details["change"])23252326if self.labels.has_key(change):2327 label = self.labels[change]2328 labelDetails = label[0]2329 labelRevisions = label[1]2330if self.verbose:2331print"Change%sis labelled%s"% (change, labelDetails)23322333 files =p4CmdList(["files"] + ["%s...@%s"% (p, change)2334for p in self.branchPrefixes])23352336iflen(files) ==len(labelRevisions):23372338 cleanedFiles = {}2339for info in files:2340if info["action"]in self.delete_actions:2341continue2342 cleanedFiles[info["depotFile"]] = info["rev"]23432344if cleanedFiles == labelRevisions:2345 self.streamTag(self.gitStream,'tag_%s'% labelDetails['label'], labelDetails, branch, epoch)23462347else:2348if not self.silent:2349print("Tag%sdoes not match with change%s: files do not match."2350% (labelDetails["label"], change))23512352else:2353if not self.silent:2354print("Tag%sdoes not match with change%s: file count is different."2355% (labelDetails["label"], change))23562357# Build a dictionary of changelists and labels, for "detect-labels" option.2358defgetLabels(self):2359 self.labels = {}23602361 l =p4CmdList(["labels"] + ["%s..."% p for p in self.depotPaths])2362iflen(l) >0and not self.silent:2363print"Finding files belonging to labels in%s"% `self.depotPaths`23642365for output in l:2366 label = output["label"]2367 revisions = {}2368 newestChange =02369if self.verbose:2370print"Querying files for label%s"% label2371forfileinp4CmdList(["files"] +2372["%s...@%s"% (p, label)2373for p in self.depotPaths]):2374 revisions[file["depotFile"]] =file["rev"]2375 change =int(file["change"])2376if change > newestChange:2377 newestChange = change23782379 self.labels[newestChange] = [output, revisions]23802381if self.verbose:2382print"Label changes:%s"% self.labels.keys()23832384# Import p4 labels as git tags. A direct mapping does not2385# exist, so assume that if all the files are at the same revision2386# then we can use that, or it's something more complicated we should2387# just ignore.2388defimportP4Labels(self, stream, p4Labels):2389if verbose:2390print"import p4 labels: "+' '.join(p4Labels)23912392 ignoredP4Labels =gitConfigList("git-p4.ignoredP4Labels")2393 validLabelRegexp =gitConfig("git-p4.labelImportRegexp")2394iflen(validLabelRegexp) ==0:2395 validLabelRegexp = defaultLabelRegexp2396 m = re.compile(validLabelRegexp)23972398for name in p4Labels:2399 commitFound =False24002401if not m.match(name):2402if verbose:2403print"label%sdoes not match regexp%s"% (name,validLabelRegexp)2404continue24052406if name in ignoredP4Labels:2407continue24082409 labelDetails =p4CmdList(['label',"-o", name])[0]24102411# get the most recent changelist for each file in this label2412 change =p4Cmd(["changes","-m","1"] + ["%s...@%s"% (p, name)2413for p in self.depotPaths])24142415if change.has_key('change'):2416# find the corresponding git commit; take the oldest commit2417 changelist =int(change['change'])2418 gitCommit =read_pipe(["git","rev-list","--max-count=1",2419"--reverse",":/\[git-p4:.*change =%d\]"% changelist])2420iflen(gitCommit) ==0:2421print"could not find git commit for changelist%d"% changelist2422else:2423 gitCommit = gitCommit.strip()2424 commitFound =True2425# Convert from p4 time format2426try:2427 tmwhen = time.strptime(labelDetails['Update'],"%Y/%m/%d%H:%M:%S")2428exceptValueError:2429print"Could not convert label time%s"% labelDetails['Update']2430 tmwhen =124312432 when =int(time.mktime(tmwhen))2433 self.streamTag(stream, name, labelDetails, gitCommit, when)2434if verbose:2435print"p4 label%smapped to git commit%s"% (name, gitCommit)2436else:2437if verbose:2438print"Label%shas no changelists - possibly deleted?"% name24392440if not commitFound:2441# We can't import this label; don't try again as it will get very2442# expensive repeatedly fetching all the files for labels that will2443# never be imported. If the label is moved in the future, the2444# ignore will need to be removed manually.2445system(["git","config","--add","git-p4.ignoredP4Labels", name])24462447defguessProjectName(self):2448for p in self.depotPaths:2449if p.endswith("/"):2450 p = p[:-1]2451 p = p[p.strip().rfind("/") +1:]2452if not p.endswith("/"):2453 p +="/"2454return p24552456defgetBranchMapping(self):2457 lostAndFoundBranches =set()24582459 user =gitConfig("git-p4.branchUser")2460iflen(user) >0:2461 command ="branches -u%s"% user2462else:2463 command ="branches"24642465for info inp4CmdList(command):2466 details =p4Cmd(["branch","-o", info["branch"]])2467 viewIdx =02468while details.has_key("View%s"% viewIdx):2469 paths = details["View%s"% viewIdx].split(" ")2470 viewIdx = viewIdx +12471# require standard //depot/foo/... //depot/bar/... mapping2472iflen(paths) !=2or not paths[0].endswith("/...")or not paths[1].endswith("/..."):2473continue2474 source = paths[0]2475 destination = paths[1]2476## HACK2477ifp4PathStartsWith(source, self.depotPaths[0])andp4PathStartsWith(destination, self.depotPaths[0]):2478 source = source[len(self.depotPaths[0]):-4]2479 destination = destination[len(self.depotPaths[0]):-4]24802481if destination in self.knownBranches:2482if not self.silent:2483print"p4 branch%sdefines a mapping from%sto%s"% (info["branch"], source, destination)2484print"but there exists another mapping from%sto%salready!"% (self.knownBranches[destination], destination)2485continue24862487 self.knownBranches[destination] = source24882489 lostAndFoundBranches.discard(destination)24902491if source not in self.knownBranches:2492 lostAndFoundBranches.add(source)24932494# Perforce does not strictly require branches to be defined, so we also2495# check git config for a branch list.2496#2497# Example of branch definition in git config file:2498# [git-p4]2499# branchList=main:branchA2500# branchList=main:branchB2501# branchList=branchA:branchC2502 configBranches =gitConfigList("git-p4.branchList")2503for branch in configBranches:2504if branch:2505(source, destination) = branch.split(":")2506 self.knownBranches[destination] = source25072508 lostAndFoundBranches.discard(destination)25092510if source not in self.knownBranches:2511 lostAndFoundBranches.add(source)251225132514for branch in lostAndFoundBranches:2515 self.knownBranches[branch] = branch25162517defgetBranchMappingFromGitBranches(self):2518 branches =p4BranchesInGit(self.importIntoRemotes)2519for branch in branches.keys():2520if branch =="master":2521 branch ="main"2522else:2523 branch = branch[len(self.projectName):]2524 self.knownBranches[branch] = branch25252526deflistExistingP4GitBranches(self):2527# branches holds mapping from name to commit2528 branches =p4BranchesInGit(self.importIntoRemotes)2529 self.p4BranchesInGit = branches.keys()2530for branch in branches.keys():2531 self.initialParents[self.refPrefix + branch] = branches[branch]25322533defupdateOptionDict(self, d):2534 option_keys = {}2535if self.keepRepoPath:2536 option_keys['keepRepoPath'] =125372538 d["options"] =' '.join(sorted(option_keys.keys()))25392540defreadOptions(self, d):2541 self.keepRepoPath = (d.has_key('options')2542and('keepRepoPath'in d['options']))25432544defgitRefForBranch(self, branch):2545if branch =="main":2546return self.refPrefix +"master"25472548iflen(branch) <=0:2549return branch25502551return self.refPrefix + self.projectName + branch25522553defgitCommitByP4Change(self, ref, change):2554if self.verbose:2555print"looking in ref "+ ref +" for change%susing bisect..."% change25562557 earliestCommit =""2558 latestCommit =parseRevision(ref)25592560while True:2561if self.verbose:2562print"trying: earliest%slatest%s"% (earliestCommit, latestCommit)2563 next =read_pipe("git rev-list --bisect%s %s"% (latestCommit, earliestCommit)).strip()2564iflen(next) ==0:2565if self.verbose:2566print"argh"2567return""2568 log =extractLogMessageFromGitCommit(next)2569 settings =extractSettingsGitLog(log)2570 currentChange =int(settings['change'])2571if self.verbose:2572print"current change%s"% currentChange25732574if currentChange == change:2575if self.verbose:2576print"found%s"% next2577return next25782579if currentChange < change:2580 earliestCommit ="^%s"% next2581else:2582 latestCommit ="%s"% next25832584return""25852586defimportNewBranch(self, branch, maxChange):2587# make fast-import flush all changes to disk and update the refs using the checkpoint2588# command so that we can try to find the branch parent in the git history2589 self.gitStream.write("checkpoint\n\n");2590 self.gitStream.flush();2591 branchPrefix = self.depotPaths[0] + branch +"/"2592range="@1,%s"% maxChange2593#print "prefix" + branchPrefix2594 changes =p4ChangesForPaths([branchPrefix],range)2595iflen(changes) <=0:2596return False2597 firstChange = changes[0]2598#print "first change in branch: %s" % firstChange2599 sourceBranch = self.knownBranches[branch]2600 sourceDepotPath = self.depotPaths[0] + sourceBranch2601 sourceRef = self.gitRefForBranch(sourceBranch)2602#print "source " + sourceBranch26032604 branchParentChange =int(p4Cmd(["changes","-m","1","%s...@1,%s"% (sourceDepotPath, firstChange)])["change"])2605#print "branch parent: %s" % branchParentChange2606 gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)2607iflen(gitParent) >0:2608 self.initialParents[self.gitRefForBranch(branch)] = gitParent2609#print "parent git commit: %s" % gitParent26102611 self.importChanges(changes)2612return True26132614defsearchParent(self, parent, branch, target):2615 parentFound =False2616for blob inread_pipe_lines(["git","rev-list","--reverse","--no-merges", parent]):2617 blob = blob.strip()2618iflen(read_pipe(["git","diff-tree", blob, target])) ==0:2619 parentFound =True2620if self.verbose:2621print"Found parent of%sin commit%s"% (branch, blob)2622break2623if parentFound:2624return blob2625else:2626return None26272628defimportChanges(self, changes):2629 cnt =12630for change in changes:2631 description =p4_describe(change)2632 self.updateOptionDict(description)26332634if not self.silent:2635 sys.stdout.write("\rImporting revision%s(%s%%)"% (change, cnt *100/len(changes)))2636 sys.stdout.flush()2637 cnt = cnt +126382639try:2640if self.detectBranches:2641 branches = self.splitFilesIntoBranches(description)2642for branch in branches.keys():2643## HACK --hwn2644 branchPrefix = self.depotPaths[0] + branch +"/"2645 self.branchPrefixes = [ branchPrefix ]26462647 parent =""26482649 filesForCommit = branches[branch]26502651if self.verbose:2652print"branch is%s"% branch26532654 self.updatedBranches.add(branch)26552656if branch not in self.createdBranches:2657 self.createdBranches.add(branch)2658 parent = self.knownBranches[branch]2659if parent == branch:2660 parent =""2661else:2662 fullBranch = self.projectName + branch2663if fullBranch not in self.p4BranchesInGit:2664if not self.silent:2665print("\nImporting new branch%s"% fullBranch);2666if self.importNewBranch(branch, change -1):2667 parent =""2668 self.p4BranchesInGit.append(fullBranch)2669if not self.silent:2670print("\nResuming with change%s"% change);26712672if self.verbose:2673print"parent determined through known branches:%s"% parent26742675 branch = self.gitRefForBranch(branch)2676 parent = self.gitRefForBranch(parent)26772678if self.verbose:2679print"looking for initial parent for%s; current parent is%s"% (branch, parent)26802681iflen(parent) ==0and branch in self.initialParents:2682 parent = self.initialParents[branch]2683del self.initialParents[branch]26842685 blob =None2686iflen(parent) >0:2687 tempBranch = os.path.join(self.tempBranchLocation,"%d"% (change))2688if self.verbose:2689print"Creating temporary branch: "+ tempBranch2690 self.commit(description, filesForCommit, tempBranch)2691 self.tempBranches.append(tempBranch)2692 self.checkpoint()2693 blob = self.searchParent(parent, branch, tempBranch)2694if blob:2695 self.commit(description, filesForCommit, branch, blob)2696else:2697if self.verbose:2698print"Parent of%snot found. Committing into head of%s"% (branch, parent)2699 self.commit(description, filesForCommit, branch, parent)2700else:2701 files = self.extractFilesFromCommit(description)2702 self.commit(description, files, self.branch,2703 self.initialParent)2704 self.initialParent =""2705exceptIOError:2706print self.gitError.read()2707 sys.exit(1)27082709defimportHeadRevision(self, revision):2710print"Doing initial import of%sfrom revision%sinto%s"% (' '.join(self.depotPaths), revision, self.branch)27112712 details = {}2713 details["user"] ="git perforce import user"2714 details["desc"] = ("Initial import of%sfrom the state at revision%s\n"2715% (' '.join(self.depotPaths), revision))2716 details["change"] = revision2717 newestRevision =027182719 fileCnt =02720 fileArgs = ["%s...%s"% (p,revision)for p in self.depotPaths]27212722for info inp4CmdList(["files"] + fileArgs):27232724if'code'in info and info['code'] =='error':2725 sys.stderr.write("p4 returned an error:%s\n"2726% info['data'])2727if info['data'].find("must refer to client") >=0:2728 sys.stderr.write("This particular p4 error is misleading.\n")2729 sys.stderr.write("Perhaps the depot path was misspelled.\n");2730 sys.stderr.write("Depot path:%s\n"%" ".join(self.depotPaths))2731 sys.exit(1)2732if'p4ExitCode'in info:2733 sys.stderr.write("p4 exitcode:%s\n"% info['p4ExitCode'])2734 sys.exit(1)273527362737 change =int(info["change"])2738if change > newestRevision:2739 newestRevision = change27402741if info["action"]in self.delete_actions:2742# don't increase the file cnt, otherwise details["depotFile123"] will have gaps!2743#fileCnt = fileCnt + 12744continue27452746for prop in["depotFile","rev","action","type"]:2747 details["%s%s"% (prop, fileCnt)] = info[prop]27482749 fileCnt = fileCnt +127502751 details["change"] = newestRevision27522753# Use time from top-most change so that all git p4 clones of2754# the same p4 repo have the same commit SHA1s.2755 res =p4_describe(newestRevision)2756 details["time"] = res["time"]27572758 self.updateOptionDict(details)2759try:2760 self.commit(details, self.extractFilesFromCommit(details), self.branch)2761exceptIOError:2762print"IO error with git fast-import. Is your git version recent enough?"2763print self.gitError.read()276427652766defrun(self, args):2767 self.depotPaths = []2768 self.changeRange =""2769 self.initialParent =""2770 self.previousDepotPaths = []27712772# map from branch depot path to parent branch2773 self.knownBranches = {}2774 self.initialParents = {}2775 self.hasOrigin =originP4BranchesExist()2776if not self.syncWithOrigin:2777 self.hasOrigin =False27782779if self.importIntoRemotes:2780 self.refPrefix ="refs/remotes/p4/"2781else:2782 self.refPrefix ="refs/heads/p4/"27832784if self.syncWithOrigin and self.hasOrigin:2785if not self.silent:2786print"Syncing with origin first by calling git fetch origin"2787system("git fetch origin")27882789iflen(self.branch) ==0:2790 self.branch = self.refPrefix +"master"2791ifgitBranchExists("refs/heads/p4")and self.importIntoRemotes:2792system("git update-ref%srefs/heads/p4"% self.branch)2793system("git branch -D p4");2794# create it /after/ importing, when master exists2795if notgitBranchExists(self.refPrefix +"HEAD")and self.importIntoRemotes andgitBranchExists(self.branch):2796system("git symbolic-ref%sHEAD%s"% (self.refPrefix, self.branch))27972798# accept either the command-line option, or the configuration variable2799if self.useClientSpec:2800# will use this after clone to set the variable2801 self.useClientSpec_from_options =True2802else:2803ifgitConfig("git-p4.useclientspec","--bool") =="true":2804 self.useClientSpec =True2805if self.useClientSpec:2806 self.clientSpecDirs =getClientSpec()28072808# TODO: should always look at previous commits,2809# merge with previous imports, if possible.2810if args == []:2811if self.hasOrigin:2812createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)2813 self.listExistingP4GitBranches()28142815iflen(self.p4BranchesInGit) >1:2816if not self.silent:2817print"Importing from/into multiple branches"2818 self.detectBranches =True28192820if self.verbose:2821print"branches:%s"% self.p4BranchesInGit28222823 p4Change =02824for branch in self.p4BranchesInGit:2825 logMsg =extractLogMessageFromGitCommit(self.refPrefix + branch)28262827 settings =extractSettingsGitLog(logMsg)28282829 self.readOptions(settings)2830if(settings.has_key('depot-paths')2831and settings.has_key('change')):2832 change =int(settings['change']) +12833 p4Change =max(p4Change, change)28342835 depotPaths =sorted(settings['depot-paths'])2836if self.previousDepotPaths == []:2837 self.previousDepotPaths = depotPaths2838else:2839 paths = []2840for(prev, cur)inzip(self.previousDepotPaths, depotPaths):2841 prev_list = prev.split("/")2842 cur_list = cur.split("/")2843for i inrange(0,min(len(cur_list),len(prev_list))):2844if cur_list[i] <> prev_list[i]:2845 i = i -12846break28472848 paths.append("/".join(cur_list[:i +1]))28492850 self.previousDepotPaths = paths28512852if p4Change >0:2853 self.depotPaths =sorted(self.previousDepotPaths)2854 self.changeRange ="@%s,#head"% p4Change2855if not self.detectBranches:2856 self.initialParent =parseRevision(self.branch)2857if not self.silent and not self.detectBranches:2858print"Performing incremental import into%sgit branch"% self.branch28592860if not self.branch.startswith("refs/"):2861 self.branch ="refs/heads/"+ self.branch28622863iflen(args) ==0and self.depotPaths:2864if not self.silent:2865print"Depot paths:%s"%' '.join(self.depotPaths)2866else:2867if self.depotPaths and self.depotPaths != args:2868print("previous import used depot path%sand now%swas specified. "2869"This doesn't work!"% (' '.join(self.depotPaths),2870' '.join(args)))2871 sys.exit(1)28722873 self.depotPaths =sorted(args)28742875 revision =""2876 self.users = {}28772878# Make sure no revision specifiers are used when --changesfile2879# is specified.2880 bad_changesfile =False2881iflen(self.changesFile) >0:2882for p in self.depotPaths:2883if p.find("@") >=0or p.find("#") >=0:2884 bad_changesfile =True2885break2886if bad_changesfile:2887die("Option --changesfile is incompatible with revision specifiers")28882889 newPaths = []2890for p in self.depotPaths:2891if p.find("@") != -1:2892 atIdx = p.index("@")2893 self.changeRange = p[atIdx:]2894if self.changeRange =="@all":2895 self.changeRange =""2896elif','not in self.changeRange:2897 revision = self.changeRange2898 self.changeRange =""2899 p = p[:atIdx]2900elif p.find("#") != -1:2901 hashIdx = p.index("#")2902 revision = p[hashIdx:]2903 p = p[:hashIdx]2904elif self.previousDepotPaths == []:2905# pay attention to changesfile, if given, else import2906# the entire p4 tree at the head revision2907iflen(self.changesFile) ==0:2908 revision ="#head"29092910 p = re.sub("\.\.\.$","", p)2911if not p.endswith("/"):2912 p +="/"29132914 newPaths.append(p)29152916 self.depotPaths = newPaths29172918# --detect-branches may change this for each branch2919 self.branchPrefixes = self.depotPaths29202921 self.loadUserMapFromCache()2922 self.labels = {}2923if self.detectLabels:2924 self.getLabels();29252926if self.detectBranches:2927## FIXME - what's a P4 projectName ?2928 self.projectName = self.guessProjectName()29292930if self.hasOrigin:2931 self.getBranchMappingFromGitBranches()2932else:2933 self.getBranchMapping()2934if self.verbose:2935print"p4-git branches:%s"% self.p4BranchesInGit2936print"initial parents:%s"% self.initialParents2937for b in self.p4BranchesInGit:2938if b !="master":29392940## FIXME2941 b = b[len(self.projectName):]2942 self.createdBranches.add(b)29432944 self.tz ="%+03d%02d"% (- time.timezone /3600, ((- time.timezone %3600) /60))29452946 self.importProcess = subprocess.Popen(["git","fast-import"],2947 stdin=subprocess.PIPE,2948 stdout=subprocess.PIPE,2949 stderr=subprocess.PIPE);2950 self.gitOutput = self.importProcess.stdout2951 self.gitStream = self.importProcess.stdin2952 self.gitError = self.importProcess.stderr29532954if revision:2955 self.importHeadRevision(revision)2956else:2957 changes = []29582959iflen(self.changesFile) >0:2960 output =open(self.changesFile).readlines()2961 changeSet =set()2962for line in output:2963 changeSet.add(int(line))29642965for change in changeSet:2966 changes.append(change)29672968 changes.sort()2969else:2970# catch "git p4 sync" with no new branches, in a repo that2971# does not have any existing p4 branches2972iflen(args) ==0and not self.p4BranchesInGit:2973die("No remote p4 branches. Perhaps you never did\"git p4 clone\"in here.");2974if self.verbose:2975print"Getting p4 changes for%s...%s"% (', '.join(self.depotPaths),2976 self.changeRange)2977 changes =p4ChangesForPaths(self.depotPaths, self.changeRange)29782979iflen(self.maxChanges) >0:2980 changes = changes[:min(int(self.maxChanges),len(changes))]29812982iflen(changes) ==0:2983if not self.silent:2984print"No changes to import!"2985else:2986if not self.silent and not self.detectBranches:2987print"Import destination:%s"% self.branch29882989 self.updatedBranches =set()29902991 self.importChanges(changes)29922993if not self.silent:2994print""2995iflen(self.updatedBranches) >0:2996 sys.stdout.write("Updated branches: ")2997for b in self.updatedBranches:2998 sys.stdout.write("%s"% b)2999 sys.stdout.write("\n")30003001ifgitConfig("git-p4.importLabels","--bool") =="true":3002 self.importLabels =True30033004if self.importLabels:3005 p4Labels =getP4Labels(self.depotPaths)3006 gitTags =getGitTags()30073008 missingP4Labels = p4Labels - gitTags3009 self.importP4Labels(self.gitStream, missingP4Labels)30103011 self.gitStream.close()3012if self.importProcess.wait() !=0:3013die("fast-import failed:%s"% self.gitError.read())3014 self.gitOutput.close()3015 self.gitError.close()30163017# Cleanup temporary branches created during import3018if self.tempBranches != []:3019for branch in self.tempBranches:3020read_pipe("git update-ref -d%s"% branch)3021 os.rmdir(os.path.join(os.environ.get("GIT_DIR",".git"), self.tempBranchLocation))30223023return True30243025classP4Rebase(Command):3026def__init__(self):3027 Command.__init__(self)3028 self.options = [3029 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),3030]3031 self.importLabels =False3032 self.description = ("Fetches the latest revision from perforce and "3033+"rebases the current work (branch) against it")30343035defrun(self, args):3036 sync =P4Sync()3037 sync.importLabels = self.importLabels3038 sync.run([])30393040return self.rebase()30413042defrebase(self):3043if os.system("git update-index --refresh") !=0:3044die("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.");3045iflen(read_pipe("git diff-index HEAD --")) >0:3046die("You have uncommited changes. Please commit them before rebasing or stash them away with git stash.");30473048[upstream, settings] =findUpstreamBranchPoint()3049iflen(upstream) ==0:3050die("Cannot find upstream branchpoint for rebase")30513052# the branchpoint may be p4/foo~3, so strip off the parent3053 upstream = re.sub("~[0-9]+$","", upstream)30543055print"Rebasing the current branch onto%s"% upstream3056 oldHead =read_pipe("git rev-parse HEAD").strip()3057system("git rebase%s"% upstream)3058system("git diff-tree --stat --summary -M%sHEAD"% oldHead)3059return True30603061classP4Clone(P4Sync):3062def__init__(self):3063 P4Sync.__init__(self)3064 self.description ="Creates a new git repository and imports from Perforce into it"3065 self.usage ="usage: %prog [options] //depot/path[@revRange]"3066 self.options += [3067 optparse.make_option("--destination", dest="cloneDestination",3068 action='store', default=None,3069help="where to leave result of the clone"),3070 optparse.make_option("-/", dest="cloneExclude",3071 action="append",type="string",3072help="exclude depot path"),3073 optparse.make_option("--bare", dest="cloneBare",3074 action="store_true", default=False),3075]3076 self.cloneDestination =None3077 self.needsGit =False3078 self.cloneBare =False30793080# This is required for the "append" cloneExclude action3081defensure_value(self, attr, value):3082if nothasattr(self, attr)orgetattr(self, attr)is None:3083setattr(self, attr, value)3084returngetattr(self, attr)30853086defdefaultDestination(self, args):3087## TODO: use common prefix of args?3088 depotPath = args[0]3089 depotDir = re.sub("(@[^@]*)$","", depotPath)3090 depotDir = re.sub("(#[^#]*)$","", depotDir)3091 depotDir = re.sub(r"\.\.\.$","", depotDir)3092 depotDir = re.sub(r"/$","", depotDir)3093return os.path.split(depotDir)[1]30943095defrun(self, args):3096iflen(args) <1:3097return False30983099if self.keepRepoPath and not self.cloneDestination:3100 sys.stderr.write("Must specify destination for --keep-path\n")3101 sys.exit(1)31023103 depotPaths = args31043105if not self.cloneDestination andlen(depotPaths) >1:3106 self.cloneDestination = depotPaths[-1]3107 depotPaths = depotPaths[:-1]31083109 self.cloneExclude = ["/"+p for p in self.cloneExclude]3110for p in depotPaths:3111if not p.startswith("//"):3112return False31133114if not self.cloneDestination:3115 self.cloneDestination = self.defaultDestination(args)31163117print"Importing from%sinto%s"% (', '.join(depotPaths), self.cloneDestination)31183119if not os.path.exists(self.cloneDestination):3120 os.makedirs(self.cloneDestination)3121chdir(self.cloneDestination)31223123 init_cmd = ["git","init"]3124if self.cloneBare:3125 init_cmd.append("--bare")3126 retcode = subprocess.call(init_cmd)3127if retcode:3128raiseCalledProcessError(retcode, init_cmd)31293130if not P4Sync.run(self, depotPaths):3131return False3132if self.branch !="master":3133if self.importIntoRemotes:3134 masterbranch ="refs/remotes/p4/master"3135else:3136 masterbranch ="refs/heads/p4/master"3137ifgitBranchExists(masterbranch):3138system("git branch master%s"% masterbranch)3139if not self.cloneBare:3140system("git checkout -f")3141else:3142print"Could not detect main branch. No checkout/master branch created."31433144# auto-set this variable if invoked with --use-client-spec3145if self.useClientSpec_from_options:3146system("git config --bool git-p4.useclientspec true")31473148return True31493150classP4Branches(Command):3151def__init__(self):3152 Command.__init__(self)3153 self.options = [ ]3154 self.description = ("Shows the git branches that hold imports and their "3155+"corresponding perforce depot paths")3156 self.verbose =False31573158defrun(self, args):3159iforiginP4BranchesExist():3160createOrUpdateBranchesFromOrigin()31613162 cmdline ="git rev-parse --symbolic "3163 cmdline +=" --remotes"31643165for line inread_pipe_lines(cmdline):3166 line = line.strip()31673168if not line.startswith('p4/')or line =="p4/HEAD":3169continue3170 branch = line31713172 log =extractLogMessageFromGitCommit("refs/remotes/%s"% branch)3173 settings =extractSettingsGitLog(log)31743175print"%s<=%s(%s)"% (branch,",".join(settings["depot-paths"]), settings["change"])3176return True31773178classHelpFormatter(optparse.IndentedHelpFormatter):3179def__init__(self):3180 optparse.IndentedHelpFormatter.__init__(self)31813182defformat_description(self, description):3183if description:3184return description +"\n"3185else:3186return""31873188defprintUsage(commands):3189print"usage:%s<command> [options]"% sys.argv[0]3190print""3191print"valid commands:%s"%", ".join(commands)3192print""3193print"Try%s<command> --help for command specific help."% sys.argv[0]3194print""31953196commands = {3197"debug": P4Debug,3198"submit": P4Submit,3199"commit": P4Submit,3200"sync": P4Sync,3201"rebase": P4Rebase,3202"clone": P4Clone,3203"rollback": P4RollBack,3204"branches": P4Branches3205}320632073208defmain():3209iflen(sys.argv[1:]) ==0:3210printUsage(commands.keys())3211 sys.exit(2)32123213 cmdName = sys.argv[1]3214try:3215 klass = commands[cmdName]3216 cmd =klass()3217exceptKeyError:3218print"unknown command%s"% cmdName3219print""3220printUsage(commands.keys())3221 sys.exit(2)32223223 options = cmd.options3224 cmd.gitdir = os.environ.get("GIT_DIR",None)32253226 args = sys.argv[2:]32273228 options.append(optparse.make_option("--verbose","-v", dest="verbose", action="store_true"))3229if cmd.needsGit:3230 options.append(optparse.make_option("--git-dir", dest="gitdir"))32313232 parser = optparse.OptionParser(cmd.usage.replace("%prog","%prog "+ cmdName),3233 options,3234 description = cmd.description,3235 formatter =HelpFormatter())32363237(cmd, args) = parser.parse_args(sys.argv[2:], cmd);3238global verbose3239 verbose = cmd.verbose3240if cmd.needsGit:3241if cmd.gitdir ==None:3242 cmd.gitdir = os.path.abspath(".git")3243if notisValidGitDir(cmd.gitdir):3244 cmd.gitdir =read_pipe("git rev-parse --git-dir").strip()3245if os.path.exists(cmd.gitdir):3246 cdup =read_pipe("git rev-parse --show-cdup").strip()3247iflen(cdup) >0:3248chdir(cdup);32493250if notisValidGitDir(cmd.gitdir):3251ifisValidGitDir(cmd.gitdir +"/.git"):3252 cmd.gitdir +="/.git"3253else:3254die("fatal: cannot locate git repository at%s"% cmd.gitdir)32553256 os.environ["GIT_DIR"] = cmd.gitdir32573258if not cmd.run(args):3259 parser.print_help()3260 sys.exit(2)326132623263if __name__ =='__main__':3264main()