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# 10import sys 11if sys.hexversion <0x02040000: 12# The limiter is the subprocess module 13 sys.stderr.write("git-p4: requires Python 2.4 or later.\n") 14 sys.exit(1) 15import os 16import optparse 17import marshal 18import subprocess 19import tempfile 20import time 21import platform 22import re 23import shutil 24 25verbose =False 26 27# Only labels/tags matching this will be imported/exported 28defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$' 29 30defp4_build_cmd(cmd): 31"""Build a suitable p4 command line. 32 33 This consolidates building and returning a p4 command line into one 34 location. It means that hooking into the environment, or other configuration 35 can be done more easily. 36 """ 37 real_cmd = ["p4"] 38 39 user =gitConfig("git-p4.user") 40iflen(user) >0: 41 real_cmd += ["-u",user] 42 43 password =gitConfig("git-p4.password") 44iflen(password) >0: 45 real_cmd += ["-P", password] 46 47 port =gitConfig("git-p4.port") 48iflen(port) >0: 49 real_cmd += ["-p", port] 50 51 host =gitConfig("git-p4.host") 52iflen(host) >0: 53 real_cmd += ["-H", host] 54 55 client =gitConfig("git-p4.client") 56iflen(client) >0: 57 real_cmd += ["-c", client] 58 59 60ifisinstance(cmd,basestring): 61 real_cmd =' '.join(real_cmd) +' '+ cmd 62else: 63 real_cmd += cmd 64return real_cmd 65 66defchdir(dir): 67# P4 uses the PWD environment variable rather than getcwd(). Since we're 68# not using the shell, we have to set it ourselves. This path could 69# be relative, so go there first, then figure out where we ended up. 70 os.chdir(dir) 71 os.environ['PWD'] = os.getcwd() 72 73defdie(msg): 74if verbose: 75raiseException(msg) 76else: 77 sys.stderr.write(msg +"\n") 78 sys.exit(1) 79 80defwrite_pipe(c, stdin): 81if verbose: 82 sys.stderr.write('Writing pipe:%s\n'%str(c)) 83 84 expand =isinstance(c,basestring) 85 p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand) 86 pipe = p.stdin 87 val = pipe.write(stdin) 88 pipe.close() 89if p.wait(): 90die('Command failed:%s'%str(c)) 91 92return val 93 94defp4_write_pipe(c, stdin): 95 real_cmd =p4_build_cmd(c) 96returnwrite_pipe(real_cmd, stdin) 97 98defread_pipe(c, ignore_error=False): 99if verbose: 100 sys.stderr.write('Reading pipe:%s\n'%str(c)) 101 102 expand =isinstance(c,basestring) 103 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand) 104 pipe = p.stdout 105 val = pipe.read() 106if p.wait()and not ignore_error: 107die('Command failed:%s'%str(c)) 108 109return val 110 111defp4_read_pipe(c, ignore_error=False): 112 real_cmd =p4_build_cmd(c) 113returnread_pipe(real_cmd, ignore_error) 114 115defread_pipe_lines(c): 116if verbose: 117 sys.stderr.write('Reading pipe:%s\n'%str(c)) 118 119 expand =isinstance(c, basestring) 120 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand) 121 pipe = p.stdout 122 val = pipe.readlines() 123if pipe.close()or p.wait(): 124die('Command failed:%s'%str(c)) 125 126return val 127 128defp4_read_pipe_lines(c): 129"""Specifically invoke p4 on the command supplied. """ 130 real_cmd =p4_build_cmd(c) 131returnread_pipe_lines(real_cmd) 132 133defp4_has_command(cmd): 134"""Ask p4 for help on this command. If it returns an error, the 135 command does not exist in this version of p4.""" 136 real_cmd =p4_build_cmd(["help", cmd]) 137 p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE, 138 stderr=subprocess.PIPE) 139 p.communicate() 140return p.returncode ==0 141 142defp4_has_move_command(): 143"""See if the move command exists, that it supports -k, and that 144 it has not been administratively disabled. The arguments 145 must be correct, but the filenames do not have to exist. Use 146 ones with wildcards so even if they exist, it will fail.""" 147 148if notp4_has_command("move"): 149return False 150 cmd =p4_build_cmd(["move","-k","@from","@to"]) 151 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 152(out, err) = p.communicate() 153# return code will be 1 in either case 154if err.find("Invalid option") >=0: 155return False 156if err.find("disabled") >=0: 157return False 158# assume it failed because @... was invalid changelist 159return True 160 161defsystem(cmd): 162 expand =isinstance(cmd,basestring) 163if verbose: 164 sys.stderr.write("executing%s\n"%str(cmd)) 165 subprocess.check_call(cmd, shell=expand) 166 167defp4_system(cmd): 168"""Specifically invoke p4 as the system command. """ 169 real_cmd =p4_build_cmd(cmd) 170 expand =isinstance(real_cmd, basestring) 171 subprocess.check_call(real_cmd, shell=expand) 172 173defp4_integrate(src, dest): 174p4_system(["integrate","-Dt",wildcard_encode(src),wildcard_encode(dest)]) 175 176defp4_sync(f, *options): 177p4_system(["sync"] +list(options) + [wildcard_encode(f)]) 178 179defp4_add(f): 180# forcibly add file names with wildcards 181ifwildcard_present(f): 182p4_system(["add","-f", f]) 183else: 184p4_system(["add", f]) 185 186defp4_delete(f): 187p4_system(["delete",wildcard_encode(f)]) 188 189defp4_edit(f): 190p4_system(["edit",wildcard_encode(f)]) 191 192defp4_revert(f): 193p4_system(["revert",wildcard_encode(f)]) 194 195defp4_reopen(type, f): 196p4_system(["reopen","-t",type,wildcard_encode(f)]) 197 198defp4_move(src, dest): 199p4_system(["move","-k",wildcard_encode(src),wildcard_encode(dest)]) 200 201defp4_describe(change): 202"""Make sure it returns a valid result by checking for 203 the presence of field "time". Return a dict of the 204 results.""" 205 206 ds =p4CmdList(["describe","-s",str(change)]) 207iflen(ds) !=1: 208die("p4 describe -s%ddid not return 1 result:%s"% (change,str(ds))) 209 210 d = ds[0] 211 212if"p4ExitCode"in d: 213die("p4 describe -s%dexited with%d:%s"% (change, d["p4ExitCode"], 214str(d))) 215if"code"in d: 216if d["code"] =="error": 217die("p4 describe -s%dreturned error code:%s"% (change,str(d))) 218 219if"time"not in d: 220die("p4 describe -s%dreturned no\"time\":%s"% (change,str(d))) 221 222return d 223 224# 225# Canonicalize the p4 type and return a tuple of the 226# base type, plus any modifiers. See "p4 help filetypes" 227# for a list and explanation. 228# 229defsplit_p4_type(p4type): 230 231 p4_filetypes_historical = { 232"ctempobj":"binary+Sw", 233"ctext":"text+C", 234"cxtext":"text+Cx", 235"ktext":"text+k", 236"kxtext":"text+kx", 237"ltext":"text+F", 238"tempobj":"binary+FSw", 239"ubinary":"binary+F", 240"uresource":"resource+F", 241"uxbinary":"binary+Fx", 242"xbinary":"binary+x", 243"xltext":"text+Fx", 244"xtempobj":"binary+Swx", 245"xtext":"text+x", 246"xunicode":"unicode+x", 247"xutf16":"utf16+x", 248} 249if p4type in p4_filetypes_historical: 250 p4type = p4_filetypes_historical[p4type] 251 mods ="" 252 s = p4type.split("+") 253 base = s[0] 254 mods ="" 255iflen(s) >1: 256 mods = s[1] 257return(base, mods) 258 259# 260# return the raw p4 type of a file (text, text+ko, etc) 261# 262defp4_type(file): 263 results =p4CmdList(["fstat","-T","headType",file]) 264return results[0]['headType'] 265 266# 267# Given a type base and modifier, return a regexp matching 268# the keywords that can be expanded in the file 269# 270defp4_keywords_regexp_for_type(base, type_mods): 271if base in("text","unicode","binary"): 272 kwords =None 273if"ko"in type_mods: 274 kwords ='Id|Header' 275elif"k"in type_mods: 276 kwords ='Id|Header|Author|Date|DateTime|Change|File|Revision' 277else: 278return None 279 pattern = r""" 280 \$ # Starts with a dollar, followed by... 281 (%s) # one of the keywords, followed by... 282 (:[^$\n]+)? # possibly an old expansion, followed by... 283 \$ # another dollar 284 """% kwords 285return pattern 286else: 287return None 288 289# 290# Given a file, return a regexp matching the possible 291# RCS keywords that will be expanded, or None for files 292# with kw expansion turned off. 293# 294defp4_keywords_regexp_for_file(file): 295if not os.path.exists(file): 296return None 297else: 298(type_base, type_mods) =split_p4_type(p4_type(file)) 299returnp4_keywords_regexp_for_type(type_base, type_mods) 300 301defsetP4ExecBit(file, mode): 302# Reopens an already open file and changes the execute bit to match 303# the execute bit setting in the passed in mode. 304 305 p4Type ="+x" 306 307if notisModeExec(mode): 308 p4Type =getP4OpenedType(file) 309 p4Type = re.sub('^([cku]?)x(.*)','\\1\\2', p4Type) 310 p4Type = re.sub('(.*?\+.*?)x(.*?)','\\1\\2', p4Type) 311if p4Type[-1] =="+": 312 p4Type = p4Type[0:-1] 313 314p4_reopen(p4Type,file) 315 316defgetP4OpenedType(file): 317# Returns the perforce file type for the given file. 318 319 result =p4_read_pipe(["opened",wildcard_encode(file)]) 320 match = re.match(".*\((.+)\)\r?$", result) 321if match: 322return match.group(1) 323else: 324die("Could not determine file type for%s(result: '%s')"% (file, result)) 325 326# Return the set of all p4 labels 327defgetP4Labels(depotPaths): 328 labels =set() 329ifisinstance(depotPaths,basestring): 330 depotPaths = [depotPaths] 331 332for l inp4CmdList(["labels"] + ["%s..."% p for p in depotPaths]): 333 label = l['label'] 334 labels.add(label) 335 336return labels 337 338# Return the set of all git tags 339defgetGitTags(): 340 gitTags =set() 341for line inread_pipe_lines(["git","tag"]): 342 tag = line.strip() 343 gitTags.add(tag) 344return gitTags 345 346defdiffTreePattern(): 347# This is a simple generator for the diff tree regex pattern. This could be 348# a class variable if this and parseDiffTreeEntry were a part of a class. 349 pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)') 350while True: 351yield pattern 352 353defparseDiffTreeEntry(entry): 354"""Parses a single diff tree entry into its component elements. 355 356 See git-diff-tree(1) manpage for details about the format of the diff 357 output. This method returns a dictionary with the following elements: 358 359 src_mode - The mode of the source file 360 dst_mode - The mode of the destination file 361 src_sha1 - The sha1 for the source file 362 dst_sha1 - The sha1 fr the destination file 363 status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc) 364 status_score - The score for the status (applicable for 'C' and 'R' 365 statuses). This is None if there is no score. 366 src - The path for the source file. 367 dst - The path for the destination file. This is only present for 368 copy or renames. If it is not present, this is None. 369 370 If the pattern is not matched, None is returned.""" 371 372 match =diffTreePattern().next().match(entry) 373if match: 374return{ 375'src_mode': match.group(1), 376'dst_mode': match.group(2), 377'src_sha1': match.group(3), 378'dst_sha1': match.group(4), 379'status': match.group(5), 380'status_score': match.group(6), 381'src': match.group(7), 382'dst': match.group(10) 383} 384return None 385 386defisModeExec(mode): 387# Returns True if the given git mode represents an executable file, 388# otherwise False. 389return mode[-3:] =="755" 390 391defisModeExecChanged(src_mode, dst_mode): 392returnisModeExec(src_mode) !=isModeExec(dst_mode) 393 394defp4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None): 395 396ifisinstance(cmd,basestring): 397 cmd ="-G "+ cmd 398 expand =True 399else: 400 cmd = ["-G"] + cmd 401 expand =False 402 403 cmd =p4_build_cmd(cmd) 404if verbose: 405 sys.stderr.write("Opening pipe:%s\n"%str(cmd)) 406 407# Use a temporary file to avoid deadlocks without 408# subprocess.communicate(), which would put another copy 409# of stdout into memory. 410 stdin_file =None 411if stdin is not None: 412 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode) 413ifisinstance(stdin,basestring): 414 stdin_file.write(stdin) 415else: 416for i in stdin: 417 stdin_file.write(i +'\n') 418 stdin_file.flush() 419 stdin_file.seek(0) 420 421 p4 = subprocess.Popen(cmd, 422 shell=expand, 423 stdin=stdin_file, 424 stdout=subprocess.PIPE) 425 426 result = [] 427try: 428while True: 429 entry = marshal.load(p4.stdout) 430if cb is not None: 431cb(entry) 432else: 433 result.append(entry) 434exceptEOFError: 435pass 436 exitCode = p4.wait() 437if exitCode !=0: 438 entry = {} 439 entry["p4ExitCode"] = exitCode 440 result.append(entry) 441 442return result 443 444defp4Cmd(cmd): 445list=p4CmdList(cmd) 446 result = {} 447for entry inlist: 448 result.update(entry) 449return result; 450 451defp4Where(depotPath): 452if not depotPath.endswith("/"): 453 depotPath +="/" 454 depotPath = depotPath +"..." 455 outputList =p4CmdList(["where", depotPath]) 456 output =None 457for entry in outputList: 458if"depotFile"in entry: 459if entry["depotFile"] == depotPath: 460 output = entry 461break 462elif"data"in entry: 463 data = entry.get("data") 464 space = data.find(" ") 465if data[:space] == depotPath: 466 output = entry 467break 468if output ==None: 469return"" 470if output["code"] =="error": 471return"" 472 clientPath ="" 473if"path"in output: 474 clientPath = output.get("path") 475elif"data"in output: 476 data = output.get("data") 477 lastSpace = data.rfind(" ") 478 clientPath = data[lastSpace +1:] 479 480if clientPath.endswith("..."): 481 clientPath = clientPath[:-3] 482return clientPath 483 484defcurrentGitBranch(): 485returnread_pipe("git name-rev HEAD").split(" ")[1].strip() 486 487defisValidGitDir(path): 488if(os.path.exists(path +"/HEAD") 489and os.path.exists(path +"/refs")and os.path.exists(path +"/objects")): 490return True; 491return False 492 493defparseRevision(ref): 494returnread_pipe("git rev-parse%s"% ref).strip() 495 496defbranchExists(ref): 497 rev =read_pipe(["git","rev-parse","-q","--verify", ref], 498 ignore_error=True) 499returnlen(rev) >0 500 501defextractLogMessageFromGitCommit(commit): 502 logMessage ="" 503 504## fixme: title is first line of commit, not 1st paragraph. 505 foundTitle =False 506for log inread_pipe_lines("git cat-file commit%s"% commit): 507if not foundTitle: 508iflen(log) ==1: 509 foundTitle =True 510continue 511 512 logMessage += log 513return logMessage 514 515defextractSettingsGitLog(log): 516 values = {} 517for line in log.split("\n"): 518 line = line.strip() 519 m = re.search(r"^ *\[git-p4: (.*)\]$", line) 520if not m: 521continue 522 523 assignments = m.group(1).split(':') 524for a in assignments: 525 vals = a.split('=') 526 key = vals[0].strip() 527 val = ('='.join(vals[1:])).strip() 528if val.endswith('\"')and val.startswith('"'): 529 val = val[1:-1] 530 531 values[key] = val 532 533 paths = values.get("depot-paths") 534if not paths: 535 paths = values.get("depot-path") 536if paths: 537 values['depot-paths'] = paths.split(',') 538return values 539 540defgitBranchExists(branch): 541 proc = subprocess.Popen(["git","rev-parse", branch], 542 stderr=subprocess.PIPE, stdout=subprocess.PIPE); 543return proc.wait() ==0; 544 545_gitConfig = {} 546defgitConfig(key, args =None):# set args to "--bool", for instance 547if not _gitConfig.has_key(key): 548 argsFilter ="" 549if args !=None: 550 argsFilter ="%s"% args 551 cmd ="git config%s%s"% (argsFilter, key) 552 _gitConfig[key] =read_pipe(cmd, ignore_error=True).strip() 553return _gitConfig[key] 554 555defgitConfigList(key): 556if not _gitConfig.has_key(key): 557 _gitConfig[key] =read_pipe("git config --get-all%s"% key, ignore_error=True).strip().split(os.linesep) 558return _gitConfig[key] 559 560defp4BranchesInGit(branchesAreInRemotes=True): 561"""Find all the branches whose names start with "p4/", looking 562 in remotes or heads as specified by the argument. Return 563 a dictionary of{ branch: revision }for each one found. 564 The branch names are the short names, without any 565 "p4/" prefix.""" 566 567 branches = {} 568 569 cmdline ="git rev-parse --symbolic " 570if branchesAreInRemotes: 571 cmdline +="--remotes" 572else: 573 cmdline +="--branches" 574 575for line inread_pipe_lines(cmdline): 576 line = line.strip() 577 578# only import to p4/ 579if not line.startswith('p4/'): 580continue 581# special symbolic ref to p4/master 582if line =="p4/HEAD": 583continue 584 585# strip off p4/ prefix 586 branch = line[len("p4/"):] 587 588 branches[branch] =parseRevision(line) 589 590return branches 591 592defbranch_exists(branch): 593"""Make sure that the given ref name really exists.""" 594 595 cmd = ["git","rev-parse","--symbolic","--verify", branch ] 596 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 597 out, _ = p.communicate() 598if p.returncode: 599return False 600# expect exactly one line of output: the branch name 601return out.rstrip() == branch 602 603deffindUpstreamBranchPoint(head ="HEAD"): 604 branches =p4BranchesInGit() 605# map from depot-path to branch name 606 branchByDepotPath = {} 607for branch in branches.keys(): 608 tip = branches[branch] 609 log =extractLogMessageFromGitCommit(tip) 610 settings =extractSettingsGitLog(log) 611if settings.has_key("depot-paths"): 612 paths =",".join(settings["depot-paths"]) 613 branchByDepotPath[paths] ="remotes/p4/"+ branch 614 615 settings =None 616 parent =0 617while parent <65535: 618 commit = head +"~%s"% parent 619 log =extractLogMessageFromGitCommit(commit) 620 settings =extractSettingsGitLog(log) 621if settings.has_key("depot-paths"): 622 paths =",".join(settings["depot-paths"]) 623if branchByDepotPath.has_key(paths): 624return[branchByDepotPath[paths], settings] 625 626 parent = parent +1 627 628return["", settings] 629 630defcreateOrUpdateBranchesFromOrigin(localRefPrefix ="refs/remotes/p4/", silent=True): 631if not silent: 632print("Creating/updating branch(es) in%sbased on origin branch(es)" 633% localRefPrefix) 634 635 originPrefix ="origin/p4/" 636 637for line inread_pipe_lines("git rev-parse --symbolic --remotes"): 638 line = line.strip() 639if(not line.startswith(originPrefix))or line.endswith("HEAD"): 640continue 641 642 headName = line[len(originPrefix):] 643 remoteHead = localRefPrefix + headName 644 originHead = line 645 646 original =extractSettingsGitLog(extractLogMessageFromGitCommit(originHead)) 647if(not original.has_key('depot-paths') 648or not original.has_key('change')): 649continue 650 651 update =False 652if notgitBranchExists(remoteHead): 653if verbose: 654print"creating%s"% remoteHead 655 update =True 656else: 657 settings =extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead)) 658if settings.has_key('change') >0: 659if settings['depot-paths'] == original['depot-paths']: 660 originP4Change =int(original['change']) 661 p4Change =int(settings['change']) 662if originP4Change > p4Change: 663print("%s(%s) is newer than%s(%s). " 664"Updating p4 branch from origin." 665% (originHead, originP4Change, 666 remoteHead, p4Change)) 667 update =True 668else: 669print("Ignoring:%swas imported from%swhile " 670"%swas imported from%s" 671% (originHead,','.join(original['depot-paths']), 672 remoteHead,','.join(settings['depot-paths']))) 673 674if update: 675system("git update-ref%s %s"% (remoteHead, originHead)) 676 677deforiginP4BranchesExist(): 678returngitBranchExists("origin")orgitBranchExists("origin/p4")orgitBranchExists("origin/p4/master") 679 680defp4ChangesForPaths(depotPaths, changeRange): 681assert depotPaths 682 cmd = ['changes'] 683for p in depotPaths: 684 cmd += ["%s...%s"% (p, changeRange)] 685 output =p4_read_pipe_lines(cmd) 686 687 changes = {} 688for line in output: 689 changeNum =int(line.split(" ")[1]) 690 changes[changeNum] =True 691 692 changelist = changes.keys() 693 changelist.sort() 694return changelist 695 696defp4PathStartsWith(path, prefix): 697# This method tries to remedy a potential mixed-case issue: 698# 699# If UserA adds //depot/DirA/file1 700# and UserB adds //depot/dira/file2 701# 702# we may or may not have a problem. If you have core.ignorecase=true, 703# we treat DirA and dira as the same directory 704 ignorecase =gitConfig("core.ignorecase","--bool") =="true" 705if ignorecase: 706return path.lower().startswith(prefix.lower()) 707return path.startswith(prefix) 708 709defgetClientSpec(): 710"""Look at the p4 client spec, create a View() object that contains 711 all the mappings, and return it.""" 712 713 specList =p4CmdList("client -o") 714iflen(specList) !=1: 715die('Output from "client -o" is%dlines, expecting 1'% 716len(specList)) 717 718# dictionary of all client parameters 719 entry = specList[0] 720 721# just the keys that start with "View" 722 view_keys = [ k for k in entry.keys()if k.startswith("View") ] 723 724# hold this new View 725 view =View() 726 727# append the lines, in order, to the view 728for view_num inrange(len(view_keys)): 729 k ="View%d"% view_num 730if k not in view_keys: 731die("Expected view key%smissing"% k) 732 view.append(entry[k]) 733 734return view 735 736defgetClientRoot(): 737"""Grab the client directory.""" 738 739 output =p4CmdList("client -o") 740iflen(output) !=1: 741die('Output from "client -o" is%dlines, expecting 1'%len(output)) 742 743 entry = output[0] 744if"Root"not in entry: 745die('Client has no "Root"') 746 747return entry["Root"] 748 749# 750# P4 wildcards are not allowed in filenames. P4 complains 751# if you simply add them, but you can force it with "-f", in 752# which case it translates them into %xx encoding internally. 753# 754defwildcard_decode(path): 755# Search for and fix just these four characters. Do % last so 756# that fixing it does not inadvertently create new %-escapes. 757# Cannot have * in a filename in windows; untested as to 758# what p4 would do in such a case. 759if not platform.system() =="Windows": 760 path = path.replace("%2A","*") 761 path = path.replace("%23","#") \ 762.replace("%40","@") \ 763.replace("%25","%") 764return path 765 766defwildcard_encode(path): 767# do % first to avoid double-encoding the %s introduced here 768 path = path.replace("%","%25") \ 769.replace("*","%2A") \ 770.replace("#","%23") \ 771.replace("@","%40") 772return path 773 774defwildcard_present(path): 775return path.translate(None,"*#@%") != path 776 777class Command: 778def__init__(self): 779 self.usage ="usage: %prog [options]" 780 self.needsGit =True 781 self.verbose =False 782 783class P4UserMap: 784def__init__(self): 785 self.userMapFromPerforceServer =False 786 self.myP4UserId =None 787 788defp4UserId(self): 789if self.myP4UserId: 790return self.myP4UserId 791 792 results =p4CmdList("user -o") 793for r in results: 794if r.has_key('User'): 795 self.myP4UserId = r['User'] 796return r['User'] 797die("Could not find your p4 user id") 798 799defp4UserIsMe(self, p4User): 800# return True if the given p4 user is actually me 801 me = self.p4UserId() 802if not p4User or p4User != me: 803return False 804else: 805return True 806 807defgetUserCacheFilename(self): 808 home = os.environ.get("HOME", os.environ.get("USERPROFILE")) 809return home +"/.gitp4-usercache.txt" 810 811defgetUserMapFromPerforceServer(self): 812if self.userMapFromPerforceServer: 813return 814 self.users = {} 815 self.emails = {} 816 817for output inp4CmdList("users"): 818if not output.has_key("User"): 819continue 820 self.users[output["User"]] = output["FullName"] +" <"+ output["Email"] +">" 821 self.emails[output["Email"]] = output["User"] 822 823 824 s ='' 825for(key, val)in self.users.items(): 826 s +="%s\t%s\n"% (key.expandtabs(1), val.expandtabs(1)) 827 828open(self.getUserCacheFilename(),"wb").write(s) 829 self.userMapFromPerforceServer =True 830 831defloadUserMapFromCache(self): 832 self.users = {} 833 self.userMapFromPerforceServer =False 834try: 835 cache =open(self.getUserCacheFilename(),"rb") 836 lines = cache.readlines() 837 cache.close() 838for line in lines: 839 entry = line.strip().split("\t") 840 self.users[entry[0]] = entry[1] 841exceptIOError: 842 self.getUserMapFromPerforceServer() 843 844classP4Debug(Command): 845def__init__(self): 846 Command.__init__(self) 847 self.options = [] 848 self.description ="A tool to debug the output of p4 -G." 849 self.needsGit =False 850 851defrun(self, args): 852 j =0 853for output inp4CmdList(args): 854print'Element:%d'% j 855 j +=1 856print output 857return True 858 859classP4RollBack(Command): 860def__init__(self): 861 Command.__init__(self) 862 self.options = [ 863 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true") 864] 865 self.description ="A tool to debug the multi-branch import. Don't use :)" 866 self.rollbackLocalBranches =False 867 868defrun(self, args): 869iflen(args) !=1: 870return False 871 maxChange =int(args[0]) 872 873if"p4ExitCode"inp4Cmd("changes -m 1"): 874die("Problems executing p4"); 875 876if self.rollbackLocalBranches: 877 refPrefix ="refs/heads/" 878 lines =read_pipe_lines("git rev-parse --symbolic --branches") 879else: 880 refPrefix ="refs/remotes/" 881 lines =read_pipe_lines("git rev-parse --symbolic --remotes") 882 883for line in lines: 884if self.rollbackLocalBranches or(line.startswith("p4/")and line !="p4/HEAD\n"): 885 line = line.strip() 886 ref = refPrefix + line 887 log =extractLogMessageFromGitCommit(ref) 888 settings =extractSettingsGitLog(log) 889 890 depotPaths = settings['depot-paths'] 891 change = settings['change'] 892 893 changed =False 894 895iflen(p4Cmd("changes -m 1 "+' '.join(['%s...@%s'% (p, maxChange) 896for p in depotPaths]))) ==0: 897print"Branch%sdid not exist at change%s, deleting."% (ref, maxChange) 898system("git update-ref -d%s`git rev-parse%s`"% (ref, ref)) 899continue 900 901while change andint(change) > maxChange: 902 changed =True 903if self.verbose: 904print"%sis at%s; rewinding towards%s"% (ref, change, maxChange) 905system("git update-ref%s\"%s^\""% (ref, ref)) 906 log =extractLogMessageFromGitCommit(ref) 907 settings =extractSettingsGitLog(log) 908 909 910 depotPaths = settings['depot-paths'] 911 change = settings['change'] 912 913if changed: 914print"%srewound to%s"% (ref, change) 915 916return True 917 918classP4Submit(Command, P4UserMap): 919 920 conflict_behavior_choices = ("ask","skip","quit") 921 922def__init__(self): 923 Command.__init__(self) 924 P4UserMap.__init__(self) 925 self.options = [ 926 optparse.make_option("--origin", dest="origin"), 927 optparse.make_option("-M", dest="detectRenames", action="store_true"), 928# preserve the user, requires relevant p4 permissions 929 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"), 930 optparse.make_option("--export-labels", dest="exportLabels", action="store_true"), 931 optparse.make_option("--dry-run","-n", dest="dry_run", action="store_true"), 932 optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"), 933 optparse.make_option("--conflict", dest="conflict_behavior", 934 choices=self.conflict_behavior_choices), 935 optparse.make_option("--branch", dest="branch"), 936] 937 self.description ="Submit changes from git to the perforce depot." 938 self.usage +=" [name of git branch to submit into perforce depot]" 939 self.origin ="" 940 self.detectRenames =False 941 self.preserveUser =gitConfig("git-p4.preserveUser").lower() =="true" 942 self.dry_run =False 943 self.prepare_p4_only =False 944 self.conflict_behavior =None 945 self.isWindows = (platform.system() =="Windows") 946 self.exportLabels =False 947 self.p4HasMoveCommand =p4_has_move_command() 948 self.branch =None 949 950defcheck(self): 951iflen(p4CmdList("opened ...")) >0: 952die("You have files opened with perforce! Close them before starting the sync.") 953 954defseparate_jobs_from_description(self, message): 955"""Extract and return a possible Jobs field in the commit 956 message. It goes into a separate section in the p4 change 957 specification. 958 959 A jobs line starts with "Jobs:" and looks like a new field 960 in a form. Values are white-space separated on the same 961 line or on following lines that start with a tab. 962 963 This does not parse and extract the full git commit message 964 like a p4 form. It just sees the Jobs: line as a marker 965 to pass everything from then on directly into the p4 form, 966 but outside the description section. 967 968 Return a tuple (stripped log message, jobs string).""" 969 970 m = re.search(r'^Jobs:', message, re.MULTILINE) 971if m is None: 972return(message,None) 973 974 jobtext = message[m.start():] 975 stripped_message = message[:m.start()].rstrip() 976return(stripped_message, jobtext) 977 978defprepareLogMessage(self, template, message, jobs): 979"""Edits the template returned from "p4 change -o" to insert 980 the message in the Description field, and the jobs text in 981 the Jobs field.""" 982 result ="" 983 984 inDescriptionSection =False 985 986for line in template.split("\n"): 987if line.startswith("#"): 988 result += line +"\n" 989continue 990 991if inDescriptionSection: 992if line.startswith("Files:")or line.startswith("Jobs:"): 993 inDescriptionSection =False 994# insert Jobs section 995if jobs: 996 result += jobs +"\n" 997else: 998continue 999else:1000if line.startswith("Description:"):1001 inDescriptionSection =True1002 line +="\n"1003for messageLine in message.split("\n"):1004 line +="\t"+ messageLine +"\n"10051006 result += line +"\n"10071008return result10091010defpatchRCSKeywords(self,file, pattern):1011# Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern1012(handle, outFileName) = tempfile.mkstemp(dir='.')1013try:1014 outFile = os.fdopen(handle,"w+")1015 inFile =open(file,"r")1016 regexp = re.compile(pattern, re.VERBOSE)1017for line in inFile.readlines():1018 line = regexp.sub(r'$\1$', line)1019 outFile.write(line)1020 inFile.close()1021 outFile.close()1022# Forcibly overwrite the original file1023 os.unlink(file)1024 shutil.move(outFileName,file)1025except:1026# cleanup our temporary file1027 os.unlink(outFileName)1028print"Failed to strip RCS keywords in%s"%file1029raise10301031print"Patched up RCS keywords in%s"%file10321033defp4UserForCommit(self,id):1034# Return the tuple (perforce user,git email) for a given git commit id1035 self.getUserMapFromPerforceServer()1036 gitEmail =read_pipe("git log --max-count=1 --format='%%ae'%s"%id)1037 gitEmail = gitEmail.strip()1038if not self.emails.has_key(gitEmail):1039return(None,gitEmail)1040else:1041return(self.emails[gitEmail],gitEmail)10421043defcheckValidP4Users(self,commits):1044# check if any git authors cannot be mapped to p4 users1045foridin commits:1046(user,email) = self.p4UserForCommit(id)1047if not user:1048 msg ="Cannot find p4 user for email%sin commit%s."% (email,id)1049ifgitConfig('git-p4.allowMissingP4Users').lower() =="true":1050print"%s"% msg1051else:1052die("Error:%s\nSet git-p4.allowMissingP4Users to true to allow this."% msg)10531054deflastP4Changelist(self):1055# Get back the last changelist number submitted in this client spec. This1056# then gets used to patch up the username in the change. If the same1057# client spec is being used by multiple processes then this might go1058# wrong.1059 results =p4CmdList("client -o")# find the current client1060 client =None1061for r in results:1062if r.has_key('Client'):1063 client = r['Client']1064break1065if not client:1066die("could not get client spec")1067 results =p4CmdList(["changes","-c", client,"-m","1"])1068for r in results:1069if r.has_key('change'):1070return r['change']1071die("Could not get changelist number for last submit - cannot patch up user details")10721073defmodifyChangelistUser(self, changelist, newUser):1074# fixup the user field of a changelist after it has been submitted.1075 changes =p4CmdList("change -o%s"% changelist)1076iflen(changes) !=1:1077die("Bad output from p4 change modifying%sto user%s"%1078(changelist, newUser))10791080 c = changes[0]1081if c['User'] == newUser:return# nothing to do1082 c['User'] = newUser1083input= marshal.dumps(c)10841085 result =p4CmdList("change -f -i", stdin=input)1086for r in result:1087if r.has_key('code'):1088if r['code'] =='error':1089die("Could not modify user field of changelist%sto%s:%s"% (changelist, newUser, r['data']))1090if r.has_key('data'):1091print("Updated user field for changelist%sto%s"% (changelist, newUser))1092return1093die("Could not modify user field of changelist%sto%s"% (changelist, newUser))10941095defcanChangeChangelists(self):1096# check to see if we have p4 admin or super-user permissions, either of1097# which are required to modify changelists.1098 results =p4CmdList(["protects", self.depotPath])1099for r in results:1100if r.has_key('perm'):1101if r['perm'] =='admin':1102return11103if r['perm'] =='super':1104return11105return011061107defprepareSubmitTemplate(self):1108"""Run "p4 change -o" to grab a change specification template.1109 This does not use "p4 -G", as it is nice to keep the submission1110 template in original order, since a human might edit it.11111112 Remove lines in the Files section that show changes to files1113 outside the depot path we're committing into."""11141115 template =""1116 inFilesSection =False1117for line inp4_read_pipe_lines(['change','-o']):1118if line.endswith("\r\n"):1119 line = line[:-2] +"\n"1120if inFilesSection:1121if line.startswith("\t"):1122# path starts and ends with a tab1123 path = line[1:]1124 lastTab = path.rfind("\t")1125if lastTab != -1:1126 path = path[:lastTab]1127if notp4PathStartsWith(path, self.depotPath):1128continue1129else:1130 inFilesSection =False1131else:1132if line.startswith("Files:"):1133 inFilesSection =True11341135 template += line11361137return template11381139defedit_template(self, template_file):1140"""Invoke the editor to let the user change the submission1141 message. Return true if okay to continue with the submit."""11421143# if configured to skip the editing part, just submit1144ifgitConfig("git-p4.skipSubmitEdit") =="true":1145return True11461147# look at the modification time, to check later if the user saved1148# the file1149 mtime = os.stat(template_file).st_mtime11501151# invoke the editor1152if os.environ.has_key("P4EDITOR")and(os.environ.get("P4EDITOR") !=""):1153 editor = os.environ.get("P4EDITOR")1154else:1155 editor =read_pipe("git var GIT_EDITOR").strip()1156system(editor +" "+ template_file)11571158# If the file was not saved, prompt to see if this patch should1159# be skipped. But skip this verification step if configured so.1160ifgitConfig("git-p4.skipSubmitEditCheck") =="true":1161return True11621163# modification time updated means user saved the file1164if os.stat(template_file).st_mtime > mtime:1165return True11661167while True:1168 response =raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")1169if response =='y':1170return True1171if response =='n':1172return False11731174defapplyCommit(self,id):1175"""Apply one commit, return True if it succeeded."""11761177print"Applying",read_pipe(["git","show","-s",1178"--format=format:%h%s",id])11791180(p4User, gitEmail) = self.p4UserForCommit(id)11811182 diff =read_pipe_lines("git diff-tree -r%s\"%s^\" \"%s\""% (self.diffOpts,id,id))1183 filesToAdd =set()1184 filesToDelete =set()1185 editedFiles =set()1186 pureRenameCopy =set()1187 filesToChangeExecBit = {}11881189for line in diff:1190 diff =parseDiffTreeEntry(line)1191 modifier = diff['status']1192 path = diff['src']1193if modifier =="M":1194p4_edit(path)1195ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1196 filesToChangeExecBit[path] = diff['dst_mode']1197 editedFiles.add(path)1198elif modifier =="A":1199 filesToAdd.add(path)1200 filesToChangeExecBit[path] = diff['dst_mode']1201if path in filesToDelete:1202 filesToDelete.remove(path)1203elif modifier =="D":1204 filesToDelete.add(path)1205if path in filesToAdd:1206 filesToAdd.remove(path)1207elif modifier =="C":1208 src, dest = diff['src'], diff['dst']1209p4_integrate(src, dest)1210 pureRenameCopy.add(dest)1211if diff['src_sha1'] != diff['dst_sha1']:1212p4_edit(dest)1213 pureRenameCopy.discard(dest)1214ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1215p4_edit(dest)1216 pureRenameCopy.discard(dest)1217 filesToChangeExecBit[dest] = diff['dst_mode']1218 os.unlink(dest)1219 editedFiles.add(dest)1220elif modifier =="R":1221 src, dest = diff['src'], diff['dst']1222if self.p4HasMoveCommand:1223p4_edit(src)# src must be open before move1224p4_move(src, dest)# opens for (move/delete, move/add)1225else:1226p4_integrate(src, dest)1227if diff['src_sha1'] != diff['dst_sha1']:1228p4_edit(dest)1229else:1230 pureRenameCopy.add(dest)1231ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1232if not self.p4HasMoveCommand:1233p4_edit(dest)# with move: already open, writable1234 filesToChangeExecBit[dest] = diff['dst_mode']1235if not self.p4HasMoveCommand:1236 os.unlink(dest)1237 filesToDelete.add(src)1238 editedFiles.add(dest)1239else:1240die("unknown modifier%sfor%s"% (modifier, path))12411242 diffcmd ="git format-patch -k --stdout\"%s^\"..\"%s\""% (id,id)1243 patchcmd = diffcmd +" | git apply "1244 tryPatchCmd = patchcmd +"--check -"1245 applyPatchCmd = patchcmd +"--check --apply -"1246 patch_succeeded =True12471248if os.system(tryPatchCmd) !=0:1249 fixed_rcs_keywords =False1250 patch_succeeded =False1251print"Unfortunately applying the change failed!"12521253# Patch failed, maybe it's just RCS keyword woes. Look through1254# the patch to see if that's possible.1255ifgitConfig("git-p4.attemptRCSCleanup","--bool") =="true":1256file=None1257 pattern =None1258 kwfiles = {}1259forfilein editedFiles | filesToDelete:1260# did this file's delta contain RCS keywords?1261 pattern =p4_keywords_regexp_for_file(file)12621263if pattern:1264# this file is a possibility...look for RCS keywords.1265 regexp = re.compile(pattern, re.VERBOSE)1266for line inread_pipe_lines(["git","diff","%s^..%s"% (id,id),file]):1267if regexp.search(line):1268if verbose:1269print"got keyword match on%sin%sin%s"% (pattern, line,file)1270 kwfiles[file] = pattern1271break12721273forfilein kwfiles:1274if verbose:1275print"zapping%swith%s"% (line,pattern)1276 self.patchRCSKeywords(file, kwfiles[file])1277 fixed_rcs_keywords =True12781279if fixed_rcs_keywords:1280print"Retrying the patch with RCS keywords cleaned up"1281if os.system(tryPatchCmd) ==0:1282 patch_succeeded =True12831284if not patch_succeeded:1285for f in editedFiles:1286p4_revert(f)1287return False12881289#1290# Apply the patch for real, and do add/delete/+x handling.1291#1292system(applyPatchCmd)12931294for f in filesToAdd:1295p4_add(f)1296for f in filesToDelete:1297p4_revert(f)1298p4_delete(f)12991300# Set/clear executable bits1301for f in filesToChangeExecBit.keys():1302 mode = filesToChangeExecBit[f]1303setP4ExecBit(f, mode)13041305#1306# Build p4 change description, starting with the contents1307# of the git commit message.1308#1309 logMessage =extractLogMessageFromGitCommit(id)1310 logMessage = logMessage.strip()1311(logMessage, jobs) = self.separate_jobs_from_description(logMessage)13121313 template = self.prepareSubmitTemplate()1314 submitTemplate = self.prepareLogMessage(template, logMessage, jobs)13151316if self.preserveUser:1317 submitTemplate +="\n######## Actual user%s, modified after commit\n"% p4User13181319if self.checkAuthorship and not self.p4UserIsMe(p4User):1320 submitTemplate +="######## git author%sdoes not match your p4 account.\n"% gitEmail1321 submitTemplate +="######## Use option --preserve-user to modify authorship.\n"1322 submitTemplate +="######## Variable git-p4.skipUserNameCheck hides this message.\n"13231324 separatorLine ="######## everything below this line is just the diff #######\n"13251326# diff1327if os.environ.has_key("P4DIFF"):1328del(os.environ["P4DIFF"])1329 diff =""1330for editedFile in editedFiles:1331 diff +=p4_read_pipe(['diff','-du',1332wildcard_encode(editedFile)])13331334# new file diff1335 newdiff =""1336for newFile in filesToAdd:1337 newdiff +="==== new file ====\n"1338 newdiff +="--- /dev/null\n"1339 newdiff +="+++%s\n"% newFile1340 f =open(newFile,"r")1341for line in f.readlines():1342 newdiff +="+"+ line1343 f.close()13441345# change description file: submitTemplate, separatorLine, diff, newdiff1346(handle, fileName) = tempfile.mkstemp()1347 tmpFile = os.fdopen(handle,"w+")1348if self.isWindows:1349 submitTemplate = submitTemplate.replace("\n","\r\n")1350 separatorLine = separatorLine.replace("\n","\r\n")1351 newdiff = newdiff.replace("\n","\r\n")1352 tmpFile.write(submitTemplate + separatorLine + diff + newdiff)1353 tmpFile.close()13541355if self.prepare_p4_only:1356#1357# Leave the p4 tree prepared, and the submit template around1358# and let the user decide what to do next1359#1360print1361print"P4 workspace prepared for submission."1362print"To submit or revert, go to client workspace"1363print" "+ self.clientPath1364print1365print"To submit, use\"p4 submit\"to write a new description,"1366print"or\"p4 submit -i%s\"to use the one prepared by" \1367"\"git p4\"."% fileName1368print"You can delete the file\"%s\"when finished."% fileName13691370if self.preserveUser and p4User and not self.p4UserIsMe(p4User):1371print"To preserve change ownership by user%s, you must\n" \1372"do\"p4 change -f <change>\"after submitting and\n" \1373"edit the User field."1374if pureRenameCopy:1375print"After submitting, renamed files must be re-synced."1376print"Invoke\"p4 sync -f\"on each of these files:"1377for f in pureRenameCopy:1378print" "+ f13791380print1381print"To revert the changes, use\"p4 revert ...\", and delete"1382print"the submit template file\"%s\""% fileName1383if filesToAdd:1384print"Since the commit adds new files, they must be deleted:"1385for f in filesToAdd:1386print" "+ f1387print1388return True13891390#1391# Let the user edit the change description, then submit it.1392#1393if self.edit_template(fileName):1394# read the edited message and submit1395 ret =True1396 tmpFile =open(fileName,"rb")1397 message = tmpFile.read()1398 tmpFile.close()1399 submitTemplate = message[:message.index(separatorLine)]1400if self.isWindows:1401 submitTemplate = submitTemplate.replace("\r\n","\n")1402p4_write_pipe(['submit','-i'], submitTemplate)14031404if self.preserveUser:1405if p4User:1406# Get last changelist number. Cannot easily get it from1407# the submit command output as the output is1408# unmarshalled.1409 changelist = self.lastP4Changelist()1410 self.modifyChangelistUser(changelist, p4User)14111412# The rename/copy happened by applying a patch that created a1413# new file. This leaves it writable, which confuses p4.1414for f in pureRenameCopy:1415p4_sync(f,"-f")14161417else:1418# skip this patch1419 ret =False1420print"Submission cancelled, undoing p4 changes."1421for f in editedFiles:1422p4_revert(f)1423for f in filesToAdd:1424p4_revert(f)1425 os.remove(f)1426for f in filesToDelete:1427p4_revert(f)14281429 os.remove(fileName)1430return ret14311432# Export git tags as p4 labels. Create a p4 label and then tag1433# with that.1434defexportGitTags(self, gitTags):1435 validLabelRegexp =gitConfig("git-p4.labelExportRegexp")1436iflen(validLabelRegexp) ==0:1437 validLabelRegexp = defaultLabelRegexp1438 m = re.compile(validLabelRegexp)14391440for name in gitTags:14411442if not m.match(name):1443if verbose:1444print"tag%sdoes not match regexp%s"% (name, validLabelRegexp)1445continue14461447# Get the p4 commit this corresponds to1448 logMessage =extractLogMessageFromGitCommit(name)1449 values =extractSettingsGitLog(logMessage)14501451if not values.has_key('change'):1452# a tag pointing to something not sent to p4; ignore1453if verbose:1454print"git tag%sdoes not give a p4 commit"% name1455continue1456else:1457 changelist = values['change']14581459# Get the tag details.1460 inHeader =True1461 isAnnotated =False1462 body = []1463for l inread_pipe_lines(["git","cat-file","-p", name]):1464 l = l.strip()1465if inHeader:1466if re.match(r'tag\s+', l):1467 isAnnotated =True1468elif re.match(r'\s*$', l):1469 inHeader =False1470continue1471else:1472 body.append(l)14731474if not isAnnotated:1475 body = ["lightweight tag imported by git p4\n"]14761477# Create the label - use the same view as the client spec we are using1478 clientSpec =getClientSpec()14791480 labelTemplate ="Label:%s\n"% name1481 labelTemplate +="Description:\n"1482for b in body:1483 labelTemplate +="\t"+ b +"\n"1484 labelTemplate +="View:\n"1485for mapping in clientSpec.mappings:1486 labelTemplate +="\t%s\n"% mapping.depot_side.path14871488if self.dry_run:1489print"Would create p4 label%sfor tag"% name1490elif self.prepare_p4_only:1491print"Not creating p4 label%sfor tag due to option" \1492" --prepare-p4-only"% name1493else:1494p4_write_pipe(["label","-i"], labelTemplate)14951496# Use the label1497p4_system(["tag","-l", name] +1498["%s@%s"% (mapping.depot_side.path, changelist)for mapping in clientSpec.mappings])14991500if verbose:1501print"created p4 label for tag%s"% name15021503defrun(self, args):1504iflen(args) ==0:1505 self.master =currentGitBranch()1506iflen(self.master) ==0or notgitBranchExists("refs/heads/%s"% self.master):1507die("Detecting current git branch failed!")1508eliflen(args) ==1:1509 self.master = args[0]1510if notbranchExists(self.master):1511die("Branch%sdoes not exist"% self.master)1512else:1513return False15141515 allowSubmit =gitConfig("git-p4.allowSubmit")1516iflen(allowSubmit) >0and not self.master in allowSubmit.split(","):1517die("%sis not in git-p4.allowSubmit"% self.master)15181519[upstream, settings] =findUpstreamBranchPoint()1520 self.depotPath = settings['depot-paths'][0]1521iflen(self.origin) ==0:1522 self.origin = upstream15231524if self.preserveUser:1525if not self.canChangeChangelists():1526die("Cannot preserve user names without p4 super-user or admin permissions")15271528# if not set from the command line, try the config file1529if self.conflict_behavior is None:1530 val =gitConfig("git-p4.conflict")1531if val:1532if val not in self.conflict_behavior_choices:1533die("Invalid value '%s' for config git-p4.conflict"% val)1534else:1535 val ="ask"1536 self.conflict_behavior = val15371538if self.verbose:1539print"Origin branch is "+ self.origin15401541iflen(self.depotPath) ==0:1542print"Internal error: cannot locate perforce depot path from existing branches"1543 sys.exit(128)15441545 self.useClientSpec =False1546ifgitConfig("git-p4.useclientspec","--bool") =="true":1547 self.useClientSpec =True1548if self.useClientSpec:1549 self.clientSpecDirs =getClientSpec()15501551if self.useClientSpec:1552# all files are relative to the client spec1553 self.clientPath =getClientRoot()1554else:1555 self.clientPath =p4Where(self.depotPath)15561557if self.clientPath =="":1558die("Error: Cannot locate perforce checkout of%sin client view"% self.depotPath)15591560print"Perforce checkout for depot path%slocated at%s"% (self.depotPath, self.clientPath)1561 self.oldWorkingDirectory = os.getcwd()15621563# ensure the clientPath exists1564 new_client_dir =False1565if not os.path.exists(self.clientPath):1566 new_client_dir =True1567 os.makedirs(self.clientPath)15681569chdir(self.clientPath)1570if self.dry_run:1571print"Would synchronize p4 checkout in%s"% self.clientPath1572else:1573print"Synchronizing p4 checkout..."1574if new_client_dir:1575# old one was destroyed, and maybe nobody told p41576p4_sync("...","-f")1577else:1578p4_sync("...")1579 self.check()15801581 commits = []1582for line inread_pipe_lines("git rev-list --no-merges%s..%s"% (self.origin, self.master)):1583 commits.append(line.strip())1584 commits.reverse()15851586if self.preserveUser or(gitConfig("git-p4.skipUserNameCheck") =="true"):1587 self.checkAuthorship =False1588else:1589 self.checkAuthorship =True15901591if self.preserveUser:1592 self.checkValidP4Users(commits)15931594#1595# Build up a set of options to be passed to diff when1596# submitting each commit to p4.1597#1598if self.detectRenames:1599# command-line -M arg1600 self.diffOpts ="-M"1601else:1602# If not explicitly set check the config variable1603 detectRenames =gitConfig("git-p4.detectRenames")16041605if detectRenames.lower() =="false"or detectRenames =="":1606 self.diffOpts =""1607elif detectRenames.lower() =="true":1608 self.diffOpts ="-M"1609else:1610 self.diffOpts ="-M%s"% detectRenames16111612# no command-line arg for -C or --find-copies-harder, just1613# config variables1614 detectCopies =gitConfig("git-p4.detectCopies")1615if detectCopies.lower() =="false"or detectCopies =="":1616pass1617elif detectCopies.lower() =="true":1618 self.diffOpts +=" -C"1619else:1620 self.diffOpts +=" -C%s"% detectCopies16211622ifgitConfig("git-p4.detectCopiesHarder","--bool") =="true":1623 self.diffOpts +=" --find-copies-harder"16241625#1626# Apply the commits, one at a time. On failure, ask if should1627# continue to try the rest of the patches, or quit.1628#1629if self.dry_run:1630print"Would apply"1631 applied = []1632 last =len(commits) -11633for i, commit inenumerate(commits):1634if self.dry_run:1635print" ",read_pipe(["git","show","-s",1636"--format=format:%h%s", commit])1637 ok =True1638else:1639 ok = self.applyCommit(commit)1640if ok:1641 applied.append(commit)1642else:1643if self.prepare_p4_only and i < last:1644print"Processing only the first commit due to option" \1645" --prepare-p4-only"1646break1647if i < last:1648 quit =False1649while True:1650# prompt for what to do, or use the option/variable1651if self.conflict_behavior =="ask":1652print"What do you want to do?"1653 response =raw_input("[s]kip this commit but apply"1654" the rest, or [q]uit? ")1655if not response:1656continue1657elif self.conflict_behavior =="skip":1658 response ="s"1659elif self.conflict_behavior =="quit":1660 response ="q"1661else:1662die("Unknown conflict_behavior '%s'"%1663 self.conflict_behavior)16641665if response[0] =="s":1666print"Skipping this commit, but applying the rest"1667break1668if response[0] =="q":1669print"Quitting"1670 quit =True1671break1672if quit:1673break16741675chdir(self.oldWorkingDirectory)16761677if self.dry_run:1678pass1679elif self.prepare_p4_only:1680pass1681eliflen(commits) ==len(applied):1682print"All commits applied!"16831684 sync =P4Sync()1685if self.branch:1686 sync.branch = self.branch1687 sync.run([])16881689 rebase =P4Rebase()1690 rebase.rebase()16911692else:1693iflen(applied) ==0:1694print"No commits applied."1695else:1696print"Applied only the commits marked with '*':"1697for c in commits:1698if c in applied:1699 star ="*"1700else:1701 star =" "1702print star,read_pipe(["git","show","-s",1703"--format=format:%h%s", c])1704print"You will have to do 'git p4 sync' and rebase."17051706ifgitConfig("git-p4.exportLabels","--bool") =="true":1707 self.exportLabels =True17081709if self.exportLabels:1710 p4Labels =getP4Labels(self.depotPath)1711 gitTags =getGitTags()17121713 missingGitTags = gitTags - p4Labels1714 self.exportGitTags(missingGitTags)17151716# exit with error unless everything applied perfecly1717iflen(commits) !=len(applied):1718 sys.exit(1)17191720return True17211722classView(object):1723"""Represent a p4 view ("p4 help views"), and map files in a1724 repo according to the view."""17251726classPath(object):1727"""A depot or client path, possibly containing wildcards.1728 The only one supported is ... at the end, currently.1729 Initialize with the full path, with //depot or //client."""17301731def__init__(self, path, is_depot):1732 self.path = path1733 self.is_depot = is_depot1734 self.find_wildcards()1735# remember the prefix bit, useful for relative mappings1736 m = re.match("(//[^/]+/)", self.path)1737if not m:1738die("Path%sdoes not start with //prefix/"% self.path)1739 prefix = m.group(1)1740if not self.is_depot:1741# strip //client/ on client paths1742 self.path = self.path[len(prefix):]17431744deffind_wildcards(self):1745"""Make sure wildcards are valid, and set up internal1746 variables."""17471748 self.ends_triple_dot =False1749# There are three wildcards allowed in p4 views1750# (see "p4 help views"). This code knows how to1751# handle "..." (only at the end), but cannot deal with1752# "%%n" or "*". Only check the depot_side, as p4 should1753# validate that the client_side matches too.1754if re.search(r'%%[1-9]', self.path):1755die("Can't handle%%n wildcards in view:%s"% self.path)1756if self.path.find("*") >=0:1757die("Can't handle * wildcards in view:%s"% self.path)1758 triple_dot_index = self.path.find("...")1759if triple_dot_index >=0:1760if triple_dot_index !=len(self.path) -3:1761die("Can handle only single ... wildcard, at end:%s"%1762 self.path)1763 self.ends_triple_dot =True17641765defensure_compatible(self, other_path):1766"""Make sure the wildcards agree."""1767if self.ends_triple_dot != other_path.ends_triple_dot:1768die("Both paths must end with ... if either does;\n"+1769"paths:%s %s"% (self.path, other_path.path))17701771defmatch_wildcards(self, test_path):1772"""See if this test_path matches us, and fill in the value1773 of the wildcards if so. Returns a tuple of1774 (True|False, wildcards[]). For now, only the ... at end1775 is supported, so at most one wildcard."""1776if self.ends_triple_dot:1777 dotless = self.path[:-3]1778if test_path.startswith(dotless):1779 wildcard = test_path[len(dotless):]1780return(True, [ wildcard ])1781else:1782if test_path == self.path:1783return(True, [])1784return(False, [])17851786defmatch(self, test_path):1787"""Just return if it matches; don't bother with the wildcards."""1788 b, _ = self.match_wildcards(test_path)1789return b17901791deffill_in_wildcards(self, wildcards):1792"""Return the relative path, with the wildcards filled in1793 if there are any."""1794if self.ends_triple_dot:1795return self.path[:-3] + wildcards[0]1796else:1797return self.path17981799classMapping(object):1800def__init__(self, depot_side, client_side, overlay, exclude):1801# depot_side is without the trailing /... if it had one1802 self.depot_side = View.Path(depot_side, is_depot=True)1803 self.client_side = View.Path(client_side, is_depot=False)1804 self.overlay = overlay # started with "+"1805 self.exclude = exclude # started with "-"1806assert not(self.overlay and self.exclude)1807 self.depot_side.ensure_compatible(self.client_side)18081809def__str__(self):1810 c =" "1811if self.overlay:1812 c ="+"1813if self.exclude:1814 c ="-"1815return"View.Mapping:%s%s->%s"% \1816(c, self.depot_side.path, self.client_side.path)18171818defmap_depot_to_client(self, depot_path):1819"""Calculate the client path if using this mapping on the1820 given depot path; does not consider the effect of other1821 mappings in a view. Even excluded mappings are returned."""1822 matches, wildcards = self.depot_side.match_wildcards(depot_path)1823if not matches:1824return""1825 client_path = self.client_side.fill_in_wildcards(wildcards)1826return client_path18271828#1829# View methods1830#1831def__init__(self):1832 self.mappings = []18331834defappend(self, view_line):1835"""Parse a view line, splitting it into depot and client1836 sides. Append to self.mappings, preserving order."""18371838# Split the view line into exactly two words. P4 enforces1839# structure on these lines that simplifies this quite a bit.1840#1841# Either or both words may be double-quoted.1842# Single quotes do not matter.1843# Double-quote marks cannot occur inside the words.1844# A + or - prefix is also inside the quotes.1845# There are no quotes unless they contain a space.1846# The line is already white-space stripped.1847# The two words are separated by a single space.1848#1849if view_line[0] =='"':1850# First word is double quoted. Find its end.1851 close_quote_index = view_line.find('"',1)1852if close_quote_index <=0:1853die("No first-word closing quote found:%s"% view_line)1854 depot_side = view_line[1:close_quote_index]1855# skip closing quote and space1856 rhs_index = close_quote_index +1+11857else:1858 space_index = view_line.find(" ")1859if space_index <=0:1860die("No word-splitting space found:%s"% view_line)1861 depot_side = view_line[0:space_index]1862 rhs_index = space_index +118631864if view_line[rhs_index] =='"':1865# Second word is double quoted. Make sure there is a1866# double quote at the end too.1867if not view_line.endswith('"'):1868die("View line with rhs quote should end with one:%s"%1869 view_line)1870# skip the quotes1871 client_side = view_line[rhs_index+1:-1]1872else:1873 client_side = view_line[rhs_index:]18741875# prefix + means overlay on previous mapping1876 overlay =False1877if depot_side.startswith("+"):1878 overlay =True1879 depot_side = depot_side[1:]18801881# prefix - means exclude this path1882 exclude =False1883if depot_side.startswith("-"):1884 exclude =True1885 depot_side = depot_side[1:]18861887 m = View.Mapping(depot_side, client_side, overlay, exclude)1888 self.mappings.append(m)18891890defmap_in_client(self, depot_path):1891"""Return the relative location in the client where this1892 depot file should live. Returns "" if the file should1893 not be mapped in the client."""18941895 paths_filled = []1896 client_path =""18971898# look at later entries first1899for m in self.mappings[::-1]:19001901# see where will this path end up in the client1902 p = m.map_depot_to_client(depot_path)19031904if p =="":1905# Depot path does not belong in client. Must remember1906# this, as previous items should not cause files to1907# exist in this path either. Remember that the list is1908# being walked from the end, which has higher precedence.1909# Overlap mappings do not exclude previous mappings.1910if not m.overlay:1911 paths_filled.append(m.client_side)19121913else:1914# This mapping matched; no need to search any further.1915# But, the mapping could be rejected if the client path1916# has already been claimed by an earlier mapping (i.e.1917# one later in the list, which we are walking backwards).1918 already_mapped_in_client =False1919for f in paths_filled:1920# this is View.Path.match1921if f.match(p):1922 already_mapped_in_client =True1923break1924if not already_mapped_in_client:1925# Include this file, unless it is from a line that1926# explicitly said to exclude it.1927if not m.exclude:1928 client_path = p19291930# a match, even if rejected, always stops the search1931break19321933return client_path19341935classP4Sync(Command, P4UserMap):1936 delete_actions = ("delete","move/delete","purge")19371938def__init__(self):1939 Command.__init__(self)1940 P4UserMap.__init__(self)1941 self.options = [1942 optparse.make_option("--branch", dest="branch"),1943 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),1944 optparse.make_option("--changesfile", dest="changesFile"),1945 optparse.make_option("--silent", dest="silent", action="store_true"),1946 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),1947 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),1948 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",1949help="Import into refs/heads/ , not refs/remotes"),1950 optparse.make_option("--max-changes", dest="maxChanges"),1951 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',1952help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),1953 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',1954help="Only sync files that are included in the Perforce Client Spec")1955]1956 self.description ="""Imports from Perforce into a git repository.\n1957 example:1958 //depot/my/project/ -- to import the current head1959 //depot/my/project/@all -- to import everything1960 //depot/my/project/@1,6 -- to import only from revision 1 to 619611962 (a ... is not needed in the path p4 specification, it's added implicitly)"""19631964 self.usage +=" //depot/path[@revRange]"1965 self.silent =False1966 self.createdBranches =set()1967 self.committedChanges =set()1968 self.branch =""1969 self.detectBranches =False1970 self.detectLabels =False1971 self.importLabels =False1972 self.changesFile =""1973 self.syncWithOrigin =True1974 self.importIntoRemotes =True1975 self.maxChanges =""1976 self.isWindows = (platform.system() =="Windows")1977 self.keepRepoPath =False1978 self.depotPaths =None1979 self.p4BranchesInGit = []1980 self.cloneExclude = []1981 self.useClientSpec =False1982 self.useClientSpec_from_options =False1983 self.clientSpecDirs =None1984 self.tempBranches = []1985 self.tempBranchLocation ="git-p4-tmp"19861987ifgitConfig("git-p4.syncFromOrigin") =="false":1988 self.syncWithOrigin =False19891990# Force a checkpoint in fast-import and wait for it to finish1991defcheckpoint(self):1992 self.gitStream.write("checkpoint\n\n")1993 self.gitStream.write("progress checkpoint\n\n")1994 out = self.gitOutput.readline()1995if self.verbose:1996print"checkpoint finished: "+ out19971998defextractFilesFromCommit(self, commit):1999 self.cloneExclude = [re.sub(r"\.\.\.$","", path)2000for path in self.cloneExclude]2001 files = []2002 fnum =02003while commit.has_key("depotFile%s"% fnum):2004 path = commit["depotFile%s"% fnum]20052006if[p for p in self.cloneExclude2007ifp4PathStartsWith(path, p)]:2008 found =False2009else:2010 found = [p for p in self.depotPaths2011ifp4PathStartsWith(path, p)]2012if not found:2013 fnum = fnum +12014continue20152016file= {}2017file["path"] = path2018file["rev"] = commit["rev%s"% fnum]2019file["action"] = commit["action%s"% fnum]2020file["type"] = commit["type%s"% fnum]2021 files.append(file)2022 fnum = fnum +12023return files20242025defstripRepoPath(self, path, prefixes):2026"""When streaming files, this is called to map a p4 depot path2027 to where it should go in git. The prefixes are either2028 self.depotPaths, or self.branchPrefixes in the case of2029 branch detection."""20302031if self.useClientSpec:2032# branch detection moves files up a level (the branch name)2033# from what client spec interpretation gives2034 path = self.clientSpecDirs.map_in_client(path)2035if self.detectBranches:2036for b in self.knownBranches:2037if path.startswith(b +"/"):2038 path = path[len(b)+1:]20392040elif self.keepRepoPath:2041# Preserve everything in relative path name except leading2042# //depot/; just look at first prefix as they all should2043# be in the same depot.2044 depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])2045ifp4PathStartsWith(path, depot):2046 path = path[len(depot):]20472048else:2049for p in prefixes:2050ifp4PathStartsWith(path, p):2051 path = path[len(p):]2052break20532054 path =wildcard_decode(path)2055return path20562057defsplitFilesIntoBranches(self, commit):2058"""Look at each depotFile in the commit to figure out to what2059 branch it belongs."""20602061 branches = {}2062 fnum =02063while commit.has_key("depotFile%s"% fnum):2064 path = commit["depotFile%s"% fnum]2065 found = [p for p in self.depotPaths2066ifp4PathStartsWith(path, p)]2067if not found:2068 fnum = fnum +12069continue20702071file= {}2072file["path"] = path2073file["rev"] = commit["rev%s"% fnum]2074file["action"] = commit["action%s"% fnum]2075file["type"] = commit["type%s"% fnum]2076 fnum = fnum +120772078# start with the full relative path where this file would2079# go in a p4 client2080if self.useClientSpec:2081 relPath = self.clientSpecDirs.map_in_client(path)2082else:2083 relPath = self.stripRepoPath(path, self.depotPaths)20842085for branch in self.knownBranches.keys():2086# add a trailing slash so that a commit into qt/4.2foo2087# doesn't end up in qt/4.2, e.g.2088if relPath.startswith(branch +"/"):2089if branch not in branches:2090 branches[branch] = []2091 branches[branch].append(file)2092break20932094return branches20952096# output one file from the P4 stream2097# - helper for streamP4Files20982099defstreamOneP4File(self,file, contents):2100 relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)2101if verbose:2102 sys.stderr.write("%s\n"% relPath)21032104(type_base, type_mods) =split_p4_type(file["type"])21052106 git_mode ="100644"2107if"x"in type_mods:2108 git_mode ="100755"2109if type_base =="symlink":2110 git_mode ="120000"2111# p4 print on a symlink contains "target\n"; remove the newline2112 data =''.join(contents)2113 contents = [data[:-1]]21142115if type_base =="utf16":2116# p4 delivers different text in the python output to -G2117# than it does when using "print -o", or normal p4 client2118# operations. utf16 is converted to ascii or utf8, perhaps.2119# But ascii text saved as -t utf16 is completely mangled.2120# Invoke print -o to get the real contents.2121 text =p4_read_pipe(['print','-q','-o','-',file['depotFile']])2122 contents = [ text ]21232124if type_base =="apple":2125# Apple filetype files will be streamed as a concatenation of2126# its appledouble header and the contents. This is useless2127# on both macs and non-macs. If using "print -q -o xx", it2128# will create "xx" with the data, and "%xx" with the header.2129# This is also not very useful.2130#2131# Ideally, someday, this script can learn how to generate2132# appledouble files directly and import those to git, but2133# non-mac machines can never find a use for apple filetype.2134print"\nIgnoring apple filetype file%s"%file['depotFile']2135return21362137# Perhaps windows wants unicode, utf16 newlines translated too;2138# but this is not doing it.2139if self.isWindows and type_base =="text":2140 mangled = []2141for data in contents:2142 data = data.replace("\r\n","\n")2143 mangled.append(data)2144 contents = mangled21452146# Note that we do not try to de-mangle keywords on utf16 files,2147# even though in theory somebody may want that.2148 pattern =p4_keywords_regexp_for_type(type_base, type_mods)2149if pattern:2150 regexp = re.compile(pattern, re.VERBOSE)2151 text =''.join(contents)2152 text = regexp.sub(r'$\1$', text)2153 contents = [ text ]21542155 self.gitStream.write("M%sinline%s\n"% (git_mode, relPath))21562157# total length...2158 length =02159for d in contents:2160 length = length +len(d)21612162 self.gitStream.write("data%d\n"% length)2163for d in contents:2164 self.gitStream.write(d)2165 self.gitStream.write("\n")21662167defstreamOneP4Deletion(self,file):2168 relPath = self.stripRepoPath(file['path'], self.branchPrefixes)2169if verbose:2170 sys.stderr.write("delete%s\n"% relPath)2171 self.gitStream.write("D%s\n"% relPath)21722173# handle another chunk of streaming data2174defstreamP4FilesCb(self, marshalled):21752176# catch p4 errors and complain2177 err =None2178if"code"in marshalled:2179if marshalled["code"] =="error":2180if"data"in marshalled:2181 err = marshalled["data"].rstrip()2182if err:2183 f =None2184if self.stream_have_file_info:2185if"depotFile"in self.stream_file:2186 f = self.stream_file["depotFile"]2187# force a failure in fast-import, else an empty2188# commit will be made2189 self.gitStream.write("\n")2190 self.gitStream.write("die-now\n")2191 self.gitStream.close()2192# ignore errors, but make sure it exits first2193 self.importProcess.wait()2194if f:2195die("Error from p4 print for%s:%s"% (f, err))2196else:2197die("Error from p4 print:%s"% err)21982199if marshalled.has_key('depotFile')and self.stream_have_file_info:2200# start of a new file - output the old one first2201 self.streamOneP4File(self.stream_file, self.stream_contents)2202 self.stream_file = {}2203 self.stream_contents = []2204 self.stream_have_file_info =False22052206# pick up the new file information... for the2207# 'data' field we need to append to our array2208for k in marshalled.keys():2209if k =='data':2210 self.stream_contents.append(marshalled['data'])2211else:2212 self.stream_file[k] = marshalled[k]22132214 self.stream_have_file_info =True22152216# Stream directly from "p4 files" into "git fast-import"2217defstreamP4Files(self, files):2218 filesForCommit = []2219 filesToRead = []2220 filesToDelete = []22212222for f in files:2223# if using a client spec, only add the files that have2224# a path in the client2225if self.clientSpecDirs:2226if self.clientSpecDirs.map_in_client(f['path']) =="":2227continue22282229 filesForCommit.append(f)2230if f['action']in self.delete_actions:2231 filesToDelete.append(f)2232else:2233 filesToRead.append(f)22342235# deleted files...2236for f in filesToDelete:2237 self.streamOneP4Deletion(f)22382239iflen(filesToRead) >0:2240 self.stream_file = {}2241 self.stream_contents = []2242 self.stream_have_file_info =False22432244# curry self argument2245defstreamP4FilesCbSelf(entry):2246 self.streamP4FilesCb(entry)22472248 fileArgs = ['%s#%s'% (f['path'], f['rev'])for f in filesToRead]22492250p4CmdList(["-x","-","print"],2251 stdin=fileArgs,2252 cb=streamP4FilesCbSelf)22532254# do the last chunk2255if self.stream_file.has_key('depotFile'):2256 self.streamOneP4File(self.stream_file, self.stream_contents)22572258defmake_email(self, userid):2259if userid in self.users:2260return self.users[userid]2261else:2262return"%s<a@b>"% userid22632264# Stream a p4 tag2265defstreamTag(self, gitStream, labelName, labelDetails, commit, epoch):2266if verbose:2267print"writing tag%sfor commit%s"% (labelName, commit)2268 gitStream.write("tag%s\n"% labelName)2269 gitStream.write("from%s\n"% commit)22702271if labelDetails.has_key('Owner'):2272 owner = labelDetails["Owner"]2273else:2274 owner =None22752276# Try to use the owner of the p4 label, or failing that,2277# the current p4 user id.2278if owner:2279 email = self.make_email(owner)2280else:2281 email = self.make_email(self.p4UserId())2282 tagger ="%s %s %s"% (email, epoch, self.tz)22832284 gitStream.write("tagger%s\n"% tagger)22852286print"labelDetails=",labelDetails2287if labelDetails.has_key('Description'):2288 description = labelDetails['Description']2289else:2290 description ='Label from git p4'22912292 gitStream.write("data%d\n"%len(description))2293 gitStream.write(description)2294 gitStream.write("\n")22952296defcommit(self, details, files, branch, parent =""):2297 epoch = details["time"]2298 author = details["user"]22992300if self.verbose:2301print"commit into%s"% branch23022303# start with reading files; if that fails, we should not2304# create a commit.2305 new_files = []2306for f in files:2307if[p for p in self.branchPrefixes ifp4PathStartsWith(f['path'], p)]:2308 new_files.append(f)2309else:2310 sys.stderr.write("Ignoring file outside of prefix:%s\n"% f['path'])23112312 self.gitStream.write("commit%s\n"% branch)2313# gitStream.write("mark :%s\n" % details["change"])2314 self.committedChanges.add(int(details["change"]))2315 committer =""2316if author not in self.users:2317 self.getUserMapFromPerforceServer()2318 committer ="%s %s %s"% (self.make_email(author), epoch, self.tz)23192320 self.gitStream.write("committer%s\n"% committer)23212322 self.gitStream.write("data <<EOT\n")2323 self.gitStream.write(details["desc"])2324 self.gitStream.write("\n[git-p4: depot-paths =\"%s\": change =%s"%2325(','.join(self.branchPrefixes), details["change"]))2326iflen(details['options']) >0:2327 self.gitStream.write(": options =%s"% details['options'])2328 self.gitStream.write("]\nEOT\n\n")23292330iflen(parent) >0:2331if self.verbose:2332print"parent%s"% parent2333 self.gitStream.write("from%s\n"% parent)23342335 self.streamP4Files(new_files)2336 self.gitStream.write("\n")23372338 change =int(details["change"])23392340if self.labels.has_key(change):2341 label = self.labels[change]2342 labelDetails = label[0]2343 labelRevisions = label[1]2344if self.verbose:2345print"Change%sis labelled%s"% (change, labelDetails)23462347 files =p4CmdList(["files"] + ["%s...@%s"% (p, change)2348for p in self.branchPrefixes])23492350iflen(files) ==len(labelRevisions):23512352 cleanedFiles = {}2353for info in files:2354if info["action"]in self.delete_actions:2355continue2356 cleanedFiles[info["depotFile"]] = info["rev"]23572358if cleanedFiles == labelRevisions:2359 self.streamTag(self.gitStream,'tag_%s'% labelDetails['label'], labelDetails, branch, epoch)23602361else:2362if not self.silent:2363print("Tag%sdoes not match with change%s: files do not match."2364% (labelDetails["label"], change))23652366else:2367if not self.silent:2368print("Tag%sdoes not match with change%s: file count is different."2369% (labelDetails["label"], change))23702371# Build a dictionary of changelists and labels, for "detect-labels" option.2372defgetLabels(self):2373 self.labels = {}23742375 l =p4CmdList(["labels"] + ["%s..."% p for p in self.depotPaths])2376iflen(l) >0and not self.silent:2377print"Finding files belonging to labels in%s"% `self.depotPaths`23782379for output in l:2380 label = output["label"]2381 revisions = {}2382 newestChange =02383if self.verbose:2384print"Querying files for label%s"% label2385forfileinp4CmdList(["files"] +2386["%s...@%s"% (p, label)2387for p in self.depotPaths]):2388 revisions[file["depotFile"]] =file["rev"]2389 change =int(file["change"])2390if change > newestChange:2391 newestChange = change23922393 self.labels[newestChange] = [output, revisions]23942395if self.verbose:2396print"Label changes:%s"% self.labels.keys()23972398# Import p4 labels as git tags. A direct mapping does not2399# exist, so assume that if all the files are at the same revision2400# then we can use that, or it's something more complicated we should2401# just ignore.2402defimportP4Labels(self, stream, p4Labels):2403if verbose:2404print"import p4 labels: "+' '.join(p4Labels)24052406 ignoredP4Labels =gitConfigList("git-p4.ignoredP4Labels")2407 validLabelRegexp =gitConfig("git-p4.labelImportRegexp")2408iflen(validLabelRegexp) ==0:2409 validLabelRegexp = defaultLabelRegexp2410 m = re.compile(validLabelRegexp)24112412for name in p4Labels:2413 commitFound =False24142415if not m.match(name):2416if verbose:2417print"label%sdoes not match regexp%s"% (name,validLabelRegexp)2418continue24192420if name in ignoredP4Labels:2421continue24222423 labelDetails =p4CmdList(['label',"-o", name])[0]24242425# get the most recent changelist for each file in this label2426 change =p4Cmd(["changes","-m","1"] + ["%s...@%s"% (p, name)2427for p in self.depotPaths])24282429if change.has_key('change'):2430# find the corresponding git commit; take the oldest commit2431 changelist =int(change['change'])2432 gitCommit =read_pipe(["git","rev-list","--max-count=1",2433"--reverse",":/\[git-p4:.*change =%d\]"% changelist])2434iflen(gitCommit) ==0:2435print"could not find git commit for changelist%d"% changelist2436else:2437 gitCommit = gitCommit.strip()2438 commitFound =True2439# Convert from p4 time format2440try:2441 tmwhen = time.strptime(labelDetails['Update'],"%Y/%m/%d%H:%M:%S")2442exceptValueError:2443print"Could not convert label time%s"% labelDetails['Update']2444 tmwhen =124452446 when =int(time.mktime(tmwhen))2447 self.streamTag(stream, name, labelDetails, gitCommit, when)2448if verbose:2449print"p4 label%smapped to git commit%s"% (name, gitCommit)2450else:2451if verbose:2452print"Label%shas no changelists - possibly deleted?"% name24532454if not commitFound:2455# We can't import this label; don't try again as it will get very2456# expensive repeatedly fetching all the files for labels that will2457# never be imported. If the label is moved in the future, the2458# ignore will need to be removed manually.2459system(["git","config","--add","git-p4.ignoredP4Labels", name])24602461defguessProjectName(self):2462for p in self.depotPaths:2463if p.endswith("/"):2464 p = p[:-1]2465 p = p[p.strip().rfind("/") +1:]2466if not p.endswith("/"):2467 p +="/"2468return p24692470defgetBranchMapping(self):2471 lostAndFoundBranches =set()24722473 user =gitConfig("git-p4.branchUser")2474iflen(user) >0:2475 command ="branches -u%s"% user2476else:2477 command ="branches"24782479for info inp4CmdList(command):2480 details =p4Cmd(["branch","-o", info["branch"]])2481 viewIdx =02482while details.has_key("View%s"% viewIdx):2483 paths = details["View%s"% viewIdx].split(" ")2484 viewIdx = viewIdx +12485# require standard //depot/foo/... //depot/bar/... mapping2486iflen(paths) !=2or not paths[0].endswith("/...")or not paths[1].endswith("/..."):2487continue2488 source = paths[0]2489 destination = paths[1]2490## HACK2491ifp4PathStartsWith(source, self.depotPaths[0])andp4PathStartsWith(destination, self.depotPaths[0]):2492 source = source[len(self.depotPaths[0]):-4]2493 destination = destination[len(self.depotPaths[0]):-4]24942495if destination in self.knownBranches:2496if not self.silent:2497print"p4 branch%sdefines a mapping from%sto%s"% (info["branch"], source, destination)2498print"but there exists another mapping from%sto%salready!"% (self.knownBranches[destination], destination)2499continue25002501 self.knownBranches[destination] = source25022503 lostAndFoundBranches.discard(destination)25042505if source not in self.knownBranches:2506 lostAndFoundBranches.add(source)25072508# Perforce does not strictly require branches to be defined, so we also2509# check git config for a branch list.2510#2511# Example of branch definition in git config file:2512# [git-p4]2513# branchList=main:branchA2514# branchList=main:branchB2515# branchList=branchA:branchC2516 configBranches =gitConfigList("git-p4.branchList")2517for branch in configBranches:2518if branch:2519(source, destination) = branch.split(":")2520 self.knownBranches[destination] = source25212522 lostAndFoundBranches.discard(destination)25232524if source not in self.knownBranches:2525 lostAndFoundBranches.add(source)252625272528for branch in lostAndFoundBranches:2529 self.knownBranches[branch] = branch25302531defgetBranchMappingFromGitBranches(self):2532 branches =p4BranchesInGit(self.importIntoRemotes)2533for branch in branches.keys():2534if branch =="master":2535 branch ="main"2536else:2537 branch = branch[len(self.projectName):]2538 self.knownBranches[branch] = branch25392540defupdateOptionDict(self, d):2541 option_keys = {}2542if self.keepRepoPath:2543 option_keys['keepRepoPath'] =125442545 d["options"] =' '.join(sorted(option_keys.keys()))25462547defreadOptions(self, d):2548 self.keepRepoPath = (d.has_key('options')2549and('keepRepoPath'in d['options']))25502551defgitRefForBranch(self, branch):2552if branch =="main":2553return self.refPrefix +"master"25542555iflen(branch) <=0:2556return branch25572558return self.refPrefix + self.projectName + branch25592560defgitCommitByP4Change(self, ref, change):2561if self.verbose:2562print"looking in ref "+ ref +" for change%susing bisect..."% change25632564 earliestCommit =""2565 latestCommit =parseRevision(ref)25662567while True:2568if self.verbose:2569print"trying: earliest%slatest%s"% (earliestCommit, latestCommit)2570 next =read_pipe("git rev-list --bisect%s %s"% (latestCommit, earliestCommit)).strip()2571iflen(next) ==0:2572if self.verbose:2573print"argh"2574return""2575 log =extractLogMessageFromGitCommit(next)2576 settings =extractSettingsGitLog(log)2577 currentChange =int(settings['change'])2578if self.verbose:2579print"current change%s"% currentChange25802581if currentChange == change:2582if self.verbose:2583print"found%s"% next2584return next25852586if currentChange < change:2587 earliestCommit ="^%s"% next2588else:2589 latestCommit ="%s"% next25902591return""25922593defimportNewBranch(self, branch, maxChange):2594# make fast-import flush all changes to disk and update the refs using the checkpoint2595# command so that we can try to find the branch parent in the git history2596 self.gitStream.write("checkpoint\n\n");2597 self.gitStream.flush();2598 branchPrefix = self.depotPaths[0] + branch +"/"2599range="@1,%s"% maxChange2600#print "prefix" + branchPrefix2601 changes =p4ChangesForPaths([branchPrefix],range)2602iflen(changes) <=0:2603return False2604 firstChange = changes[0]2605#print "first change in branch: %s" % firstChange2606 sourceBranch = self.knownBranches[branch]2607 sourceDepotPath = self.depotPaths[0] + sourceBranch2608 sourceRef = self.gitRefForBranch(sourceBranch)2609#print "source " + sourceBranch26102611 branchParentChange =int(p4Cmd(["changes","-m","1","%s...@1,%s"% (sourceDepotPath, firstChange)])["change"])2612#print "branch parent: %s" % branchParentChange2613 gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)2614iflen(gitParent) >0:2615 self.initialParents[self.gitRefForBranch(branch)] = gitParent2616#print "parent git commit: %s" % gitParent26172618 self.importChanges(changes)2619return True26202621defsearchParent(self, parent, branch, target):2622 parentFound =False2623for blob inread_pipe_lines(["git","rev-list","--reverse","--no-merges", parent]):2624 blob = blob.strip()2625iflen(read_pipe(["git","diff-tree", blob, target])) ==0:2626 parentFound =True2627if self.verbose:2628print"Found parent of%sin commit%s"% (branch, blob)2629break2630if parentFound:2631return blob2632else:2633return None26342635defimportChanges(self, changes):2636 cnt =12637for change in changes:2638 description =p4_describe(change)2639 self.updateOptionDict(description)26402641if not self.silent:2642 sys.stdout.write("\rImporting revision%s(%s%%)"% (change, cnt *100/len(changes)))2643 sys.stdout.flush()2644 cnt = cnt +126452646try:2647if self.detectBranches:2648 branches = self.splitFilesIntoBranches(description)2649for branch in branches.keys():2650## HACK --hwn2651 branchPrefix = self.depotPaths[0] + branch +"/"2652 self.branchPrefixes = [ branchPrefix ]26532654 parent =""26552656 filesForCommit = branches[branch]26572658if self.verbose:2659print"branch is%s"% branch26602661 self.updatedBranches.add(branch)26622663if branch not in self.createdBranches:2664 self.createdBranches.add(branch)2665 parent = self.knownBranches[branch]2666if parent == branch:2667 parent =""2668else:2669 fullBranch = self.projectName + branch2670if fullBranch not in self.p4BranchesInGit:2671if not self.silent:2672print("\nImporting new branch%s"% fullBranch);2673if self.importNewBranch(branch, change -1):2674 parent =""2675 self.p4BranchesInGit.append(fullBranch)2676if not self.silent:2677print("\nResuming with change%s"% change);26782679if self.verbose:2680print"parent determined through known branches:%s"% parent26812682 branch = self.gitRefForBranch(branch)2683 parent = self.gitRefForBranch(parent)26842685if self.verbose:2686print"looking for initial parent for%s; current parent is%s"% (branch, parent)26872688iflen(parent) ==0and branch in self.initialParents:2689 parent = self.initialParents[branch]2690del self.initialParents[branch]26912692 blob =None2693iflen(parent) >0:2694 tempBranch ="%s/%d"% (self.tempBranchLocation, change)2695if self.verbose:2696print"Creating temporary branch: "+ tempBranch2697 self.commit(description, filesForCommit, tempBranch)2698 self.tempBranches.append(tempBranch)2699 self.checkpoint()2700 blob = self.searchParent(parent, branch, tempBranch)2701if blob:2702 self.commit(description, filesForCommit, branch, blob)2703else:2704if self.verbose:2705print"Parent of%snot found. Committing into head of%s"% (branch, parent)2706 self.commit(description, filesForCommit, branch, parent)2707else:2708 files = self.extractFilesFromCommit(description)2709 self.commit(description, files, self.branch,2710 self.initialParent)2711# only needed once, to connect to the previous commit2712 self.initialParent =""2713exceptIOError:2714print self.gitError.read()2715 sys.exit(1)27162717defimportHeadRevision(self, revision):2718print"Doing initial import of%sfrom revision%sinto%s"% (' '.join(self.depotPaths), revision, self.branch)27192720 details = {}2721 details["user"] ="git perforce import user"2722 details["desc"] = ("Initial import of%sfrom the state at revision%s\n"2723% (' '.join(self.depotPaths), revision))2724 details["change"] = revision2725 newestRevision =027262727 fileCnt =02728 fileArgs = ["%s...%s"% (p,revision)for p in self.depotPaths]27292730for info inp4CmdList(["files"] + fileArgs):27312732if'code'in info and info['code'] =='error':2733 sys.stderr.write("p4 returned an error:%s\n"2734% info['data'])2735if info['data'].find("must refer to client") >=0:2736 sys.stderr.write("This particular p4 error is misleading.\n")2737 sys.stderr.write("Perhaps the depot path was misspelled.\n");2738 sys.stderr.write("Depot path:%s\n"%" ".join(self.depotPaths))2739 sys.exit(1)2740if'p4ExitCode'in info:2741 sys.stderr.write("p4 exitcode:%s\n"% info['p4ExitCode'])2742 sys.exit(1)274327442745 change =int(info["change"])2746if change > newestRevision:2747 newestRevision = change27482749if info["action"]in self.delete_actions:2750# don't increase the file cnt, otherwise details["depotFile123"] will have gaps!2751#fileCnt = fileCnt + 12752continue27532754for prop in["depotFile","rev","action","type"]:2755 details["%s%s"% (prop, fileCnt)] = info[prop]27562757 fileCnt = fileCnt +127582759 details["change"] = newestRevision27602761# Use time from top-most change so that all git p4 clones of2762# the same p4 repo have the same commit SHA1s.2763 res =p4_describe(newestRevision)2764 details["time"] = res["time"]27652766 self.updateOptionDict(details)2767try:2768 self.commit(details, self.extractFilesFromCommit(details), self.branch)2769exceptIOError:2770print"IO error with git fast-import. Is your git version recent enough?"2771print self.gitError.read()277227732774defrun(self, args):2775 self.depotPaths = []2776 self.changeRange =""2777 self.previousDepotPaths = []2778 self.hasOrigin =False27792780# map from branch depot path to parent branch2781 self.knownBranches = {}2782 self.initialParents = {}27832784if self.importIntoRemotes:2785 self.refPrefix ="refs/remotes/p4/"2786else:2787 self.refPrefix ="refs/heads/p4/"27882789if self.syncWithOrigin:2790 self.hasOrigin =originP4BranchesExist()2791if self.hasOrigin:2792if not self.silent:2793print'Syncing with origin first, using "git fetch origin"'2794system("git fetch origin")27952796 branch_arg_given =bool(self.branch)2797iflen(self.branch) ==0:2798 self.branch = self.refPrefix +"master"2799ifgitBranchExists("refs/heads/p4")and self.importIntoRemotes:2800system("git update-ref%srefs/heads/p4"% self.branch)2801system("git branch -D p4")28022803# accept either the command-line option, or the configuration variable2804if self.useClientSpec:2805# will use this after clone to set the variable2806 self.useClientSpec_from_options =True2807else:2808ifgitConfig("git-p4.useclientspec","--bool") =="true":2809 self.useClientSpec =True2810if self.useClientSpec:2811 self.clientSpecDirs =getClientSpec()28122813# TODO: should always look at previous commits,2814# merge with previous imports, if possible.2815if args == []:2816if self.hasOrigin:2817createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)28182819# branches holds mapping from branch name to sha12820 branches =p4BranchesInGit(self.importIntoRemotes)28212822# restrict to just this one, disabling detect-branches2823if branch_arg_given:2824 short = self.branch.split("/")[-1]2825if short in branches:2826 self.p4BranchesInGit = [ short ]2827else:2828 self.p4BranchesInGit = branches.keys()28292830iflen(self.p4BranchesInGit) >1:2831if not self.silent:2832print"Importing from/into multiple branches"2833 self.detectBranches =True2834for branch in branches.keys():2835 self.initialParents[self.refPrefix + branch] = \2836 branches[branch]28372838if self.verbose:2839print"branches:%s"% self.p4BranchesInGit28402841 p4Change =02842for branch in self.p4BranchesInGit:2843 logMsg =extractLogMessageFromGitCommit(self.refPrefix + branch)28442845 settings =extractSettingsGitLog(logMsg)28462847 self.readOptions(settings)2848if(settings.has_key('depot-paths')2849and settings.has_key('change')):2850 change =int(settings['change']) +12851 p4Change =max(p4Change, change)28522853 depotPaths =sorted(settings['depot-paths'])2854if self.previousDepotPaths == []:2855 self.previousDepotPaths = depotPaths2856else:2857 paths = []2858for(prev, cur)inzip(self.previousDepotPaths, depotPaths):2859 prev_list = prev.split("/")2860 cur_list = cur.split("/")2861for i inrange(0,min(len(cur_list),len(prev_list))):2862if cur_list[i] <> prev_list[i]:2863 i = i -12864break28652866 paths.append("/".join(cur_list[:i +1]))28672868 self.previousDepotPaths = paths28692870if p4Change >0:2871 self.depotPaths =sorted(self.previousDepotPaths)2872 self.changeRange ="@%s,#head"% p4Change2873if not self.silent and not self.detectBranches:2874print"Performing incremental import into%sgit branch"% self.branch28752876# accept multiple ref name abbreviations:2877# refs/foo/bar/branch -> use it exactly2878# p4/branch -> prepend refs/remotes/ or refs/heads/2879# branch -> prepend refs/remotes/p4/ or refs/heads/p4/2880if not self.branch.startswith("refs/"):2881if self.importIntoRemotes:2882 prepend ="refs/remotes/"2883else:2884 prepend ="refs/heads/"2885if not self.branch.startswith("p4/"):2886 prepend +="p4/"2887 self.branch = prepend + self.branch28882889iflen(args) ==0and self.depotPaths:2890if not self.silent:2891print"Depot paths:%s"%' '.join(self.depotPaths)2892else:2893if self.depotPaths and self.depotPaths != args:2894print("previous import used depot path%sand now%swas specified. "2895"This doesn't work!"% (' '.join(self.depotPaths),2896' '.join(args)))2897 sys.exit(1)28982899 self.depotPaths =sorted(args)29002901 revision =""2902 self.users = {}29032904# Make sure no revision specifiers are used when --changesfile2905# is specified.2906 bad_changesfile =False2907iflen(self.changesFile) >0:2908for p in self.depotPaths:2909if p.find("@") >=0or p.find("#") >=0:2910 bad_changesfile =True2911break2912if bad_changesfile:2913die("Option --changesfile is incompatible with revision specifiers")29142915 newPaths = []2916for p in self.depotPaths:2917if p.find("@") != -1:2918 atIdx = p.index("@")2919 self.changeRange = p[atIdx:]2920if self.changeRange =="@all":2921 self.changeRange =""2922elif','not in self.changeRange:2923 revision = self.changeRange2924 self.changeRange =""2925 p = p[:atIdx]2926elif p.find("#") != -1:2927 hashIdx = p.index("#")2928 revision = p[hashIdx:]2929 p = p[:hashIdx]2930elif self.previousDepotPaths == []:2931# pay attention to changesfile, if given, else import2932# the entire p4 tree at the head revision2933iflen(self.changesFile) ==0:2934 revision ="#head"29352936 p = re.sub("\.\.\.$","", p)2937if not p.endswith("/"):2938 p +="/"29392940 newPaths.append(p)29412942 self.depotPaths = newPaths29432944# --detect-branches may change this for each branch2945 self.branchPrefixes = self.depotPaths29462947 self.loadUserMapFromCache()2948 self.labels = {}2949if self.detectLabels:2950 self.getLabels();29512952if self.detectBranches:2953## FIXME - what's a P4 projectName ?2954 self.projectName = self.guessProjectName()29552956if self.hasOrigin:2957 self.getBranchMappingFromGitBranches()2958else:2959 self.getBranchMapping()2960if self.verbose:2961print"p4-git branches:%s"% self.p4BranchesInGit2962print"initial parents:%s"% self.initialParents2963for b in self.p4BranchesInGit:2964if b !="master":29652966## FIXME2967 b = b[len(self.projectName):]2968 self.createdBranches.add(b)29692970 self.tz ="%+03d%02d"% (- time.timezone /3600, ((- time.timezone %3600) /60))29712972 self.importProcess = subprocess.Popen(["git","fast-import"],2973 stdin=subprocess.PIPE,2974 stdout=subprocess.PIPE,2975 stderr=subprocess.PIPE);2976 self.gitOutput = self.importProcess.stdout2977 self.gitStream = self.importProcess.stdin2978 self.gitError = self.importProcess.stderr29792980if revision:2981 self.importHeadRevision(revision)2982else:2983 changes = []29842985iflen(self.changesFile) >0:2986 output =open(self.changesFile).readlines()2987 changeSet =set()2988for line in output:2989 changeSet.add(int(line))29902991for change in changeSet:2992 changes.append(change)29932994 changes.sort()2995else:2996# catch "git p4 sync" with no new branches, in a repo that2997# does not have any existing p4 branches2998iflen(args) ==0:2999if not self.p4BranchesInGit:3000die("No remote p4 branches. Perhaps you never did\"git p4 clone\"in here.")30013002# The default branch is master, unless --branch is used to3003# specify something else. Make sure it exists, or complain3004# nicely about how to use --branch.3005if not self.detectBranches:3006if notbranch_exists(self.branch):3007if branch_arg_given:3008die("Error: branch%sdoes not exist."% self.branch)3009else:3010die("Error: no branch%s; perhaps specify one with --branch."%3011 self.branch)30123013if self.verbose:3014print"Getting p4 changes for%s...%s"% (', '.join(self.depotPaths),3015 self.changeRange)3016 changes =p4ChangesForPaths(self.depotPaths, self.changeRange)30173018iflen(self.maxChanges) >0:3019 changes = changes[:min(int(self.maxChanges),len(changes))]30203021iflen(changes) ==0:3022if not self.silent:3023print"No changes to import!"3024else:3025if not self.silent and not self.detectBranches:3026print"Import destination:%s"% self.branch30273028 self.updatedBranches =set()30293030if not self.detectBranches:3031if args:3032# start a new branch3033 self.initialParent =""3034else:3035# build on a previous revision3036 self.initialParent =parseRevision(self.branch)30373038 self.importChanges(changes)30393040if not self.silent:3041print""3042iflen(self.updatedBranches) >0:3043 sys.stdout.write("Updated branches: ")3044for b in self.updatedBranches:3045 sys.stdout.write("%s"% b)3046 sys.stdout.write("\n")30473048ifgitConfig("git-p4.importLabels","--bool") =="true":3049 self.importLabels =True30503051if self.importLabels:3052 p4Labels =getP4Labels(self.depotPaths)3053 gitTags =getGitTags()30543055 missingP4Labels = p4Labels - gitTags3056 self.importP4Labels(self.gitStream, missingP4Labels)30573058 self.gitStream.close()3059if self.importProcess.wait() !=0:3060die("fast-import failed:%s"% self.gitError.read())3061 self.gitOutput.close()3062 self.gitError.close()30633064# Cleanup temporary branches created during import3065if self.tempBranches != []:3066for branch in self.tempBranches:3067read_pipe("git update-ref -d%s"% branch)3068 os.rmdir(os.path.join(os.environ.get("GIT_DIR",".git"), self.tempBranchLocation))30693070# Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow3071# a convenient shortcut refname "p4".3072if self.importIntoRemotes:3073 head_ref = self.refPrefix +"HEAD"3074if notgitBranchExists(head_ref)andgitBranchExists(self.branch):3075system(["git","symbolic-ref", head_ref, self.branch])30763077return True30783079classP4Rebase(Command):3080def__init__(self):3081 Command.__init__(self)3082 self.options = [3083 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),3084]3085 self.importLabels =False3086 self.description = ("Fetches the latest revision from perforce and "3087+"rebases the current work (branch) against it")30883089defrun(self, args):3090 sync =P4Sync()3091 sync.importLabels = self.importLabels3092 sync.run([])30933094return self.rebase()30953096defrebase(self):3097if os.system("git update-index --refresh") !=0:3098die("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.");3099iflen(read_pipe("git diff-index HEAD --")) >0:3100die("You have uncommited changes. Please commit them before rebasing or stash them away with git stash.");31013102[upstream, settings] =findUpstreamBranchPoint()3103iflen(upstream) ==0:3104die("Cannot find upstream branchpoint for rebase")31053106# the branchpoint may be p4/foo~3, so strip off the parent3107 upstream = re.sub("~[0-9]+$","", upstream)31083109print"Rebasing the current branch onto%s"% upstream3110 oldHead =read_pipe("git rev-parse HEAD").strip()3111system("git rebase%s"% upstream)3112system("git diff-tree --stat --summary -M%sHEAD"% oldHead)3113return True31143115classP4Clone(P4Sync):3116def__init__(self):3117 P4Sync.__init__(self)3118 self.description ="Creates a new git repository and imports from Perforce into it"3119 self.usage ="usage: %prog [options] //depot/path[@revRange]"3120 self.options += [3121 optparse.make_option("--destination", dest="cloneDestination",3122 action='store', default=None,3123help="where to leave result of the clone"),3124 optparse.make_option("-/", dest="cloneExclude",3125 action="append",type="string",3126help="exclude depot path"),3127 optparse.make_option("--bare", dest="cloneBare",3128 action="store_true", default=False),3129]3130 self.cloneDestination =None3131 self.needsGit =False3132 self.cloneBare =False31333134# This is required for the "append" cloneExclude action3135defensure_value(self, attr, value):3136if nothasattr(self, attr)orgetattr(self, attr)is None:3137setattr(self, attr, value)3138returngetattr(self, attr)31393140defdefaultDestination(self, args):3141## TODO: use common prefix of args?3142 depotPath = args[0]3143 depotDir = re.sub("(@[^@]*)$","", depotPath)3144 depotDir = re.sub("(#[^#]*)$","", depotDir)3145 depotDir = re.sub(r"\.\.\.$","", depotDir)3146 depotDir = re.sub(r"/$","", depotDir)3147return os.path.split(depotDir)[1]31483149defrun(self, args):3150iflen(args) <1:3151return False31523153if self.keepRepoPath and not self.cloneDestination:3154 sys.stderr.write("Must specify destination for --keep-path\n")3155 sys.exit(1)31563157 depotPaths = args31583159if not self.cloneDestination andlen(depotPaths) >1:3160 self.cloneDestination = depotPaths[-1]3161 depotPaths = depotPaths[:-1]31623163 self.cloneExclude = ["/"+p for p in self.cloneExclude]3164for p in depotPaths:3165if not p.startswith("//"):3166 sys.stderr.write('Depot paths must start with "//":%s\n'% p)3167return False31683169if not self.cloneDestination:3170 self.cloneDestination = self.defaultDestination(args)31713172print"Importing from%sinto%s"% (', '.join(depotPaths), self.cloneDestination)31733174if not os.path.exists(self.cloneDestination):3175 os.makedirs(self.cloneDestination)3176chdir(self.cloneDestination)31773178 init_cmd = ["git","init"]3179if self.cloneBare:3180 init_cmd.append("--bare")3181 subprocess.check_call(init_cmd)31823183if not P4Sync.run(self, depotPaths):3184return False31853186# create a master branch and check out a work tree3187ifgitBranchExists(self.branch):3188system(["git","branch","master", self.branch ])3189if not self.cloneBare:3190system(["git","checkout","-f"])3191else:3192print'Not checking out any branch, use ' \3193'"git checkout -q -b master <branch>"'31943195# auto-set this variable if invoked with --use-client-spec3196if self.useClientSpec_from_options:3197system("git config --bool git-p4.useclientspec true")31983199return True32003201classP4Branches(Command):3202def__init__(self):3203 Command.__init__(self)3204 self.options = [ ]3205 self.description = ("Shows the git branches that hold imports and their "3206+"corresponding perforce depot paths")3207 self.verbose =False32083209defrun(self, args):3210iforiginP4BranchesExist():3211createOrUpdateBranchesFromOrigin()32123213 cmdline ="git rev-parse --symbolic "3214 cmdline +=" --remotes"32153216for line inread_pipe_lines(cmdline):3217 line = line.strip()32183219if not line.startswith('p4/')or line =="p4/HEAD":3220continue3221 branch = line32223223 log =extractLogMessageFromGitCommit("refs/remotes/%s"% branch)3224 settings =extractSettingsGitLog(log)32253226print"%s<=%s(%s)"% (branch,",".join(settings["depot-paths"]), settings["change"])3227return True32283229classHelpFormatter(optparse.IndentedHelpFormatter):3230def__init__(self):3231 optparse.IndentedHelpFormatter.__init__(self)32323233defformat_description(self, description):3234if description:3235return description +"\n"3236else:3237return""32383239defprintUsage(commands):3240print"usage:%s<command> [options]"% sys.argv[0]3241print""3242print"valid commands:%s"%", ".join(commands)3243print""3244print"Try%s<command> --help for command specific help."% sys.argv[0]3245print""32463247commands = {3248"debug": P4Debug,3249"submit": P4Submit,3250"commit": P4Submit,3251"sync": P4Sync,3252"rebase": P4Rebase,3253"clone": P4Clone,3254"rollback": P4RollBack,3255"branches": P4Branches3256}325732583259defmain():3260iflen(sys.argv[1:]) ==0:3261printUsage(commands.keys())3262 sys.exit(2)32633264 cmdName = sys.argv[1]3265try:3266 klass = commands[cmdName]3267 cmd =klass()3268exceptKeyError:3269print"unknown command%s"% cmdName3270print""3271printUsage(commands.keys())3272 sys.exit(2)32733274 options = cmd.options3275 cmd.gitdir = os.environ.get("GIT_DIR",None)32763277 args = sys.argv[2:]32783279 options.append(optparse.make_option("--verbose","-v", dest="verbose", action="store_true"))3280if cmd.needsGit:3281 options.append(optparse.make_option("--git-dir", dest="gitdir"))32823283 parser = optparse.OptionParser(cmd.usage.replace("%prog","%prog "+ cmdName),3284 options,3285 description = cmd.description,3286 formatter =HelpFormatter())32873288(cmd, args) = parser.parse_args(sys.argv[2:], cmd);3289global verbose3290 verbose = cmd.verbose3291if cmd.needsGit:3292if cmd.gitdir ==None:3293 cmd.gitdir = os.path.abspath(".git")3294if notisValidGitDir(cmd.gitdir):3295 cmd.gitdir =read_pipe("git rev-parse --git-dir").strip()3296if os.path.exists(cmd.gitdir):3297 cdup =read_pipe("git rev-parse --show-cdup").strip()3298iflen(cdup) >0:3299chdir(cdup);33003301if notisValidGitDir(cmd.gitdir):3302ifisValidGitDir(cmd.gitdir +"/.git"):3303 cmd.gitdir +="/.git"3304else:3305die("fatal: cannot locate git repository at%s"% cmd.gitdir)33063307 os.environ["GIT_DIR"] = cmd.gitdir33083309if not cmd.run(args):3310 parser.print_help()3311 sys.exit(2)331233133314if __name__ =='__main__':3315main()