1#!/usr/bin/env python 2# 3# git-p4.py -- A tool for bidirectional operation between a Perforce depot and git. 4# 5# Author: Simon Hausmann <simon@lst.de> 6# Copyright: 2007 Simon Hausmann <simon@lst.de> 7# 2007 Trolltech ASA 8# License: MIT <http://www.opensource.org/licenses/mit-license.php> 9# 10import sys 11if sys.hexversion <0x02040000: 12# The limiter is the subprocess module 13 sys.stderr.write("git-p4: requires Python 2.4 or later.\n") 14 sys.exit(1) 15import os 16import optparse 17import marshal 18import subprocess 19import tempfile 20import time 21import platform 22import re 23import shutil 24import stat 25import ctypes 26 27try: 28from subprocess import CalledProcessError 29exceptImportError: 30# from python2.7:subprocess.py 31# Exception classes used by this module. 32classCalledProcessError(Exception): 33"""This exception is raised when a process run by check_call() returns 34 a non-zero exit status. The exit status will be stored in the 35 returncode attribute.""" 36def__init__(self, returncode, cmd): 37 self.returncode = returncode 38 self.cmd = cmd 39def__str__(self): 40return"Command '%s' returned non-zero exit status%d"% (self.cmd, self.returncode) 41 42verbose =False 43 44# Only labels/tags matching this will be imported/exported 45defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$' 46 47# Grab changes in blocks of this many revisions, unless otherwise requested 48defaultBlockSize =512 49 50defp4_build_cmd(cmd): 51"""Build a suitable p4 command line. 52 53 This consolidates building and returning a p4 command line into one 54 location. It means that hooking into the environment, or other configuration 55 can be done more easily. 56 """ 57 real_cmd = ["p4"] 58 59 user =gitConfig("git-p4.user") 60iflen(user) >0: 61 real_cmd += ["-u",user] 62 63 password =gitConfig("git-p4.password") 64iflen(password) >0: 65 real_cmd += ["-P", password] 66 67 port =gitConfig("git-p4.port") 68iflen(port) >0: 69 real_cmd += ["-p", port] 70 71 host =gitConfig("git-p4.host") 72iflen(host) >0: 73 real_cmd += ["-H", host] 74 75 client =gitConfig("git-p4.client") 76iflen(client) >0: 77 real_cmd += ["-c", client] 78 79 80ifisinstance(cmd,basestring): 81 real_cmd =' '.join(real_cmd) +' '+ cmd 82else: 83 real_cmd += cmd 84return real_cmd 85 86defchdir(path, is_client_path=False): 87"""Do chdir to the given path, and set the PWD environment 88 variable for use by P4. It does not look at getcwd() output. 89 Since we're not using the shell, it is necessary to set the 90 PWD environment variable explicitly. 91 92 Normally, expand the path to force it to be absolute. This 93 addresses the use of relative path names inside P4 settings, 94 e.g. P4CONFIG=.p4config. P4 does not simply open the filename 95 as given; it looks for .p4config using PWD. 96 97 If is_client_path, the path was handed to us directly by p4, 98 and may be a symbolic link. Do not call os.getcwd() in this 99 case, because it will cause p4 to think that PWD is not inside 100 the client path. 101 """ 102 103 os.chdir(path) 104if not is_client_path: 105 path = os.getcwd() 106 os.environ['PWD'] = path 107 108defcalcDiskFree(): 109"""Return free space in bytes on the disk of the given dirname.""" 110if platform.system() =='Windows': 111 free_bytes = ctypes.c_ulonglong(0) 112 ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(os.getcwd()),None,None, ctypes.pointer(free_bytes)) 113return free_bytes.value 114else: 115 st = os.statvfs(os.getcwd()) 116return st.f_bavail * st.f_frsize 117 118defdie(msg): 119if verbose: 120raiseException(msg) 121else: 122 sys.stderr.write(msg +"\n") 123 sys.exit(1) 124 125defwrite_pipe(c, stdin): 126if verbose: 127 sys.stderr.write('Writing pipe:%s\n'%str(c)) 128 129 expand =isinstance(c,basestring) 130 p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand) 131 pipe = p.stdin 132 val = pipe.write(stdin) 133 pipe.close() 134if p.wait(): 135die('Command failed:%s'%str(c)) 136 137return val 138 139defp4_write_pipe(c, stdin): 140 real_cmd =p4_build_cmd(c) 141returnwrite_pipe(real_cmd, stdin) 142 143defread_pipe(c, ignore_error=False): 144if verbose: 145 sys.stderr.write('Reading pipe:%s\n'%str(c)) 146 147 expand =isinstance(c,basestring) 148 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand) 149 pipe = p.stdout 150 val = pipe.read() 151if p.wait()and not ignore_error: 152die('Command failed:%s'%str(c)) 153 154return val 155 156defp4_read_pipe(c, ignore_error=False): 157 real_cmd =p4_build_cmd(c) 158returnread_pipe(real_cmd, ignore_error) 159 160defread_pipe_lines(c): 161if verbose: 162 sys.stderr.write('Reading pipe:%s\n'%str(c)) 163 164 expand =isinstance(c, basestring) 165 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand) 166 pipe = p.stdout 167 val = pipe.readlines() 168if pipe.close()or p.wait(): 169die('Command failed:%s'%str(c)) 170 171return val 172 173defp4_read_pipe_lines(c): 174"""Specifically invoke p4 on the command supplied. """ 175 real_cmd =p4_build_cmd(c) 176returnread_pipe_lines(real_cmd) 177 178defp4_has_command(cmd): 179"""Ask p4 for help on this command. If it returns an error, the 180 command does not exist in this version of p4.""" 181 real_cmd =p4_build_cmd(["help", cmd]) 182 p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE, 183 stderr=subprocess.PIPE) 184 p.communicate() 185return p.returncode ==0 186 187defp4_has_move_command(): 188"""See if the move command exists, that it supports -k, and that 189 it has not been administratively disabled. The arguments 190 must be correct, but the filenames do not have to exist. Use 191 ones with wildcards so even if they exist, it will fail.""" 192 193if notp4_has_command("move"): 194return False 195 cmd =p4_build_cmd(["move","-k","@from","@to"]) 196 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 197(out, err) = p.communicate() 198# return code will be 1 in either case 199if err.find("Invalid option") >=0: 200return False 201if err.find("disabled") >=0: 202return False 203# assume it failed because @... was invalid changelist 204return True 205 206defsystem(cmd): 207 expand =isinstance(cmd,basestring) 208if verbose: 209 sys.stderr.write("executing%s\n"%str(cmd)) 210 retcode = subprocess.call(cmd, shell=expand) 211if retcode: 212raiseCalledProcessError(retcode, cmd) 213 214defp4_system(cmd): 215"""Specifically invoke p4 as the system command. """ 216 real_cmd =p4_build_cmd(cmd) 217 expand =isinstance(real_cmd, basestring) 218 retcode = subprocess.call(real_cmd, shell=expand) 219if retcode: 220raiseCalledProcessError(retcode, real_cmd) 221 222_p4_version_string =None 223defp4_version_string(): 224"""Read the version string, showing just the last line, which 225 hopefully is the interesting version bit. 226 227 $ p4 -V 228 Perforce - The Fast Software Configuration Management System. 229 Copyright 1995-2011 Perforce Software. All rights reserved. 230 Rev. P4/NTX86/2011.1/393975 (2011/12/16). 231 """ 232global _p4_version_string 233if not _p4_version_string: 234 a =p4_read_pipe_lines(["-V"]) 235 _p4_version_string = a[-1].rstrip() 236return _p4_version_string 237 238defp4_integrate(src, dest): 239p4_system(["integrate","-Dt",wildcard_encode(src),wildcard_encode(dest)]) 240 241defp4_sync(f, *options): 242p4_system(["sync"] +list(options) + [wildcard_encode(f)]) 243 244defp4_add(f): 245# forcibly add file names with wildcards 246ifwildcard_present(f): 247p4_system(["add","-f", f]) 248else: 249p4_system(["add", f]) 250 251defp4_delete(f): 252p4_system(["delete",wildcard_encode(f)]) 253 254defp4_edit(f): 255p4_system(["edit",wildcard_encode(f)]) 256 257defp4_revert(f): 258p4_system(["revert",wildcard_encode(f)]) 259 260defp4_reopen(type, f): 261p4_system(["reopen","-t",type,wildcard_encode(f)]) 262 263defp4_move(src, dest): 264p4_system(["move","-k",wildcard_encode(src),wildcard_encode(dest)]) 265 266defp4_last_change(): 267 results =p4CmdList(["changes","-m","1"]) 268returnint(results[0]['change']) 269 270defp4_describe(change): 271"""Make sure it returns a valid result by checking for 272 the presence of field "time". Return a dict of the 273 results.""" 274 275 ds =p4CmdList(["describe","-s",str(change)]) 276iflen(ds) !=1: 277die("p4 describe -s%ddid not return 1 result:%s"% (change,str(ds))) 278 279 d = ds[0] 280 281if"p4ExitCode"in d: 282die("p4 describe -s%dexited with%d:%s"% (change, d["p4ExitCode"], 283str(d))) 284if"code"in d: 285if d["code"] =="error": 286die("p4 describe -s%dreturned error code:%s"% (change,str(d))) 287 288if"time"not in d: 289die("p4 describe -s%dreturned no\"time\":%s"% (change,str(d))) 290 291return d 292 293# 294# Canonicalize the p4 type and return a tuple of the 295# base type, plus any modifiers. See "p4 help filetypes" 296# for a list and explanation. 297# 298defsplit_p4_type(p4type): 299 300 p4_filetypes_historical = { 301"ctempobj":"binary+Sw", 302"ctext":"text+C", 303"cxtext":"text+Cx", 304"ktext":"text+k", 305"kxtext":"text+kx", 306"ltext":"text+F", 307"tempobj":"binary+FSw", 308"ubinary":"binary+F", 309"uresource":"resource+F", 310"uxbinary":"binary+Fx", 311"xbinary":"binary+x", 312"xltext":"text+Fx", 313"xtempobj":"binary+Swx", 314"xtext":"text+x", 315"xunicode":"unicode+x", 316"xutf16":"utf16+x", 317} 318if p4type in p4_filetypes_historical: 319 p4type = p4_filetypes_historical[p4type] 320 mods ="" 321 s = p4type.split("+") 322 base = s[0] 323 mods ="" 324iflen(s) >1: 325 mods = s[1] 326return(base, mods) 327 328# 329# return the raw p4 type of a file (text, text+ko, etc) 330# 331defp4_type(f): 332 results =p4CmdList(["fstat","-T","headType",wildcard_encode(f)]) 333return results[0]['headType'] 334 335# 336# Given a type base and modifier, return a regexp matching 337# the keywords that can be expanded in the file 338# 339defp4_keywords_regexp_for_type(base, type_mods): 340if base in("text","unicode","binary"): 341 kwords =None 342if"ko"in type_mods: 343 kwords ='Id|Header' 344elif"k"in type_mods: 345 kwords ='Id|Header|Author|Date|DateTime|Change|File|Revision' 346else: 347return None 348 pattern = r""" 349 \$ # Starts with a dollar, followed by... 350 (%s) # one of the keywords, followed by... 351 (:[^$\n]+)? # possibly an old expansion, followed by... 352 \$ # another dollar 353 """% kwords 354return pattern 355else: 356return None 357 358# 359# Given a file, return a regexp matching the possible 360# RCS keywords that will be expanded, or None for files 361# with kw expansion turned off. 362# 363defp4_keywords_regexp_for_file(file): 364if not os.path.exists(file): 365return None 366else: 367(type_base, type_mods) =split_p4_type(p4_type(file)) 368returnp4_keywords_regexp_for_type(type_base, type_mods) 369 370defsetP4ExecBit(file, mode): 371# Reopens an already open file and changes the execute bit to match 372# the execute bit setting in the passed in mode. 373 374 p4Type ="+x" 375 376if notisModeExec(mode): 377 p4Type =getP4OpenedType(file) 378 p4Type = re.sub('^([cku]?)x(.*)','\\1\\2', p4Type) 379 p4Type = re.sub('(.*?\+.*?)x(.*?)','\\1\\2', p4Type) 380if p4Type[-1] =="+": 381 p4Type = p4Type[0:-1] 382 383p4_reopen(p4Type,file) 384 385defgetP4OpenedType(file): 386# Returns the perforce file type for the given file. 387 388 result =p4_read_pipe(["opened",wildcard_encode(file)]) 389 match = re.match(".*\((.+)\)( \*exclusive\*)?\r?$", result) 390if match: 391return match.group(1) 392else: 393die("Could not determine file type for%s(result: '%s')"% (file, result)) 394 395# Return the set of all p4 labels 396defgetP4Labels(depotPaths): 397 labels =set() 398ifisinstance(depotPaths,basestring): 399 depotPaths = [depotPaths] 400 401for l inp4CmdList(["labels"] + ["%s..."% p for p in depotPaths]): 402 label = l['label'] 403 labels.add(label) 404 405return labels 406 407# Return the set of all git tags 408defgetGitTags(): 409 gitTags =set() 410for line inread_pipe_lines(["git","tag"]): 411 tag = line.strip() 412 gitTags.add(tag) 413return gitTags 414 415defdiffTreePattern(): 416# This is a simple generator for the diff tree regex pattern. This could be 417# a class variable if this and parseDiffTreeEntry were a part of a class. 418 pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)') 419while True: 420yield pattern 421 422defparseDiffTreeEntry(entry): 423"""Parses a single diff tree entry into its component elements. 424 425 See git-diff-tree(1) manpage for details about the format of the diff 426 output. This method returns a dictionary with the following elements: 427 428 src_mode - The mode of the source file 429 dst_mode - The mode of the destination file 430 src_sha1 - The sha1 for the source file 431 dst_sha1 - The sha1 fr the destination file 432 status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc) 433 status_score - The score for the status (applicable for 'C' and 'R' 434 statuses). This is None if there is no score. 435 src - The path for the source file. 436 dst - The path for the destination file. This is only present for 437 copy or renames. If it is not present, this is None. 438 439 If the pattern is not matched, None is returned.""" 440 441 match =diffTreePattern().next().match(entry) 442if match: 443return{ 444'src_mode': match.group(1), 445'dst_mode': match.group(2), 446'src_sha1': match.group(3), 447'dst_sha1': match.group(4), 448'status': match.group(5), 449'status_score': match.group(6), 450'src': match.group(7), 451'dst': match.group(10) 452} 453return None 454 455defisModeExec(mode): 456# Returns True if the given git mode represents an executable file, 457# otherwise False. 458return mode[-3:] =="755" 459 460defisModeExecChanged(src_mode, dst_mode): 461returnisModeExec(src_mode) !=isModeExec(dst_mode) 462 463defp4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None): 464 465ifisinstance(cmd,basestring): 466 cmd ="-G "+ cmd 467 expand =True 468else: 469 cmd = ["-G"] + cmd 470 expand =False 471 472 cmd =p4_build_cmd(cmd) 473if verbose: 474 sys.stderr.write("Opening pipe:%s\n"%str(cmd)) 475 476# Use a temporary file to avoid deadlocks without 477# subprocess.communicate(), which would put another copy 478# of stdout into memory. 479 stdin_file =None 480if stdin is not None: 481 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode) 482ifisinstance(stdin,basestring): 483 stdin_file.write(stdin) 484else: 485for i in stdin: 486 stdin_file.write(i +'\n') 487 stdin_file.flush() 488 stdin_file.seek(0) 489 490 p4 = subprocess.Popen(cmd, 491 shell=expand, 492 stdin=stdin_file, 493 stdout=subprocess.PIPE) 494 495 result = [] 496try: 497while True: 498 entry = marshal.load(p4.stdout) 499if cb is not None: 500cb(entry) 501else: 502 result.append(entry) 503exceptEOFError: 504pass 505 exitCode = p4.wait() 506if exitCode !=0: 507 entry = {} 508 entry["p4ExitCode"] = exitCode 509 result.append(entry) 510 511return result 512 513defp4Cmd(cmd): 514list=p4CmdList(cmd) 515 result = {} 516for entry inlist: 517 result.update(entry) 518return result; 519 520defp4Where(depotPath): 521if not depotPath.endswith("/"): 522 depotPath +="/" 523 depotPathLong = depotPath +"..." 524 outputList =p4CmdList(["where", depotPathLong]) 525 output =None 526for entry in outputList: 527if"depotFile"in entry: 528# Search for the base client side depot path, as long as it starts with the branch's P4 path. 529# The base path always ends with "/...". 530if entry["depotFile"].find(depotPath) ==0and entry["depotFile"][-4:] =="/...": 531 output = entry 532break 533elif"data"in entry: 534 data = entry.get("data") 535 space = data.find(" ") 536if data[:space] == depotPath: 537 output = entry 538break 539if output ==None: 540return"" 541if output["code"] =="error": 542return"" 543 clientPath ="" 544if"path"in output: 545 clientPath = output.get("path") 546elif"data"in output: 547 data = output.get("data") 548 lastSpace = data.rfind(" ") 549 clientPath = data[lastSpace +1:] 550 551if clientPath.endswith("..."): 552 clientPath = clientPath[:-3] 553return clientPath 554 555defcurrentGitBranch(): 556returnread_pipe("git name-rev HEAD").split(" ")[1].strip() 557 558defisValidGitDir(path): 559if(os.path.exists(path +"/HEAD") 560and os.path.exists(path +"/refs")and os.path.exists(path +"/objects")): 561return True; 562return False 563 564defparseRevision(ref): 565returnread_pipe("git rev-parse%s"% ref).strip() 566 567defbranchExists(ref): 568 rev =read_pipe(["git","rev-parse","-q","--verify", ref], 569 ignore_error=True) 570returnlen(rev) >0 571 572defextractLogMessageFromGitCommit(commit): 573 logMessage ="" 574 575## fixme: title is first line of commit, not 1st paragraph. 576 foundTitle =False 577for log inread_pipe_lines("git cat-file commit%s"% commit): 578if not foundTitle: 579iflen(log) ==1: 580 foundTitle =True 581continue 582 583 logMessage += log 584return logMessage 585 586defextractSettingsGitLog(log): 587 values = {} 588for line in log.split("\n"): 589 line = line.strip() 590 m = re.search(r"^ *\[git-p4: (.*)\]$", line) 591if not m: 592continue 593 594 assignments = m.group(1).split(':') 595for a in assignments: 596 vals = a.split('=') 597 key = vals[0].strip() 598 val = ('='.join(vals[1:])).strip() 599if val.endswith('\"')and val.startswith('"'): 600 val = val[1:-1] 601 602 values[key] = val 603 604 paths = values.get("depot-paths") 605if not paths: 606 paths = values.get("depot-path") 607if paths: 608 values['depot-paths'] = paths.split(',') 609return values 610 611defgitBranchExists(branch): 612 proc = subprocess.Popen(["git","rev-parse", branch], 613 stderr=subprocess.PIPE, stdout=subprocess.PIPE); 614return proc.wait() ==0; 615 616_gitConfig = {} 617 618defgitConfig(key, typeSpecifier=None): 619if not _gitConfig.has_key(key): 620 cmd = ["git","config"] 621if typeSpecifier: 622 cmd += [ typeSpecifier ] 623 cmd += [ key ] 624 s =read_pipe(cmd, ignore_error=True) 625 _gitConfig[key] = s.strip() 626return _gitConfig[key] 627 628defgitConfigBool(key): 629"""Return a bool, using git config --bool. It is True only if the 630 variable is set to true, and False if set to false or not present 631 in the config.""" 632 633if not _gitConfig.has_key(key): 634 _gitConfig[key] =gitConfig(key,'--bool') =="true" 635return _gitConfig[key] 636 637defgitConfigInt(key): 638if not _gitConfig.has_key(key): 639 cmd = ["git","config","--int", key ] 640 s =read_pipe(cmd, ignore_error=True) 641 v = s.strip() 642try: 643 _gitConfig[key] =int(gitConfig(key,'--int')) 644exceptValueError: 645 _gitConfig[key] =None 646return _gitConfig[key] 647 648defgitConfigList(key): 649if not _gitConfig.has_key(key): 650 s =read_pipe(["git","config","--get-all", key], ignore_error=True) 651 _gitConfig[key] = s.strip().split(os.linesep) 652if _gitConfig[key] == ['']: 653 _gitConfig[key] = [] 654return _gitConfig[key] 655 656defp4BranchesInGit(branchesAreInRemotes=True): 657"""Find all the branches whose names start with "p4/", looking 658 in remotes or heads as specified by the argument. Return 659 a dictionary of{ branch: revision }for each one found. 660 The branch names are the short names, without any 661 "p4/" prefix.""" 662 663 branches = {} 664 665 cmdline ="git rev-parse --symbolic " 666if branchesAreInRemotes: 667 cmdline +="--remotes" 668else: 669 cmdline +="--branches" 670 671for line inread_pipe_lines(cmdline): 672 line = line.strip() 673 674# only import to p4/ 675if not line.startswith('p4/'): 676continue 677# special symbolic ref to p4/master 678if line =="p4/HEAD": 679continue 680 681# strip off p4/ prefix 682 branch = line[len("p4/"):] 683 684 branches[branch] =parseRevision(line) 685 686return branches 687 688defbranch_exists(branch): 689"""Make sure that the given ref name really exists.""" 690 691 cmd = ["git","rev-parse","--symbolic","--verify", branch ] 692 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 693 out, _ = p.communicate() 694if p.returncode: 695return False 696# expect exactly one line of output: the branch name 697return out.rstrip() == branch 698 699deffindUpstreamBranchPoint(head ="HEAD"): 700 branches =p4BranchesInGit() 701# map from depot-path to branch name 702 branchByDepotPath = {} 703for branch in branches.keys(): 704 tip = branches[branch] 705 log =extractLogMessageFromGitCommit(tip) 706 settings =extractSettingsGitLog(log) 707if settings.has_key("depot-paths"): 708 paths =",".join(settings["depot-paths"]) 709 branchByDepotPath[paths] ="remotes/p4/"+ branch 710 711 settings =None 712 parent =0 713while parent <65535: 714 commit = head +"~%s"% parent 715 log =extractLogMessageFromGitCommit(commit) 716 settings =extractSettingsGitLog(log) 717if settings.has_key("depot-paths"): 718 paths =",".join(settings["depot-paths"]) 719if branchByDepotPath.has_key(paths): 720return[branchByDepotPath[paths], settings] 721 722 parent = parent +1 723 724return["", settings] 725 726defcreateOrUpdateBranchesFromOrigin(localRefPrefix ="refs/remotes/p4/", silent=True): 727if not silent: 728print("Creating/updating branch(es) in%sbased on origin branch(es)" 729% localRefPrefix) 730 731 originPrefix ="origin/p4/" 732 733for line inread_pipe_lines("git rev-parse --symbolic --remotes"): 734 line = line.strip() 735if(not line.startswith(originPrefix))or line.endswith("HEAD"): 736continue 737 738 headName = line[len(originPrefix):] 739 remoteHead = localRefPrefix + headName 740 originHead = line 741 742 original =extractSettingsGitLog(extractLogMessageFromGitCommit(originHead)) 743if(not original.has_key('depot-paths') 744or not original.has_key('change')): 745continue 746 747 update =False 748if notgitBranchExists(remoteHead): 749if verbose: 750print"creating%s"% remoteHead 751 update =True 752else: 753 settings =extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead)) 754if settings.has_key('change') >0: 755if settings['depot-paths'] == original['depot-paths']: 756 originP4Change =int(original['change']) 757 p4Change =int(settings['change']) 758if originP4Change > p4Change: 759print("%s(%s) is newer than%s(%s). " 760"Updating p4 branch from origin." 761% (originHead, originP4Change, 762 remoteHead, p4Change)) 763 update =True 764else: 765print("Ignoring:%swas imported from%swhile " 766"%swas imported from%s" 767% (originHead,','.join(original['depot-paths']), 768 remoteHead,','.join(settings['depot-paths']))) 769 770if update: 771system("git update-ref%s %s"% (remoteHead, originHead)) 772 773deforiginP4BranchesExist(): 774returngitBranchExists("origin")orgitBranchExists("origin/p4")orgitBranchExists("origin/p4/master") 775 776 777defp4ParseNumericChangeRange(parts): 778 changeStart =int(parts[0][1:]) 779if parts[1] =='#head': 780 changeEnd =p4_last_change() 781else: 782 changeEnd =int(parts[1]) 783 784return(changeStart, changeEnd) 785 786defchooseBlockSize(blockSize): 787if blockSize: 788return blockSize 789else: 790return defaultBlockSize 791 792defp4ChangesForPaths(depotPaths, changeRange, requestedBlockSize): 793assert depotPaths 794 795# Parse the change range into start and end. Try to find integer 796# revision ranges as these can be broken up into blocks to avoid 797# hitting server-side limits (maxrows, maxscanresults). But if 798# that doesn't work, fall back to using the raw revision specifier 799# strings, without using block mode. 800 801if changeRange is None or changeRange =='': 802 changeStart =1 803 changeEnd =p4_last_change() 804 block_size =chooseBlockSize(requestedBlockSize) 805else: 806 parts = changeRange.split(',') 807assertlen(parts) ==2 808try: 809(changeStart, changeEnd) =p4ParseNumericChangeRange(parts) 810 block_size =chooseBlockSize(requestedBlockSize) 811except: 812 changeStart = parts[0][1:] 813 changeEnd = parts[1] 814if requestedBlockSize: 815die("cannot use --changes-block-size with non-numeric revisions") 816 block_size =None 817 818# Accumulate change numbers in a dictionary to avoid duplicates 819 changes = {} 820 821for p in depotPaths: 822# Retrieve changes a block at a time, to prevent running 823# into a MaxResults/MaxScanRows error from the server. 824 825while True: 826 cmd = ['changes'] 827 828if block_size: 829 end =min(changeEnd, changeStart + block_size) 830 revisionRange ="%d,%d"% (changeStart, end) 831else: 832 revisionRange ="%s,%s"% (changeStart, changeEnd) 833 834 cmd += ["%s...@%s"% (p, revisionRange)] 835 836for line inp4_read_pipe_lines(cmd): 837 changeNum =int(line.split(" ")[1]) 838 changes[changeNum] =True 839 840if not block_size: 841break 842 843if end >= changeEnd: 844break 845 846 changeStart = end +1 847 848 changelist = changes.keys() 849 changelist.sort() 850return changelist 851 852defp4PathStartsWith(path, prefix): 853# This method tries to remedy a potential mixed-case issue: 854# 855# If UserA adds //depot/DirA/file1 856# and UserB adds //depot/dira/file2 857# 858# we may or may not have a problem. If you have core.ignorecase=true, 859# we treat DirA and dira as the same directory 860ifgitConfigBool("core.ignorecase"): 861return path.lower().startswith(prefix.lower()) 862return path.startswith(prefix) 863 864defgetClientSpec(): 865"""Look at the p4 client spec, create a View() object that contains 866 all the mappings, and return it.""" 867 868 specList =p4CmdList("client -o") 869iflen(specList) !=1: 870die('Output from "client -o" is%dlines, expecting 1'% 871len(specList)) 872 873# dictionary of all client parameters 874 entry = specList[0] 875 876# the //client/ name 877 client_name = entry["Client"] 878 879# just the keys that start with "View" 880 view_keys = [ k for k in entry.keys()if k.startswith("View") ] 881 882# hold this new View 883 view =View(client_name) 884 885# append the lines, in order, to the view 886for view_num inrange(len(view_keys)): 887 k ="View%d"% view_num 888if k not in view_keys: 889die("Expected view key%smissing"% k) 890 view.append(entry[k]) 891 892return view 893 894defgetClientRoot(): 895"""Grab the client directory.""" 896 897 output =p4CmdList("client -o") 898iflen(output) !=1: 899die('Output from "client -o" is%dlines, expecting 1'%len(output)) 900 901 entry = output[0] 902if"Root"not in entry: 903die('Client has no "Root"') 904 905return entry["Root"] 906 907# 908# P4 wildcards are not allowed in filenames. P4 complains 909# if you simply add them, but you can force it with "-f", in 910# which case it translates them into %xx encoding internally. 911# 912defwildcard_decode(path): 913# Search for and fix just these four characters. Do % last so 914# that fixing it does not inadvertently create new %-escapes. 915# Cannot have * in a filename in windows; untested as to 916# what p4 would do in such a case. 917if not platform.system() =="Windows": 918 path = path.replace("%2A","*") 919 path = path.replace("%23","#") \ 920.replace("%40","@") \ 921.replace("%25","%") 922return path 923 924defwildcard_encode(path): 925# do % first to avoid double-encoding the %s introduced here 926 path = path.replace("%","%25") \ 927.replace("*","%2A") \ 928.replace("#","%23") \ 929.replace("@","%40") 930return path 931 932defwildcard_present(path): 933 m = re.search("[*#@%]", path) 934return m is not None 935 936class Command: 937def__init__(self): 938 self.usage ="usage: %prog [options]" 939 self.needsGit =True 940 self.verbose =False 941 942class P4UserMap: 943def__init__(self): 944 self.userMapFromPerforceServer =False 945 self.myP4UserId =None 946 947defp4UserId(self): 948if self.myP4UserId: 949return self.myP4UserId 950 951 results =p4CmdList("user -o") 952for r in results: 953if r.has_key('User'): 954 self.myP4UserId = r['User'] 955return r['User'] 956die("Could not find your p4 user id") 957 958defp4UserIsMe(self, p4User): 959# return True if the given p4 user is actually me 960 me = self.p4UserId() 961if not p4User or p4User != me: 962return False 963else: 964return True 965 966defgetUserCacheFilename(self): 967 home = os.environ.get("HOME", os.environ.get("USERPROFILE")) 968return home +"/.gitp4-usercache.txt" 969 970defgetUserMapFromPerforceServer(self): 971if self.userMapFromPerforceServer: 972return 973 self.users = {} 974 self.emails = {} 975 976for output inp4CmdList("users"): 977if not output.has_key("User"): 978continue 979 self.users[output["User"]] = output["FullName"] +" <"+ output["Email"] +">" 980 self.emails[output["Email"]] = output["User"] 981 982 983 s ='' 984for(key, val)in self.users.items(): 985 s +="%s\t%s\n"% (key.expandtabs(1), val.expandtabs(1)) 986 987open(self.getUserCacheFilename(),"wb").write(s) 988 self.userMapFromPerforceServer =True 989 990defloadUserMapFromCache(self): 991 self.users = {} 992 self.userMapFromPerforceServer =False 993try: 994 cache =open(self.getUserCacheFilename(),"rb") 995 lines = cache.readlines() 996 cache.close() 997for line in lines: 998 entry = line.strip().split("\t") 999 self.users[entry[0]] = entry[1]1000exceptIOError:1001 self.getUserMapFromPerforceServer()10021003classP4Debug(Command):1004def__init__(self):1005 Command.__init__(self)1006 self.options = []1007 self.description ="A tool to debug the output of p4 -G."1008 self.needsGit =False10091010defrun(self, args):1011 j =01012for output inp4CmdList(args):1013print'Element:%d'% j1014 j +=11015print output1016return True10171018classP4RollBack(Command):1019def__init__(self):1020 Command.__init__(self)1021 self.options = [1022 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")1023]1024 self.description ="A tool to debug the multi-branch import. Don't use :)"1025 self.rollbackLocalBranches =False10261027defrun(self, args):1028iflen(args) !=1:1029return False1030 maxChange =int(args[0])10311032if"p4ExitCode"inp4Cmd("changes -m 1"):1033die("Problems executing p4");10341035if self.rollbackLocalBranches:1036 refPrefix ="refs/heads/"1037 lines =read_pipe_lines("git rev-parse --symbolic --branches")1038else:1039 refPrefix ="refs/remotes/"1040 lines =read_pipe_lines("git rev-parse --symbolic --remotes")10411042for line in lines:1043if self.rollbackLocalBranches or(line.startswith("p4/")and line !="p4/HEAD\n"):1044 line = line.strip()1045 ref = refPrefix + line1046 log =extractLogMessageFromGitCommit(ref)1047 settings =extractSettingsGitLog(log)10481049 depotPaths = settings['depot-paths']1050 change = settings['change']10511052 changed =False10531054iflen(p4Cmd("changes -m 1 "+' '.join(['%s...@%s'% (p, maxChange)1055for p in depotPaths]))) ==0:1056print"Branch%sdid not exist at change%s, deleting."% (ref, maxChange)1057system("git update-ref -d%s`git rev-parse%s`"% (ref, ref))1058continue10591060while change andint(change) > maxChange:1061 changed =True1062if self.verbose:1063print"%sis at%s; rewinding towards%s"% (ref, change, maxChange)1064system("git update-ref%s\"%s^\""% (ref, ref))1065 log =extractLogMessageFromGitCommit(ref)1066 settings =extractSettingsGitLog(log)106710681069 depotPaths = settings['depot-paths']1070 change = settings['change']10711072if changed:1073print"%srewound to%s"% (ref, change)10741075return True10761077classP4Submit(Command, P4UserMap):10781079 conflict_behavior_choices = ("ask","skip","quit")10801081def__init__(self):1082 Command.__init__(self)1083 P4UserMap.__init__(self)1084 self.options = [1085 optparse.make_option("--origin", dest="origin"),1086 optparse.make_option("-M", dest="detectRenames", action="store_true"),1087# preserve the user, requires relevant p4 permissions1088 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),1089 optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),1090 optparse.make_option("--dry-run","-n", dest="dry_run", action="store_true"),1091 optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),1092 optparse.make_option("--conflict", dest="conflict_behavior",1093 choices=self.conflict_behavior_choices),1094 optparse.make_option("--branch", dest="branch"),1095]1096 self.description ="Submit changes from git to the perforce depot."1097 self.usage +=" [name of git branch to submit into perforce depot]"1098 self.origin =""1099 self.detectRenames =False1100 self.preserveUser =gitConfigBool("git-p4.preserveUser")1101 self.dry_run =False1102 self.prepare_p4_only =False1103 self.conflict_behavior =None1104 self.isWindows = (platform.system() =="Windows")1105 self.exportLabels =False1106 self.p4HasMoveCommand =p4_has_move_command()1107 self.branch =None11081109defcheck(self):1110iflen(p4CmdList("opened ...")) >0:1111die("You have files opened with perforce! Close them before starting the sync.")11121113defseparate_jobs_from_description(self, message):1114"""Extract and return a possible Jobs field in the commit1115 message. It goes into a separate section in the p4 change1116 specification.11171118 A jobs line starts with "Jobs:" and looks like a new field1119 in a form. Values are white-space separated on the same1120 line or on following lines that start with a tab.11211122 This does not parse and extract the full git commit message1123 like a p4 form. It just sees the Jobs: line as a marker1124 to pass everything from then on directly into the p4 form,1125 but outside the description section.11261127 Return a tuple (stripped log message, jobs string)."""11281129 m = re.search(r'^Jobs:', message, re.MULTILINE)1130if m is None:1131return(message,None)11321133 jobtext = message[m.start():]1134 stripped_message = message[:m.start()].rstrip()1135return(stripped_message, jobtext)11361137defprepareLogMessage(self, template, message, jobs):1138"""Edits the template returned from "p4 change -o" to insert1139 the message in the Description field, and the jobs text in1140 the Jobs field."""1141 result =""11421143 inDescriptionSection =False11441145for line in template.split("\n"):1146if line.startswith("#"):1147 result += line +"\n"1148continue11491150if inDescriptionSection:1151if line.startswith("Files:")or line.startswith("Jobs:"):1152 inDescriptionSection =False1153# insert Jobs section1154if jobs:1155 result += jobs +"\n"1156else:1157continue1158else:1159if line.startswith("Description:"):1160 inDescriptionSection =True1161 line +="\n"1162for messageLine in message.split("\n"):1163 line +="\t"+ messageLine +"\n"11641165 result += line +"\n"11661167return result11681169defpatchRCSKeywords(self,file, pattern):1170# Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern1171(handle, outFileName) = tempfile.mkstemp(dir='.')1172try:1173 outFile = os.fdopen(handle,"w+")1174 inFile =open(file,"r")1175 regexp = re.compile(pattern, re.VERBOSE)1176for line in inFile.readlines():1177 line = regexp.sub(r'$\1$', line)1178 outFile.write(line)1179 inFile.close()1180 outFile.close()1181# Forcibly overwrite the original file1182 os.unlink(file)1183 shutil.move(outFileName,file)1184except:1185# cleanup our temporary file1186 os.unlink(outFileName)1187print"Failed to strip RCS keywords in%s"%file1188raise11891190print"Patched up RCS keywords in%s"%file11911192defp4UserForCommit(self,id):1193# Return the tuple (perforce user,git email) for a given git commit id1194 self.getUserMapFromPerforceServer()1195 gitEmail =read_pipe(["git","log","--max-count=1",1196"--format=%ae",id])1197 gitEmail = gitEmail.strip()1198if not self.emails.has_key(gitEmail):1199return(None,gitEmail)1200else:1201return(self.emails[gitEmail],gitEmail)12021203defcheckValidP4Users(self,commits):1204# check if any git authors cannot be mapped to p4 users1205foridin commits:1206(user,email) = self.p4UserForCommit(id)1207if not user:1208 msg ="Cannot find p4 user for email%sin commit%s."% (email,id)1209ifgitConfigBool("git-p4.allowMissingP4Users"):1210print"%s"% msg1211else:1212die("Error:%s\nSet git-p4.allowMissingP4Users to true to allow this."% msg)12131214deflastP4Changelist(self):1215# Get back the last changelist number submitted in this client spec. This1216# then gets used to patch up the username in the change. If the same1217# client spec is being used by multiple processes then this might go1218# wrong.1219 results =p4CmdList("client -o")# find the current client1220 client =None1221for r in results:1222if r.has_key('Client'):1223 client = r['Client']1224break1225if not client:1226die("could not get client spec")1227 results =p4CmdList(["changes","-c", client,"-m","1"])1228for r in results:1229if r.has_key('change'):1230return r['change']1231die("Could not get changelist number for last submit - cannot patch up user details")12321233defmodifyChangelistUser(self, changelist, newUser):1234# fixup the user field of a changelist after it has been submitted.1235 changes =p4CmdList("change -o%s"% changelist)1236iflen(changes) !=1:1237die("Bad output from p4 change modifying%sto user%s"%1238(changelist, newUser))12391240 c = changes[0]1241if c['User'] == newUser:return# nothing to do1242 c['User'] = newUser1243input= marshal.dumps(c)12441245 result =p4CmdList("change -f -i", stdin=input)1246for r in result:1247if r.has_key('code'):1248if r['code'] =='error':1249die("Could not modify user field of changelist%sto%s:%s"% (changelist, newUser, r['data']))1250if r.has_key('data'):1251print("Updated user field for changelist%sto%s"% (changelist, newUser))1252return1253die("Could not modify user field of changelist%sto%s"% (changelist, newUser))12541255defcanChangeChangelists(self):1256# check to see if we have p4 admin or super-user permissions, either of1257# which are required to modify changelists.1258 results =p4CmdList(["protects", self.depotPath])1259for r in results:1260if r.has_key('perm'):1261if r['perm'] =='admin':1262return11263if r['perm'] =='super':1264return11265return012661267defprepareSubmitTemplate(self):1268"""Run "p4 change -o" to grab a change specification template.1269 This does not use "p4 -G", as it is nice to keep the submission1270 template in original order, since a human might edit it.12711272 Remove lines in the Files section that show changes to files1273 outside the depot path we're committing into."""12741275 template =""1276 inFilesSection =False1277for line inp4_read_pipe_lines(['change','-o']):1278if line.endswith("\r\n"):1279 line = line[:-2] +"\n"1280if inFilesSection:1281if line.startswith("\t"):1282# path starts and ends with a tab1283 path = line[1:]1284 lastTab = path.rfind("\t")1285if lastTab != -1:1286 path = path[:lastTab]1287if notp4PathStartsWith(path, self.depotPath):1288continue1289else:1290 inFilesSection =False1291else:1292if line.startswith("Files:"):1293 inFilesSection =True12941295 template += line12961297return template12981299defedit_template(self, template_file):1300"""Invoke the editor to let the user change the submission1301 message. Return true if okay to continue with the submit."""13021303# if configured to skip the editing part, just submit1304ifgitConfigBool("git-p4.skipSubmitEdit"):1305return True13061307# look at the modification time, to check later if the user saved1308# the file1309 mtime = os.stat(template_file).st_mtime13101311# invoke the editor1312if os.environ.has_key("P4EDITOR")and(os.environ.get("P4EDITOR") !=""):1313 editor = os.environ.get("P4EDITOR")1314else:1315 editor =read_pipe("git var GIT_EDITOR").strip()1316system(["sh","-c", ('%s"$@"'% editor), editor, template_file])13171318# If the file was not saved, prompt to see if this patch should1319# be skipped. But skip this verification step if configured so.1320ifgitConfigBool("git-p4.skipSubmitEditCheck"):1321return True13221323# modification time updated means user saved the file1324if os.stat(template_file).st_mtime > mtime:1325return True13261327while True:1328 response =raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")1329if response =='y':1330return True1331if response =='n':1332return False13331334defget_diff_description(self, editedFiles, filesToAdd):1335# diff1336if os.environ.has_key("P4DIFF"):1337del(os.environ["P4DIFF"])1338 diff =""1339for editedFile in editedFiles:1340 diff +=p4_read_pipe(['diff','-du',1341wildcard_encode(editedFile)])13421343# new file diff1344 newdiff =""1345for newFile in filesToAdd:1346 newdiff +="==== new file ====\n"1347 newdiff +="--- /dev/null\n"1348 newdiff +="+++%s\n"% newFile1349 f =open(newFile,"r")1350for line in f.readlines():1351 newdiff +="+"+ line1352 f.close()13531354return(diff + newdiff).replace('\r\n','\n')13551356defapplyCommit(self,id):1357"""Apply one commit, return True if it succeeded."""13581359print"Applying",read_pipe(["git","show","-s",1360"--format=format:%h%s",id])13611362(p4User, gitEmail) = self.p4UserForCommit(id)13631364 diff =read_pipe_lines("git diff-tree -r%s\"%s^\" \"%s\""% (self.diffOpts,id,id))1365 filesToAdd =set()1366 filesToDelete =set()1367 editedFiles =set()1368 pureRenameCopy =set()1369 filesToChangeExecBit = {}13701371for line in diff:1372 diff =parseDiffTreeEntry(line)1373 modifier = diff['status']1374 path = diff['src']1375if modifier =="M":1376p4_edit(path)1377ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1378 filesToChangeExecBit[path] = diff['dst_mode']1379 editedFiles.add(path)1380elif modifier =="A":1381 filesToAdd.add(path)1382 filesToChangeExecBit[path] = diff['dst_mode']1383if path in filesToDelete:1384 filesToDelete.remove(path)1385elif modifier =="D":1386 filesToDelete.add(path)1387if path in filesToAdd:1388 filesToAdd.remove(path)1389elif modifier =="C":1390 src, dest = diff['src'], diff['dst']1391p4_integrate(src, dest)1392 pureRenameCopy.add(dest)1393if diff['src_sha1'] != diff['dst_sha1']:1394p4_edit(dest)1395 pureRenameCopy.discard(dest)1396ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1397p4_edit(dest)1398 pureRenameCopy.discard(dest)1399 filesToChangeExecBit[dest] = diff['dst_mode']1400if self.isWindows:1401# turn off read-only attribute1402 os.chmod(dest, stat.S_IWRITE)1403 os.unlink(dest)1404 editedFiles.add(dest)1405elif modifier =="R":1406 src, dest = diff['src'], diff['dst']1407if self.p4HasMoveCommand:1408p4_edit(src)# src must be open before move1409p4_move(src, dest)# opens for (move/delete, move/add)1410else:1411p4_integrate(src, dest)1412if diff['src_sha1'] != diff['dst_sha1']:1413p4_edit(dest)1414else:1415 pureRenameCopy.add(dest)1416ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1417if not self.p4HasMoveCommand:1418p4_edit(dest)# with move: already open, writable1419 filesToChangeExecBit[dest] = diff['dst_mode']1420if not self.p4HasMoveCommand:1421if self.isWindows:1422 os.chmod(dest, stat.S_IWRITE)1423 os.unlink(dest)1424 filesToDelete.add(src)1425 editedFiles.add(dest)1426else:1427die("unknown modifier%sfor%s"% (modifier, path))14281429 diffcmd ="git diff-tree --full-index -p\"%s\""% (id)1430 patchcmd = diffcmd +" | git apply "1431 tryPatchCmd = patchcmd +"--check -"1432 applyPatchCmd = patchcmd +"--check --apply -"1433 patch_succeeded =True14341435if os.system(tryPatchCmd) !=0:1436 fixed_rcs_keywords =False1437 patch_succeeded =False1438print"Unfortunately applying the change failed!"14391440# Patch failed, maybe it's just RCS keyword woes. Look through1441# the patch to see if that's possible.1442ifgitConfigBool("git-p4.attemptRCSCleanup"):1443file=None1444 pattern =None1445 kwfiles = {}1446forfilein editedFiles | filesToDelete:1447# did this file's delta contain RCS keywords?1448 pattern =p4_keywords_regexp_for_file(file)14491450if pattern:1451# this file is a possibility...look for RCS keywords.1452 regexp = re.compile(pattern, re.VERBOSE)1453for line inread_pipe_lines(["git","diff","%s^..%s"% (id,id),file]):1454if regexp.search(line):1455if verbose:1456print"got keyword match on%sin%sin%s"% (pattern, line,file)1457 kwfiles[file] = pattern1458break14591460forfilein kwfiles:1461if verbose:1462print"zapping%swith%s"% (line,pattern)1463# File is being deleted, so not open in p4. Must1464# disable the read-only bit on windows.1465if self.isWindows andfilenot in editedFiles:1466 os.chmod(file, stat.S_IWRITE)1467 self.patchRCSKeywords(file, kwfiles[file])1468 fixed_rcs_keywords =True14691470if fixed_rcs_keywords:1471print"Retrying the patch with RCS keywords cleaned up"1472if os.system(tryPatchCmd) ==0:1473 patch_succeeded =True14741475if not patch_succeeded:1476for f in editedFiles:1477p4_revert(f)1478return False14791480#1481# Apply the patch for real, and do add/delete/+x handling.1482#1483system(applyPatchCmd)14841485for f in filesToAdd:1486p4_add(f)1487for f in filesToDelete:1488p4_revert(f)1489p4_delete(f)14901491# Set/clear executable bits1492for f in filesToChangeExecBit.keys():1493 mode = filesToChangeExecBit[f]1494setP4ExecBit(f, mode)14951496#1497# Build p4 change description, starting with the contents1498# of the git commit message.1499#1500 logMessage =extractLogMessageFromGitCommit(id)1501 logMessage = logMessage.strip()1502(logMessage, jobs) = self.separate_jobs_from_description(logMessage)15031504 template = self.prepareSubmitTemplate()1505 submitTemplate = self.prepareLogMessage(template, logMessage, jobs)15061507if self.preserveUser:1508 submitTemplate +="\n######## Actual user%s, modified after commit\n"% p4User15091510if self.checkAuthorship and not self.p4UserIsMe(p4User):1511 submitTemplate +="######## git author%sdoes not match your p4 account.\n"% gitEmail1512 submitTemplate +="######## Use option --preserve-user to modify authorship.\n"1513 submitTemplate +="######## Variable git-p4.skipUserNameCheck hides this message.\n"15141515 separatorLine ="######## everything below this line is just the diff #######\n"1516if not self.prepare_p4_only:1517 submitTemplate += separatorLine1518 submitTemplate += self.get_diff_description(editedFiles, filesToAdd)15191520(handle, fileName) = tempfile.mkstemp()1521 tmpFile = os.fdopen(handle,"w+b")1522if self.isWindows:1523 submitTemplate = submitTemplate.replace("\n","\r\n")1524 tmpFile.write(submitTemplate)1525 tmpFile.close()15261527if self.prepare_p4_only:1528#1529# Leave the p4 tree prepared, and the submit template around1530# and let the user decide what to do next1531#1532print1533print"P4 workspace prepared for submission."1534print"To submit or revert, go to client workspace"1535print" "+ self.clientPath1536print1537print"To submit, use\"p4 submit\"to write a new description,"1538print"or\"p4 submit -i <%s\"to use the one prepared by" \1539"\"git p4\"."% fileName1540print"You can delete the file\"%s\"when finished."% fileName15411542if self.preserveUser and p4User and not self.p4UserIsMe(p4User):1543print"To preserve change ownership by user%s, you must\n" \1544"do\"p4 change -f <change>\"after submitting and\n" \1545"edit the User field."1546if pureRenameCopy:1547print"After submitting, renamed files must be re-synced."1548print"Invoke\"p4 sync -f\"on each of these files:"1549for f in pureRenameCopy:1550print" "+ f15511552print1553print"To revert the changes, use\"p4 revert ...\", and delete"1554print"the submit template file\"%s\""% fileName1555if filesToAdd:1556print"Since the commit adds new files, they must be deleted:"1557for f in filesToAdd:1558print" "+ f1559print1560return True15611562#1563# Let the user edit the change description, then submit it.1564#1565if self.edit_template(fileName):1566# read the edited message and submit1567 ret =True1568 tmpFile =open(fileName,"rb")1569 message = tmpFile.read()1570 tmpFile.close()1571if self.isWindows:1572 message = message.replace("\r\n","\n")1573 submitTemplate = message[:message.index(separatorLine)]1574p4_write_pipe(['submit','-i'], submitTemplate)15751576if self.preserveUser:1577if p4User:1578# Get last changelist number. Cannot easily get it from1579# the submit command output as the output is1580# unmarshalled.1581 changelist = self.lastP4Changelist()1582 self.modifyChangelistUser(changelist, p4User)15831584# The rename/copy happened by applying a patch that created a1585# new file. This leaves it writable, which confuses p4.1586for f in pureRenameCopy:1587p4_sync(f,"-f")15881589else:1590# skip this patch1591 ret =False1592print"Submission cancelled, undoing p4 changes."1593for f in editedFiles:1594p4_revert(f)1595for f in filesToAdd:1596p4_revert(f)1597 os.remove(f)1598for f in filesToDelete:1599p4_revert(f)16001601 os.remove(fileName)1602return ret16031604# Export git tags as p4 labels. Create a p4 label and then tag1605# with that.1606defexportGitTags(self, gitTags):1607 validLabelRegexp =gitConfig("git-p4.labelExportRegexp")1608iflen(validLabelRegexp) ==0:1609 validLabelRegexp = defaultLabelRegexp1610 m = re.compile(validLabelRegexp)16111612for name in gitTags:16131614if not m.match(name):1615if verbose:1616print"tag%sdoes not match regexp%s"% (name, validLabelRegexp)1617continue16181619# Get the p4 commit this corresponds to1620 logMessage =extractLogMessageFromGitCommit(name)1621 values =extractSettingsGitLog(logMessage)16221623if not values.has_key('change'):1624# a tag pointing to something not sent to p4; ignore1625if verbose:1626print"git tag%sdoes not give a p4 commit"% name1627continue1628else:1629 changelist = values['change']16301631# Get the tag details.1632 inHeader =True1633 isAnnotated =False1634 body = []1635for l inread_pipe_lines(["git","cat-file","-p", name]):1636 l = l.strip()1637if inHeader:1638if re.match(r'tag\s+', l):1639 isAnnotated =True1640elif re.match(r'\s*$', l):1641 inHeader =False1642continue1643else:1644 body.append(l)16451646if not isAnnotated:1647 body = ["lightweight tag imported by git p4\n"]16481649# Create the label - use the same view as the client spec we are using1650 clientSpec =getClientSpec()16511652 labelTemplate ="Label:%s\n"% name1653 labelTemplate +="Description:\n"1654for b in body:1655 labelTemplate +="\t"+ b +"\n"1656 labelTemplate +="View:\n"1657for depot_side in clientSpec.mappings:1658 labelTemplate +="\t%s\n"% depot_side16591660if self.dry_run:1661print"Would create p4 label%sfor tag"% name1662elif self.prepare_p4_only:1663print"Not creating p4 label%sfor tag due to option" \1664" --prepare-p4-only"% name1665else:1666p4_write_pipe(["label","-i"], labelTemplate)16671668# Use the label1669p4_system(["tag","-l", name] +1670["%s@%s"% (depot_side, changelist)for depot_side in clientSpec.mappings])16711672if verbose:1673print"created p4 label for tag%s"% name16741675defrun(self, args):1676iflen(args) ==0:1677 self.master =currentGitBranch()1678iflen(self.master) ==0or notgitBranchExists("refs/heads/%s"% self.master):1679die("Detecting current git branch failed!")1680eliflen(args) ==1:1681 self.master = args[0]1682if notbranchExists(self.master):1683die("Branch%sdoes not exist"% self.master)1684else:1685return False16861687 allowSubmit =gitConfig("git-p4.allowSubmit")1688iflen(allowSubmit) >0and not self.master in allowSubmit.split(","):1689die("%sis not in git-p4.allowSubmit"% self.master)16901691[upstream, settings] =findUpstreamBranchPoint()1692 self.depotPath = settings['depot-paths'][0]1693iflen(self.origin) ==0:1694 self.origin = upstream16951696if self.preserveUser:1697if not self.canChangeChangelists():1698die("Cannot preserve user names without p4 super-user or admin permissions")16991700# if not set from the command line, try the config file1701if self.conflict_behavior is None:1702 val =gitConfig("git-p4.conflict")1703if val:1704if val not in self.conflict_behavior_choices:1705die("Invalid value '%s' for config git-p4.conflict"% val)1706else:1707 val ="ask"1708 self.conflict_behavior = val17091710if self.verbose:1711print"Origin branch is "+ self.origin17121713iflen(self.depotPath) ==0:1714print"Internal error: cannot locate perforce depot path from existing branches"1715 sys.exit(128)17161717 self.useClientSpec =False1718ifgitConfigBool("git-p4.useclientspec"):1719 self.useClientSpec =True1720if self.useClientSpec:1721 self.clientSpecDirs =getClientSpec()17221723# Check for the existance of P4 branches1724 branchesDetected = (len(p4BranchesInGit().keys()) >1)17251726if self.useClientSpec and not branchesDetected:1727# all files are relative to the client spec1728 self.clientPath =getClientRoot()1729else:1730 self.clientPath =p4Where(self.depotPath)17311732if self.clientPath =="":1733die("Error: Cannot locate perforce checkout of%sin client view"% self.depotPath)17341735print"Perforce checkout for depot path%slocated at%s"% (self.depotPath, self.clientPath)1736 self.oldWorkingDirectory = os.getcwd()17371738# ensure the clientPath exists1739 new_client_dir =False1740if not os.path.exists(self.clientPath):1741 new_client_dir =True1742 os.makedirs(self.clientPath)17431744chdir(self.clientPath, is_client_path=True)1745if self.dry_run:1746print"Would synchronize p4 checkout in%s"% self.clientPath1747else:1748print"Synchronizing p4 checkout..."1749if new_client_dir:1750# old one was destroyed, and maybe nobody told p41751p4_sync("...","-f")1752else:1753p4_sync("...")1754 self.check()17551756 commits = []1757for line inread_pipe_lines(["git","rev-list","--no-merges","%s..%s"% (self.origin, self.master)]):1758 commits.append(line.strip())1759 commits.reverse()17601761if self.preserveUser orgitConfigBool("git-p4.skipUserNameCheck"):1762 self.checkAuthorship =False1763else:1764 self.checkAuthorship =True17651766if self.preserveUser:1767 self.checkValidP4Users(commits)17681769#1770# Build up a set of options to be passed to diff when1771# submitting each commit to p4.1772#1773if self.detectRenames:1774# command-line -M arg1775 self.diffOpts ="-M"1776else:1777# If not explicitly set check the config variable1778 detectRenames =gitConfig("git-p4.detectRenames")17791780if detectRenames.lower() =="false"or detectRenames =="":1781 self.diffOpts =""1782elif detectRenames.lower() =="true":1783 self.diffOpts ="-M"1784else:1785 self.diffOpts ="-M%s"% detectRenames17861787# no command-line arg for -C or --find-copies-harder, just1788# config variables1789 detectCopies =gitConfig("git-p4.detectCopies")1790if detectCopies.lower() =="false"or detectCopies =="":1791pass1792elif detectCopies.lower() =="true":1793 self.diffOpts +=" -C"1794else:1795 self.diffOpts +=" -C%s"% detectCopies17961797ifgitConfigBool("git-p4.detectCopiesHarder"):1798 self.diffOpts +=" --find-copies-harder"17991800#1801# Apply the commits, one at a time. On failure, ask if should1802# continue to try the rest of the patches, or quit.1803#1804if self.dry_run:1805print"Would apply"1806 applied = []1807 last =len(commits) -11808for i, commit inenumerate(commits):1809if self.dry_run:1810print" ",read_pipe(["git","show","-s",1811"--format=format:%h%s", commit])1812 ok =True1813else:1814 ok = self.applyCommit(commit)1815if ok:1816 applied.append(commit)1817else:1818if self.prepare_p4_only and i < last:1819print"Processing only the first commit due to option" \1820" --prepare-p4-only"1821break1822if i < last:1823 quit =False1824while True:1825# prompt for what to do, or use the option/variable1826if self.conflict_behavior =="ask":1827print"What do you want to do?"1828 response =raw_input("[s]kip this commit but apply"1829" the rest, or [q]uit? ")1830if not response:1831continue1832elif self.conflict_behavior =="skip":1833 response ="s"1834elif self.conflict_behavior =="quit":1835 response ="q"1836else:1837die("Unknown conflict_behavior '%s'"%1838 self.conflict_behavior)18391840if response[0] =="s":1841print"Skipping this commit, but applying the rest"1842break1843if response[0] =="q":1844print"Quitting"1845 quit =True1846break1847if quit:1848break18491850chdir(self.oldWorkingDirectory)18511852if self.dry_run:1853pass1854elif self.prepare_p4_only:1855pass1856eliflen(commits) ==len(applied):1857print"All commits applied!"18581859 sync =P4Sync()1860if self.branch:1861 sync.branch = self.branch1862 sync.run([])18631864 rebase =P4Rebase()1865 rebase.rebase()18661867else:1868iflen(applied) ==0:1869print"No commits applied."1870else:1871print"Applied only the commits marked with '*':"1872for c in commits:1873if c in applied:1874 star ="*"1875else:1876 star =" "1877print star,read_pipe(["git","show","-s",1878"--format=format:%h%s", c])1879print"You will have to do 'git p4 sync' and rebase."18801881ifgitConfigBool("git-p4.exportLabels"):1882 self.exportLabels =True18831884if self.exportLabels:1885 p4Labels =getP4Labels(self.depotPath)1886 gitTags =getGitTags()18871888 missingGitTags = gitTags - p4Labels1889 self.exportGitTags(missingGitTags)18901891# exit with error unless everything applied perfectly1892iflen(commits) !=len(applied):1893 sys.exit(1)18941895return True18961897classView(object):1898"""Represent a p4 view ("p4 help views"), and map files in a1899 repo according to the view."""19001901def__init__(self, client_name):1902 self.mappings = []1903 self.client_prefix ="//%s/"% client_name1904# cache results of "p4 where" to lookup client file locations1905 self.client_spec_path_cache = {}19061907defappend(self, view_line):1908"""Parse a view line, splitting it into depot and client1909 sides. Append to self.mappings, preserving order. This1910 is only needed for tag creation."""19111912# Split the view line into exactly two words. P4 enforces1913# structure on these lines that simplifies this quite a bit.1914#1915# Either or both words may be double-quoted.1916# Single quotes do not matter.1917# Double-quote marks cannot occur inside the words.1918# A + or - prefix is also inside the quotes.1919# There are no quotes unless they contain a space.1920# The line is already white-space stripped.1921# The two words are separated by a single space.1922#1923if view_line[0] =='"':1924# First word is double quoted. Find its end.1925 close_quote_index = view_line.find('"',1)1926if close_quote_index <=0:1927die("No first-word closing quote found:%s"% view_line)1928 depot_side = view_line[1:close_quote_index]1929# skip closing quote and space1930 rhs_index = close_quote_index +1+11931else:1932 space_index = view_line.find(" ")1933if space_index <=0:1934die("No word-splitting space found:%s"% view_line)1935 depot_side = view_line[0:space_index]1936 rhs_index = space_index +119371938# prefix + means overlay on previous mapping1939if depot_side.startswith("+"):1940 depot_side = depot_side[1:]19411942# prefix - means exclude this path, leave out of mappings1943 exclude =False1944if depot_side.startswith("-"):1945 exclude =True1946 depot_side = depot_side[1:]19471948if not exclude:1949 self.mappings.append(depot_side)19501951defconvert_client_path(self, clientFile):1952# chop off //client/ part to make it relative1953if not clientFile.startswith(self.client_prefix):1954die("No prefix '%s' on clientFile '%s'"%1955(self.client_prefix, clientFile))1956return clientFile[len(self.client_prefix):]19571958defupdate_client_spec_path_cache(self, files):1959""" Caching file paths by "p4 where" batch query """19601961# List depot file paths exclude that already cached1962 fileArgs = [f['path']for f in files if f['path']not in self.client_spec_path_cache]19631964iflen(fileArgs) ==0:1965return# All files in cache19661967 where_result =p4CmdList(["-x","-","where"], stdin=fileArgs)1968for res in where_result:1969if"code"in res and res["code"] =="error":1970# assume error is "... file(s) not in client view"1971continue1972if"clientFile"not in res:1973die("No clientFile in 'p4 where' output")1974if"unmap"in res:1975# it will list all of them, but only one not unmap-ped1976continue1977ifgitConfigBool("core.ignorecase"):1978 res['depotFile'] = res['depotFile'].lower()1979 self.client_spec_path_cache[res['depotFile']] = self.convert_client_path(res["clientFile"])19801981# not found files or unmap files set to ""1982for depotFile in fileArgs:1983ifgitConfigBool("core.ignorecase"):1984 depotFile = depotFile.lower()1985if depotFile not in self.client_spec_path_cache:1986 self.client_spec_path_cache[depotFile] =""19871988defmap_in_client(self, depot_path):1989"""Return the relative location in the client where this1990 depot file should live. Returns "" if the file should1991 not be mapped in the client."""19921993ifgitConfigBool("core.ignorecase"):1994 depot_path = depot_path.lower()19951996if depot_path in self.client_spec_path_cache:1997return self.client_spec_path_cache[depot_path]19981999die("Error:%sis not found in client spec path"% depot_path )2000return""20012002classP4Sync(Command, P4UserMap):2003 delete_actions = ("delete","move/delete","purge")20042005def__init__(self):2006 Command.__init__(self)2007 P4UserMap.__init__(self)2008 self.options = [2009 optparse.make_option("--branch", dest="branch"),2010 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),2011 optparse.make_option("--changesfile", dest="changesFile"),2012 optparse.make_option("--silent", dest="silent", action="store_true"),2013 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),2014 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),2015 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",2016help="Import into refs/heads/ , not refs/remotes"),2017 optparse.make_option("--max-changes", dest="maxChanges",2018help="Maximum number of changes to import"),2019 optparse.make_option("--changes-block-size", dest="changes_block_size",type="int",2020help="Internal block size to use when iteratively calling p4 changes"),2021 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',2022help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),2023 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',2024help="Only sync files that are included in the Perforce Client Spec"),2025 optparse.make_option("-/", dest="cloneExclude",2026 action="append",type="string",2027help="exclude depot path"),2028]2029 self.description ="""Imports from Perforce into a git repository.\n2030 example:2031 //depot/my/project/ -- to import the current head2032 //depot/my/project/@all -- to import everything2033 //depot/my/project/@1,6 -- to import only from revision 1 to 620342035 (a ... is not needed in the path p4 specification, it's added implicitly)"""20362037 self.usage +=" //depot/path[@revRange]"2038 self.silent =False2039 self.createdBranches =set()2040 self.committedChanges =set()2041 self.branch =""2042 self.detectBranches =False2043 self.detectLabels =False2044 self.importLabels =False2045 self.changesFile =""2046 self.syncWithOrigin =True2047 self.importIntoRemotes =True2048 self.maxChanges =""2049 self.changes_block_size =None2050 self.keepRepoPath =False2051 self.depotPaths =None2052 self.p4BranchesInGit = []2053 self.cloneExclude = []2054 self.useClientSpec =False2055 self.useClientSpec_from_options =False2056 self.clientSpecDirs =None2057 self.tempBranches = []2058 self.tempBranchLocation ="git-p4-tmp"20592060ifgitConfig("git-p4.syncFromOrigin") =="false":2061 self.syncWithOrigin =False20622063# This is required for the "append" cloneExclude action2064defensure_value(self, attr, value):2065if nothasattr(self, attr)orgetattr(self, attr)is None:2066setattr(self, attr, value)2067returngetattr(self, attr)20682069# Force a checkpoint in fast-import and wait for it to finish2070defcheckpoint(self):2071 self.gitStream.write("checkpoint\n\n")2072 self.gitStream.write("progress checkpoint\n\n")2073 out = self.gitOutput.readline()2074if self.verbose:2075print"checkpoint finished: "+ out20762077defextractFilesFromCommit(self, commit):2078 self.cloneExclude = [re.sub(r"\.\.\.$","", path)2079for path in self.cloneExclude]2080 files = []2081 fnum =02082while commit.has_key("depotFile%s"% fnum):2083 path = commit["depotFile%s"% fnum]20842085if[p for p in self.cloneExclude2086ifp4PathStartsWith(path, p)]:2087 found =False2088else:2089 found = [p for p in self.depotPaths2090ifp4PathStartsWith(path, p)]2091if not found:2092 fnum = fnum +12093continue20942095file= {}2096file["path"] = path2097file["rev"] = commit["rev%s"% fnum]2098file["action"] = commit["action%s"% fnum]2099file["type"] = commit["type%s"% fnum]2100 files.append(file)2101 fnum = fnum +12102return files21032104defstripRepoPath(self, path, prefixes):2105"""When streaming files, this is called to map a p4 depot path2106 to where it should go in git. The prefixes are either2107 self.depotPaths, or self.branchPrefixes in the case of2108 branch detection."""21092110if self.useClientSpec:2111# branch detection moves files up a level (the branch name)2112# from what client spec interpretation gives2113 path = self.clientSpecDirs.map_in_client(path)2114if self.detectBranches:2115for b in self.knownBranches:2116if path.startswith(b +"/"):2117 path = path[len(b)+1:]21182119elif self.keepRepoPath:2120# Preserve everything in relative path name except leading2121# //depot/; just look at first prefix as they all should2122# be in the same depot.2123 depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])2124ifp4PathStartsWith(path, depot):2125 path = path[len(depot):]21262127else:2128for p in prefixes:2129ifp4PathStartsWith(path, p):2130 path = path[len(p):]2131break21322133 path =wildcard_decode(path)2134return path21352136defsplitFilesIntoBranches(self, commit):2137"""Look at each depotFile in the commit to figure out to what2138 branch it belongs."""21392140if self.clientSpecDirs:2141 files = self.extractFilesFromCommit(commit)2142 self.clientSpecDirs.update_client_spec_path_cache(files)21432144 branches = {}2145 fnum =02146while commit.has_key("depotFile%s"% fnum):2147 path = commit["depotFile%s"% fnum]2148 found = [p for p in self.depotPaths2149ifp4PathStartsWith(path, p)]2150if not found:2151 fnum = fnum +12152continue21532154file= {}2155file["path"] = path2156file["rev"] = commit["rev%s"% fnum]2157file["action"] = commit["action%s"% fnum]2158file["type"] = commit["type%s"% fnum]2159 fnum = fnum +121602161# start with the full relative path where this file would2162# go in a p4 client2163if self.useClientSpec:2164 relPath = self.clientSpecDirs.map_in_client(path)2165else:2166 relPath = self.stripRepoPath(path, self.depotPaths)21672168for branch in self.knownBranches.keys():2169# add a trailing slash so that a commit into qt/4.2foo2170# doesn't end up in qt/4.2, e.g.2171if relPath.startswith(branch +"/"):2172if branch not in branches:2173 branches[branch] = []2174 branches[branch].append(file)2175break21762177return branches21782179# output one file from the P4 stream2180# - helper for streamP4Files21812182defstreamOneP4File(self,file, contents):2183 relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)2184if verbose:2185 size =int(self.stream_file['fileSize'])2186 sys.stdout.write('\r%s-->%s(%iMB)\n'% (file['depotFile'], relPath, size/1024/1024))2187 sys.stdout.flush()21882189(type_base, type_mods) =split_p4_type(file["type"])21902191 git_mode ="100644"2192if"x"in type_mods:2193 git_mode ="100755"2194if type_base =="symlink":2195 git_mode ="120000"2196# p4 print on a symlink sometimes contains "target\n";2197# if it does, remove the newline2198 data =''.join(contents)2199if not data:2200# Some version of p4 allowed creating a symlink that pointed2201# to nothing. This causes p4 errors when checking out such2202# a change, and errors here too. Work around it by ignoring2203# the bad symlink; hopefully a future change fixes it.2204print"\nIgnoring empty symlink in%s"%file['depotFile']2205return2206elif data[-1] =='\n':2207 contents = [data[:-1]]2208else:2209 contents = [data]22102211if type_base =="utf16":2212# p4 delivers different text in the python output to -G2213# than it does when using "print -o", or normal p4 client2214# operations. utf16 is converted to ascii or utf8, perhaps.2215# But ascii text saved as -t utf16 is completely mangled.2216# Invoke print -o to get the real contents.2217#2218# On windows, the newlines will always be mangled by print, so put2219# them back too. This is not needed to the cygwin windows version,2220# just the native "NT" type.2221#2222 text =p4_read_pipe(['print','-q','-o','-',"%s@%s"% (file['depotFile'],file['change']) ])2223ifp4_version_string().find("/NT") >=0:2224 text = text.replace("\r\n","\n")2225 contents = [ text ]22262227if type_base =="apple":2228# Apple filetype files will be streamed as a concatenation of2229# its appledouble header and the contents. This is useless2230# on both macs and non-macs. If using "print -q -o xx", it2231# will create "xx" with the data, and "%xx" with the header.2232# This is also not very useful.2233#2234# Ideally, someday, this script can learn how to generate2235# appledouble files directly and import those to git, but2236# non-mac machines can never find a use for apple filetype.2237print"\nIgnoring apple filetype file%s"%file['depotFile']2238return22392240# Note that we do not try to de-mangle keywords on utf16 files,2241# even though in theory somebody may want that.2242 pattern =p4_keywords_regexp_for_type(type_base, type_mods)2243if pattern:2244 regexp = re.compile(pattern, re.VERBOSE)2245 text =''.join(contents)2246 text = regexp.sub(r'$\1$', text)2247 contents = [ text ]22482249 self.gitStream.write("M%sinline%s\n"% (git_mode, relPath))22502251# total length...2252 length =02253for d in contents:2254 length = length +len(d)22552256 self.gitStream.write("data%d\n"% length)2257for d in contents:2258 self.gitStream.write(d)2259 self.gitStream.write("\n")22602261defstreamOneP4Deletion(self,file):2262 relPath = self.stripRepoPath(file['path'], self.branchPrefixes)2263if verbose:2264 sys.stdout.write("delete%s\n"% relPath)2265 sys.stdout.flush()2266 self.gitStream.write("D%s\n"% relPath)22672268# handle another chunk of streaming data2269defstreamP4FilesCb(self, marshalled):22702271# catch p4 errors and complain2272 err =None2273if"code"in marshalled:2274if marshalled["code"] =="error":2275if"data"in marshalled:2276 err = marshalled["data"].rstrip()22772278if not err and'fileSize'in self.stream_file:2279 required_bytes =int((4*int(self.stream_file["fileSize"])) -calcDiskFree())2280if required_bytes >0:2281 err ='Not enough space left on%s! Free at least%iMB.'% (2282 os.getcwd(), required_bytes/1024/10242283)22842285if err:2286 f =None2287if self.stream_have_file_info:2288if"depotFile"in self.stream_file:2289 f = self.stream_file["depotFile"]2290# force a failure in fast-import, else an empty2291# commit will be made2292 self.gitStream.write("\n")2293 self.gitStream.write("die-now\n")2294 self.gitStream.close()2295# ignore errors, but make sure it exits first2296 self.importProcess.wait()2297if f:2298die("Error from p4 print for%s:%s"% (f, err))2299else:2300die("Error from p4 print:%s"% err)23012302if marshalled.has_key('depotFile')and self.stream_have_file_info:2303# start of a new file - output the old one first2304 self.streamOneP4File(self.stream_file, self.stream_contents)2305 self.stream_file = {}2306 self.stream_contents = []2307 self.stream_have_file_info =False23082309# pick up the new file information... for the2310# 'data' field we need to append to our array2311for k in marshalled.keys():2312if k =='data':2313if'streamContentSize'not in self.stream_file:2314 self.stream_file['streamContentSize'] =02315 self.stream_file['streamContentSize'] +=len(marshalled['data'])2316 self.stream_contents.append(marshalled['data'])2317else:2318 self.stream_file[k] = marshalled[k]23192320if(verbose and2321'streamContentSize'in self.stream_file and2322'fileSize'in self.stream_file and2323'depotFile'in self.stream_file):2324 size =int(self.stream_file["fileSize"])2325if size >0:2326 progress =100*self.stream_file['streamContentSize']/size2327 sys.stdout.write('\r%s %d%%(%iMB)'% (self.stream_file['depotFile'], progress,int(size/1024/1024)))2328 sys.stdout.flush()23292330 self.stream_have_file_info =True23312332# Stream directly from "p4 files" into "git fast-import"2333defstreamP4Files(self, files):2334 filesForCommit = []2335 filesToRead = []2336 filesToDelete = []23372338for f in files:2339# if using a client spec, only add the files that have2340# a path in the client2341if self.clientSpecDirs:2342if self.clientSpecDirs.map_in_client(f['path']) =="":2343continue23442345 filesForCommit.append(f)2346if f['action']in self.delete_actions:2347 filesToDelete.append(f)2348else:2349 filesToRead.append(f)23502351# deleted files...2352for f in filesToDelete:2353 self.streamOneP4Deletion(f)23542355iflen(filesToRead) >0:2356 self.stream_file = {}2357 self.stream_contents = []2358 self.stream_have_file_info =False23592360# curry self argument2361defstreamP4FilesCbSelf(entry):2362 self.streamP4FilesCb(entry)23632364 fileArgs = ['%s#%s'% (f['path'], f['rev'])for f in filesToRead]23652366p4CmdList(["-x","-","print"],2367 stdin=fileArgs,2368 cb=streamP4FilesCbSelf)23692370# do the last chunk2371if self.stream_file.has_key('depotFile'):2372 self.streamOneP4File(self.stream_file, self.stream_contents)23732374defmake_email(self, userid):2375if userid in self.users:2376return self.users[userid]2377else:2378return"%s<a@b>"% userid23792380# Stream a p4 tag2381defstreamTag(self, gitStream, labelName, labelDetails, commit, epoch):2382if verbose:2383print"writing tag%sfor commit%s"% (labelName, commit)2384 gitStream.write("tag%s\n"% labelName)2385 gitStream.write("from%s\n"% commit)23862387if labelDetails.has_key('Owner'):2388 owner = labelDetails["Owner"]2389else:2390 owner =None23912392# Try to use the owner of the p4 label, or failing that,2393# the current p4 user id.2394if owner:2395 email = self.make_email(owner)2396else:2397 email = self.make_email(self.p4UserId())2398 tagger ="%s %s %s"% (email, epoch, self.tz)23992400 gitStream.write("tagger%s\n"% tagger)24012402print"labelDetails=",labelDetails2403if labelDetails.has_key('Description'):2404 description = labelDetails['Description']2405else:2406 description ='Label from git p4'24072408 gitStream.write("data%d\n"%len(description))2409 gitStream.write(description)2410 gitStream.write("\n")24112412defcommit(self, details, files, branch, parent =""):2413 epoch = details["time"]2414 author = details["user"]24152416if self.verbose:2417print"commit into%s"% branch24182419# start with reading files; if that fails, we should not2420# create a commit.2421 new_files = []2422for f in files:2423if[p for p in self.branchPrefixes ifp4PathStartsWith(f['path'], p)]:2424 new_files.append(f)2425else:2426 sys.stderr.write("Ignoring file outside of prefix:%s\n"% f['path'])24272428if self.clientSpecDirs:2429 self.clientSpecDirs.update_client_spec_path_cache(files)24302431 self.gitStream.write("commit%s\n"% branch)2432# gitStream.write("mark :%s\n" % details["change"])2433 self.committedChanges.add(int(details["change"]))2434 committer =""2435if author not in self.users:2436 self.getUserMapFromPerforceServer()2437 committer ="%s %s %s"% (self.make_email(author), epoch, self.tz)24382439 self.gitStream.write("committer%s\n"% committer)24402441 self.gitStream.write("data <<EOT\n")2442 self.gitStream.write(details["desc"])2443 self.gitStream.write("\n[git-p4: depot-paths =\"%s\": change =%s"%2444(','.join(self.branchPrefixes), details["change"]))2445iflen(details['options']) >0:2446 self.gitStream.write(": options =%s"% details['options'])2447 self.gitStream.write("]\nEOT\n\n")24482449iflen(parent) >0:2450if self.verbose:2451print"parent%s"% parent2452 self.gitStream.write("from%s\n"% parent)24532454 self.streamP4Files(new_files)2455 self.gitStream.write("\n")24562457 change =int(details["change"])24582459if self.labels.has_key(change):2460 label = self.labels[change]2461 labelDetails = label[0]2462 labelRevisions = label[1]2463if self.verbose:2464print"Change%sis labelled%s"% (change, labelDetails)24652466 files =p4CmdList(["files"] + ["%s...@%s"% (p, change)2467for p in self.branchPrefixes])24682469iflen(files) ==len(labelRevisions):24702471 cleanedFiles = {}2472for info in files:2473if info["action"]in self.delete_actions:2474continue2475 cleanedFiles[info["depotFile"]] = info["rev"]24762477if cleanedFiles == labelRevisions:2478 self.streamTag(self.gitStream,'tag_%s'% labelDetails['label'], labelDetails, branch, epoch)24792480else:2481if not self.silent:2482print("Tag%sdoes not match with change%s: files do not match."2483% (labelDetails["label"], change))24842485else:2486if not self.silent:2487print("Tag%sdoes not match with change%s: file count is different."2488% (labelDetails["label"], change))24892490# Build a dictionary of changelists and labels, for "detect-labels" option.2491defgetLabels(self):2492 self.labels = {}24932494 l =p4CmdList(["labels"] + ["%s..."% p for p in self.depotPaths])2495iflen(l) >0and not self.silent:2496print"Finding files belonging to labels in%s"% `self.depotPaths`24972498for output in l:2499 label = output["label"]2500 revisions = {}2501 newestChange =02502if self.verbose:2503print"Querying files for label%s"% label2504forfileinp4CmdList(["files"] +2505["%s...@%s"% (p, label)2506for p in self.depotPaths]):2507 revisions[file["depotFile"]] =file["rev"]2508 change =int(file["change"])2509if change > newestChange:2510 newestChange = change25112512 self.labels[newestChange] = [output, revisions]25132514if self.verbose:2515print"Label changes:%s"% self.labels.keys()25162517# Import p4 labels as git tags. A direct mapping does not2518# exist, so assume that if all the files are at the same revision2519# then we can use that, or it's something more complicated we should2520# just ignore.2521defimportP4Labels(self, stream, p4Labels):2522if verbose:2523print"import p4 labels: "+' '.join(p4Labels)25242525 ignoredP4Labels =gitConfigList("git-p4.ignoredP4Labels")2526 validLabelRegexp =gitConfig("git-p4.labelImportRegexp")2527iflen(validLabelRegexp) ==0:2528 validLabelRegexp = defaultLabelRegexp2529 m = re.compile(validLabelRegexp)25302531for name in p4Labels:2532 commitFound =False25332534if not m.match(name):2535if verbose:2536print"label%sdoes not match regexp%s"% (name,validLabelRegexp)2537continue25382539if name in ignoredP4Labels:2540continue25412542 labelDetails =p4CmdList(['label',"-o", name])[0]25432544# get the most recent changelist for each file in this label2545 change =p4Cmd(["changes","-m","1"] + ["%s...@%s"% (p, name)2546for p in self.depotPaths])25472548if change.has_key('change'):2549# find the corresponding git commit; take the oldest commit2550 changelist =int(change['change'])2551 gitCommit =read_pipe(["git","rev-list","--max-count=1",2552"--reverse",":/\[git-p4:.*change =%d\]"% changelist])2553iflen(gitCommit) ==0:2554print"could not find git commit for changelist%d"% changelist2555else:2556 gitCommit = gitCommit.strip()2557 commitFound =True2558# Convert from p4 time format2559try:2560 tmwhen = time.strptime(labelDetails['Update'],"%Y/%m/%d%H:%M:%S")2561exceptValueError:2562print"Could not convert label time%s"% labelDetails['Update']2563 tmwhen =125642565 when =int(time.mktime(tmwhen))2566 self.streamTag(stream, name, labelDetails, gitCommit, when)2567if verbose:2568print"p4 label%smapped to git commit%s"% (name, gitCommit)2569else:2570if verbose:2571print"Label%shas no changelists - possibly deleted?"% name25722573if not commitFound:2574# We can't import this label; don't try again as it will get very2575# expensive repeatedly fetching all the files for labels that will2576# never be imported. If the label is moved in the future, the2577# ignore will need to be removed manually.2578system(["git","config","--add","git-p4.ignoredP4Labels", name])25792580defguessProjectName(self):2581for p in self.depotPaths:2582if p.endswith("/"):2583 p = p[:-1]2584 p = p[p.strip().rfind("/") +1:]2585if not p.endswith("/"):2586 p +="/"2587return p25882589defgetBranchMapping(self):2590 lostAndFoundBranches =set()25912592 user =gitConfig("git-p4.branchUser")2593iflen(user) >0:2594 command ="branches -u%s"% user2595else:2596 command ="branches"25972598for info inp4CmdList(command):2599 details =p4Cmd(["branch","-o", info["branch"]])2600 viewIdx =02601while details.has_key("View%s"% viewIdx):2602 paths = details["View%s"% viewIdx].split(" ")2603 viewIdx = viewIdx +12604# require standard //depot/foo/... //depot/bar/... mapping2605iflen(paths) !=2or not paths[0].endswith("/...")or not paths[1].endswith("/..."):2606continue2607 source = paths[0]2608 destination = paths[1]2609## HACK2610ifp4PathStartsWith(source, self.depotPaths[0])andp4PathStartsWith(destination, self.depotPaths[0]):2611 source = source[len(self.depotPaths[0]):-4]2612 destination = destination[len(self.depotPaths[0]):-4]26132614if destination in self.knownBranches:2615if not self.silent:2616print"p4 branch%sdefines a mapping from%sto%s"% (info["branch"], source, destination)2617print"but there exists another mapping from%sto%salready!"% (self.knownBranches[destination], destination)2618continue26192620 self.knownBranches[destination] = source26212622 lostAndFoundBranches.discard(destination)26232624if source not in self.knownBranches:2625 lostAndFoundBranches.add(source)26262627# Perforce does not strictly require branches to be defined, so we also2628# check git config for a branch list.2629#2630# Example of branch definition in git config file:2631# [git-p4]2632# branchList=main:branchA2633# branchList=main:branchB2634# branchList=branchA:branchC2635 configBranches =gitConfigList("git-p4.branchList")2636for branch in configBranches:2637if branch:2638(source, destination) = branch.split(":")2639 self.knownBranches[destination] = source26402641 lostAndFoundBranches.discard(destination)26422643if source not in self.knownBranches:2644 lostAndFoundBranches.add(source)264526462647for branch in lostAndFoundBranches:2648 self.knownBranches[branch] = branch26492650defgetBranchMappingFromGitBranches(self):2651 branches =p4BranchesInGit(self.importIntoRemotes)2652for branch in branches.keys():2653if branch =="master":2654 branch ="main"2655else:2656 branch = branch[len(self.projectName):]2657 self.knownBranches[branch] = branch26582659defupdateOptionDict(self, d):2660 option_keys = {}2661if self.keepRepoPath:2662 option_keys['keepRepoPath'] =126632664 d["options"] =' '.join(sorted(option_keys.keys()))26652666defreadOptions(self, d):2667 self.keepRepoPath = (d.has_key('options')2668and('keepRepoPath'in d['options']))26692670defgitRefForBranch(self, branch):2671if branch =="main":2672return self.refPrefix +"master"26732674iflen(branch) <=0:2675return branch26762677return self.refPrefix + self.projectName + branch26782679defgitCommitByP4Change(self, ref, change):2680if self.verbose:2681print"looking in ref "+ ref +" for change%susing bisect..."% change26822683 earliestCommit =""2684 latestCommit =parseRevision(ref)26852686while True:2687if self.verbose:2688print"trying: earliest%slatest%s"% (earliestCommit, latestCommit)2689 next =read_pipe("git rev-list --bisect%s %s"% (latestCommit, earliestCommit)).strip()2690iflen(next) ==0:2691if self.verbose:2692print"argh"2693return""2694 log =extractLogMessageFromGitCommit(next)2695 settings =extractSettingsGitLog(log)2696 currentChange =int(settings['change'])2697if self.verbose:2698print"current change%s"% currentChange26992700if currentChange == change:2701if self.verbose:2702print"found%s"% next2703return next27042705if currentChange < change:2706 earliestCommit ="^%s"% next2707else:2708 latestCommit ="%s"% next27092710return""27112712defimportNewBranch(self, branch, maxChange):2713# make fast-import flush all changes to disk and update the refs using the checkpoint2714# command so that we can try to find the branch parent in the git history2715 self.gitStream.write("checkpoint\n\n");2716 self.gitStream.flush();2717 branchPrefix = self.depotPaths[0] + branch +"/"2718range="@1,%s"% maxChange2719#print "prefix" + branchPrefix2720 changes =p4ChangesForPaths([branchPrefix],range, self.changes_block_size)2721iflen(changes) <=0:2722return False2723 firstChange = changes[0]2724#print "first change in branch: %s" % firstChange2725 sourceBranch = self.knownBranches[branch]2726 sourceDepotPath = self.depotPaths[0] + sourceBranch2727 sourceRef = self.gitRefForBranch(sourceBranch)2728#print "source " + sourceBranch27292730 branchParentChange =int(p4Cmd(["changes","-m","1","%s...@1,%s"% (sourceDepotPath, firstChange)])["change"])2731#print "branch parent: %s" % branchParentChange2732 gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)2733iflen(gitParent) >0:2734 self.initialParents[self.gitRefForBranch(branch)] = gitParent2735#print "parent git commit: %s" % gitParent27362737 self.importChanges(changes)2738return True27392740defsearchParent(self, parent, branch, target):2741 parentFound =False2742for blob inread_pipe_lines(["git","rev-list","--reverse",2743"--no-merges", parent]):2744 blob = blob.strip()2745iflen(read_pipe(["git","diff-tree", blob, target])) ==0:2746 parentFound =True2747if self.verbose:2748print"Found parent of%sin commit%s"% (branch, blob)2749break2750if parentFound:2751return blob2752else:2753return None27542755defimportChanges(self, changes):2756 cnt =12757for change in changes:2758 description =p4_describe(change)2759 self.updateOptionDict(description)27602761if not self.silent:2762 sys.stdout.write("\rImporting revision%s(%s%%)"% (change, cnt *100/len(changes)))2763 sys.stdout.flush()2764 cnt = cnt +127652766try:2767if self.detectBranches:2768 branches = self.splitFilesIntoBranches(description)2769for branch in branches.keys():2770## HACK --hwn2771 branchPrefix = self.depotPaths[0] + branch +"/"2772 self.branchPrefixes = [ branchPrefix ]27732774 parent =""27752776 filesForCommit = branches[branch]27772778if self.verbose:2779print"branch is%s"% branch27802781 self.updatedBranches.add(branch)27822783if branch not in self.createdBranches:2784 self.createdBranches.add(branch)2785 parent = self.knownBranches[branch]2786if parent == branch:2787 parent =""2788else:2789 fullBranch = self.projectName + branch2790if fullBranch not in self.p4BranchesInGit:2791if not self.silent:2792print("\nImporting new branch%s"% fullBranch);2793if self.importNewBranch(branch, change -1):2794 parent =""2795 self.p4BranchesInGit.append(fullBranch)2796if not self.silent:2797print("\nResuming with change%s"% change);27982799if self.verbose:2800print"parent determined through known branches:%s"% parent28012802 branch = self.gitRefForBranch(branch)2803 parent = self.gitRefForBranch(parent)28042805if self.verbose:2806print"looking for initial parent for%s; current parent is%s"% (branch, parent)28072808iflen(parent) ==0and branch in self.initialParents:2809 parent = self.initialParents[branch]2810del self.initialParents[branch]28112812 blob =None2813iflen(parent) >0:2814 tempBranch ="%s/%d"% (self.tempBranchLocation, change)2815if self.verbose:2816print"Creating temporary branch: "+ tempBranch2817 self.commit(description, filesForCommit, tempBranch)2818 self.tempBranches.append(tempBranch)2819 self.checkpoint()2820 blob = self.searchParent(parent, branch, tempBranch)2821if blob:2822 self.commit(description, filesForCommit, branch, blob)2823else:2824if self.verbose:2825print"Parent of%snot found. Committing into head of%s"% (branch, parent)2826 self.commit(description, filesForCommit, branch, parent)2827else:2828 files = self.extractFilesFromCommit(description)2829 self.commit(description, files, self.branch,2830 self.initialParent)2831# only needed once, to connect to the previous commit2832 self.initialParent =""2833exceptIOError:2834print self.gitError.read()2835 sys.exit(1)28362837defimportHeadRevision(self, revision):2838print"Doing initial import of%sfrom revision%sinto%s"% (' '.join(self.depotPaths), revision, self.branch)28392840 details = {}2841 details["user"] ="git perforce import user"2842 details["desc"] = ("Initial import of%sfrom the state at revision%s\n"2843% (' '.join(self.depotPaths), revision))2844 details["change"] = revision2845 newestRevision =028462847 fileCnt =02848 fileArgs = ["%s...%s"% (p,revision)for p in self.depotPaths]28492850for info inp4CmdList(["files"] + fileArgs):28512852if'code'in info and info['code'] =='error':2853 sys.stderr.write("p4 returned an error:%s\n"2854% info['data'])2855if info['data'].find("must refer to client") >=0:2856 sys.stderr.write("This particular p4 error is misleading.\n")2857 sys.stderr.write("Perhaps the depot path was misspelled.\n");2858 sys.stderr.write("Depot path:%s\n"%" ".join(self.depotPaths))2859 sys.exit(1)2860if'p4ExitCode'in info:2861 sys.stderr.write("p4 exitcode:%s\n"% info['p4ExitCode'])2862 sys.exit(1)286328642865 change =int(info["change"])2866if change > newestRevision:2867 newestRevision = change28682869if info["action"]in self.delete_actions:2870# don't increase the file cnt, otherwise details["depotFile123"] will have gaps!2871#fileCnt = fileCnt + 12872continue28732874for prop in["depotFile","rev","action","type"]:2875 details["%s%s"% (prop, fileCnt)] = info[prop]28762877 fileCnt = fileCnt +128782879 details["change"] = newestRevision28802881# Use time from top-most change so that all git p4 clones of2882# the same p4 repo have the same commit SHA1s.2883 res =p4_describe(newestRevision)2884 details["time"] = res["time"]28852886 self.updateOptionDict(details)2887try:2888 self.commit(details, self.extractFilesFromCommit(details), self.branch)2889exceptIOError:2890print"IO error with git fast-import. Is your git version recent enough?"2891print self.gitError.read()289228932894defrun(self, args):2895 self.depotPaths = []2896 self.changeRange =""2897 self.previousDepotPaths = []2898 self.hasOrigin =False28992900# map from branch depot path to parent branch2901 self.knownBranches = {}2902 self.initialParents = {}29032904if self.importIntoRemotes:2905 self.refPrefix ="refs/remotes/p4/"2906else:2907 self.refPrefix ="refs/heads/p4/"29082909if self.syncWithOrigin:2910 self.hasOrigin =originP4BranchesExist()2911if self.hasOrigin:2912if not self.silent:2913print'Syncing with origin first, using "git fetch origin"'2914system("git fetch origin")29152916 branch_arg_given =bool(self.branch)2917iflen(self.branch) ==0:2918 self.branch = self.refPrefix +"master"2919ifgitBranchExists("refs/heads/p4")and self.importIntoRemotes:2920system("git update-ref%srefs/heads/p4"% self.branch)2921system("git branch -D p4")29222923# accept either the command-line option, or the configuration variable2924if self.useClientSpec:2925# will use this after clone to set the variable2926 self.useClientSpec_from_options =True2927else:2928ifgitConfigBool("git-p4.useclientspec"):2929 self.useClientSpec =True2930if self.useClientSpec:2931 self.clientSpecDirs =getClientSpec()29322933# TODO: should always look at previous commits,2934# merge with previous imports, if possible.2935if args == []:2936if self.hasOrigin:2937createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)29382939# branches holds mapping from branch name to sha12940 branches =p4BranchesInGit(self.importIntoRemotes)29412942# restrict to just this one, disabling detect-branches2943if branch_arg_given:2944 short = self.branch.split("/")[-1]2945if short in branches:2946 self.p4BranchesInGit = [ short ]2947else:2948 self.p4BranchesInGit = branches.keys()29492950iflen(self.p4BranchesInGit) >1:2951if not self.silent:2952print"Importing from/into multiple branches"2953 self.detectBranches =True2954for branch in branches.keys():2955 self.initialParents[self.refPrefix + branch] = \2956 branches[branch]29572958if self.verbose:2959print"branches:%s"% self.p4BranchesInGit29602961 p4Change =02962for branch in self.p4BranchesInGit:2963 logMsg =extractLogMessageFromGitCommit(self.refPrefix + branch)29642965 settings =extractSettingsGitLog(logMsg)29662967 self.readOptions(settings)2968if(settings.has_key('depot-paths')2969and settings.has_key('change')):2970 change =int(settings['change']) +12971 p4Change =max(p4Change, change)29722973 depotPaths =sorted(settings['depot-paths'])2974if self.previousDepotPaths == []:2975 self.previousDepotPaths = depotPaths2976else:2977 paths = []2978for(prev, cur)inzip(self.previousDepotPaths, depotPaths):2979 prev_list = prev.split("/")2980 cur_list = cur.split("/")2981for i inrange(0,min(len(cur_list),len(prev_list))):2982if cur_list[i] <> prev_list[i]:2983 i = i -12984break29852986 paths.append("/".join(cur_list[:i +1]))29872988 self.previousDepotPaths = paths29892990if p4Change >0:2991 self.depotPaths =sorted(self.previousDepotPaths)2992 self.changeRange ="@%s,#head"% p4Change2993if not self.silent and not self.detectBranches:2994print"Performing incremental import into%sgit branch"% self.branch29952996# accept multiple ref name abbreviations:2997# refs/foo/bar/branch -> use it exactly2998# p4/branch -> prepend refs/remotes/ or refs/heads/2999# branch -> prepend refs/remotes/p4/ or refs/heads/p4/3000if not self.branch.startswith("refs/"):3001if self.importIntoRemotes:3002 prepend ="refs/remotes/"3003else:3004 prepend ="refs/heads/"3005if not self.branch.startswith("p4/"):3006 prepend +="p4/"3007 self.branch = prepend + self.branch30083009iflen(args) ==0and self.depotPaths:3010if not self.silent:3011print"Depot paths:%s"%' '.join(self.depotPaths)3012else:3013if self.depotPaths and self.depotPaths != args:3014print("previous import used depot path%sand now%swas specified. "3015"This doesn't work!"% (' '.join(self.depotPaths),3016' '.join(args)))3017 sys.exit(1)30183019 self.depotPaths =sorted(args)30203021 revision =""3022 self.users = {}30233024# Make sure no revision specifiers are used when --changesfile3025# is specified.3026 bad_changesfile =False3027iflen(self.changesFile) >0:3028for p in self.depotPaths:3029if p.find("@") >=0or p.find("#") >=0:3030 bad_changesfile =True3031break3032if bad_changesfile:3033die("Option --changesfile is incompatible with revision specifiers")30343035 newPaths = []3036for p in self.depotPaths:3037if p.find("@") != -1:3038 atIdx = p.index("@")3039 self.changeRange = p[atIdx:]3040if self.changeRange =="@all":3041 self.changeRange =""3042elif','not in self.changeRange:3043 revision = self.changeRange3044 self.changeRange =""3045 p = p[:atIdx]3046elif p.find("#") != -1:3047 hashIdx = p.index("#")3048 revision = p[hashIdx:]3049 p = p[:hashIdx]3050elif self.previousDepotPaths == []:3051# pay attention to changesfile, if given, else import3052# the entire p4 tree at the head revision3053iflen(self.changesFile) ==0:3054 revision ="#head"30553056 p = re.sub("\.\.\.$","", p)3057if not p.endswith("/"):3058 p +="/"30593060 newPaths.append(p)30613062 self.depotPaths = newPaths30633064# --detect-branches may change this for each branch3065 self.branchPrefixes = self.depotPaths30663067 self.loadUserMapFromCache()3068 self.labels = {}3069if self.detectLabels:3070 self.getLabels();30713072if self.detectBranches:3073## FIXME - what's a P4 projectName ?3074 self.projectName = self.guessProjectName()30753076if self.hasOrigin:3077 self.getBranchMappingFromGitBranches()3078else:3079 self.getBranchMapping()3080if self.verbose:3081print"p4-git branches:%s"% self.p4BranchesInGit3082print"initial parents:%s"% self.initialParents3083for b in self.p4BranchesInGit:3084if b !="master":30853086## FIXME3087 b = b[len(self.projectName):]3088 self.createdBranches.add(b)30893090 self.tz ="%+03d%02d"% (- time.timezone /3600, ((- time.timezone %3600) /60))30913092 self.importProcess = subprocess.Popen(["git","fast-import"],3093 stdin=subprocess.PIPE,3094 stdout=subprocess.PIPE,3095 stderr=subprocess.PIPE);3096 self.gitOutput = self.importProcess.stdout3097 self.gitStream = self.importProcess.stdin3098 self.gitError = self.importProcess.stderr30993100if revision:3101 self.importHeadRevision(revision)3102else:3103 changes = []31043105iflen(self.changesFile) >0:3106 output =open(self.changesFile).readlines()3107 changeSet =set()3108for line in output:3109 changeSet.add(int(line))31103111for change in changeSet:3112 changes.append(change)31133114 changes.sort()3115else:3116# catch "git p4 sync" with no new branches, in a repo that3117# does not have any existing p4 branches3118iflen(args) ==0:3119if not self.p4BranchesInGit:3120die("No remote p4 branches. Perhaps you never did\"git p4 clone\"in here.")31213122# The default branch is master, unless --branch is used to3123# specify something else. Make sure it exists, or complain3124# nicely about how to use --branch.3125if not self.detectBranches:3126if notbranch_exists(self.branch):3127if branch_arg_given:3128die("Error: branch%sdoes not exist."% self.branch)3129else:3130die("Error: no branch%s; perhaps specify one with --branch."%3131 self.branch)31323133if self.verbose:3134print"Getting p4 changes for%s...%s"% (', '.join(self.depotPaths),3135 self.changeRange)3136 changes =p4ChangesForPaths(self.depotPaths, self.changeRange, self.changes_block_size)31373138iflen(self.maxChanges) >0:3139 changes = changes[:min(int(self.maxChanges),len(changes))]31403141iflen(changes) ==0:3142if not self.silent:3143print"No changes to import!"3144else:3145if not self.silent and not self.detectBranches:3146print"Import destination:%s"% self.branch31473148 self.updatedBranches =set()31493150if not self.detectBranches:3151if args:3152# start a new branch3153 self.initialParent =""3154else:3155# build on a previous revision3156 self.initialParent =parseRevision(self.branch)31573158 self.importChanges(changes)31593160if not self.silent:3161print""3162iflen(self.updatedBranches) >0:3163 sys.stdout.write("Updated branches: ")3164for b in self.updatedBranches:3165 sys.stdout.write("%s"% b)3166 sys.stdout.write("\n")31673168ifgitConfigBool("git-p4.importLabels"):3169 self.importLabels =True31703171if self.importLabels:3172 p4Labels =getP4Labels(self.depotPaths)3173 gitTags =getGitTags()31743175 missingP4Labels = p4Labels - gitTags3176 self.importP4Labels(self.gitStream, missingP4Labels)31773178 self.gitStream.close()3179if self.importProcess.wait() !=0:3180die("fast-import failed:%s"% self.gitError.read())3181 self.gitOutput.close()3182 self.gitError.close()31833184# Cleanup temporary branches created during import3185if self.tempBranches != []:3186for branch in self.tempBranches:3187read_pipe("git update-ref -d%s"% branch)3188 os.rmdir(os.path.join(os.environ.get("GIT_DIR",".git"), self.tempBranchLocation))31893190# Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow3191# a convenient shortcut refname "p4".3192if self.importIntoRemotes:3193 head_ref = self.refPrefix +"HEAD"3194if notgitBranchExists(head_ref)andgitBranchExists(self.branch):3195system(["git","symbolic-ref", head_ref, self.branch])31963197return True31983199classP4Rebase(Command):3200def__init__(self):3201 Command.__init__(self)3202 self.options = [3203 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),3204]3205 self.importLabels =False3206 self.description = ("Fetches the latest revision from perforce and "3207+"rebases the current work (branch) against it")32083209defrun(self, args):3210 sync =P4Sync()3211 sync.importLabels = self.importLabels3212 sync.run([])32133214return self.rebase()32153216defrebase(self):3217if os.system("git update-index --refresh") !=0:3218die("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.");3219iflen(read_pipe("git diff-index HEAD --")) >0:3220die("You have uncommitted changes. Please commit them before rebasing or stash them away with git stash.");32213222[upstream, settings] =findUpstreamBranchPoint()3223iflen(upstream) ==0:3224die("Cannot find upstream branchpoint for rebase")32253226# the branchpoint may be p4/foo~3, so strip off the parent3227 upstream = re.sub("~[0-9]+$","", upstream)32283229print"Rebasing the current branch onto%s"% upstream3230 oldHead =read_pipe("git rev-parse HEAD").strip()3231system("git rebase%s"% upstream)3232system("git diff-tree --stat --summary -M%sHEAD --"% oldHead)3233return True32343235classP4Clone(P4Sync):3236def__init__(self):3237 P4Sync.__init__(self)3238 self.description ="Creates a new git repository and imports from Perforce into it"3239 self.usage ="usage: %prog [options] //depot/path[@revRange]"3240 self.options += [3241 optparse.make_option("--destination", dest="cloneDestination",3242 action='store', default=None,3243help="where to leave result of the clone"),3244 optparse.make_option("--bare", dest="cloneBare",3245 action="store_true", default=False),3246]3247 self.cloneDestination =None3248 self.needsGit =False3249 self.cloneBare =False32503251defdefaultDestination(self, args):3252## TODO: use common prefix of args?3253 depotPath = args[0]3254 depotDir = re.sub("(@[^@]*)$","", depotPath)3255 depotDir = re.sub("(#[^#]*)$","", depotDir)3256 depotDir = re.sub(r"\.\.\.$","", depotDir)3257 depotDir = re.sub(r"/$","", depotDir)3258return os.path.split(depotDir)[1]32593260defrun(self, args):3261iflen(args) <1:3262return False32633264if self.keepRepoPath and not self.cloneDestination:3265 sys.stderr.write("Must specify destination for --keep-path\n")3266 sys.exit(1)32673268 depotPaths = args32693270if not self.cloneDestination andlen(depotPaths) >1:3271 self.cloneDestination = depotPaths[-1]3272 depotPaths = depotPaths[:-1]32733274 self.cloneExclude = ["/"+p for p in self.cloneExclude]3275for p in depotPaths:3276if not p.startswith("//"):3277 sys.stderr.write('Depot paths must start with "//":%s\n'% p)3278return False32793280if not self.cloneDestination:3281 self.cloneDestination = self.defaultDestination(args)32823283print"Importing from%sinto%s"% (', '.join(depotPaths), self.cloneDestination)32843285if not os.path.exists(self.cloneDestination):3286 os.makedirs(self.cloneDestination)3287chdir(self.cloneDestination)32883289 init_cmd = ["git","init"]3290if self.cloneBare:3291 init_cmd.append("--bare")3292 retcode = subprocess.call(init_cmd)3293if retcode:3294raiseCalledProcessError(retcode, init_cmd)32953296if not P4Sync.run(self, depotPaths):3297return False32983299# create a master branch and check out a work tree3300ifgitBranchExists(self.branch):3301system(["git","branch","master", self.branch ])3302if not self.cloneBare:3303system(["git","checkout","-f"])3304else:3305print'Not checking out any branch, use ' \3306'"git checkout -q -b master <branch>"'33073308# auto-set this variable if invoked with --use-client-spec3309if self.useClientSpec_from_options:3310system("git config --bool git-p4.useclientspec true")33113312return True33133314classP4Branches(Command):3315def__init__(self):3316 Command.__init__(self)3317 self.options = [ ]3318 self.description = ("Shows the git branches that hold imports and their "3319+"corresponding perforce depot paths")3320 self.verbose =False33213322defrun(self, args):3323iforiginP4BranchesExist():3324createOrUpdateBranchesFromOrigin()33253326 cmdline ="git rev-parse --symbolic "3327 cmdline +=" --remotes"33283329for line inread_pipe_lines(cmdline):3330 line = line.strip()33313332if not line.startswith('p4/')or line =="p4/HEAD":3333continue3334 branch = line33353336 log =extractLogMessageFromGitCommit("refs/remotes/%s"% branch)3337 settings =extractSettingsGitLog(log)33383339print"%s<=%s(%s)"% (branch,",".join(settings["depot-paths"]), settings["change"])3340return True33413342classHelpFormatter(optparse.IndentedHelpFormatter):3343def__init__(self):3344 optparse.IndentedHelpFormatter.__init__(self)33453346defformat_description(self, description):3347if description:3348return description +"\n"3349else:3350return""33513352defprintUsage(commands):3353print"usage:%s<command> [options]"% sys.argv[0]3354print""3355print"valid commands:%s"%", ".join(commands)3356print""3357print"Try%s<command> --help for command specific help."% sys.argv[0]3358print""33593360commands = {3361"debug": P4Debug,3362"submit": P4Submit,3363"commit": P4Submit,3364"sync": P4Sync,3365"rebase": P4Rebase,3366"clone": P4Clone,3367"rollback": P4RollBack,3368"branches": P4Branches3369}337033713372defmain():3373iflen(sys.argv[1:]) ==0:3374printUsage(commands.keys())3375 sys.exit(2)33763377 cmdName = sys.argv[1]3378try:3379 klass = commands[cmdName]3380 cmd =klass()3381exceptKeyError:3382print"unknown command%s"% cmdName3383print""3384printUsage(commands.keys())3385 sys.exit(2)33863387 options = cmd.options3388 cmd.gitdir = os.environ.get("GIT_DIR",None)33893390 args = sys.argv[2:]33913392 options.append(optparse.make_option("--verbose","-v", dest="verbose", action="store_true"))3393if cmd.needsGit:3394 options.append(optparse.make_option("--git-dir", dest="gitdir"))33953396 parser = optparse.OptionParser(cmd.usage.replace("%prog","%prog "+ cmdName),3397 options,3398 description = cmd.description,3399 formatter =HelpFormatter())34003401(cmd, args) = parser.parse_args(sys.argv[2:], cmd);3402global verbose3403 verbose = cmd.verbose3404if cmd.needsGit:3405if cmd.gitdir ==None:3406 cmd.gitdir = os.path.abspath(".git")3407if notisValidGitDir(cmd.gitdir):3408 cmd.gitdir =read_pipe("git rev-parse --git-dir").strip()3409if os.path.exists(cmd.gitdir):3410 cdup =read_pipe("git rev-parse --show-cdup").strip()3411iflen(cdup) >0:3412chdir(cdup);34133414if notisValidGitDir(cmd.gitdir):3415ifisValidGitDir(cmd.gitdir +"/.git"):3416 cmd.gitdir +="/.git"3417else:3418die("fatal: cannot locate git repository at%s"% cmd.gitdir)34193420 os.environ["GIT_DIR"] = cmd.gitdir34213422if not cmd.run(args):3423 parser.print_help()3424 sys.exit(2)342534263427if __name__ =='__main__':3428main()