1#!/usr/bin/env python 2# 3# git-p4.py -- A tool for bidirectional operation between a Perforce depot and git. 4# 5# Author: Simon Hausmann <simon@lst.de> 6# Copyright: 2007 Simon Hausmann <simon@lst.de> 7# 2007 Trolltech ASA 8# License: MIT <http://www.opensource.org/licenses/mit-license.php> 9# 10 11import sys 12if sys.hexversion <0x02040000: 13# The limiter is the subprocess module 14 sys.stderr.write("git-p4: requires Python 2.4 or later.\n") 15 sys.exit(1) 16 17import optparse, os, marshal, subprocess, shelve 18import tempfile, getopt, os.path, time, platform 19import re, shutil 20 21verbose =False 22 23# Only labels/tags matching this will be imported/exported 24defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$' 25 26defp4_build_cmd(cmd): 27"""Build a suitable p4 command line. 28 29 This consolidates building and returning a p4 command line into one 30 location. It means that hooking into the environment, or other configuration 31 can be done more easily. 32 """ 33 real_cmd = ["p4"] 34 35 user =gitConfig("git-p4.user") 36iflen(user) >0: 37 real_cmd += ["-u",user] 38 39 password =gitConfig("git-p4.password") 40iflen(password) >0: 41 real_cmd += ["-P", password] 42 43 port =gitConfig("git-p4.port") 44iflen(port) >0: 45 real_cmd += ["-p", port] 46 47 host =gitConfig("git-p4.host") 48iflen(host) >0: 49 real_cmd += ["-H", host] 50 51 client =gitConfig("git-p4.client") 52iflen(client) >0: 53 real_cmd += ["-c", client] 54 55 56ifisinstance(cmd,basestring): 57 real_cmd =' '.join(real_cmd) +' '+ cmd 58else: 59 real_cmd += cmd 60return real_cmd 61 62defchdir(dir): 63# P4 uses the PWD environment variable rather than getcwd(). Since we're 64# not using the shell, we have to set it ourselves. This path could 65# be relative, so go there first, then figure out where we ended up. 66 os.chdir(dir) 67 os.environ['PWD'] = os.getcwd() 68 69defdie(msg): 70if verbose: 71raiseException(msg) 72else: 73 sys.stderr.write(msg +"\n") 74 sys.exit(1) 75 76defwrite_pipe(c, stdin): 77if verbose: 78 sys.stderr.write('Writing pipe:%s\n'%str(c)) 79 80 expand =isinstance(c,basestring) 81 p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand) 82 pipe = p.stdin 83 val = pipe.write(stdin) 84 pipe.close() 85if p.wait(): 86die('Command failed:%s'%str(c)) 87 88return val 89 90defp4_write_pipe(c, stdin): 91 real_cmd =p4_build_cmd(c) 92returnwrite_pipe(real_cmd, stdin) 93 94defread_pipe(c, ignore_error=False): 95if verbose: 96 sys.stderr.write('Reading pipe:%s\n'%str(c)) 97 98 expand =isinstance(c,basestring) 99 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand) 100 pipe = p.stdout 101 val = pipe.read() 102if p.wait()and not ignore_error: 103die('Command failed:%s'%str(c)) 104 105return val 106 107defp4_read_pipe(c, ignore_error=False): 108 real_cmd =p4_build_cmd(c) 109returnread_pipe(real_cmd, ignore_error) 110 111defread_pipe_lines(c): 112if verbose: 113 sys.stderr.write('Reading pipe:%s\n'%str(c)) 114 115 expand =isinstance(c, basestring) 116 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand) 117 pipe = p.stdout 118 val = pipe.readlines() 119if pipe.close()or p.wait(): 120die('Command failed:%s'%str(c)) 121 122return val 123 124defp4_read_pipe_lines(c): 125"""Specifically invoke p4 on the command supplied. """ 126 real_cmd =p4_build_cmd(c) 127returnread_pipe_lines(real_cmd) 128 129defp4_has_command(cmd): 130"""Ask p4 for help on this command. If it returns an error, the 131 command does not exist in this version of p4.""" 132 real_cmd =p4_build_cmd(["help", cmd]) 133 p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE, 134 stderr=subprocess.PIPE) 135 p.communicate() 136return p.returncode ==0 137 138defp4_has_move_command(): 139"""See if the move command exists, that it supports -k, and that 140 it has not been administratively disabled. The arguments 141 must be correct, but the filenames do not have to exist. Use 142 ones with wildcards so even if they exist, it will fail.""" 143 144if notp4_has_command("move"): 145return False 146 cmd =p4_build_cmd(["move","-k","@from","@to"]) 147 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 148(out, err) = p.communicate() 149# return code will be 1 in either case 150if err.find("Invalid option") >=0: 151return False 152if err.find("disabled") >=0: 153return False 154# assume it failed because @... was invalid changelist 155return True 156 157defsystem(cmd): 158 expand =isinstance(cmd,basestring) 159if verbose: 160 sys.stderr.write("executing%s\n"%str(cmd)) 161 subprocess.check_call(cmd, shell=expand) 162 163defp4_system(cmd): 164"""Specifically invoke p4 as the system command. """ 165 real_cmd =p4_build_cmd(cmd) 166 expand =isinstance(real_cmd, basestring) 167 subprocess.check_call(real_cmd, shell=expand) 168 169defp4_integrate(src, dest): 170p4_system(["integrate","-Dt",wildcard_encode(src),wildcard_encode(dest)]) 171 172defp4_sync(f, *options): 173p4_system(["sync"] +list(options) + [wildcard_encode(f)]) 174 175defp4_add(f): 176# forcibly add file names with wildcards 177ifwildcard_present(f): 178p4_system(["add","-f", f]) 179else: 180p4_system(["add", f]) 181 182defp4_delete(f): 183p4_system(["delete",wildcard_encode(f)]) 184 185defp4_edit(f): 186p4_system(["edit",wildcard_encode(f)]) 187 188defp4_revert(f): 189p4_system(["revert",wildcard_encode(f)]) 190 191defp4_reopen(type, f): 192p4_system(["reopen","-t",type,wildcard_encode(f)]) 193 194defp4_move(src, dest): 195p4_system(["move","-k",wildcard_encode(src),wildcard_encode(dest)]) 196 197defp4_describe(change): 198"""Make sure it returns a valid result by checking for 199 the presence of field "time". Return a dict of the 200 results.""" 201 202 ds =p4CmdList(["describe","-s",str(change)]) 203iflen(ds) !=1: 204die("p4 describe -s%ddid not return 1 result:%s"% (change,str(ds))) 205 206 d = ds[0] 207 208if"p4ExitCode"in d: 209die("p4 describe -s%dexited with%d:%s"% (change, d["p4ExitCode"], 210str(d))) 211if"code"in d: 212if d["code"] =="error": 213die("p4 describe -s%dreturned error code:%s"% (change,str(d))) 214 215if"time"not in d: 216die("p4 describe -s%dreturned no\"time\":%s"% (change,str(d))) 217 218return d 219 220# 221# Canonicalize the p4 type and return a tuple of the 222# base type, plus any modifiers. See "p4 help filetypes" 223# for a list and explanation. 224# 225defsplit_p4_type(p4type): 226 227 p4_filetypes_historical = { 228"ctempobj":"binary+Sw", 229"ctext":"text+C", 230"cxtext":"text+Cx", 231"ktext":"text+k", 232"kxtext":"text+kx", 233"ltext":"text+F", 234"tempobj":"binary+FSw", 235"ubinary":"binary+F", 236"uresource":"resource+F", 237"uxbinary":"binary+Fx", 238"xbinary":"binary+x", 239"xltext":"text+Fx", 240"xtempobj":"binary+Swx", 241"xtext":"text+x", 242"xunicode":"unicode+x", 243"xutf16":"utf16+x", 244} 245if p4type in p4_filetypes_historical: 246 p4type = p4_filetypes_historical[p4type] 247 mods ="" 248 s = p4type.split("+") 249 base = s[0] 250 mods ="" 251iflen(s) >1: 252 mods = s[1] 253return(base, mods) 254 255# 256# return the raw p4 type of a file (text, text+ko, etc) 257# 258defp4_type(file): 259 results =p4CmdList(["fstat","-T","headType",file]) 260return results[0]['headType'] 261 262# 263# Given a type base and modifier, return a regexp matching 264# the keywords that can be expanded in the file 265# 266defp4_keywords_regexp_for_type(base, type_mods): 267if base in("text","unicode","binary"): 268 kwords =None 269if"ko"in type_mods: 270 kwords ='Id|Header' 271elif"k"in type_mods: 272 kwords ='Id|Header|Author|Date|DateTime|Change|File|Revision' 273else: 274return None 275 pattern = r""" 276 \$ # Starts with a dollar, followed by... 277 (%s) # one of the keywords, followed by... 278 (:[^$\n]+)? # possibly an old expansion, followed by... 279 \$ # another dollar 280 """% kwords 281return pattern 282else: 283return None 284 285# 286# Given a file, return a regexp matching the possible 287# RCS keywords that will be expanded, or None for files 288# with kw expansion turned off. 289# 290defp4_keywords_regexp_for_file(file): 291if not os.path.exists(file): 292return None 293else: 294(type_base, type_mods) =split_p4_type(p4_type(file)) 295returnp4_keywords_regexp_for_type(type_base, type_mods) 296 297defsetP4ExecBit(file, mode): 298# Reopens an already open file and changes the execute bit to match 299# the execute bit setting in the passed in mode. 300 301 p4Type ="+x" 302 303if notisModeExec(mode): 304 p4Type =getP4OpenedType(file) 305 p4Type = re.sub('^([cku]?)x(.*)','\\1\\2', p4Type) 306 p4Type = re.sub('(.*?\+.*?)x(.*?)','\\1\\2', p4Type) 307if p4Type[-1] =="+": 308 p4Type = p4Type[0:-1] 309 310p4_reopen(p4Type,file) 311 312defgetP4OpenedType(file): 313# Returns the perforce file type for the given file. 314 315 result =p4_read_pipe(["opened",wildcard_encode(file)]) 316 match = re.match(".*\((.+)\)\r?$", result) 317if match: 318return match.group(1) 319else: 320die("Could not determine file type for%s(result: '%s')"% (file, result)) 321 322# Return the set of all p4 labels 323defgetP4Labels(depotPaths): 324 labels =set() 325ifisinstance(depotPaths,basestring): 326 depotPaths = [depotPaths] 327 328for l inp4CmdList(["labels"] + ["%s..."% p for p in depotPaths]): 329 label = l['label'] 330 labels.add(label) 331 332return labels 333 334# Return the set of all git tags 335defgetGitTags(): 336 gitTags =set() 337for line inread_pipe_lines(["git","tag"]): 338 tag = line.strip() 339 gitTags.add(tag) 340return gitTags 341 342defdiffTreePattern(): 343# This is a simple generator for the diff tree regex pattern. This could be 344# a class variable if this and parseDiffTreeEntry were a part of a class. 345 pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)') 346while True: 347yield pattern 348 349defparseDiffTreeEntry(entry): 350"""Parses a single diff tree entry into its component elements. 351 352 See git-diff-tree(1) manpage for details about the format of the diff 353 output. This method returns a dictionary with the following elements: 354 355 src_mode - The mode of the source file 356 dst_mode - The mode of the destination file 357 src_sha1 - The sha1 for the source file 358 dst_sha1 - The sha1 fr the destination file 359 status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc) 360 status_score - The score for the status (applicable for 'C' and 'R' 361 statuses). This is None if there is no score. 362 src - The path for the source file. 363 dst - The path for the destination file. This is only present for 364 copy or renames. If it is not present, this is None. 365 366 If the pattern is not matched, None is returned.""" 367 368 match =diffTreePattern().next().match(entry) 369if match: 370return{ 371'src_mode': match.group(1), 372'dst_mode': match.group(2), 373'src_sha1': match.group(3), 374'dst_sha1': match.group(4), 375'status': match.group(5), 376'status_score': match.group(6), 377'src': match.group(7), 378'dst': match.group(10) 379} 380return None 381 382defisModeExec(mode): 383# Returns True if the given git mode represents an executable file, 384# otherwise False. 385return mode[-3:] =="755" 386 387defisModeExecChanged(src_mode, dst_mode): 388returnisModeExec(src_mode) !=isModeExec(dst_mode) 389 390defp4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None): 391 392ifisinstance(cmd,basestring): 393 cmd ="-G "+ cmd 394 expand =True 395else: 396 cmd = ["-G"] + cmd 397 expand =False 398 399 cmd =p4_build_cmd(cmd) 400if verbose: 401 sys.stderr.write("Opening pipe:%s\n"%str(cmd)) 402 403# Use a temporary file to avoid deadlocks without 404# subprocess.communicate(), which would put another copy 405# of stdout into memory. 406 stdin_file =None 407if stdin is not None: 408 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode) 409ifisinstance(stdin,basestring): 410 stdin_file.write(stdin) 411else: 412for i in stdin: 413 stdin_file.write(i +'\n') 414 stdin_file.flush() 415 stdin_file.seek(0) 416 417 p4 = subprocess.Popen(cmd, 418 shell=expand, 419 stdin=stdin_file, 420 stdout=subprocess.PIPE) 421 422 result = [] 423try: 424while True: 425 entry = marshal.load(p4.stdout) 426if cb is not None: 427cb(entry) 428else: 429 result.append(entry) 430exceptEOFError: 431pass 432 exitCode = p4.wait() 433if exitCode !=0: 434 entry = {} 435 entry["p4ExitCode"] = exitCode 436 result.append(entry) 437 438return result 439 440defp4Cmd(cmd): 441list=p4CmdList(cmd) 442 result = {} 443for entry inlist: 444 result.update(entry) 445return result; 446 447defp4Where(depotPath): 448if not depotPath.endswith("/"): 449 depotPath +="/" 450 depotPath = depotPath +"..." 451 outputList =p4CmdList(["where", depotPath]) 452 output =None 453for entry in outputList: 454if"depotFile"in entry: 455if entry["depotFile"] == depotPath: 456 output = entry 457break 458elif"data"in entry: 459 data = entry.get("data") 460 space = data.find(" ") 461if data[:space] == depotPath: 462 output = entry 463break 464if output ==None: 465return"" 466if output["code"] =="error": 467return"" 468 clientPath ="" 469if"path"in output: 470 clientPath = output.get("path") 471elif"data"in output: 472 data = output.get("data") 473 lastSpace = data.rfind(" ") 474 clientPath = data[lastSpace +1:] 475 476if clientPath.endswith("..."): 477 clientPath = clientPath[:-3] 478return clientPath 479 480defcurrentGitBranch(): 481returnread_pipe("git name-rev HEAD").split(" ")[1].strip() 482 483defisValidGitDir(path): 484if(os.path.exists(path +"/HEAD") 485and os.path.exists(path +"/refs")and os.path.exists(path +"/objects")): 486return True; 487return False 488 489defparseRevision(ref): 490returnread_pipe("git rev-parse%s"% ref).strip() 491 492defbranchExists(ref): 493 rev =read_pipe(["git","rev-parse","-q","--verify", ref], 494 ignore_error=True) 495returnlen(rev) >0 496 497defextractLogMessageFromGitCommit(commit): 498 logMessage ="" 499 500## fixme: title is first line of commit, not 1st paragraph. 501 foundTitle =False 502for log inread_pipe_lines("git cat-file commit%s"% commit): 503if not foundTitle: 504iflen(log) ==1: 505 foundTitle =True 506continue 507 508 logMessage += log 509return logMessage 510 511defextractSettingsGitLog(log): 512 values = {} 513for line in log.split("\n"): 514 line = line.strip() 515 m = re.search(r"^ *\[git-p4: (.*)\]$", line) 516if not m: 517continue 518 519 assignments = m.group(1).split(':') 520for a in assignments: 521 vals = a.split('=') 522 key = vals[0].strip() 523 val = ('='.join(vals[1:])).strip() 524if val.endswith('\"')and val.startswith('"'): 525 val = val[1:-1] 526 527 values[key] = val 528 529 paths = values.get("depot-paths") 530if not paths: 531 paths = values.get("depot-path") 532if paths: 533 values['depot-paths'] = paths.split(',') 534return values 535 536defgitBranchExists(branch): 537 proc = subprocess.Popen(["git","rev-parse", branch], 538 stderr=subprocess.PIPE, stdout=subprocess.PIPE); 539return proc.wait() ==0; 540 541_gitConfig = {} 542defgitConfig(key, args =None):# set args to "--bool", for instance 543if not _gitConfig.has_key(key): 544 argsFilter ="" 545if args !=None: 546 argsFilter ="%s"% args 547 cmd ="git config%s%s"% (argsFilter, key) 548 _gitConfig[key] =read_pipe(cmd, ignore_error=True).strip() 549return _gitConfig[key] 550 551defgitConfigList(key): 552if not _gitConfig.has_key(key): 553 _gitConfig[key] =read_pipe("git config --get-all%s"% key, ignore_error=True).strip().split(os.linesep) 554return _gitConfig[key] 555 556defp4BranchesInGit(branchesAreInRemotes=True): 557"""Find all the branches whose names start with "p4/", looking 558 in remotes or heads as specified by the argument. Return 559 a dictionary of{ branch: revision }for each one found. 560 The branch names are the short names, without any 561 "p4/" prefix.""" 562 563 branches = {} 564 565 cmdline ="git rev-parse --symbolic " 566if branchesAreInRemotes: 567 cmdline +="--remotes" 568else: 569 cmdline +="--branches" 570 571for line inread_pipe_lines(cmdline): 572 line = line.strip() 573 574# only import to p4/ 575if not line.startswith('p4/'): 576continue 577# special symbolic ref to p4/master 578if line =="p4/HEAD": 579continue 580 581# strip off p4/ prefix 582 branch = line[len("p4/"):] 583 584 branches[branch] =parseRevision(line) 585 586return branches 587 588defbranch_exists(branch): 589"""Make sure that the given ref name really exists.""" 590 591 cmd = ["git","rev-parse","--symbolic","--verify", branch ] 592 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 593 out, _ = p.communicate() 594if p.returncode: 595return False 596# expect exactly one line of output: the branch name 597return out.rstrip() == branch 598 599deffindUpstreamBranchPoint(head ="HEAD"): 600 branches =p4BranchesInGit() 601# map from depot-path to branch name 602 branchByDepotPath = {} 603for branch in branches.keys(): 604 tip = branches[branch] 605 log =extractLogMessageFromGitCommit(tip) 606 settings =extractSettingsGitLog(log) 607if settings.has_key("depot-paths"): 608 paths =",".join(settings["depot-paths"]) 609 branchByDepotPath[paths] ="remotes/p4/"+ branch 610 611 settings =None 612 parent =0 613while parent <65535: 614 commit = head +"~%s"% parent 615 log =extractLogMessageFromGitCommit(commit) 616 settings =extractSettingsGitLog(log) 617if settings.has_key("depot-paths"): 618 paths =",".join(settings["depot-paths"]) 619if branchByDepotPath.has_key(paths): 620return[branchByDepotPath[paths], settings] 621 622 parent = parent +1 623 624return["", settings] 625 626defcreateOrUpdateBranchesFromOrigin(localRefPrefix ="refs/remotes/p4/", silent=True): 627if not silent: 628print("Creating/updating branch(es) in%sbased on origin branch(es)" 629% localRefPrefix) 630 631 originPrefix ="origin/p4/" 632 633for line inread_pipe_lines("git rev-parse --symbolic --remotes"): 634 line = line.strip() 635if(not line.startswith(originPrefix))or line.endswith("HEAD"): 636continue 637 638 headName = line[len(originPrefix):] 639 remoteHead = localRefPrefix + headName 640 originHead = line 641 642 original =extractSettingsGitLog(extractLogMessageFromGitCommit(originHead)) 643if(not original.has_key('depot-paths') 644or not original.has_key('change')): 645continue 646 647 update =False 648if notgitBranchExists(remoteHead): 649if verbose: 650print"creating%s"% remoteHead 651 update =True 652else: 653 settings =extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead)) 654if settings.has_key('change') >0: 655if settings['depot-paths'] == original['depot-paths']: 656 originP4Change =int(original['change']) 657 p4Change =int(settings['change']) 658if originP4Change > p4Change: 659print("%s(%s) is newer than%s(%s). " 660"Updating p4 branch from origin." 661% (originHead, originP4Change, 662 remoteHead, p4Change)) 663 update =True 664else: 665print("Ignoring:%swas imported from%swhile " 666"%swas imported from%s" 667% (originHead,','.join(original['depot-paths']), 668 remoteHead,','.join(settings['depot-paths']))) 669 670if update: 671system("git update-ref%s %s"% (remoteHead, originHead)) 672 673deforiginP4BranchesExist(): 674returngitBranchExists("origin")orgitBranchExists("origin/p4")orgitBranchExists("origin/p4/master") 675 676defp4ChangesForPaths(depotPaths, changeRange): 677assert depotPaths 678 cmd = ['changes'] 679for p in depotPaths: 680 cmd += ["%s...%s"% (p, changeRange)] 681 output =p4_read_pipe_lines(cmd) 682 683 changes = {} 684for line in output: 685 changeNum =int(line.split(" ")[1]) 686 changes[changeNum] =True 687 688 changelist = changes.keys() 689 changelist.sort() 690return changelist 691 692defp4PathStartsWith(path, prefix): 693# This method tries to remedy a potential mixed-case issue: 694# 695# If UserA adds //depot/DirA/file1 696# and UserB adds //depot/dira/file2 697# 698# we may or may not have a problem. If you have core.ignorecase=true, 699# we treat DirA and dira as the same directory 700 ignorecase =gitConfig("core.ignorecase","--bool") =="true" 701if ignorecase: 702return path.lower().startswith(prefix.lower()) 703return path.startswith(prefix) 704 705defgetClientSpec(): 706"""Look at the p4 client spec, create a View() object that contains 707 all the mappings, and return it.""" 708 709 specList =p4CmdList("client -o") 710iflen(specList) !=1: 711die('Output from "client -o" is%dlines, expecting 1'% 712len(specList)) 713 714# dictionary of all client parameters 715 entry = specList[0] 716 717# just the keys that start with "View" 718 view_keys = [ k for k in entry.keys()if k.startswith("View") ] 719 720# hold this new View 721 view =View() 722 723# append the lines, in order, to the view 724for view_num inrange(len(view_keys)): 725 k ="View%d"% view_num 726if k not in view_keys: 727die("Expected view key%smissing"% k) 728 view.append(entry[k]) 729 730return view 731 732defgetClientRoot(): 733"""Grab the client directory.""" 734 735 output =p4CmdList("client -o") 736iflen(output) !=1: 737die('Output from "client -o" is%dlines, expecting 1'%len(output)) 738 739 entry = output[0] 740if"Root"not in entry: 741die('Client has no "Root"') 742 743return entry["Root"] 744 745# 746# P4 wildcards are not allowed in filenames. P4 complains 747# if you simply add them, but you can force it with "-f", in 748# which case it translates them into %xx encoding internally. 749# 750defwildcard_decode(path): 751# Search for and fix just these four characters. Do % last so 752# that fixing it does not inadvertently create new %-escapes. 753# Cannot have * in a filename in windows; untested as to 754# what p4 would do in such a case. 755if not platform.system() =="Windows": 756 path = path.replace("%2A","*") 757 path = path.replace("%23","#") \ 758.replace("%40","@") \ 759.replace("%25","%") 760return path 761 762defwildcard_encode(path): 763# do % first to avoid double-encoding the %s introduced here 764 path = path.replace("%","%25") \ 765.replace("*","%2A") \ 766.replace("#","%23") \ 767.replace("@","%40") 768return path 769 770defwildcard_present(path): 771return path.translate(None,"*#@%") != path 772 773class Command: 774def__init__(self): 775 self.usage ="usage: %prog [options]" 776 self.needsGit =True 777 self.verbose =False 778 779class P4UserMap: 780def__init__(self): 781 self.userMapFromPerforceServer =False 782 self.myP4UserId =None 783 784defp4UserId(self): 785if self.myP4UserId: 786return self.myP4UserId 787 788 results =p4CmdList("user -o") 789for r in results: 790if r.has_key('User'): 791 self.myP4UserId = r['User'] 792return r['User'] 793die("Could not find your p4 user id") 794 795defp4UserIsMe(self, p4User): 796# return True if the given p4 user is actually me 797 me = self.p4UserId() 798if not p4User or p4User != me: 799return False 800else: 801return True 802 803defgetUserCacheFilename(self): 804 home = os.environ.get("HOME", os.environ.get("USERPROFILE")) 805return home +"/.gitp4-usercache.txt" 806 807defgetUserMapFromPerforceServer(self): 808if self.userMapFromPerforceServer: 809return 810 self.users = {} 811 self.emails = {} 812 813for output inp4CmdList("users"): 814if not output.has_key("User"): 815continue 816 self.users[output["User"]] = output["FullName"] +" <"+ output["Email"] +">" 817 self.emails[output["Email"]] = output["User"] 818 819 820 s ='' 821for(key, val)in self.users.items(): 822 s +="%s\t%s\n"% (key.expandtabs(1), val.expandtabs(1)) 823 824open(self.getUserCacheFilename(),"wb").write(s) 825 self.userMapFromPerforceServer =True 826 827defloadUserMapFromCache(self): 828 self.users = {} 829 self.userMapFromPerforceServer =False 830try: 831 cache =open(self.getUserCacheFilename(),"rb") 832 lines = cache.readlines() 833 cache.close() 834for line in lines: 835 entry = line.strip().split("\t") 836 self.users[entry[0]] = entry[1] 837exceptIOError: 838 self.getUserMapFromPerforceServer() 839 840classP4Debug(Command): 841def__init__(self): 842 Command.__init__(self) 843 self.options = [] 844 self.description ="A tool to debug the output of p4 -G." 845 self.needsGit =False 846 847defrun(self, args): 848 j =0 849for output inp4CmdList(args): 850print'Element:%d'% j 851 j +=1 852print output 853return True 854 855classP4RollBack(Command): 856def__init__(self): 857 Command.__init__(self) 858 self.options = [ 859 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true") 860] 861 self.description ="A tool to debug the multi-branch import. Don't use :)" 862 self.rollbackLocalBranches =False 863 864defrun(self, args): 865iflen(args) !=1: 866return False 867 maxChange =int(args[0]) 868 869if"p4ExitCode"inp4Cmd("changes -m 1"): 870die("Problems executing p4"); 871 872if self.rollbackLocalBranches: 873 refPrefix ="refs/heads/" 874 lines =read_pipe_lines("git rev-parse --symbolic --branches") 875else: 876 refPrefix ="refs/remotes/" 877 lines =read_pipe_lines("git rev-parse --symbolic --remotes") 878 879for line in lines: 880if self.rollbackLocalBranches or(line.startswith("p4/")and line !="p4/HEAD\n"): 881 line = line.strip() 882 ref = refPrefix + line 883 log =extractLogMessageFromGitCommit(ref) 884 settings =extractSettingsGitLog(log) 885 886 depotPaths = settings['depot-paths'] 887 change = settings['change'] 888 889 changed =False 890 891iflen(p4Cmd("changes -m 1 "+' '.join(['%s...@%s'% (p, maxChange) 892for p in depotPaths]))) ==0: 893print"Branch%sdid not exist at change%s, deleting."% (ref, maxChange) 894system("git update-ref -d%s`git rev-parse%s`"% (ref, ref)) 895continue 896 897while change andint(change) > maxChange: 898 changed =True 899if self.verbose: 900print"%sis at%s; rewinding towards%s"% (ref, change, maxChange) 901system("git update-ref%s\"%s^\""% (ref, ref)) 902 log =extractLogMessageFromGitCommit(ref) 903 settings =extractSettingsGitLog(log) 904 905 906 depotPaths = settings['depot-paths'] 907 change = settings['change'] 908 909if changed: 910print"%srewound to%s"% (ref, change) 911 912return True 913 914classP4Submit(Command, P4UserMap): 915 916 conflict_behavior_choices = ("ask","skip","quit") 917 918def__init__(self): 919 Command.__init__(self) 920 P4UserMap.__init__(self) 921 self.options = [ 922 optparse.make_option("--origin", dest="origin"), 923 optparse.make_option("-M", dest="detectRenames", action="store_true"), 924# preserve the user, requires relevant p4 permissions 925 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"), 926 optparse.make_option("--export-labels", dest="exportLabels", action="store_true"), 927 optparse.make_option("--dry-run","-n", dest="dry_run", action="store_true"), 928 optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"), 929 optparse.make_option("--conflict", dest="conflict_behavior", 930 choices=self.conflict_behavior_choices), 931 optparse.make_option("--branch", dest="branch"), 932] 933 self.description ="Submit changes from git to the perforce depot." 934 self.usage +=" [name of git branch to submit into perforce depot]" 935 self.origin ="" 936 self.detectRenames =False 937 self.preserveUser =gitConfig("git-p4.preserveUser").lower() =="true" 938 self.dry_run =False 939 self.prepare_p4_only =False 940 self.conflict_behavior =None 941 self.isWindows = (platform.system() =="Windows") 942 self.exportLabels =False 943 self.p4HasMoveCommand =p4_has_move_command() 944 self.branch =None 945 946defcheck(self): 947iflen(p4CmdList("opened ...")) >0: 948die("You have files opened with perforce! Close them before starting the sync.") 949 950defseparate_jobs_from_description(self, message): 951"""Extract and return a possible Jobs field in the commit 952 message. It goes into a separate section in the p4 change 953 specification. 954 955 A jobs line starts with "Jobs:" and looks like a new field 956 in a form. Values are white-space separated on the same 957 line or on following lines that start with a tab. 958 959 This does not parse and extract the full git commit message 960 like a p4 form. It just sees the Jobs: line as a marker 961 to pass everything from then on directly into the p4 form, 962 but outside the description section. 963 964 Return a tuple (stripped log message, jobs string).""" 965 966 m = re.search(r'^Jobs:', message, re.MULTILINE) 967if m is None: 968return(message,None) 969 970 jobtext = message[m.start():] 971 stripped_message = message[:m.start()].rstrip() 972return(stripped_message, jobtext) 973 974defprepareLogMessage(self, template, message, jobs): 975"""Edits the template returned from "p4 change -o" to insert 976 the message in the Description field, and the jobs text in 977 the Jobs field.""" 978 result ="" 979 980 inDescriptionSection =False 981 982for line in template.split("\n"): 983if line.startswith("#"): 984 result += line +"\n" 985continue 986 987if inDescriptionSection: 988if line.startswith("Files:")or line.startswith("Jobs:"): 989 inDescriptionSection =False 990# insert Jobs section 991if jobs: 992 result += jobs +"\n" 993else: 994continue 995else: 996if line.startswith("Description:"): 997 inDescriptionSection =True 998 line +="\n" 999for messageLine in message.split("\n"):1000 line +="\t"+ messageLine +"\n"10011002 result += line +"\n"10031004return result10051006defpatchRCSKeywords(self,file, pattern):1007# Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern1008(handle, outFileName) = tempfile.mkstemp(dir='.')1009try:1010 outFile = os.fdopen(handle,"w+")1011 inFile =open(file,"r")1012 regexp = re.compile(pattern, re.VERBOSE)1013for line in inFile.readlines():1014 line = regexp.sub(r'$\1$', line)1015 outFile.write(line)1016 inFile.close()1017 outFile.close()1018# Forcibly overwrite the original file1019 os.unlink(file)1020 shutil.move(outFileName,file)1021except:1022# cleanup our temporary file1023 os.unlink(outFileName)1024print"Failed to strip RCS keywords in%s"%file1025raise10261027print"Patched up RCS keywords in%s"%file10281029defp4UserForCommit(self,id):1030# Return the tuple (perforce user,git email) for a given git commit id1031 self.getUserMapFromPerforceServer()1032 gitEmail =read_pipe("git log --max-count=1 --format='%%ae'%s"%id)1033 gitEmail = gitEmail.strip()1034if not self.emails.has_key(gitEmail):1035return(None,gitEmail)1036else:1037return(self.emails[gitEmail],gitEmail)10381039defcheckValidP4Users(self,commits):1040# check if any git authors cannot be mapped to p4 users1041foridin commits:1042(user,email) = self.p4UserForCommit(id)1043if not user:1044 msg ="Cannot find p4 user for email%sin commit%s."% (email,id)1045ifgitConfig('git-p4.allowMissingP4Users').lower() =="true":1046print"%s"% msg1047else:1048die("Error:%s\nSet git-p4.allowMissingP4Users to true to allow this."% msg)10491050deflastP4Changelist(self):1051# Get back the last changelist number submitted in this client spec. This1052# then gets used to patch up the username in the change. If the same1053# client spec is being used by multiple processes then this might go1054# wrong.1055 results =p4CmdList("client -o")# find the current client1056 client =None1057for r in results:1058if r.has_key('Client'):1059 client = r['Client']1060break1061if not client:1062die("could not get client spec")1063 results =p4CmdList(["changes","-c", client,"-m","1"])1064for r in results:1065if r.has_key('change'):1066return r['change']1067die("Could not get changelist number for last submit - cannot patch up user details")10681069defmodifyChangelistUser(self, changelist, newUser):1070# fixup the user field of a changelist after it has been submitted.1071 changes =p4CmdList("change -o%s"% changelist)1072iflen(changes) !=1:1073die("Bad output from p4 change modifying%sto user%s"%1074(changelist, newUser))10751076 c = changes[0]1077if c['User'] == newUser:return# nothing to do1078 c['User'] = newUser1079input= marshal.dumps(c)10801081 result =p4CmdList("change -f -i", stdin=input)1082for r in result:1083if r.has_key('code'):1084if r['code'] =='error':1085die("Could not modify user field of changelist%sto%s:%s"% (changelist, newUser, r['data']))1086if r.has_key('data'):1087print("Updated user field for changelist%sto%s"% (changelist, newUser))1088return1089die("Could not modify user field of changelist%sto%s"% (changelist, newUser))10901091defcanChangeChangelists(self):1092# check to see if we have p4 admin or super-user permissions, either of1093# which are required to modify changelists.1094 results =p4CmdList(["protects", self.depotPath])1095for r in results:1096if r.has_key('perm'):1097if r['perm'] =='admin':1098return11099if r['perm'] =='super':1100return11101return011021103defprepareSubmitTemplate(self):1104"""Run "p4 change -o" to grab a change specification template.1105 This does not use "p4 -G", as it is nice to keep the submission1106 template in original order, since a human might edit it.11071108 Remove lines in the Files section that show changes to files1109 outside the depot path we're committing into."""11101111 template =""1112 inFilesSection =False1113for line inp4_read_pipe_lines(['change','-o']):1114if line.endswith("\r\n"):1115 line = line[:-2] +"\n"1116if inFilesSection:1117if line.startswith("\t"):1118# path starts and ends with a tab1119 path = line[1:]1120 lastTab = path.rfind("\t")1121if lastTab != -1:1122 path = path[:lastTab]1123if notp4PathStartsWith(path, self.depotPath):1124continue1125else:1126 inFilesSection =False1127else:1128if line.startswith("Files:"):1129 inFilesSection =True11301131 template += line11321133return template11341135defedit_template(self, template_file):1136"""Invoke the editor to let the user change the submission1137 message. Return true if okay to continue with the submit."""11381139# if configured to skip the editing part, just submit1140ifgitConfig("git-p4.skipSubmitEdit") =="true":1141return True11421143# look at the modification time, to check later if the user saved1144# the file1145 mtime = os.stat(template_file).st_mtime11461147# invoke the editor1148if os.environ.has_key("P4EDITOR")and(os.environ.get("P4EDITOR") !=""):1149 editor = os.environ.get("P4EDITOR")1150else:1151 editor =read_pipe("git var GIT_EDITOR").strip()1152system(editor +" "+ template_file)11531154# If the file was not saved, prompt to see if this patch should1155# be skipped. But skip this verification step if configured so.1156ifgitConfig("git-p4.skipSubmitEditCheck") =="true":1157return True11581159# modification time updated means user saved the file1160if os.stat(template_file).st_mtime > mtime:1161return True11621163while True:1164 response =raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")1165if response =='y':1166return True1167if response =='n':1168return False11691170defapplyCommit(self,id):1171"""Apply one commit, return True if it succeeded."""11721173print"Applying",read_pipe(["git","show","-s",1174"--format=format:%h%s",id])11751176(p4User, gitEmail) = self.p4UserForCommit(id)11771178 diff =read_pipe_lines("git diff-tree -r%s\"%s^\" \"%s\""% (self.diffOpts,id,id))1179 filesToAdd =set()1180 filesToDelete =set()1181 editedFiles =set()1182 pureRenameCopy =set()1183 filesToChangeExecBit = {}11841185for line in diff:1186 diff =parseDiffTreeEntry(line)1187 modifier = diff['status']1188 path = diff['src']1189if modifier =="M":1190p4_edit(path)1191ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1192 filesToChangeExecBit[path] = diff['dst_mode']1193 editedFiles.add(path)1194elif modifier =="A":1195 filesToAdd.add(path)1196 filesToChangeExecBit[path] = diff['dst_mode']1197if path in filesToDelete:1198 filesToDelete.remove(path)1199elif modifier =="D":1200 filesToDelete.add(path)1201if path in filesToAdd:1202 filesToAdd.remove(path)1203elif modifier =="C":1204 src, dest = diff['src'], diff['dst']1205p4_integrate(src, dest)1206 pureRenameCopy.add(dest)1207if diff['src_sha1'] != diff['dst_sha1']:1208p4_edit(dest)1209 pureRenameCopy.discard(dest)1210ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1211p4_edit(dest)1212 pureRenameCopy.discard(dest)1213 filesToChangeExecBit[dest] = diff['dst_mode']1214 os.unlink(dest)1215 editedFiles.add(dest)1216elif modifier =="R":1217 src, dest = diff['src'], diff['dst']1218if self.p4HasMoveCommand:1219p4_edit(src)# src must be open before move1220p4_move(src, dest)# opens for (move/delete, move/add)1221else:1222p4_integrate(src, dest)1223if diff['src_sha1'] != diff['dst_sha1']:1224p4_edit(dest)1225else:1226 pureRenameCopy.add(dest)1227ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1228if not self.p4HasMoveCommand:1229p4_edit(dest)# with move: already open, writable1230 filesToChangeExecBit[dest] = diff['dst_mode']1231if not self.p4HasMoveCommand:1232 os.unlink(dest)1233 filesToDelete.add(src)1234 editedFiles.add(dest)1235else:1236die("unknown modifier%sfor%s"% (modifier, path))12371238 diffcmd ="git format-patch -k --stdout\"%s^\"..\"%s\""% (id,id)1239 patchcmd = diffcmd +" | git apply "1240 tryPatchCmd = patchcmd +"--check -"1241 applyPatchCmd = patchcmd +"--check --apply -"1242 patch_succeeded =True12431244if os.system(tryPatchCmd) !=0:1245 fixed_rcs_keywords =False1246 patch_succeeded =False1247print"Unfortunately applying the change failed!"12481249# Patch failed, maybe it's just RCS keyword woes. Look through1250# the patch to see if that's possible.1251ifgitConfig("git-p4.attemptRCSCleanup","--bool") =="true":1252file=None1253 pattern =None1254 kwfiles = {}1255forfilein editedFiles | filesToDelete:1256# did this file's delta contain RCS keywords?1257 pattern =p4_keywords_regexp_for_file(file)12581259if pattern:1260# this file is a possibility...look for RCS keywords.1261 regexp = re.compile(pattern, re.VERBOSE)1262for line inread_pipe_lines(["git","diff","%s^..%s"% (id,id),file]):1263if regexp.search(line):1264if verbose:1265print"got keyword match on%sin%sin%s"% (pattern, line,file)1266 kwfiles[file] = pattern1267break12681269forfilein kwfiles:1270if verbose:1271print"zapping%swith%s"% (line,pattern)1272 self.patchRCSKeywords(file, kwfiles[file])1273 fixed_rcs_keywords =True12741275if fixed_rcs_keywords:1276print"Retrying the patch with RCS keywords cleaned up"1277if os.system(tryPatchCmd) ==0:1278 patch_succeeded =True12791280if not patch_succeeded:1281for f in editedFiles:1282p4_revert(f)1283return False12841285#1286# Apply the patch for real, and do add/delete/+x handling.1287#1288system(applyPatchCmd)12891290for f in filesToAdd:1291p4_add(f)1292for f in filesToDelete:1293p4_revert(f)1294p4_delete(f)12951296# Set/clear executable bits1297for f in filesToChangeExecBit.keys():1298 mode = filesToChangeExecBit[f]1299setP4ExecBit(f, mode)13001301#1302# Build p4 change description, starting with the contents1303# of the git commit message.1304#1305 logMessage =extractLogMessageFromGitCommit(id)1306 logMessage = logMessage.strip()1307(logMessage, jobs) = self.separate_jobs_from_description(logMessage)13081309 template = self.prepareSubmitTemplate()1310 submitTemplate = self.prepareLogMessage(template, logMessage, jobs)13111312if self.preserveUser:1313 submitTemplate +="\n######## Actual user%s, modified after commit\n"% p4User13141315if self.checkAuthorship and not self.p4UserIsMe(p4User):1316 submitTemplate +="######## git author%sdoes not match your p4 account.\n"% gitEmail1317 submitTemplate +="######## Use option --preserve-user to modify authorship.\n"1318 submitTemplate +="######## Variable git-p4.skipUserNameCheck hides this message.\n"13191320 separatorLine ="######## everything below this line is just the diff #######\n"13211322# diff1323if os.environ.has_key("P4DIFF"):1324del(os.environ["P4DIFF"])1325 diff =""1326for editedFile in editedFiles:1327 diff +=p4_read_pipe(['diff','-du',1328wildcard_encode(editedFile)])13291330# new file diff1331 newdiff =""1332for newFile in filesToAdd:1333 newdiff +="==== new file ====\n"1334 newdiff +="--- /dev/null\n"1335 newdiff +="+++%s\n"% newFile1336 f =open(newFile,"r")1337for line in f.readlines():1338 newdiff +="+"+ line1339 f.close()13401341# change description file: submitTemplate, separatorLine, diff, newdiff1342(handle, fileName) = tempfile.mkstemp()1343 tmpFile = os.fdopen(handle,"w+")1344if self.isWindows:1345 submitTemplate = submitTemplate.replace("\n","\r\n")1346 separatorLine = separatorLine.replace("\n","\r\n")1347 newdiff = newdiff.replace("\n","\r\n")1348 tmpFile.write(submitTemplate + separatorLine + diff + newdiff)1349 tmpFile.close()13501351if self.prepare_p4_only:1352#1353# Leave the p4 tree prepared, and the submit template around1354# and let the user decide what to do next1355#1356print1357print"P4 workspace prepared for submission."1358print"To submit or revert, go to client workspace"1359print" "+ self.clientPath1360print1361print"To submit, use\"p4 submit\"to write a new description,"1362print"or\"p4 submit -i%s\"to use the one prepared by" \1363"\"git p4\"."% fileName1364print"You can delete the file\"%s\"when finished."% fileName13651366if self.preserveUser and p4User and not self.p4UserIsMe(p4User):1367print"To preserve change ownership by user%s, you must\n" \1368"do\"p4 change -f <change>\"after submitting and\n" \1369"edit the User field."1370if pureRenameCopy:1371print"After submitting, renamed files must be re-synced."1372print"Invoke\"p4 sync -f\"on each of these files:"1373for f in pureRenameCopy:1374print" "+ f13751376print1377print"To revert the changes, use\"p4 revert ...\", and delete"1378print"the submit template file\"%s\""% fileName1379if filesToAdd:1380print"Since the commit adds new files, they must be deleted:"1381for f in filesToAdd:1382print" "+ f1383print1384return True13851386#1387# Let the user edit the change description, then submit it.1388#1389if self.edit_template(fileName):1390# read the edited message and submit1391 ret =True1392 tmpFile =open(fileName,"rb")1393 message = tmpFile.read()1394 tmpFile.close()1395 submitTemplate = message[:message.index(separatorLine)]1396if self.isWindows:1397 submitTemplate = submitTemplate.replace("\r\n","\n")1398p4_write_pipe(['submit','-i'], submitTemplate)13991400if self.preserveUser:1401if p4User:1402# Get last changelist number. Cannot easily get it from1403# the submit command output as the output is1404# unmarshalled.1405 changelist = self.lastP4Changelist()1406 self.modifyChangelistUser(changelist, p4User)14071408# The rename/copy happened by applying a patch that created a1409# new file. This leaves it writable, which confuses p4.1410for f in pureRenameCopy:1411p4_sync(f,"-f")14121413else:1414# skip this patch1415 ret =False1416print"Submission cancelled, undoing p4 changes."1417for f in editedFiles:1418p4_revert(f)1419for f in filesToAdd:1420p4_revert(f)1421 os.remove(f)1422for f in filesToDelete:1423p4_revert(f)14241425 os.remove(fileName)1426return ret14271428# Export git tags as p4 labels. Create a p4 label and then tag1429# with that.1430defexportGitTags(self, gitTags):1431 validLabelRegexp =gitConfig("git-p4.labelExportRegexp")1432iflen(validLabelRegexp) ==0:1433 validLabelRegexp = defaultLabelRegexp1434 m = re.compile(validLabelRegexp)14351436for name in gitTags:14371438if not m.match(name):1439if verbose:1440print"tag%sdoes not match regexp%s"% (name, validLabelRegexp)1441continue14421443# Get the p4 commit this corresponds to1444 logMessage =extractLogMessageFromGitCommit(name)1445 values =extractSettingsGitLog(logMessage)14461447if not values.has_key('change'):1448# a tag pointing to something not sent to p4; ignore1449if verbose:1450print"git tag%sdoes not give a p4 commit"% name1451continue1452else:1453 changelist = values['change']14541455# Get the tag details.1456 inHeader =True1457 isAnnotated =False1458 body = []1459for l inread_pipe_lines(["git","cat-file","-p", name]):1460 l = l.strip()1461if inHeader:1462if re.match(r'tag\s+', l):1463 isAnnotated =True1464elif re.match(r'\s*$', l):1465 inHeader =False1466continue1467else:1468 body.append(l)14691470if not isAnnotated:1471 body = ["lightweight tag imported by git p4\n"]14721473# Create the label - use the same view as the client spec we are using1474 clientSpec =getClientSpec()14751476 labelTemplate ="Label:%s\n"% name1477 labelTemplate +="Description:\n"1478for b in body:1479 labelTemplate +="\t"+ b +"\n"1480 labelTemplate +="View:\n"1481for mapping in clientSpec.mappings:1482 labelTemplate +="\t%s\n"% mapping.depot_side.path14831484if self.dry_run:1485print"Would create p4 label%sfor tag"% name1486elif self.prepare_p4_only:1487print"Not creating p4 label%sfor tag due to option" \1488" --prepare-p4-only"% name1489else:1490p4_write_pipe(["label","-i"], labelTemplate)14911492# Use the label1493p4_system(["tag","-l", name] +1494["%s@%s"% (mapping.depot_side.path, changelist)for mapping in clientSpec.mappings])14951496if verbose:1497print"created p4 label for tag%s"% name14981499defrun(self, args):1500iflen(args) ==0:1501 self.master =currentGitBranch()1502iflen(self.master) ==0or notgitBranchExists("refs/heads/%s"% self.master):1503die("Detecting current git branch failed!")1504eliflen(args) ==1:1505 self.master = args[0]1506if notbranchExists(self.master):1507die("Branch%sdoes not exist"% self.master)1508else:1509return False15101511 allowSubmit =gitConfig("git-p4.allowSubmit")1512iflen(allowSubmit) >0and not self.master in allowSubmit.split(","):1513die("%sis not in git-p4.allowSubmit"% self.master)15141515[upstream, settings] =findUpstreamBranchPoint()1516 self.depotPath = settings['depot-paths'][0]1517iflen(self.origin) ==0:1518 self.origin = upstream15191520if self.preserveUser:1521if not self.canChangeChangelists():1522die("Cannot preserve user names without p4 super-user or admin permissions")15231524# if not set from the command line, try the config file1525if self.conflict_behavior is None:1526 val =gitConfig("git-p4.conflict")1527if val:1528if val not in self.conflict_behavior_choices:1529die("Invalid value '%s' for config git-p4.conflict"% val)1530else:1531 val ="ask"1532 self.conflict_behavior = val15331534if self.verbose:1535print"Origin branch is "+ self.origin15361537iflen(self.depotPath) ==0:1538print"Internal error: cannot locate perforce depot path from existing branches"1539 sys.exit(128)15401541 self.useClientSpec =False1542ifgitConfig("git-p4.useclientspec","--bool") =="true":1543 self.useClientSpec =True1544if self.useClientSpec:1545 self.clientSpecDirs =getClientSpec()15461547if self.useClientSpec:1548# all files are relative to the client spec1549 self.clientPath =getClientRoot()1550else:1551 self.clientPath =p4Where(self.depotPath)15521553if self.clientPath =="":1554die("Error: Cannot locate perforce checkout of%sin client view"% self.depotPath)15551556print"Perforce checkout for depot path%slocated at%s"% (self.depotPath, self.clientPath)1557 self.oldWorkingDirectory = os.getcwd()15581559# ensure the clientPath exists1560 new_client_dir =False1561if not os.path.exists(self.clientPath):1562 new_client_dir =True1563 os.makedirs(self.clientPath)15641565chdir(self.clientPath)1566if self.dry_run:1567print"Would synchronize p4 checkout in%s"% self.clientPath1568else:1569print"Synchronizing p4 checkout..."1570if new_client_dir:1571# old one was destroyed, and maybe nobody told p41572p4_sync("...","-f")1573else:1574p4_sync("...")1575 self.check()15761577 commits = []1578for line inread_pipe_lines("git rev-list --no-merges%s..%s"% (self.origin, self.master)):1579 commits.append(line.strip())1580 commits.reverse()15811582if self.preserveUser or(gitConfig("git-p4.skipUserNameCheck") =="true"):1583 self.checkAuthorship =False1584else:1585 self.checkAuthorship =True15861587if self.preserveUser:1588 self.checkValidP4Users(commits)15891590#1591# Build up a set of options to be passed to diff when1592# submitting each commit to p4.1593#1594if self.detectRenames:1595# command-line -M arg1596 self.diffOpts ="-M"1597else:1598# If not explicitly set check the config variable1599 detectRenames =gitConfig("git-p4.detectRenames")16001601if detectRenames.lower() =="false"or detectRenames =="":1602 self.diffOpts =""1603elif detectRenames.lower() =="true":1604 self.diffOpts ="-M"1605else:1606 self.diffOpts ="-M%s"% detectRenames16071608# no command-line arg for -C or --find-copies-harder, just1609# config variables1610 detectCopies =gitConfig("git-p4.detectCopies")1611if detectCopies.lower() =="false"or detectCopies =="":1612pass1613elif detectCopies.lower() =="true":1614 self.diffOpts +=" -C"1615else:1616 self.diffOpts +=" -C%s"% detectCopies16171618ifgitConfig("git-p4.detectCopiesHarder","--bool") =="true":1619 self.diffOpts +=" --find-copies-harder"16201621#1622# Apply the commits, one at a time. On failure, ask if should1623# continue to try the rest of the patches, or quit.1624#1625if self.dry_run:1626print"Would apply"1627 applied = []1628 last =len(commits) -11629for i, commit inenumerate(commits):1630if self.dry_run:1631print" ",read_pipe(["git","show","-s",1632"--format=format:%h%s", commit])1633 ok =True1634else:1635 ok = self.applyCommit(commit)1636if ok:1637 applied.append(commit)1638else:1639if self.prepare_p4_only and i < last:1640print"Processing only the first commit due to option" \1641" --prepare-p4-only"1642break1643if i < last:1644 quit =False1645while True:1646# prompt for what to do, or use the option/variable1647if self.conflict_behavior =="ask":1648print"What do you want to do?"1649 response =raw_input("[s]kip this commit but apply"1650" the rest, or [q]uit? ")1651if not response:1652continue1653elif self.conflict_behavior =="skip":1654 response ="s"1655elif self.conflict_behavior =="quit":1656 response ="q"1657else:1658die("Unknown conflict_behavior '%s'"%1659 self.conflict_behavior)16601661if response[0] =="s":1662print"Skipping this commit, but applying the rest"1663break1664if response[0] =="q":1665print"Quitting"1666 quit =True1667break1668if quit:1669break16701671chdir(self.oldWorkingDirectory)16721673if self.dry_run:1674pass1675elif self.prepare_p4_only:1676pass1677eliflen(commits) ==len(applied):1678print"All commits applied!"16791680 sync =P4Sync()1681if self.branch:1682 sync.branch = self.branch1683 sync.run([])16841685 rebase =P4Rebase()1686 rebase.rebase()16871688else:1689iflen(applied) ==0:1690print"No commits applied."1691else:1692print"Applied only the commits marked with '*':"1693for c in commits:1694if c in applied:1695 star ="*"1696else:1697 star =" "1698print star,read_pipe(["git","show","-s",1699"--format=format:%h%s", c])1700print"You will have to do 'git p4 sync' and rebase."17011702ifgitConfig("git-p4.exportLabels","--bool") =="true":1703 self.exportLabels =True17041705if self.exportLabels:1706 p4Labels =getP4Labels(self.depotPath)1707 gitTags =getGitTags()17081709 missingGitTags = gitTags - p4Labels1710 self.exportGitTags(missingGitTags)17111712# exit with error unless everything applied perfecly1713iflen(commits) !=len(applied):1714 sys.exit(1)17151716return True17171718classView(object):1719"""Represent a p4 view ("p4 help views"), and map files in a1720 repo according to the view."""17211722classPath(object):1723"""A depot or client path, possibly containing wildcards.1724 The only one supported is ... at the end, currently.1725 Initialize with the full path, with //depot or //client."""17261727def__init__(self, path, is_depot):1728 self.path = path1729 self.is_depot = is_depot1730 self.find_wildcards()1731# remember the prefix bit, useful for relative mappings1732 m = re.match("(//[^/]+/)", self.path)1733if not m:1734die("Path%sdoes not start with //prefix/"% self.path)1735 prefix = m.group(1)1736if not self.is_depot:1737# strip //client/ on client paths1738 self.path = self.path[len(prefix):]17391740deffind_wildcards(self):1741"""Make sure wildcards are valid, and set up internal1742 variables."""17431744 self.ends_triple_dot =False1745# There are three wildcards allowed in p4 views1746# (see "p4 help views"). This code knows how to1747# handle "..." (only at the end), but cannot deal with1748# "%%n" or "*". Only check the depot_side, as p4 should1749# validate that the client_side matches too.1750if re.search(r'%%[1-9]', self.path):1751die("Can't handle%%n wildcards in view:%s"% self.path)1752if self.path.find("*") >=0:1753die("Can't handle * wildcards in view:%s"% self.path)1754 triple_dot_index = self.path.find("...")1755if triple_dot_index >=0:1756if triple_dot_index !=len(self.path) -3:1757die("Can handle only single ... wildcard, at end:%s"%1758 self.path)1759 self.ends_triple_dot =True17601761defensure_compatible(self, other_path):1762"""Make sure the wildcards agree."""1763if self.ends_triple_dot != other_path.ends_triple_dot:1764die("Both paths must end with ... if either does;\n"+1765"paths:%s %s"% (self.path, other_path.path))17661767defmatch_wildcards(self, test_path):1768"""See if this test_path matches us, and fill in the value1769 of the wildcards if so. Returns a tuple of1770 (True|False, wildcards[]). For now, only the ... at end1771 is supported, so at most one wildcard."""1772if self.ends_triple_dot:1773 dotless = self.path[:-3]1774if test_path.startswith(dotless):1775 wildcard = test_path[len(dotless):]1776return(True, [ wildcard ])1777else:1778if test_path == self.path:1779return(True, [])1780return(False, [])17811782defmatch(self, test_path):1783"""Just return if it matches; don't bother with the wildcards."""1784 b, _ = self.match_wildcards(test_path)1785return b17861787deffill_in_wildcards(self, wildcards):1788"""Return the relative path, with the wildcards filled in1789 if there are any."""1790if self.ends_triple_dot:1791return self.path[:-3] + wildcards[0]1792else:1793return self.path17941795classMapping(object):1796def__init__(self, depot_side, client_side, overlay, exclude):1797# depot_side is without the trailing /... if it had one1798 self.depot_side = View.Path(depot_side, is_depot=True)1799 self.client_side = View.Path(client_side, is_depot=False)1800 self.overlay = overlay # started with "+"1801 self.exclude = exclude # started with "-"1802assert not(self.overlay and self.exclude)1803 self.depot_side.ensure_compatible(self.client_side)18041805def__str__(self):1806 c =" "1807if self.overlay:1808 c ="+"1809if self.exclude:1810 c ="-"1811return"View.Mapping:%s%s->%s"% \1812(c, self.depot_side.path, self.client_side.path)18131814defmap_depot_to_client(self, depot_path):1815"""Calculate the client path if using this mapping on the1816 given depot path; does not consider the effect of other1817 mappings in a view. Even excluded mappings are returned."""1818 matches, wildcards = self.depot_side.match_wildcards(depot_path)1819if not matches:1820return""1821 client_path = self.client_side.fill_in_wildcards(wildcards)1822return client_path18231824#1825# View methods1826#1827def__init__(self):1828 self.mappings = []18291830defappend(self, view_line):1831"""Parse a view line, splitting it into depot and client1832 sides. Append to self.mappings, preserving order."""18331834# Split the view line into exactly two words. P4 enforces1835# structure on these lines that simplifies this quite a bit.1836#1837# Either or both words may be double-quoted.1838# Single quotes do not matter.1839# Double-quote marks cannot occur inside the words.1840# A + or - prefix is also inside the quotes.1841# There are no quotes unless they contain a space.1842# The line is already white-space stripped.1843# The two words are separated by a single space.1844#1845if view_line[0] =='"':1846# First word is double quoted. Find its end.1847 close_quote_index = view_line.find('"',1)1848if close_quote_index <=0:1849die("No first-word closing quote found:%s"% view_line)1850 depot_side = view_line[1:close_quote_index]1851# skip closing quote and space1852 rhs_index = close_quote_index +1+11853else:1854 space_index = view_line.find(" ")1855if space_index <=0:1856die("No word-splitting space found:%s"% view_line)1857 depot_side = view_line[0:space_index]1858 rhs_index = space_index +118591860if view_line[rhs_index] =='"':1861# Second word is double quoted. Make sure there is a1862# double quote at the end too.1863if not view_line.endswith('"'):1864die("View line with rhs quote should end with one:%s"%1865 view_line)1866# skip the quotes1867 client_side = view_line[rhs_index+1:-1]1868else:1869 client_side = view_line[rhs_index:]18701871# prefix + means overlay on previous mapping1872 overlay =False1873if depot_side.startswith("+"):1874 overlay =True1875 depot_side = depot_side[1:]18761877# prefix - means exclude this path1878 exclude =False1879if depot_side.startswith("-"):1880 exclude =True1881 depot_side = depot_side[1:]18821883 m = View.Mapping(depot_side, client_side, overlay, exclude)1884 self.mappings.append(m)18851886defmap_in_client(self, depot_path):1887"""Return the relative location in the client where this1888 depot file should live. Returns "" if the file should1889 not be mapped in the client."""18901891 paths_filled = []1892 client_path =""18931894# look at later entries first1895for m in self.mappings[::-1]:18961897# see where will this path end up in the client1898 p = m.map_depot_to_client(depot_path)18991900if p =="":1901# Depot path does not belong in client. Must remember1902# this, as previous items should not cause files to1903# exist in this path either. Remember that the list is1904# being walked from the end, which has higher precedence.1905# Overlap mappings do not exclude previous mappings.1906if not m.overlay:1907 paths_filled.append(m.client_side)19081909else:1910# This mapping matched; no need to search any further.1911# But, the mapping could be rejected if the client path1912# has already been claimed by an earlier mapping (i.e.1913# one later in the list, which we are walking backwards).1914 already_mapped_in_client =False1915for f in paths_filled:1916# this is View.Path.match1917if f.match(p):1918 already_mapped_in_client =True1919break1920if not already_mapped_in_client:1921# Include this file, unless it is from a line that1922# explicitly said to exclude it.1923if not m.exclude:1924 client_path = p19251926# a match, even if rejected, always stops the search1927break19281929return client_path19301931classP4Sync(Command, P4UserMap):1932 delete_actions = ("delete","move/delete","purge")19331934def__init__(self):1935 Command.__init__(self)1936 P4UserMap.__init__(self)1937 self.options = [1938 optparse.make_option("--branch", dest="branch"),1939 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),1940 optparse.make_option("--changesfile", dest="changesFile"),1941 optparse.make_option("--silent", dest="silent", action="store_true"),1942 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),1943 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),1944 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",1945help="Import into refs/heads/ , not refs/remotes"),1946 optparse.make_option("--max-changes", dest="maxChanges"),1947 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',1948help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),1949 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',1950help="Only sync files that are included in the Perforce Client Spec")1951]1952 self.description ="""Imports from Perforce into a git repository.\n1953 example:1954 //depot/my/project/ -- to import the current head1955 //depot/my/project/@all -- to import everything1956 //depot/my/project/@1,6 -- to import only from revision 1 to 619571958 (a ... is not needed in the path p4 specification, it's added implicitly)"""19591960 self.usage +=" //depot/path[@revRange]"1961 self.silent =False1962 self.createdBranches =set()1963 self.committedChanges =set()1964 self.branch =""1965 self.detectBranches =False1966 self.detectLabels =False1967 self.importLabels =False1968 self.changesFile =""1969 self.syncWithOrigin =True1970 self.importIntoRemotes =True1971 self.maxChanges =""1972 self.isWindows = (platform.system() =="Windows")1973 self.keepRepoPath =False1974 self.depotPaths =None1975 self.p4BranchesInGit = []1976 self.cloneExclude = []1977 self.useClientSpec =False1978 self.useClientSpec_from_options =False1979 self.clientSpecDirs =None1980 self.tempBranches = []1981 self.tempBranchLocation ="git-p4-tmp"19821983ifgitConfig("git-p4.syncFromOrigin") =="false":1984 self.syncWithOrigin =False19851986# Force a checkpoint in fast-import and wait for it to finish1987defcheckpoint(self):1988 self.gitStream.write("checkpoint\n\n")1989 self.gitStream.write("progress checkpoint\n\n")1990 out = self.gitOutput.readline()1991if self.verbose:1992print"checkpoint finished: "+ out19931994defextractFilesFromCommit(self, commit):1995 self.cloneExclude = [re.sub(r"\.\.\.$","", path)1996for path in self.cloneExclude]1997 files = []1998 fnum =01999while commit.has_key("depotFile%s"% fnum):2000 path = commit["depotFile%s"% fnum]20012002if[p for p in self.cloneExclude2003ifp4PathStartsWith(path, p)]:2004 found =False2005else:2006 found = [p for p in self.depotPaths2007ifp4PathStartsWith(path, p)]2008if not found:2009 fnum = fnum +12010continue20112012file= {}2013file["path"] = path2014file["rev"] = commit["rev%s"% fnum]2015file["action"] = commit["action%s"% fnum]2016file["type"] = commit["type%s"% fnum]2017 files.append(file)2018 fnum = fnum +12019return files20202021defstripRepoPath(self, path, prefixes):2022"""When streaming files, this is called to map a p4 depot path2023 to where it should go in git. The prefixes are either2024 self.depotPaths, or self.branchPrefixes in the case of2025 branch detection."""20262027if self.useClientSpec:2028# branch detection moves files up a level (the branch name)2029# from what client spec interpretation gives2030 path = self.clientSpecDirs.map_in_client(path)2031if self.detectBranches:2032for b in self.knownBranches:2033if path.startswith(b +"/"):2034 path = path[len(b)+1:]20352036elif self.keepRepoPath:2037# Preserve everything in relative path name except leading2038# //depot/; just look at first prefix as they all should2039# be in the same depot.2040 depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])2041ifp4PathStartsWith(path, depot):2042 path = path[len(depot):]20432044else:2045for p in prefixes:2046ifp4PathStartsWith(path, p):2047 path = path[len(p):]2048break20492050 path =wildcard_decode(path)2051return path20522053defsplitFilesIntoBranches(self, commit):2054"""Look at each depotFile in the commit to figure out to what2055 branch it belongs."""20562057 branches = {}2058 fnum =02059while commit.has_key("depotFile%s"% fnum):2060 path = commit["depotFile%s"% fnum]2061 found = [p for p in self.depotPaths2062ifp4PathStartsWith(path, p)]2063if not found:2064 fnum = fnum +12065continue20662067file= {}2068file["path"] = path2069file["rev"] = commit["rev%s"% fnum]2070file["action"] = commit["action%s"% fnum]2071file["type"] = commit["type%s"% fnum]2072 fnum = fnum +120732074# start with the full relative path where this file would2075# go in a p4 client2076if self.useClientSpec:2077 relPath = self.clientSpecDirs.map_in_client(path)2078else:2079 relPath = self.stripRepoPath(path, self.depotPaths)20802081for branch in self.knownBranches.keys():2082# add a trailing slash so that a commit into qt/4.2foo2083# doesn't end up in qt/4.2, e.g.2084if relPath.startswith(branch +"/"):2085if branch not in branches:2086 branches[branch] = []2087 branches[branch].append(file)2088break20892090return branches20912092# output one file from the P4 stream2093# - helper for streamP4Files20942095defstreamOneP4File(self,file, contents):2096 relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)2097if verbose:2098 sys.stderr.write("%s\n"% relPath)20992100(type_base, type_mods) =split_p4_type(file["type"])21012102 git_mode ="100644"2103if"x"in type_mods:2104 git_mode ="100755"2105if type_base =="symlink":2106 git_mode ="120000"2107# p4 print on a symlink contains "target\n"; remove the newline2108 data =''.join(contents)2109 contents = [data[:-1]]21102111if type_base =="utf16":2112# p4 delivers different text in the python output to -G2113# than it does when using "print -o", or normal p4 client2114# operations. utf16 is converted to ascii or utf8, perhaps.2115# But ascii text saved as -t utf16 is completely mangled.2116# Invoke print -o to get the real contents.2117 text =p4_read_pipe(['print','-q','-o','-',file['depotFile']])2118 contents = [ text ]21192120if type_base =="apple":2121# Apple filetype files will be streamed as a concatenation of2122# its appledouble header and the contents. This is useless2123# on both macs and non-macs. If using "print -q -o xx", it2124# will create "xx" with the data, and "%xx" with the header.2125# This is also not very useful.2126#2127# Ideally, someday, this script can learn how to generate2128# appledouble files directly and import those to git, but2129# non-mac machines can never find a use for apple filetype.2130print"\nIgnoring apple filetype file%s"%file['depotFile']2131return21322133# Perhaps windows wants unicode, utf16 newlines translated too;2134# but this is not doing it.2135if self.isWindows and type_base =="text":2136 mangled = []2137for data in contents:2138 data = data.replace("\r\n","\n")2139 mangled.append(data)2140 contents = mangled21412142# Note that we do not try to de-mangle keywords on utf16 files,2143# even though in theory somebody may want that.2144 pattern =p4_keywords_regexp_for_type(type_base, type_mods)2145if pattern:2146 regexp = re.compile(pattern, re.VERBOSE)2147 text =''.join(contents)2148 text = regexp.sub(r'$\1$', text)2149 contents = [ text ]21502151 self.gitStream.write("M%sinline%s\n"% (git_mode, relPath))21522153# total length...2154 length =02155for d in contents:2156 length = length +len(d)21572158 self.gitStream.write("data%d\n"% length)2159for d in contents:2160 self.gitStream.write(d)2161 self.gitStream.write("\n")21622163defstreamOneP4Deletion(self,file):2164 relPath = self.stripRepoPath(file['path'], self.branchPrefixes)2165if verbose:2166 sys.stderr.write("delete%s\n"% relPath)2167 self.gitStream.write("D%s\n"% relPath)21682169# handle another chunk of streaming data2170defstreamP4FilesCb(self, marshalled):21712172# catch p4 errors and complain2173 err =None2174if"code"in marshalled:2175if marshalled["code"] =="error":2176if"data"in marshalled:2177 err = marshalled["data"].rstrip()2178if err:2179 f =None2180if self.stream_have_file_info:2181if"depotFile"in self.stream_file:2182 f = self.stream_file["depotFile"]2183# force a failure in fast-import, else an empty2184# commit will be made2185 self.gitStream.write("\n")2186 self.gitStream.write("die-now\n")2187 self.gitStream.close()2188# ignore errors, but make sure it exits first2189 self.importProcess.wait()2190if f:2191die("Error from p4 print for%s:%s"% (f, err))2192else:2193die("Error from p4 print:%s"% err)21942195if marshalled.has_key('depotFile')and self.stream_have_file_info:2196# start of a new file - output the old one first2197 self.streamOneP4File(self.stream_file, self.stream_contents)2198 self.stream_file = {}2199 self.stream_contents = []2200 self.stream_have_file_info =False22012202# pick up the new file information... for the2203# 'data' field we need to append to our array2204for k in marshalled.keys():2205if k =='data':2206 self.stream_contents.append(marshalled['data'])2207else:2208 self.stream_file[k] = marshalled[k]22092210 self.stream_have_file_info =True22112212# Stream directly from "p4 files" into "git fast-import"2213defstreamP4Files(self, files):2214 filesForCommit = []2215 filesToRead = []2216 filesToDelete = []22172218for f in files:2219# if using a client spec, only add the files that have2220# a path in the client2221if self.clientSpecDirs:2222if self.clientSpecDirs.map_in_client(f['path']) =="":2223continue22242225 filesForCommit.append(f)2226if f['action']in self.delete_actions:2227 filesToDelete.append(f)2228else:2229 filesToRead.append(f)22302231# deleted files...2232for f in filesToDelete:2233 self.streamOneP4Deletion(f)22342235iflen(filesToRead) >0:2236 self.stream_file = {}2237 self.stream_contents = []2238 self.stream_have_file_info =False22392240# curry self argument2241defstreamP4FilesCbSelf(entry):2242 self.streamP4FilesCb(entry)22432244 fileArgs = ['%s#%s'% (f['path'], f['rev'])for f in filesToRead]22452246p4CmdList(["-x","-","print"],2247 stdin=fileArgs,2248 cb=streamP4FilesCbSelf)22492250# do the last chunk2251if self.stream_file.has_key('depotFile'):2252 self.streamOneP4File(self.stream_file, self.stream_contents)22532254defmake_email(self, userid):2255if userid in self.users:2256return self.users[userid]2257else:2258return"%s<a@b>"% userid22592260# Stream a p4 tag2261defstreamTag(self, gitStream, labelName, labelDetails, commit, epoch):2262if verbose:2263print"writing tag%sfor commit%s"% (labelName, commit)2264 gitStream.write("tag%s\n"% labelName)2265 gitStream.write("from%s\n"% commit)22662267if labelDetails.has_key('Owner'):2268 owner = labelDetails["Owner"]2269else:2270 owner =None22712272# Try to use the owner of the p4 label, or failing that,2273# the current p4 user id.2274if owner:2275 email = self.make_email(owner)2276else:2277 email = self.make_email(self.p4UserId())2278 tagger ="%s %s %s"% (email, epoch, self.tz)22792280 gitStream.write("tagger%s\n"% tagger)22812282print"labelDetails=",labelDetails2283if labelDetails.has_key('Description'):2284 description = labelDetails['Description']2285else:2286 description ='Label from git p4'22872288 gitStream.write("data%d\n"%len(description))2289 gitStream.write(description)2290 gitStream.write("\n")22912292defcommit(self, details, files, branch, parent =""):2293 epoch = details["time"]2294 author = details["user"]22952296if self.verbose:2297print"commit into%s"% branch22982299# start with reading files; if that fails, we should not2300# create a commit.2301 new_files = []2302for f in files:2303if[p for p in self.branchPrefixes ifp4PathStartsWith(f['path'], p)]:2304 new_files.append(f)2305else:2306 sys.stderr.write("Ignoring file outside of prefix:%s\n"% f['path'])23072308 self.gitStream.write("commit%s\n"% branch)2309# gitStream.write("mark :%s\n" % details["change"])2310 self.committedChanges.add(int(details["change"]))2311 committer =""2312if author not in self.users:2313 self.getUserMapFromPerforceServer()2314 committer ="%s %s %s"% (self.make_email(author), epoch, self.tz)23152316 self.gitStream.write("committer%s\n"% committer)23172318 self.gitStream.write("data <<EOT\n")2319 self.gitStream.write(details["desc"])2320 self.gitStream.write("\n[git-p4: depot-paths =\"%s\": change =%s"%2321(','.join(self.branchPrefixes), details["change"]))2322iflen(details['options']) >0:2323 self.gitStream.write(": options =%s"% details['options'])2324 self.gitStream.write("]\nEOT\n\n")23252326iflen(parent) >0:2327if self.verbose:2328print"parent%s"% parent2329 self.gitStream.write("from%s\n"% parent)23302331 self.streamP4Files(new_files)2332 self.gitStream.write("\n")23332334 change =int(details["change"])23352336if self.labels.has_key(change):2337 label = self.labels[change]2338 labelDetails = label[0]2339 labelRevisions = label[1]2340if self.verbose:2341print"Change%sis labelled%s"% (change, labelDetails)23422343 files =p4CmdList(["files"] + ["%s...@%s"% (p, change)2344for p in self.branchPrefixes])23452346iflen(files) ==len(labelRevisions):23472348 cleanedFiles = {}2349for info in files:2350if info["action"]in self.delete_actions:2351continue2352 cleanedFiles[info["depotFile"]] = info["rev"]23532354if cleanedFiles == labelRevisions:2355 self.streamTag(self.gitStream,'tag_%s'% labelDetails['label'], labelDetails, branch, epoch)23562357else:2358if not self.silent:2359print("Tag%sdoes not match with change%s: files do not match."2360% (labelDetails["label"], change))23612362else:2363if not self.silent:2364print("Tag%sdoes not match with change%s: file count is different."2365% (labelDetails["label"], change))23662367# Build a dictionary of changelists and labels, for "detect-labels" option.2368defgetLabels(self):2369 self.labels = {}23702371 l =p4CmdList(["labels"] + ["%s..."% p for p in self.depotPaths])2372iflen(l) >0and not self.silent:2373print"Finding files belonging to labels in%s"% `self.depotPaths`23742375for output in l:2376 label = output["label"]2377 revisions = {}2378 newestChange =02379if self.verbose:2380print"Querying files for label%s"% label2381forfileinp4CmdList(["files"] +2382["%s...@%s"% (p, label)2383for p in self.depotPaths]):2384 revisions[file["depotFile"]] =file["rev"]2385 change =int(file["change"])2386if change > newestChange:2387 newestChange = change23882389 self.labels[newestChange] = [output, revisions]23902391if self.verbose:2392print"Label changes:%s"% self.labels.keys()23932394# Import p4 labels as git tags. A direct mapping does not2395# exist, so assume that if all the files are at the same revision2396# then we can use that, or it's something more complicated we should2397# just ignore.2398defimportP4Labels(self, stream, p4Labels):2399if verbose:2400print"import p4 labels: "+' '.join(p4Labels)24012402 ignoredP4Labels =gitConfigList("git-p4.ignoredP4Labels")2403 validLabelRegexp =gitConfig("git-p4.labelImportRegexp")2404iflen(validLabelRegexp) ==0:2405 validLabelRegexp = defaultLabelRegexp2406 m = re.compile(validLabelRegexp)24072408for name in p4Labels:2409 commitFound =False24102411if not m.match(name):2412if verbose:2413print"label%sdoes not match regexp%s"% (name,validLabelRegexp)2414continue24152416if name in ignoredP4Labels:2417continue24182419 labelDetails =p4CmdList(['label',"-o", name])[0]24202421# get the most recent changelist for each file in this label2422 change =p4Cmd(["changes","-m","1"] + ["%s...@%s"% (p, name)2423for p in self.depotPaths])24242425if change.has_key('change'):2426# find the corresponding git commit; take the oldest commit2427 changelist =int(change['change'])2428 gitCommit =read_pipe(["git","rev-list","--max-count=1",2429"--reverse",":/\[git-p4:.*change =%d\]"% changelist])2430iflen(gitCommit) ==0:2431print"could not find git commit for changelist%d"% changelist2432else:2433 gitCommit = gitCommit.strip()2434 commitFound =True2435# Convert from p4 time format2436try:2437 tmwhen = time.strptime(labelDetails['Update'],"%Y/%m/%d%H:%M:%S")2438exceptValueError:2439print"Could not convert label time%s"% labelDetails['Update']2440 tmwhen =124412442 when =int(time.mktime(tmwhen))2443 self.streamTag(stream, name, labelDetails, gitCommit, when)2444if verbose:2445print"p4 label%smapped to git commit%s"% (name, gitCommit)2446else:2447if verbose:2448print"Label%shas no changelists - possibly deleted?"% name24492450if not commitFound:2451# We can't import this label; don't try again as it will get very2452# expensive repeatedly fetching all the files for labels that will2453# never be imported. If the label is moved in the future, the2454# ignore will need to be removed manually.2455system(["git","config","--add","git-p4.ignoredP4Labels", name])24562457defguessProjectName(self):2458for p in self.depotPaths:2459if p.endswith("/"):2460 p = p[:-1]2461 p = p[p.strip().rfind("/") +1:]2462if not p.endswith("/"):2463 p +="/"2464return p24652466defgetBranchMapping(self):2467 lostAndFoundBranches =set()24682469 user =gitConfig("git-p4.branchUser")2470iflen(user) >0:2471 command ="branches -u%s"% user2472else:2473 command ="branches"24742475for info inp4CmdList(command):2476 details =p4Cmd(["branch","-o", info["branch"]])2477 viewIdx =02478while details.has_key("View%s"% viewIdx):2479 paths = details["View%s"% viewIdx].split(" ")2480 viewIdx = viewIdx +12481# require standard //depot/foo/... //depot/bar/... mapping2482iflen(paths) !=2or not paths[0].endswith("/...")or not paths[1].endswith("/..."):2483continue2484 source = paths[0]2485 destination = paths[1]2486## HACK2487ifp4PathStartsWith(source, self.depotPaths[0])andp4PathStartsWith(destination, self.depotPaths[0]):2488 source = source[len(self.depotPaths[0]):-4]2489 destination = destination[len(self.depotPaths[0]):-4]24902491if destination in self.knownBranches:2492if not self.silent:2493print"p4 branch%sdefines a mapping from%sto%s"% (info["branch"], source, destination)2494print"but there exists another mapping from%sto%salready!"% (self.knownBranches[destination], destination)2495continue24962497 self.knownBranches[destination] = source24982499 lostAndFoundBranches.discard(destination)25002501if source not in self.knownBranches:2502 lostAndFoundBranches.add(source)25032504# Perforce does not strictly require branches to be defined, so we also2505# check git config for a branch list.2506#2507# Example of branch definition in git config file:2508# [git-p4]2509# branchList=main:branchA2510# branchList=main:branchB2511# branchList=branchA:branchC2512 configBranches =gitConfigList("git-p4.branchList")2513for branch in configBranches:2514if branch:2515(source, destination) = branch.split(":")2516 self.knownBranches[destination] = source25172518 lostAndFoundBranches.discard(destination)25192520if source not in self.knownBranches:2521 lostAndFoundBranches.add(source)252225232524for branch in lostAndFoundBranches:2525 self.knownBranches[branch] = branch25262527defgetBranchMappingFromGitBranches(self):2528 branches =p4BranchesInGit(self.importIntoRemotes)2529for branch in branches.keys():2530if branch =="master":2531 branch ="main"2532else:2533 branch = branch[len(self.projectName):]2534 self.knownBranches[branch] = branch25352536defupdateOptionDict(self, d):2537 option_keys = {}2538if self.keepRepoPath:2539 option_keys['keepRepoPath'] =125402541 d["options"] =' '.join(sorted(option_keys.keys()))25422543defreadOptions(self, d):2544 self.keepRepoPath = (d.has_key('options')2545and('keepRepoPath'in d['options']))25462547defgitRefForBranch(self, branch):2548if branch =="main":2549return self.refPrefix +"master"25502551iflen(branch) <=0:2552return branch25532554return self.refPrefix + self.projectName + branch25552556defgitCommitByP4Change(self, ref, change):2557if self.verbose:2558print"looking in ref "+ ref +" for change%susing bisect..."% change25592560 earliestCommit =""2561 latestCommit =parseRevision(ref)25622563while True:2564if self.verbose:2565print"trying: earliest%slatest%s"% (earliestCommit, latestCommit)2566 next =read_pipe("git rev-list --bisect%s %s"% (latestCommit, earliestCommit)).strip()2567iflen(next) ==0:2568if self.verbose:2569print"argh"2570return""2571 log =extractLogMessageFromGitCommit(next)2572 settings =extractSettingsGitLog(log)2573 currentChange =int(settings['change'])2574if self.verbose:2575print"current change%s"% currentChange25762577if currentChange == change:2578if self.verbose:2579print"found%s"% next2580return next25812582if currentChange < change:2583 earliestCommit ="^%s"% next2584else:2585 latestCommit ="%s"% next25862587return""25882589defimportNewBranch(self, branch, maxChange):2590# make fast-import flush all changes to disk and update the refs using the checkpoint2591# command so that we can try to find the branch parent in the git history2592 self.gitStream.write("checkpoint\n\n");2593 self.gitStream.flush();2594 branchPrefix = self.depotPaths[0] + branch +"/"2595range="@1,%s"% maxChange2596#print "prefix" + branchPrefix2597 changes =p4ChangesForPaths([branchPrefix],range)2598iflen(changes) <=0:2599return False2600 firstChange = changes[0]2601#print "first change in branch: %s" % firstChange2602 sourceBranch = self.knownBranches[branch]2603 sourceDepotPath = self.depotPaths[0] + sourceBranch2604 sourceRef = self.gitRefForBranch(sourceBranch)2605#print "source " + sourceBranch26062607 branchParentChange =int(p4Cmd(["changes","-m","1","%s...@1,%s"% (sourceDepotPath, firstChange)])["change"])2608#print "branch parent: %s" % branchParentChange2609 gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)2610iflen(gitParent) >0:2611 self.initialParents[self.gitRefForBranch(branch)] = gitParent2612#print "parent git commit: %s" % gitParent26132614 self.importChanges(changes)2615return True26162617defsearchParent(self, parent, branch, target):2618 parentFound =False2619for blob inread_pipe_lines(["git","rev-list","--reverse","--no-merges", parent]):2620 blob = blob.strip()2621iflen(read_pipe(["git","diff-tree", blob, target])) ==0:2622 parentFound =True2623if self.verbose:2624print"Found parent of%sin commit%s"% (branch, blob)2625break2626if parentFound:2627return blob2628else:2629return None26302631defimportChanges(self, changes):2632 cnt =12633for change in changes:2634 description =p4_describe(change)2635 self.updateOptionDict(description)26362637if not self.silent:2638 sys.stdout.write("\rImporting revision%s(%s%%)"% (change, cnt *100/len(changes)))2639 sys.stdout.flush()2640 cnt = cnt +126412642try:2643if self.detectBranches:2644 branches = self.splitFilesIntoBranches(description)2645for branch in branches.keys():2646## HACK --hwn2647 branchPrefix = self.depotPaths[0] + branch +"/"2648 self.branchPrefixes = [ branchPrefix ]26492650 parent =""26512652 filesForCommit = branches[branch]26532654if self.verbose:2655print"branch is%s"% branch26562657 self.updatedBranches.add(branch)26582659if branch not in self.createdBranches:2660 self.createdBranches.add(branch)2661 parent = self.knownBranches[branch]2662if parent == branch:2663 parent =""2664else:2665 fullBranch = self.projectName + branch2666if fullBranch not in self.p4BranchesInGit:2667if not self.silent:2668print("\nImporting new branch%s"% fullBranch);2669if self.importNewBranch(branch, change -1):2670 parent =""2671 self.p4BranchesInGit.append(fullBranch)2672if not self.silent:2673print("\nResuming with change%s"% change);26742675if self.verbose:2676print"parent determined through known branches:%s"% parent26772678 branch = self.gitRefForBranch(branch)2679 parent = self.gitRefForBranch(parent)26802681if self.verbose:2682print"looking for initial parent for%s; current parent is%s"% (branch, parent)26832684iflen(parent) ==0and branch in self.initialParents:2685 parent = self.initialParents[branch]2686del self.initialParents[branch]26872688 blob =None2689iflen(parent) >0:2690 tempBranch = os.path.join(self.tempBranchLocation,"%d"% (change))2691if self.verbose:2692print"Creating temporary branch: "+ tempBranch2693 self.commit(description, filesForCommit, tempBranch)2694 self.tempBranches.append(tempBranch)2695 self.checkpoint()2696 blob = self.searchParent(parent, branch, tempBranch)2697if blob:2698 self.commit(description, filesForCommit, branch, blob)2699else:2700if self.verbose:2701print"Parent of%snot found. Committing into head of%s"% (branch, parent)2702 self.commit(description, filesForCommit, branch, parent)2703else:2704 files = self.extractFilesFromCommit(description)2705 self.commit(description, files, self.branch,2706 self.initialParent)2707# only needed once, to connect to the previous commit2708 self.initialParent =""2709exceptIOError:2710print self.gitError.read()2711 sys.exit(1)27122713defimportHeadRevision(self, revision):2714print"Doing initial import of%sfrom revision%sinto%s"% (' '.join(self.depotPaths), revision, self.branch)27152716 details = {}2717 details["user"] ="git perforce import user"2718 details["desc"] = ("Initial import of%sfrom the state at revision%s\n"2719% (' '.join(self.depotPaths), revision))2720 details["change"] = revision2721 newestRevision =027222723 fileCnt =02724 fileArgs = ["%s...%s"% (p,revision)for p in self.depotPaths]27252726for info inp4CmdList(["files"] + fileArgs):27272728if'code'in info and info['code'] =='error':2729 sys.stderr.write("p4 returned an error:%s\n"2730% info['data'])2731if info['data'].find("must refer to client") >=0:2732 sys.stderr.write("This particular p4 error is misleading.\n")2733 sys.stderr.write("Perhaps the depot path was misspelled.\n");2734 sys.stderr.write("Depot path:%s\n"%" ".join(self.depotPaths))2735 sys.exit(1)2736if'p4ExitCode'in info:2737 sys.stderr.write("p4 exitcode:%s\n"% info['p4ExitCode'])2738 sys.exit(1)273927402741 change =int(info["change"])2742if change > newestRevision:2743 newestRevision = change27442745if info["action"]in self.delete_actions:2746# don't increase the file cnt, otherwise details["depotFile123"] will have gaps!2747#fileCnt = fileCnt + 12748continue27492750for prop in["depotFile","rev","action","type"]:2751 details["%s%s"% (prop, fileCnt)] = info[prop]27522753 fileCnt = fileCnt +127542755 details["change"] = newestRevision27562757# Use time from top-most change so that all git p4 clones of2758# the same p4 repo have the same commit SHA1s.2759 res =p4_describe(newestRevision)2760 details["time"] = res["time"]27612762 self.updateOptionDict(details)2763try:2764 self.commit(details, self.extractFilesFromCommit(details), self.branch)2765exceptIOError:2766print"IO error with git fast-import. Is your git version recent enough?"2767print self.gitError.read()276827692770defrun(self, args):2771 self.depotPaths = []2772 self.changeRange =""2773 self.previousDepotPaths = []2774 self.hasOrigin =False27752776# map from branch depot path to parent branch2777 self.knownBranches = {}2778 self.initialParents = {}27792780if self.importIntoRemotes:2781 self.refPrefix ="refs/remotes/p4/"2782else:2783 self.refPrefix ="refs/heads/p4/"27842785if self.syncWithOrigin:2786 self.hasOrigin =originP4BranchesExist()2787if self.hasOrigin:2788if not self.silent:2789print'Syncing with origin first, using "git fetch origin"'2790system("git fetch origin")27912792 branch_arg_given =bool(self.branch)2793iflen(self.branch) ==0:2794 self.branch = self.refPrefix +"master"2795ifgitBranchExists("refs/heads/p4")and self.importIntoRemotes:2796system("git update-ref%srefs/heads/p4"% self.branch)2797system("git branch -D p4")27982799# accept either the command-line option, or the configuration variable2800if self.useClientSpec:2801# will use this after clone to set the variable2802 self.useClientSpec_from_options =True2803else:2804ifgitConfig("git-p4.useclientspec","--bool") =="true":2805 self.useClientSpec =True2806if self.useClientSpec:2807 self.clientSpecDirs =getClientSpec()28082809# TODO: should always look at previous commits,2810# merge with previous imports, if possible.2811if args == []:2812if self.hasOrigin:2813createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)28142815# branches holds mapping from branch name to sha12816 branches =p4BranchesInGit(self.importIntoRemotes)28172818# restrict to just this one, disabling detect-branches2819if branch_arg_given:2820 short = self.branch.split("/")[-1]2821if short in branches:2822 self.p4BranchesInGit = [ short ]2823else:2824 self.p4BranchesInGit = branches.keys()28252826iflen(self.p4BranchesInGit) >1:2827if not self.silent:2828print"Importing from/into multiple branches"2829 self.detectBranches =True2830for branch in branches.keys():2831 self.initialParents[self.refPrefix + branch] = \2832 branches[branch]28332834if self.verbose:2835print"branches:%s"% self.p4BranchesInGit28362837 p4Change =02838for branch in self.p4BranchesInGit:2839 logMsg =extractLogMessageFromGitCommit(self.refPrefix + branch)28402841 settings =extractSettingsGitLog(logMsg)28422843 self.readOptions(settings)2844if(settings.has_key('depot-paths')2845and settings.has_key('change')):2846 change =int(settings['change']) +12847 p4Change =max(p4Change, change)28482849 depotPaths =sorted(settings['depot-paths'])2850if self.previousDepotPaths == []:2851 self.previousDepotPaths = depotPaths2852else:2853 paths = []2854for(prev, cur)inzip(self.previousDepotPaths, depotPaths):2855 prev_list = prev.split("/")2856 cur_list = cur.split("/")2857for i inrange(0,min(len(cur_list),len(prev_list))):2858if cur_list[i] <> prev_list[i]:2859 i = i -12860break28612862 paths.append("/".join(cur_list[:i +1]))28632864 self.previousDepotPaths = paths28652866if p4Change >0:2867 self.depotPaths =sorted(self.previousDepotPaths)2868 self.changeRange ="@%s,#head"% p4Change2869if not self.silent and not self.detectBranches:2870print"Performing incremental import into%sgit branch"% self.branch28712872# accept multiple ref name abbreviations:2873# refs/foo/bar/branch -> use it exactly2874# p4/branch -> prepend refs/remotes/ or refs/heads/2875# branch -> prepend refs/remotes/p4/ or refs/heads/p4/2876if not self.branch.startswith("refs/"):2877if self.importIntoRemotes:2878 prepend ="refs/remotes/"2879else:2880 prepend ="refs/heads/"2881if not self.branch.startswith("p4/"):2882 prepend +="p4/"2883 self.branch = prepend + self.branch28842885iflen(args) ==0and self.depotPaths:2886if not self.silent:2887print"Depot paths:%s"%' '.join(self.depotPaths)2888else:2889if self.depotPaths and self.depotPaths != args:2890print("previous import used depot path%sand now%swas specified. "2891"This doesn't work!"% (' '.join(self.depotPaths),2892' '.join(args)))2893 sys.exit(1)28942895 self.depotPaths =sorted(args)28962897 revision =""2898 self.users = {}28992900# Make sure no revision specifiers are used when --changesfile2901# is specified.2902 bad_changesfile =False2903iflen(self.changesFile) >0:2904for p in self.depotPaths:2905if p.find("@") >=0or p.find("#") >=0:2906 bad_changesfile =True2907break2908if bad_changesfile:2909die("Option --changesfile is incompatible with revision specifiers")29102911 newPaths = []2912for p in self.depotPaths:2913if p.find("@") != -1:2914 atIdx = p.index("@")2915 self.changeRange = p[atIdx:]2916if self.changeRange =="@all":2917 self.changeRange =""2918elif','not in self.changeRange:2919 revision = self.changeRange2920 self.changeRange =""2921 p = p[:atIdx]2922elif p.find("#") != -1:2923 hashIdx = p.index("#")2924 revision = p[hashIdx:]2925 p = p[:hashIdx]2926elif self.previousDepotPaths == []:2927# pay attention to changesfile, if given, else import2928# the entire p4 tree at the head revision2929iflen(self.changesFile) ==0:2930 revision ="#head"29312932 p = re.sub("\.\.\.$","", p)2933if not p.endswith("/"):2934 p +="/"29352936 newPaths.append(p)29372938 self.depotPaths = newPaths29392940# --detect-branches may change this for each branch2941 self.branchPrefixes = self.depotPaths29422943 self.loadUserMapFromCache()2944 self.labels = {}2945if self.detectLabels:2946 self.getLabels();29472948if self.detectBranches:2949## FIXME - what's a P4 projectName ?2950 self.projectName = self.guessProjectName()29512952if self.hasOrigin:2953 self.getBranchMappingFromGitBranches()2954else:2955 self.getBranchMapping()2956if self.verbose:2957print"p4-git branches:%s"% self.p4BranchesInGit2958print"initial parents:%s"% self.initialParents2959for b in self.p4BranchesInGit:2960if b !="master":29612962## FIXME2963 b = b[len(self.projectName):]2964 self.createdBranches.add(b)29652966 self.tz ="%+03d%02d"% (- time.timezone /3600, ((- time.timezone %3600) /60))29672968 self.importProcess = subprocess.Popen(["git","fast-import"],2969 stdin=subprocess.PIPE,2970 stdout=subprocess.PIPE,2971 stderr=subprocess.PIPE);2972 self.gitOutput = self.importProcess.stdout2973 self.gitStream = self.importProcess.stdin2974 self.gitError = self.importProcess.stderr29752976if revision:2977 self.importHeadRevision(revision)2978else:2979 changes = []29802981iflen(self.changesFile) >0:2982 output =open(self.changesFile).readlines()2983 changeSet =set()2984for line in output:2985 changeSet.add(int(line))29862987for change in changeSet:2988 changes.append(change)29892990 changes.sort()2991else:2992# catch "git p4 sync" with no new branches, in a repo that2993# does not have any existing p4 branches2994iflen(args) ==0:2995if not self.p4BranchesInGit:2996die("No remote p4 branches. Perhaps you never did\"git p4 clone\"in here.")29972998# The default branch is master, unless --branch is used to2999# specify something else. Make sure it exists, or complain3000# nicely about how to use --branch.3001if not self.detectBranches:3002if notbranch_exists(self.branch):3003if branch_arg_given:3004die("Error: branch%sdoes not exist."% self.branch)3005else:3006die("Error: no branch%s; perhaps specify one with --branch."%3007 self.branch)30083009if self.verbose:3010print"Getting p4 changes for%s...%s"% (', '.join(self.depotPaths),3011 self.changeRange)3012 changes =p4ChangesForPaths(self.depotPaths, self.changeRange)30133014iflen(self.maxChanges) >0:3015 changes = changes[:min(int(self.maxChanges),len(changes))]30163017iflen(changes) ==0:3018if not self.silent:3019print"No changes to import!"3020else:3021if not self.silent and not self.detectBranches:3022print"Import destination:%s"% self.branch30233024 self.updatedBranches =set()30253026if not self.detectBranches:3027if args:3028# start a new branch3029 self.initialParent =""3030else:3031# build on a previous revision3032 self.initialParent =parseRevision(self.branch)30333034 self.importChanges(changes)30353036if not self.silent:3037print""3038iflen(self.updatedBranches) >0:3039 sys.stdout.write("Updated branches: ")3040for b in self.updatedBranches:3041 sys.stdout.write("%s"% b)3042 sys.stdout.write("\n")30433044ifgitConfig("git-p4.importLabels","--bool") =="true":3045 self.importLabels =True30463047if self.importLabels:3048 p4Labels =getP4Labels(self.depotPaths)3049 gitTags =getGitTags()30503051 missingP4Labels = p4Labels - gitTags3052 self.importP4Labels(self.gitStream, missingP4Labels)30533054 self.gitStream.close()3055if self.importProcess.wait() !=0:3056die("fast-import failed:%s"% self.gitError.read())3057 self.gitOutput.close()3058 self.gitError.close()30593060# Cleanup temporary branches created during import3061if self.tempBranches != []:3062for branch in self.tempBranches:3063read_pipe("git update-ref -d%s"% branch)3064 os.rmdir(os.path.join(os.environ.get("GIT_DIR",".git"), self.tempBranchLocation))30653066# Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow3067# a convenient shortcut refname "p4".3068if self.importIntoRemotes:3069 head_ref = self.refPrefix +"HEAD"3070if notgitBranchExists(head_ref)andgitBranchExists(self.branch):3071system(["git","symbolic-ref", head_ref, self.branch])30723073return True30743075classP4Rebase(Command):3076def__init__(self):3077 Command.__init__(self)3078 self.options = [3079 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),3080]3081 self.importLabels =False3082 self.description = ("Fetches the latest revision from perforce and "3083+"rebases the current work (branch) against it")30843085defrun(self, args):3086 sync =P4Sync()3087 sync.importLabels = self.importLabels3088 sync.run([])30893090return self.rebase()30913092defrebase(self):3093if os.system("git update-index --refresh") !=0:3094die("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.");3095iflen(read_pipe("git diff-index HEAD --")) >0:3096die("You have uncommited changes. Please commit them before rebasing or stash them away with git stash.");30973098[upstream, settings] =findUpstreamBranchPoint()3099iflen(upstream) ==0:3100die("Cannot find upstream branchpoint for rebase")31013102# the branchpoint may be p4/foo~3, so strip off the parent3103 upstream = re.sub("~[0-9]+$","", upstream)31043105print"Rebasing the current branch onto%s"% upstream3106 oldHead =read_pipe("git rev-parse HEAD").strip()3107system("git rebase%s"% upstream)3108system("git diff-tree --stat --summary -M%sHEAD"% oldHead)3109return True31103111classP4Clone(P4Sync):3112def__init__(self):3113 P4Sync.__init__(self)3114 self.description ="Creates a new git repository and imports from Perforce into it"3115 self.usage ="usage: %prog [options] //depot/path[@revRange]"3116 self.options += [3117 optparse.make_option("--destination", dest="cloneDestination",3118 action='store', default=None,3119help="where to leave result of the clone"),3120 optparse.make_option("-/", dest="cloneExclude",3121 action="append",type="string",3122help="exclude depot path"),3123 optparse.make_option("--bare", dest="cloneBare",3124 action="store_true", default=False),3125]3126 self.cloneDestination =None3127 self.needsGit =False3128 self.cloneBare =False31293130# This is required for the "append" cloneExclude action3131defensure_value(self, attr, value):3132if nothasattr(self, attr)orgetattr(self, attr)is None:3133setattr(self, attr, value)3134returngetattr(self, attr)31353136defdefaultDestination(self, args):3137## TODO: use common prefix of args?3138 depotPath = args[0]3139 depotDir = re.sub("(@[^@]*)$","", depotPath)3140 depotDir = re.sub("(#[^#]*)$","", depotDir)3141 depotDir = re.sub(r"\.\.\.$","", depotDir)3142 depotDir = re.sub(r"/$","", depotDir)3143return os.path.split(depotDir)[1]31443145defrun(self, args):3146iflen(args) <1:3147return False31483149if self.keepRepoPath and not self.cloneDestination:3150 sys.stderr.write("Must specify destination for --keep-path\n")3151 sys.exit(1)31523153 depotPaths = args31543155if not self.cloneDestination andlen(depotPaths) >1:3156 self.cloneDestination = depotPaths[-1]3157 depotPaths = depotPaths[:-1]31583159 self.cloneExclude = ["/"+p for p in self.cloneExclude]3160for p in depotPaths:3161if not p.startswith("//"):3162return False31633164if not self.cloneDestination:3165 self.cloneDestination = self.defaultDestination(args)31663167print"Importing from%sinto%s"% (', '.join(depotPaths), self.cloneDestination)31683169if not os.path.exists(self.cloneDestination):3170 os.makedirs(self.cloneDestination)3171chdir(self.cloneDestination)31723173 init_cmd = ["git","init"]3174if self.cloneBare:3175 init_cmd.append("--bare")3176 subprocess.check_call(init_cmd)31773178if not P4Sync.run(self, depotPaths):3179return False31803181# create a master branch and check out a work tree3182ifgitBranchExists(self.branch):3183system(["git","branch","master", self.branch ])3184if not self.cloneBare:3185system(["git","checkout","-f"])3186else:3187print'Not checking out any branch, use ' \3188'"git checkout -q -b master <branch>"'31893190# auto-set this variable if invoked with --use-client-spec3191if self.useClientSpec_from_options:3192system("git config --bool git-p4.useclientspec true")31933194return True31953196classP4Branches(Command):3197def__init__(self):3198 Command.__init__(self)3199 self.options = [ ]3200 self.description = ("Shows the git branches that hold imports and their "3201+"corresponding perforce depot paths")3202 self.verbose =False32033204defrun(self, args):3205iforiginP4BranchesExist():3206createOrUpdateBranchesFromOrigin()32073208 cmdline ="git rev-parse --symbolic "3209 cmdline +=" --remotes"32103211for line inread_pipe_lines(cmdline):3212 line = line.strip()32133214if not line.startswith('p4/')or line =="p4/HEAD":3215continue3216 branch = line32173218 log =extractLogMessageFromGitCommit("refs/remotes/%s"% branch)3219 settings =extractSettingsGitLog(log)32203221print"%s<=%s(%s)"% (branch,",".join(settings["depot-paths"]), settings["change"])3222return True32233224classHelpFormatter(optparse.IndentedHelpFormatter):3225def__init__(self):3226 optparse.IndentedHelpFormatter.__init__(self)32273228defformat_description(self, description):3229if description:3230return description +"\n"3231else:3232return""32333234defprintUsage(commands):3235print"usage:%s<command> [options]"% sys.argv[0]3236print""3237print"valid commands:%s"%", ".join(commands)3238print""3239print"Try%s<command> --help for command specific help."% sys.argv[0]3240print""32413242commands = {3243"debug": P4Debug,3244"submit": P4Submit,3245"commit": P4Submit,3246"sync": P4Sync,3247"rebase": P4Rebase,3248"clone": P4Clone,3249"rollback": P4RollBack,3250"branches": P4Branches3251}325232533254defmain():3255iflen(sys.argv[1:]) ==0:3256printUsage(commands.keys())3257 sys.exit(2)32583259 cmdName = sys.argv[1]3260try:3261 klass = commands[cmdName]3262 cmd =klass()3263exceptKeyError:3264print"unknown command%s"% cmdName3265print""3266printUsage(commands.keys())3267 sys.exit(2)32683269 options = cmd.options3270 cmd.gitdir = os.environ.get("GIT_DIR",None)32713272 args = sys.argv[2:]32733274 options.append(optparse.make_option("--verbose","-v", dest="verbose", action="store_true"))3275if cmd.needsGit:3276 options.append(optparse.make_option("--git-dir", dest="gitdir"))32773278 parser = optparse.OptionParser(cmd.usage.replace("%prog","%prog "+ cmdName),3279 options,3280 description = cmd.description,3281 formatter =HelpFormatter())32823283(cmd, args) = parser.parse_args(sys.argv[2:], cmd);3284global verbose3285 verbose = cmd.verbose3286if cmd.needsGit:3287if cmd.gitdir ==None:3288 cmd.gitdir = os.path.abspath(".git")3289if notisValidGitDir(cmd.gitdir):3290 cmd.gitdir =read_pipe("git rev-parse --git-dir").strip()3291if os.path.exists(cmd.gitdir):3292 cdup =read_pipe("git rev-parse --show-cdup").strip()3293iflen(cdup) >0:3294chdir(cdup);32953296if notisValidGitDir(cmd.gitdir):3297ifisValidGitDir(cmd.gitdir +"/.git"):3298 cmd.gitdir +="/.git"3299else:3300die("fatal: cannot locate git repository at%s"% cmd.gitdir)33013302 os.environ["GIT_DIR"] = cmd.gitdir33033304if not cmd.run(args):3305 parser.print_help()3306 sys.exit(2)330733083309if __name__ =='__main__':3310main()