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 zipfile 26import zlib 27import ctypes 28 29try: 30from subprocess import CalledProcessError 31exceptImportError: 32# from python2.7:subprocess.py 33# Exception classes used by this module. 34classCalledProcessError(Exception): 35"""This exception is raised when a process run by check_call() returns 36 a non-zero exit status. The exit status will be stored in the 37 returncode attribute.""" 38def__init__(self, returncode, cmd): 39 self.returncode = returncode 40 self.cmd = cmd 41def__str__(self): 42return"Command '%s' returned non-zero exit status%d"% (self.cmd, self.returncode) 43 44verbose =False 45 46# Only labels/tags matching this will be imported/exported 47defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$' 48 49# Grab changes in blocks of this many revisions, unless otherwise requested 50defaultBlockSize =512 51 52defp4_build_cmd(cmd): 53"""Build a suitable p4 command line. 54 55 This consolidates building and returning a p4 command line into one 56 location. It means that hooking into the environment, or other configuration 57 can be done more easily. 58 """ 59 real_cmd = ["p4"] 60 61 user =gitConfig("git-p4.user") 62iflen(user) >0: 63 real_cmd += ["-u",user] 64 65 password =gitConfig("git-p4.password") 66iflen(password) >0: 67 real_cmd += ["-P", password] 68 69 port =gitConfig("git-p4.port") 70iflen(port) >0: 71 real_cmd += ["-p", port] 72 73 host =gitConfig("git-p4.host") 74iflen(host) >0: 75 real_cmd += ["-H", host] 76 77 client =gitConfig("git-p4.client") 78iflen(client) >0: 79 real_cmd += ["-c", client] 80 81 82ifisinstance(cmd,basestring): 83 real_cmd =' '.join(real_cmd) +' '+ cmd 84else: 85 real_cmd += cmd 86return real_cmd 87 88defchdir(path, is_client_path=False): 89"""Do chdir to the given path, and set the PWD environment 90 variable for use by P4. It does not look at getcwd() output. 91 Since we're not using the shell, it is necessary to set the 92 PWD environment variable explicitly. 93 94 Normally, expand the path to force it to be absolute. This 95 addresses the use of relative path names inside P4 settings, 96 e.g. P4CONFIG=.p4config. P4 does not simply open the filename 97 as given; it looks for .p4config using PWD. 98 99 If is_client_path, the path was handed to us directly by p4, 100 and may be a symbolic link. Do not call os.getcwd() in this 101 case, because it will cause p4 to think that PWD is not inside 102 the client path. 103 """ 104 105 os.chdir(path) 106if not is_client_path: 107 path = os.getcwd() 108 os.environ['PWD'] = path 109 110defcalcDiskFree(): 111"""Return free space in bytes on the disk of the given dirname.""" 112if platform.system() =='Windows': 113 free_bytes = ctypes.c_ulonglong(0) 114 ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(os.getcwd()),None,None, ctypes.pointer(free_bytes)) 115return free_bytes.value 116else: 117 st = os.statvfs(os.getcwd()) 118return st.f_bavail * st.f_frsize 119 120defdie(msg): 121if verbose: 122raiseException(msg) 123else: 124 sys.stderr.write(msg +"\n") 125 sys.exit(1) 126 127defwrite_pipe(c, stdin): 128if verbose: 129 sys.stderr.write('Writing pipe:%s\n'%str(c)) 130 131 expand =isinstance(c,basestring) 132 p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand) 133 pipe = p.stdin 134 val = pipe.write(stdin) 135 pipe.close() 136if p.wait(): 137die('Command failed:%s'%str(c)) 138 139return val 140 141defp4_write_pipe(c, stdin): 142 real_cmd =p4_build_cmd(c) 143returnwrite_pipe(real_cmd, stdin) 144 145defread_pipe(c, ignore_error=False): 146if verbose: 147 sys.stderr.write('Reading pipe:%s\n'%str(c)) 148 149 expand =isinstance(c,basestring) 150 p = subprocess.Popen(c, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=expand) 151(out, err) = p.communicate() 152if p.returncode !=0and not ignore_error: 153die('Command failed:%s\nError:%s'% (str(c), err)) 154return out 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, ignore_error=False): 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 and not ignore_error: 212raiseCalledProcessError(retcode, cmd) 213 214return retcode 215 216defp4_system(cmd): 217"""Specifically invoke p4 as the system command. """ 218 real_cmd =p4_build_cmd(cmd) 219 expand =isinstance(real_cmd, basestring) 220 retcode = subprocess.call(real_cmd, shell=expand) 221if retcode: 222raiseCalledProcessError(retcode, real_cmd) 223 224_p4_version_string =None 225defp4_version_string(): 226"""Read the version string, showing just the last line, which 227 hopefully is the interesting version bit. 228 229 $ p4 -V 230 Perforce - The Fast Software Configuration Management System. 231 Copyright 1995-2011 Perforce Software. All rights reserved. 232 Rev. P4/NTX86/2011.1/393975 (2011/12/16). 233 """ 234global _p4_version_string 235if not _p4_version_string: 236 a =p4_read_pipe_lines(["-V"]) 237 _p4_version_string = a[-1].rstrip() 238return _p4_version_string 239 240defp4_integrate(src, dest): 241p4_system(["integrate","-Dt",wildcard_encode(src),wildcard_encode(dest)]) 242 243defp4_sync(f, *options): 244p4_system(["sync"] +list(options) + [wildcard_encode(f)]) 245 246defp4_add(f): 247# forcibly add file names with wildcards 248ifwildcard_present(f): 249p4_system(["add","-f", f]) 250else: 251p4_system(["add", f]) 252 253defp4_delete(f): 254p4_system(["delete",wildcard_encode(f)]) 255 256defp4_edit(f, *options): 257p4_system(["edit"] +list(options) + [wildcard_encode(f)]) 258 259defp4_revert(f): 260p4_system(["revert",wildcard_encode(f)]) 261 262defp4_reopen(type, f): 263p4_system(["reopen","-t",type,wildcard_encode(f)]) 264 265defp4_move(src, dest): 266p4_system(["move","-k",wildcard_encode(src),wildcard_encode(dest)]) 267 268defp4_last_change(): 269 results =p4CmdList(["changes","-m","1"]) 270returnint(results[0]['change']) 271 272defp4_describe(change): 273"""Make sure it returns a valid result by checking for 274 the presence of field "time". Return a dict of the 275 results.""" 276 277 ds =p4CmdList(["describe","-s",str(change)]) 278iflen(ds) !=1: 279die("p4 describe -s%ddid not return 1 result:%s"% (change,str(ds))) 280 281 d = ds[0] 282 283if"p4ExitCode"in d: 284die("p4 describe -s%dexited with%d:%s"% (change, d["p4ExitCode"], 285str(d))) 286if"code"in d: 287if d["code"] =="error": 288die("p4 describe -s%dreturned error code:%s"% (change,str(d))) 289 290if"time"not in d: 291die("p4 describe -s%dreturned no\"time\":%s"% (change,str(d))) 292 293return d 294 295# 296# Canonicalize the p4 type and return a tuple of the 297# base type, plus any modifiers. See "p4 help filetypes" 298# for a list and explanation. 299# 300defsplit_p4_type(p4type): 301 302 p4_filetypes_historical = { 303"ctempobj":"binary+Sw", 304"ctext":"text+C", 305"cxtext":"text+Cx", 306"ktext":"text+k", 307"kxtext":"text+kx", 308"ltext":"text+F", 309"tempobj":"binary+FSw", 310"ubinary":"binary+F", 311"uresource":"resource+F", 312"uxbinary":"binary+Fx", 313"xbinary":"binary+x", 314"xltext":"text+Fx", 315"xtempobj":"binary+Swx", 316"xtext":"text+x", 317"xunicode":"unicode+x", 318"xutf16":"utf16+x", 319} 320if p4type in p4_filetypes_historical: 321 p4type = p4_filetypes_historical[p4type] 322 mods ="" 323 s = p4type.split("+") 324 base = s[0] 325 mods ="" 326iflen(s) >1: 327 mods = s[1] 328return(base, mods) 329 330# 331# return the raw p4 type of a file (text, text+ko, etc) 332# 333defp4_type(f): 334 results =p4CmdList(["fstat","-T","headType",wildcard_encode(f)]) 335return results[0]['headType'] 336 337# 338# Given a type base and modifier, return a regexp matching 339# the keywords that can be expanded in the file 340# 341defp4_keywords_regexp_for_type(base, type_mods): 342if base in("text","unicode","binary"): 343 kwords =None 344if"ko"in type_mods: 345 kwords ='Id|Header' 346elif"k"in type_mods: 347 kwords ='Id|Header|Author|Date|DateTime|Change|File|Revision' 348else: 349return None 350 pattern = r""" 351 \$ # Starts with a dollar, followed by... 352 (%s) # one of the keywords, followed by... 353 (:[^$\n]+)? # possibly an old expansion, followed by... 354 \$ # another dollar 355 """% kwords 356return pattern 357else: 358return None 359 360# 361# Given a file, return a regexp matching the possible 362# RCS keywords that will be expanded, or None for files 363# with kw expansion turned off. 364# 365defp4_keywords_regexp_for_file(file): 366if not os.path.exists(file): 367return None 368else: 369(type_base, type_mods) =split_p4_type(p4_type(file)) 370returnp4_keywords_regexp_for_type(type_base, type_mods) 371 372defsetP4ExecBit(file, mode): 373# Reopens an already open file and changes the execute bit to match 374# the execute bit setting in the passed in mode. 375 376 p4Type ="+x" 377 378if notisModeExec(mode): 379 p4Type =getP4OpenedType(file) 380 p4Type = re.sub('^([cku]?)x(.*)','\\1\\2', p4Type) 381 p4Type = re.sub('(.*?\+.*?)x(.*?)','\\1\\2', p4Type) 382if p4Type[-1] =="+": 383 p4Type = p4Type[0:-1] 384 385p4_reopen(p4Type,file) 386 387defgetP4OpenedType(file): 388# Returns the perforce file type for the given file. 389 390 result =p4_read_pipe(["opened",wildcard_encode(file)]) 391 match = re.match(".*\((.+)\)( \*exclusive\*)?\r?$", result) 392if match: 393return match.group(1) 394else: 395die("Could not determine file type for%s(result: '%s')"% (file, result)) 396 397# Return the set of all p4 labels 398defgetP4Labels(depotPaths): 399 labels =set() 400ifisinstance(depotPaths,basestring): 401 depotPaths = [depotPaths] 402 403for l inp4CmdList(["labels"] + ["%s..."% p for p in depotPaths]): 404 label = l['label'] 405 labels.add(label) 406 407return labels 408 409# Return the set of all git tags 410defgetGitTags(): 411 gitTags =set() 412for line inread_pipe_lines(["git","tag"]): 413 tag = line.strip() 414 gitTags.add(tag) 415return gitTags 416 417defdiffTreePattern(): 418# This is a simple generator for the diff tree regex pattern. This could be 419# a class variable if this and parseDiffTreeEntry were a part of a class. 420 pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)') 421while True: 422yield pattern 423 424defparseDiffTreeEntry(entry): 425"""Parses a single diff tree entry into its component elements. 426 427 See git-diff-tree(1) manpage for details about the format of the diff 428 output. This method returns a dictionary with the following elements: 429 430 src_mode - The mode of the source file 431 dst_mode - The mode of the destination file 432 src_sha1 - The sha1 for the source file 433 dst_sha1 - The sha1 fr the destination file 434 status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc) 435 status_score - The score for the status (applicable for 'C' and 'R' 436 statuses). This is None if there is no score. 437 src - The path for the source file. 438 dst - The path for the destination file. This is only present for 439 copy or renames. If it is not present, this is None. 440 441 If the pattern is not matched, None is returned.""" 442 443 match =diffTreePattern().next().match(entry) 444if match: 445return{ 446'src_mode': match.group(1), 447'dst_mode': match.group(2), 448'src_sha1': match.group(3), 449'dst_sha1': match.group(4), 450'status': match.group(5), 451'status_score': match.group(6), 452'src': match.group(7), 453'dst': match.group(10) 454} 455return None 456 457defisModeExec(mode): 458# Returns True if the given git mode represents an executable file, 459# otherwise False. 460return mode[-3:] =="755" 461 462defisModeExecChanged(src_mode, dst_mode): 463returnisModeExec(src_mode) !=isModeExec(dst_mode) 464 465defp4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None): 466 467ifisinstance(cmd,basestring): 468 cmd ="-G "+ cmd 469 expand =True 470else: 471 cmd = ["-G"] + cmd 472 expand =False 473 474 cmd =p4_build_cmd(cmd) 475if verbose: 476 sys.stderr.write("Opening pipe:%s\n"%str(cmd)) 477 478# Use a temporary file to avoid deadlocks without 479# subprocess.communicate(), which would put another copy 480# of stdout into memory. 481 stdin_file =None 482if stdin is not None: 483 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode) 484ifisinstance(stdin,basestring): 485 stdin_file.write(stdin) 486else: 487for i in stdin: 488 stdin_file.write(i +'\n') 489 stdin_file.flush() 490 stdin_file.seek(0) 491 492 p4 = subprocess.Popen(cmd, 493 shell=expand, 494 stdin=stdin_file, 495 stdout=subprocess.PIPE) 496 497 result = [] 498try: 499while True: 500 entry = marshal.load(p4.stdout) 501if cb is not None: 502cb(entry) 503else: 504 result.append(entry) 505exceptEOFError: 506pass 507 exitCode = p4.wait() 508if exitCode !=0: 509 entry = {} 510 entry["p4ExitCode"] = exitCode 511 result.append(entry) 512 513return result 514 515defp4Cmd(cmd): 516list=p4CmdList(cmd) 517 result = {} 518for entry inlist: 519 result.update(entry) 520return result; 521 522defp4Where(depotPath): 523if not depotPath.endswith("/"): 524 depotPath +="/" 525 depotPathLong = depotPath +"..." 526 outputList =p4CmdList(["where", depotPathLong]) 527 output =None 528for entry in outputList: 529if"depotFile"in entry: 530# Search for the base client side depot path, as long as it starts with the branch's P4 path. 531# The base path always ends with "/...". 532if entry["depotFile"].find(depotPath) ==0and entry["depotFile"][-4:] =="/...": 533 output = entry 534break 535elif"data"in entry: 536 data = entry.get("data") 537 space = data.find(" ") 538if data[:space] == depotPath: 539 output = entry 540break 541if output ==None: 542return"" 543if output["code"] =="error": 544return"" 545 clientPath ="" 546if"path"in output: 547 clientPath = output.get("path") 548elif"data"in output: 549 data = output.get("data") 550 lastSpace = data.rfind(" ") 551 clientPath = data[lastSpace +1:] 552 553if clientPath.endswith("..."): 554 clientPath = clientPath[:-3] 555return clientPath 556 557defcurrentGitBranch(): 558 retcode =system(["git","symbolic-ref","-q","HEAD"], ignore_error=True) 559if retcode !=0: 560# on a detached head 561return None 562else: 563returnread_pipe(["git","name-rev","HEAD"]).split(" ")[1].strip() 564 565defisValidGitDir(path): 566if(os.path.exists(path +"/HEAD") 567and os.path.exists(path +"/refs")and os.path.exists(path +"/objects")): 568return True; 569return False 570 571defparseRevision(ref): 572returnread_pipe("git rev-parse%s"% ref).strip() 573 574defbranchExists(ref): 575 rev =read_pipe(["git","rev-parse","-q","--verify", ref], 576 ignore_error=True) 577returnlen(rev) >0 578 579defextractLogMessageFromGitCommit(commit): 580 logMessage ="" 581 582## fixme: title is first line of commit, not 1st paragraph. 583 foundTitle =False 584for log inread_pipe_lines("git cat-file commit%s"% commit): 585if not foundTitle: 586iflen(log) ==1: 587 foundTitle =True 588continue 589 590 logMessage += log 591return logMessage 592 593defextractSettingsGitLog(log): 594 values = {} 595for line in log.split("\n"): 596 line = line.strip() 597 m = re.search(r"^ *\[git-p4: (.*)\]$", line) 598if not m: 599continue 600 601 assignments = m.group(1).split(':') 602for a in assignments: 603 vals = a.split('=') 604 key = vals[0].strip() 605 val = ('='.join(vals[1:])).strip() 606if val.endswith('\"')and val.startswith('"'): 607 val = val[1:-1] 608 609 values[key] = val 610 611 paths = values.get("depot-paths") 612if not paths: 613 paths = values.get("depot-path") 614if paths: 615 values['depot-paths'] = paths.split(',') 616return values 617 618defgitBranchExists(branch): 619 proc = subprocess.Popen(["git","rev-parse", branch], 620 stderr=subprocess.PIPE, stdout=subprocess.PIPE); 621return proc.wait() ==0; 622 623_gitConfig = {} 624 625defgitConfig(key, typeSpecifier=None): 626if not _gitConfig.has_key(key): 627 cmd = ["git","config"] 628if typeSpecifier: 629 cmd += [ typeSpecifier ] 630 cmd += [ key ] 631 s =read_pipe(cmd, ignore_error=True) 632 _gitConfig[key] = s.strip() 633return _gitConfig[key] 634 635defgitConfigBool(key): 636"""Return a bool, using git config --bool. It is True only if the 637 variable is set to true, and False if set to false or not present 638 in the config.""" 639 640if not _gitConfig.has_key(key): 641 _gitConfig[key] =gitConfig(key,'--bool') =="true" 642return _gitConfig[key] 643 644defgitConfigInt(key): 645if not _gitConfig.has_key(key): 646 cmd = ["git","config","--int", key ] 647 s =read_pipe(cmd, ignore_error=True) 648 v = s.strip() 649try: 650 _gitConfig[key] =int(gitConfig(key,'--int')) 651exceptValueError: 652 _gitConfig[key] =None 653return _gitConfig[key] 654 655defgitConfigList(key): 656if not _gitConfig.has_key(key): 657 s =read_pipe(["git","config","--get-all", key], ignore_error=True) 658 _gitConfig[key] = s.strip().split(os.linesep) 659if _gitConfig[key] == ['']: 660 _gitConfig[key] = [] 661return _gitConfig[key] 662 663defp4BranchesInGit(branchesAreInRemotes=True): 664"""Find all the branches whose names start with "p4/", looking 665 in remotes or heads as specified by the argument. Return 666 a dictionary of{ branch: revision }for each one found. 667 The branch names are the short names, without any 668 "p4/" prefix.""" 669 670 branches = {} 671 672 cmdline ="git rev-parse --symbolic " 673if branchesAreInRemotes: 674 cmdline +="--remotes" 675else: 676 cmdline +="--branches" 677 678for line inread_pipe_lines(cmdline): 679 line = line.strip() 680 681# only import to p4/ 682if not line.startswith('p4/'): 683continue 684# special symbolic ref to p4/master 685if line =="p4/HEAD": 686continue 687 688# strip off p4/ prefix 689 branch = line[len("p4/"):] 690 691 branches[branch] =parseRevision(line) 692 693return branches 694 695defbranch_exists(branch): 696"""Make sure that the given ref name really exists.""" 697 698 cmd = ["git","rev-parse","--symbolic","--verify", branch ] 699 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 700 out, _ = p.communicate() 701if p.returncode: 702return False 703# expect exactly one line of output: the branch name 704return out.rstrip() == branch 705 706deffindUpstreamBranchPoint(head ="HEAD"): 707 branches =p4BranchesInGit() 708# map from depot-path to branch name 709 branchByDepotPath = {} 710for branch in branches.keys(): 711 tip = branches[branch] 712 log =extractLogMessageFromGitCommit(tip) 713 settings =extractSettingsGitLog(log) 714if settings.has_key("depot-paths"): 715 paths =",".join(settings["depot-paths"]) 716 branchByDepotPath[paths] ="remotes/p4/"+ branch 717 718 settings =None 719 parent =0 720while parent <65535: 721 commit = head +"~%s"% parent 722 log =extractLogMessageFromGitCommit(commit) 723 settings =extractSettingsGitLog(log) 724if settings.has_key("depot-paths"): 725 paths =",".join(settings["depot-paths"]) 726if branchByDepotPath.has_key(paths): 727return[branchByDepotPath[paths], settings] 728 729 parent = parent +1 730 731return["", settings] 732 733defcreateOrUpdateBranchesFromOrigin(localRefPrefix ="refs/remotes/p4/", silent=True): 734if not silent: 735print("Creating/updating branch(es) in%sbased on origin branch(es)" 736% localRefPrefix) 737 738 originPrefix ="origin/p4/" 739 740for line inread_pipe_lines("git rev-parse --symbolic --remotes"): 741 line = line.strip() 742if(not line.startswith(originPrefix))or line.endswith("HEAD"): 743continue 744 745 headName = line[len(originPrefix):] 746 remoteHead = localRefPrefix + headName 747 originHead = line 748 749 original =extractSettingsGitLog(extractLogMessageFromGitCommit(originHead)) 750if(not original.has_key('depot-paths') 751or not original.has_key('change')): 752continue 753 754 update =False 755if notgitBranchExists(remoteHead): 756if verbose: 757print"creating%s"% remoteHead 758 update =True 759else: 760 settings =extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead)) 761if settings.has_key('change') >0: 762if settings['depot-paths'] == original['depot-paths']: 763 originP4Change =int(original['change']) 764 p4Change =int(settings['change']) 765if originP4Change > p4Change: 766print("%s(%s) is newer than%s(%s). " 767"Updating p4 branch from origin." 768% (originHead, originP4Change, 769 remoteHead, p4Change)) 770 update =True 771else: 772print("Ignoring:%swas imported from%swhile " 773"%swas imported from%s" 774% (originHead,','.join(original['depot-paths']), 775 remoteHead,','.join(settings['depot-paths']))) 776 777if update: 778system("git update-ref%s %s"% (remoteHead, originHead)) 779 780deforiginP4BranchesExist(): 781returngitBranchExists("origin")orgitBranchExists("origin/p4")orgitBranchExists("origin/p4/master") 782 783 784defp4ParseNumericChangeRange(parts): 785 changeStart =int(parts[0][1:]) 786if parts[1] =='#head': 787 changeEnd =p4_last_change() 788else: 789 changeEnd =int(parts[1]) 790 791return(changeStart, changeEnd) 792 793defchooseBlockSize(blockSize): 794if blockSize: 795return blockSize 796else: 797return defaultBlockSize 798 799defp4ChangesForPaths(depotPaths, changeRange, requestedBlockSize): 800assert depotPaths 801 802# Parse the change range into start and end. Try to find integer 803# revision ranges as these can be broken up into blocks to avoid 804# hitting server-side limits (maxrows, maxscanresults). But if 805# that doesn't work, fall back to using the raw revision specifier 806# strings, without using block mode. 807 808if changeRange is None or changeRange =='': 809 changeStart =1 810 changeEnd =p4_last_change() 811 block_size =chooseBlockSize(requestedBlockSize) 812else: 813 parts = changeRange.split(',') 814assertlen(parts) ==2 815try: 816(changeStart, changeEnd) =p4ParseNumericChangeRange(parts) 817 block_size =chooseBlockSize(requestedBlockSize) 818except: 819 changeStart = parts[0][1:] 820 changeEnd = parts[1] 821if requestedBlockSize: 822die("cannot use --changes-block-size with non-numeric revisions") 823 block_size =None 824 825 changes = [] 826 827# Retrieve changes a block at a time, to prevent running 828# into a MaxResults/MaxScanRows error from the server. 829 830while True: 831 cmd = ['changes'] 832 833if block_size: 834 end =min(changeEnd, changeStart + block_size) 835 revisionRange ="%d,%d"% (changeStart, end) 836else: 837 revisionRange ="%s,%s"% (changeStart, changeEnd) 838 839for p in depotPaths: 840 cmd += ["%s...@%s"% (p, revisionRange)] 841 842# Insert changes in chronological order 843for line inreversed(p4_read_pipe_lines(cmd)): 844 changes.append(int(line.split(" ")[1])) 845 846if not block_size: 847break 848 849if end >= changeEnd: 850break 851 852 changeStart = end +1 853 854 changes =sorted(changes) 855return changes 856 857defp4PathStartsWith(path, prefix): 858# This method tries to remedy a potential mixed-case issue: 859# 860# If UserA adds //depot/DirA/file1 861# and UserB adds //depot/dira/file2 862# 863# we may or may not have a problem. If you have core.ignorecase=true, 864# we treat DirA and dira as the same directory 865ifgitConfigBool("core.ignorecase"): 866return path.lower().startswith(prefix.lower()) 867return path.startswith(prefix) 868 869defgetClientSpec(): 870"""Look at the p4 client spec, create a View() object that contains 871 all the mappings, and return it.""" 872 873 specList =p4CmdList("client -o") 874iflen(specList) !=1: 875die('Output from "client -o" is%dlines, expecting 1'% 876len(specList)) 877 878# dictionary of all client parameters 879 entry = specList[0] 880 881# the //client/ name 882 client_name = entry["Client"] 883 884# just the keys that start with "View" 885 view_keys = [ k for k in entry.keys()if k.startswith("View") ] 886 887# hold this new View 888 view =View(client_name) 889 890# append the lines, in order, to the view 891for view_num inrange(len(view_keys)): 892 k ="View%d"% view_num 893if k not in view_keys: 894die("Expected view key%smissing"% k) 895 view.append(entry[k]) 896 897return view 898 899defgetClientRoot(): 900"""Grab the client directory.""" 901 902 output =p4CmdList("client -o") 903iflen(output) !=1: 904die('Output from "client -o" is%dlines, expecting 1'%len(output)) 905 906 entry = output[0] 907if"Root"not in entry: 908die('Client has no "Root"') 909 910return entry["Root"] 911 912# 913# P4 wildcards are not allowed in filenames. P4 complains 914# if you simply add them, but you can force it with "-f", in 915# which case it translates them into %xx encoding internally. 916# 917defwildcard_decode(path): 918# Search for and fix just these four characters. Do % last so 919# that fixing it does not inadvertently create new %-escapes. 920# Cannot have * in a filename in windows; untested as to 921# what p4 would do in such a case. 922if not platform.system() =="Windows": 923 path = path.replace("%2A","*") 924 path = path.replace("%23","#") \ 925.replace("%40","@") \ 926.replace("%25","%") 927return path 928 929defwildcard_encode(path): 930# do % first to avoid double-encoding the %s introduced here 931 path = path.replace("%","%25") \ 932.replace("*","%2A") \ 933.replace("#","%23") \ 934.replace("@","%40") 935return path 936 937defwildcard_present(path): 938 m = re.search("[*#@%]", path) 939return m is not None 940 941classLargeFileSystem(object): 942"""Base class for large file system support.""" 943 944def__init__(self, writeToGitStream): 945 self.largeFiles =set() 946 self.writeToGitStream = writeToGitStream 947 948defgeneratePointer(self, cloneDestination, contentFile): 949"""Return the content of a pointer file that is stored in Git instead of 950 the actual content.""" 951assert False,"Method 'generatePointer' required in "+ self.__class__.__name__ 952 953defpushFile(self, localLargeFile): 954"""Push the actual content which is not stored in the Git repository to 955 a server.""" 956assert False,"Method 'pushFile' required in "+ self.__class__.__name__ 957 958defhasLargeFileExtension(self, relPath): 959returnreduce( 960lambda a, b: a or b, 961[relPath.endswith('.'+ e)for e ingitConfigList('git-p4.largeFileExtensions')], 962False 963) 964 965defgenerateTempFile(self, contents): 966 contentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False) 967for d in contents: 968 contentFile.write(d) 969 contentFile.close() 970return contentFile.name 971 972defexceedsLargeFileThreshold(self, relPath, contents): 973ifgitConfigInt('git-p4.largeFileThreshold'): 974 contentsSize =sum(len(d)for d in contents) 975if contentsSize >gitConfigInt('git-p4.largeFileThreshold'): 976return True 977ifgitConfigInt('git-p4.largeFileCompressedThreshold'): 978 contentsSize =sum(len(d)for d in contents) 979if contentsSize <=gitConfigInt('git-p4.largeFileCompressedThreshold'): 980return False 981 contentTempFile = self.generateTempFile(contents) 982 compressedContentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False) 983 zf = zipfile.ZipFile(compressedContentFile.name, mode='w') 984 zf.write(contentTempFile, compress_type=zipfile.ZIP_DEFLATED) 985 zf.close() 986 compressedContentsSize = zf.infolist()[0].compress_size 987 os.remove(contentTempFile) 988 os.remove(compressedContentFile.name) 989if compressedContentsSize >gitConfigInt('git-p4.largeFileCompressedThreshold'): 990return True 991return False 992 993defaddLargeFile(self, relPath): 994 self.largeFiles.add(relPath) 995 996defremoveLargeFile(self, relPath): 997 self.largeFiles.remove(relPath) 998 999defisLargeFile(self, relPath):1000return relPath in self.largeFiles10011002defprocessContent(self, git_mode, relPath, contents):1003"""Processes the content of git fast import. This method decides if a1004 file is stored in the large file system and handles all necessary1005 steps."""1006if self.exceedsLargeFileThreshold(relPath, contents)or self.hasLargeFileExtension(relPath):1007 contentTempFile = self.generateTempFile(contents)1008(git_mode, contents, localLargeFile) = self.generatePointer(contentTempFile)10091010# Move temp file to final location in large file system1011 largeFileDir = os.path.dirname(localLargeFile)1012if not os.path.isdir(largeFileDir):1013 os.makedirs(largeFileDir)1014 shutil.move(contentTempFile, localLargeFile)1015 self.addLargeFile(relPath)1016ifgitConfigBool('git-p4.largeFilePush'):1017 self.pushFile(localLargeFile)1018if verbose:1019 sys.stderr.write("%smoved to large file system (%s)\n"% (relPath, localLargeFile))1020return(git_mode, contents)10211022classMockLFS(LargeFileSystem):1023"""Mock large file system for testing."""10241025defgeneratePointer(self, contentFile):1026"""The pointer content is the original content prefixed with "pointer-".1027 The local filename of the large file storage is derived from the file content.1028 """1029withopen(contentFile,'r')as f:1030 content =next(f)1031 gitMode ='100644'1032 pointerContents ='pointer-'+ content1033 localLargeFile = os.path.join(os.getcwd(),'.git','mock-storage','local', content[:-1])1034return(gitMode, pointerContents, localLargeFile)10351036defpushFile(self, localLargeFile):1037"""The remote filename of the large file storage is the same as the local1038 one but in a different directory.1039 """1040 remotePath = os.path.join(os.path.dirname(localLargeFile),'..','remote')1041if not os.path.exists(remotePath):1042 os.makedirs(remotePath)1043 shutil.copyfile(localLargeFile, os.path.join(remotePath, os.path.basename(localLargeFile)))10441045classGitLFS(LargeFileSystem):1046"""Git LFS as backend for the git-p4 large file system.1047 See https://git-lfs.github.com/ for details."""10481049def__init__(self, *args):1050 LargeFileSystem.__init__(self, *args)1051 self.baseGitAttributes = []10521053defgeneratePointer(self, contentFile):1054"""Generate a Git LFS pointer for the content. Return LFS Pointer file1055 mode and content which is stored in the Git repository instead of1056 the actual content. Return also the new location of the actual1057 content.1058 """1059 pointerProcess = subprocess.Popen(1060['git','lfs','pointer','--file='+ contentFile],1061 stdout=subprocess.PIPE1062)1063 pointerFile = pointerProcess.stdout.read()1064if pointerProcess.wait():1065 os.remove(contentFile)1066die('git-lfs pointer command failed. Did you install the extension?')10671068# Git LFS removed the preamble in the output of the 'pointer' command1069# starting from version 1.2.0. Check for the preamble here to support1070# earlier versions.1071# c.f. https://github.com/github/git-lfs/commit/da2935d9a739592bc775c98d8ef4df9c72ea3b431072if pointerFile.startswith('Git LFS pointer for'):1073 pointerFile = re.sub(r'Git LFS pointer for.*\n\n','', pointerFile)10741075 oid = re.search(r'^oid \w+:(\w+)', pointerFile, re.MULTILINE).group(1)1076 localLargeFile = os.path.join(1077 os.getcwd(),1078'.git','lfs','objects', oid[:2], oid[2:4],1079 oid,1080)1081# LFS Spec states that pointer files should not have the executable bit set.1082 gitMode ='100644'1083return(gitMode, pointerFile, localLargeFile)10841085defpushFile(self, localLargeFile):1086 uploadProcess = subprocess.Popen(1087['git','lfs','push','--object-id','origin', os.path.basename(localLargeFile)]1088)1089if uploadProcess.wait():1090die('git-lfs push command failed. Did you define a remote?')10911092defgenerateGitAttributes(self):1093return(1094 self.baseGitAttributes +1095[1096'\n',1097'#\n',1098'# Git LFS (see https://git-lfs.github.com/)\n',1099'#\n',1100] +1101['*.'+ f.replace(' ','[[:space:]]') +' filter=lfs -text\n'1102for f insorted(gitConfigList('git-p4.largeFileExtensions'))1103] +1104['/'+ f.replace(' ','[[:space:]]') +' filter=lfs -text\n'1105for f insorted(self.largeFiles)if not self.hasLargeFileExtension(f)1106]1107)11081109defaddLargeFile(self, relPath):1110 LargeFileSystem.addLargeFile(self, relPath)1111 self.writeToGitStream('100644','.gitattributes', self.generateGitAttributes())11121113defremoveLargeFile(self, relPath):1114 LargeFileSystem.removeLargeFile(self, relPath)1115 self.writeToGitStream('100644','.gitattributes', self.generateGitAttributes())11161117defprocessContent(self, git_mode, relPath, contents):1118if relPath =='.gitattributes':1119 self.baseGitAttributes = contents1120return(git_mode, self.generateGitAttributes())1121else:1122return LargeFileSystem.processContent(self, git_mode, relPath, contents)11231124class Command:1125def__init__(self):1126 self.usage ="usage: %prog [options]"1127 self.needsGit =True1128 self.verbose =False11291130class P4UserMap:1131def__init__(self):1132 self.userMapFromPerforceServer =False1133 self.myP4UserId =None11341135defp4UserId(self):1136if self.myP4UserId:1137return self.myP4UserId11381139 results =p4CmdList("user -o")1140for r in results:1141if r.has_key('User'):1142 self.myP4UserId = r['User']1143return r['User']1144die("Could not find your p4 user id")11451146defp4UserIsMe(self, p4User):1147# return True if the given p4 user is actually me1148 me = self.p4UserId()1149if not p4User or p4User != me:1150return False1151else:1152return True11531154defgetUserCacheFilename(self):1155 home = os.environ.get("HOME", os.environ.get("USERPROFILE"))1156return home +"/.gitp4-usercache.txt"11571158defgetUserMapFromPerforceServer(self):1159if self.userMapFromPerforceServer:1160return1161 self.users = {}1162 self.emails = {}11631164for output inp4CmdList("users"):1165if not output.has_key("User"):1166continue1167 self.users[output["User"]] = output["FullName"] +" <"+ output["Email"] +">"1168 self.emails[output["Email"]] = output["User"]116911701171 s =''1172for(key, val)in self.users.items():1173 s +="%s\t%s\n"% (key.expandtabs(1), val.expandtabs(1))11741175open(self.getUserCacheFilename(),"wb").write(s)1176 self.userMapFromPerforceServer =True11771178defloadUserMapFromCache(self):1179 self.users = {}1180 self.userMapFromPerforceServer =False1181try:1182 cache =open(self.getUserCacheFilename(),"rb")1183 lines = cache.readlines()1184 cache.close()1185for line in lines:1186 entry = line.strip().split("\t")1187 self.users[entry[0]] = entry[1]1188exceptIOError:1189 self.getUserMapFromPerforceServer()11901191classP4Debug(Command):1192def__init__(self):1193 Command.__init__(self)1194 self.options = []1195 self.description ="A tool to debug the output of p4 -G."1196 self.needsGit =False11971198defrun(self, args):1199 j =01200for output inp4CmdList(args):1201print'Element:%d'% j1202 j +=11203print output1204return True12051206classP4RollBack(Command):1207def__init__(self):1208 Command.__init__(self)1209 self.options = [1210 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")1211]1212 self.description ="A tool to debug the multi-branch import. Don't use :)"1213 self.rollbackLocalBranches =False12141215defrun(self, args):1216iflen(args) !=1:1217return False1218 maxChange =int(args[0])12191220if"p4ExitCode"inp4Cmd("changes -m 1"):1221die("Problems executing p4");12221223if self.rollbackLocalBranches:1224 refPrefix ="refs/heads/"1225 lines =read_pipe_lines("git rev-parse --symbolic --branches")1226else:1227 refPrefix ="refs/remotes/"1228 lines =read_pipe_lines("git rev-parse --symbolic --remotes")12291230for line in lines:1231if self.rollbackLocalBranches or(line.startswith("p4/")and line !="p4/HEAD\n"):1232 line = line.strip()1233 ref = refPrefix + line1234 log =extractLogMessageFromGitCommit(ref)1235 settings =extractSettingsGitLog(log)12361237 depotPaths = settings['depot-paths']1238 change = settings['change']12391240 changed =False12411242iflen(p4Cmd("changes -m 1 "+' '.join(['%s...@%s'% (p, maxChange)1243for p in depotPaths]))) ==0:1244print"Branch%sdid not exist at change%s, deleting."% (ref, maxChange)1245system("git update-ref -d%s`git rev-parse%s`"% (ref, ref))1246continue12471248while change andint(change) > maxChange:1249 changed =True1250if self.verbose:1251print"%sis at%s; rewinding towards%s"% (ref, change, maxChange)1252system("git update-ref%s\"%s^\""% (ref, ref))1253 log =extractLogMessageFromGitCommit(ref)1254 settings =extractSettingsGitLog(log)125512561257 depotPaths = settings['depot-paths']1258 change = settings['change']12591260if changed:1261print"%srewound to%s"% (ref, change)12621263return True12641265classP4Submit(Command, P4UserMap):12661267 conflict_behavior_choices = ("ask","skip","quit")12681269def__init__(self):1270 Command.__init__(self)1271 P4UserMap.__init__(self)1272 self.options = [1273 optparse.make_option("--origin", dest="origin"),1274 optparse.make_option("-M", dest="detectRenames", action="store_true"),1275# preserve the user, requires relevant p4 permissions1276 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),1277 optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),1278 optparse.make_option("--dry-run","-n", dest="dry_run", action="store_true"),1279 optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),1280 optparse.make_option("--conflict", dest="conflict_behavior",1281 choices=self.conflict_behavior_choices),1282 optparse.make_option("--branch", dest="branch"),1283]1284 self.description ="Submit changes from git to the perforce depot."1285 self.usage +=" [name of git branch to submit into perforce depot]"1286 self.origin =""1287 self.detectRenames =False1288 self.preserveUser =gitConfigBool("git-p4.preserveUser")1289 self.dry_run =False1290 self.prepare_p4_only =False1291 self.conflict_behavior =None1292 self.isWindows = (platform.system() =="Windows")1293 self.exportLabels =False1294 self.p4HasMoveCommand =p4_has_move_command()1295 self.branch =None12961297ifgitConfig('git-p4.largeFileSystem'):1298die("Large file system not supported for git-p4 submit command. Please remove it from config.")12991300defcheck(self):1301iflen(p4CmdList("opened ...")) >0:1302die("You have files opened with perforce! Close them before starting the sync.")13031304defseparate_jobs_from_description(self, message):1305"""Extract and return a possible Jobs field in the commit1306 message. It goes into a separate section in the p4 change1307 specification.13081309 A jobs line starts with "Jobs:" and looks like a new field1310 in a form. Values are white-space separated on the same1311 line or on following lines that start with a tab.13121313 This does not parse and extract the full git commit message1314 like a p4 form. It just sees the Jobs: line as a marker1315 to pass everything from then on directly into the p4 form,1316 but outside the description section.13171318 Return a tuple (stripped log message, jobs string)."""13191320 m = re.search(r'^Jobs:', message, re.MULTILINE)1321if m is None:1322return(message,None)13231324 jobtext = message[m.start():]1325 stripped_message = message[:m.start()].rstrip()1326return(stripped_message, jobtext)13271328defprepareLogMessage(self, template, message, jobs):1329"""Edits the template returned from "p4 change -o" to insert1330 the message in the Description field, and the jobs text in1331 the Jobs field."""1332 result =""13331334 inDescriptionSection =False13351336for line in template.split("\n"):1337if line.startswith("#"):1338 result += line +"\n"1339continue13401341if inDescriptionSection:1342if line.startswith("Files:")or line.startswith("Jobs:"):1343 inDescriptionSection =False1344# insert Jobs section1345if jobs:1346 result += jobs +"\n"1347else:1348continue1349else:1350if line.startswith("Description:"):1351 inDescriptionSection =True1352 line +="\n"1353for messageLine in message.split("\n"):1354 line +="\t"+ messageLine +"\n"13551356 result += line +"\n"13571358return result13591360defpatchRCSKeywords(self,file, pattern):1361# Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern1362(handle, outFileName) = tempfile.mkstemp(dir='.')1363try:1364 outFile = os.fdopen(handle,"w+")1365 inFile =open(file,"r")1366 regexp = re.compile(pattern, re.VERBOSE)1367for line in inFile.readlines():1368 line = regexp.sub(r'$\1$', line)1369 outFile.write(line)1370 inFile.close()1371 outFile.close()1372# Forcibly overwrite the original file1373 os.unlink(file)1374 shutil.move(outFileName,file)1375except:1376# cleanup our temporary file1377 os.unlink(outFileName)1378print"Failed to strip RCS keywords in%s"%file1379raise13801381print"Patched up RCS keywords in%s"%file13821383defp4UserForCommit(self,id):1384# Return the tuple (perforce user,git email) for a given git commit id1385 self.getUserMapFromPerforceServer()1386 gitEmail =read_pipe(["git","log","--max-count=1",1387"--format=%ae",id])1388 gitEmail = gitEmail.strip()1389if not self.emails.has_key(gitEmail):1390return(None,gitEmail)1391else:1392return(self.emails[gitEmail],gitEmail)13931394defcheckValidP4Users(self,commits):1395# check if any git authors cannot be mapped to p4 users1396foridin commits:1397(user,email) = self.p4UserForCommit(id)1398if not user:1399 msg ="Cannot find p4 user for email%sin commit%s."% (email,id)1400ifgitConfigBool("git-p4.allowMissingP4Users"):1401print"%s"% msg1402else:1403die("Error:%s\nSet git-p4.allowMissingP4Users to true to allow this."% msg)14041405deflastP4Changelist(self):1406# Get back the last changelist number submitted in this client spec. This1407# then gets used to patch up the username in the change. If the same1408# client spec is being used by multiple processes then this might go1409# wrong.1410 results =p4CmdList("client -o")# find the current client1411 client =None1412for r in results:1413if r.has_key('Client'):1414 client = r['Client']1415break1416if not client:1417die("could not get client spec")1418 results =p4CmdList(["changes","-c", client,"-m","1"])1419for r in results:1420if r.has_key('change'):1421return r['change']1422die("Could not get changelist number for last submit - cannot patch up user details")14231424defmodifyChangelistUser(self, changelist, newUser):1425# fixup the user field of a changelist after it has been submitted.1426 changes =p4CmdList("change -o%s"% changelist)1427iflen(changes) !=1:1428die("Bad output from p4 change modifying%sto user%s"%1429(changelist, newUser))14301431 c = changes[0]1432if c['User'] == newUser:return# nothing to do1433 c['User'] = newUser1434input= marshal.dumps(c)14351436 result =p4CmdList("change -f -i", stdin=input)1437for r in result:1438if r.has_key('code'):1439if r['code'] =='error':1440die("Could not modify user field of changelist%sto%s:%s"% (changelist, newUser, r['data']))1441if r.has_key('data'):1442print("Updated user field for changelist%sto%s"% (changelist, newUser))1443return1444die("Could not modify user field of changelist%sto%s"% (changelist, newUser))14451446defcanChangeChangelists(self):1447# check to see if we have p4 admin or super-user permissions, either of1448# which are required to modify changelists.1449 results =p4CmdList(["protects", self.depotPath])1450for r in results:1451if r.has_key('perm'):1452if r['perm'] =='admin':1453return11454if r['perm'] =='super':1455return11456return014571458defprepareSubmitTemplate(self):1459"""Run "p4 change -o" to grab a change specification template.1460 This does not use "p4 -G", as it is nice to keep the submission1461 template in original order, since a human might edit it.14621463 Remove lines in the Files section that show changes to files1464 outside the depot path we're committing into."""14651466[upstream, settings] =findUpstreamBranchPoint()14671468 template =""1469 inFilesSection =False1470for line inp4_read_pipe_lines(['change','-o']):1471if line.endswith("\r\n"):1472 line = line[:-2] +"\n"1473if inFilesSection:1474if line.startswith("\t"):1475# path starts and ends with a tab1476 path = line[1:]1477 lastTab = path.rfind("\t")1478if lastTab != -1:1479 path = path[:lastTab]1480if settings.has_key('depot-paths'):1481if not[p for p in settings['depot-paths']1482ifp4PathStartsWith(path, p)]:1483continue1484else:1485if notp4PathStartsWith(path, self.depotPath):1486continue1487else:1488 inFilesSection =False1489else:1490if line.startswith("Files:"):1491 inFilesSection =True14921493 template += line14941495return template14961497defedit_template(self, template_file):1498"""Invoke the editor to let the user change the submission1499 message. Return true if okay to continue with the submit."""15001501# if configured to skip the editing part, just submit1502ifgitConfigBool("git-p4.skipSubmitEdit"):1503return True15041505# look at the modification time, to check later if the user saved1506# the file1507 mtime = os.stat(template_file).st_mtime15081509# invoke the editor1510if os.environ.has_key("P4EDITOR")and(os.environ.get("P4EDITOR") !=""):1511 editor = os.environ.get("P4EDITOR")1512else:1513 editor =read_pipe("git var GIT_EDITOR").strip()1514system(["sh","-c", ('%s"$@"'% editor), editor, template_file])15151516# If the file was not saved, prompt to see if this patch should1517# be skipped. But skip this verification step if configured so.1518ifgitConfigBool("git-p4.skipSubmitEditCheck"):1519return True15201521# modification time updated means user saved the file1522if os.stat(template_file).st_mtime > mtime:1523return True15241525while True:1526 response =raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")1527if response =='y':1528return True1529if response =='n':1530return False15311532defget_diff_description(self, editedFiles, filesToAdd):1533# diff1534if os.environ.has_key("P4DIFF"):1535del(os.environ["P4DIFF"])1536 diff =""1537for editedFile in editedFiles:1538 diff +=p4_read_pipe(['diff','-du',1539wildcard_encode(editedFile)])15401541# new file diff1542 newdiff =""1543for newFile in filesToAdd:1544 newdiff +="==== new file ====\n"1545 newdiff +="--- /dev/null\n"1546 newdiff +="+++%s\n"% newFile1547 f =open(newFile,"r")1548for line in f.readlines():1549 newdiff +="+"+ line1550 f.close()15511552return(diff + newdiff).replace('\r\n','\n')15531554defapplyCommit(self,id):1555"""Apply one commit, return True if it succeeded."""15561557print"Applying",read_pipe(["git","show","-s",1558"--format=format:%h%s",id])15591560(p4User, gitEmail) = self.p4UserForCommit(id)15611562 diff =read_pipe_lines("git diff-tree -r%s\"%s^\" \"%s\""% (self.diffOpts,id,id))1563 filesToAdd =set()1564 filesToChangeType =set()1565 filesToDelete =set()1566 editedFiles =set()1567 pureRenameCopy =set()1568 filesToChangeExecBit = {}15691570for line in diff:1571 diff =parseDiffTreeEntry(line)1572 modifier = diff['status']1573 path = diff['src']1574if modifier =="M":1575p4_edit(path)1576ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1577 filesToChangeExecBit[path] = diff['dst_mode']1578 editedFiles.add(path)1579elif modifier =="A":1580 filesToAdd.add(path)1581 filesToChangeExecBit[path] = diff['dst_mode']1582if path in filesToDelete:1583 filesToDelete.remove(path)1584elif modifier =="D":1585 filesToDelete.add(path)1586if path in filesToAdd:1587 filesToAdd.remove(path)1588elif modifier =="C":1589 src, dest = diff['src'], diff['dst']1590p4_integrate(src, dest)1591 pureRenameCopy.add(dest)1592if diff['src_sha1'] != diff['dst_sha1']:1593p4_edit(dest)1594 pureRenameCopy.discard(dest)1595ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1596p4_edit(dest)1597 pureRenameCopy.discard(dest)1598 filesToChangeExecBit[dest] = diff['dst_mode']1599if self.isWindows:1600# turn off read-only attribute1601 os.chmod(dest, stat.S_IWRITE)1602 os.unlink(dest)1603 editedFiles.add(dest)1604elif modifier =="R":1605 src, dest = diff['src'], diff['dst']1606if self.p4HasMoveCommand:1607p4_edit(src)# src must be open before move1608p4_move(src, dest)# opens for (move/delete, move/add)1609else:1610p4_integrate(src, dest)1611if diff['src_sha1'] != diff['dst_sha1']:1612p4_edit(dest)1613else:1614 pureRenameCopy.add(dest)1615ifisModeExecChanged(diff['src_mode'], diff['dst_mode']):1616if not self.p4HasMoveCommand:1617p4_edit(dest)# with move: already open, writable1618 filesToChangeExecBit[dest] = diff['dst_mode']1619if not self.p4HasMoveCommand:1620if self.isWindows:1621 os.chmod(dest, stat.S_IWRITE)1622 os.unlink(dest)1623 filesToDelete.add(src)1624 editedFiles.add(dest)1625elif modifier =="T":1626 filesToChangeType.add(path)1627else:1628die("unknown modifier%sfor%s"% (modifier, path))16291630 diffcmd ="git diff-tree --full-index -p\"%s\""% (id)1631 patchcmd = diffcmd +" | git apply "1632 tryPatchCmd = patchcmd +"--check -"1633 applyPatchCmd = patchcmd +"--check --apply -"1634 patch_succeeded =True16351636if os.system(tryPatchCmd) !=0:1637 fixed_rcs_keywords =False1638 patch_succeeded =False1639print"Unfortunately applying the change failed!"16401641# Patch failed, maybe it's just RCS keyword woes. Look through1642# the patch to see if that's possible.1643ifgitConfigBool("git-p4.attemptRCSCleanup"):1644file=None1645 pattern =None1646 kwfiles = {}1647forfilein editedFiles | filesToDelete:1648# did this file's delta contain RCS keywords?1649 pattern =p4_keywords_regexp_for_file(file)16501651if pattern:1652# this file is a possibility...look for RCS keywords.1653 regexp = re.compile(pattern, re.VERBOSE)1654for line inread_pipe_lines(["git","diff","%s^..%s"% (id,id),file]):1655if regexp.search(line):1656if verbose:1657print"got keyword match on%sin%sin%s"% (pattern, line,file)1658 kwfiles[file] = pattern1659break16601661forfilein kwfiles:1662if verbose:1663print"zapping%swith%s"% (line,pattern)1664# File is being deleted, so not open in p4. Must1665# disable the read-only bit on windows.1666if self.isWindows andfilenot in editedFiles:1667 os.chmod(file, stat.S_IWRITE)1668 self.patchRCSKeywords(file, kwfiles[file])1669 fixed_rcs_keywords =True16701671if fixed_rcs_keywords:1672print"Retrying the patch with RCS keywords cleaned up"1673if os.system(tryPatchCmd) ==0:1674 patch_succeeded =True16751676if not patch_succeeded:1677for f in editedFiles:1678p4_revert(f)1679return False16801681#1682# Apply the patch for real, and do add/delete/+x handling.1683#1684system(applyPatchCmd)16851686for f in filesToChangeType:1687p4_edit(f,"-t","auto")1688for f in filesToAdd:1689p4_add(f)1690for f in filesToDelete:1691p4_revert(f)1692p4_delete(f)16931694# Set/clear executable bits1695for f in filesToChangeExecBit.keys():1696 mode = filesToChangeExecBit[f]1697setP4ExecBit(f, mode)16981699#1700# Build p4 change description, starting with the contents1701# of the git commit message.1702#1703 logMessage =extractLogMessageFromGitCommit(id)1704 logMessage = logMessage.strip()1705(logMessage, jobs) = self.separate_jobs_from_description(logMessage)17061707 template = self.prepareSubmitTemplate()1708 submitTemplate = self.prepareLogMessage(template, logMessage, jobs)17091710if self.preserveUser:1711 submitTemplate +="\n######## Actual user%s, modified after commit\n"% p4User17121713if self.checkAuthorship and not self.p4UserIsMe(p4User):1714 submitTemplate +="######## git author%sdoes not match your p4 account.\n"% gitEmail1715 submitTemplate +="######## Use option --preserve-user to modify authorship.\n"1716 submitTemplate +="######## Variable git-p4.skipUserNameCheck hides this message.\n"17171718 separatorLine ="######## everything below this line is just the diff #######\n"1719if not self.prepare_p4_only:1720 submitTemplate += separatorLine1721 submitTemplate += self.get_diff_description(editedFiles, filesToAdd)17221723(handle, fileName) = tempfile.mkstemp()1724 tmpFile = os.fdopen(handle,"w+b")1725if self.isWindows:1726 submitTemplate = submitTemplate.replace("\n","\r\n")1727 tmpFile.write(submitTemplate)1728 tmpFile.close()17291730if self.prepare_p4_only:1731#1732# Leave the p4 tree prepared, and the submit template around1733# and let the user decide what to do next1734#1735print1736print"P4 workspace prepared for submission."1737print"To submit or revert, go to client workspace"1738print" "+ self.clientPath1739print1740print"To submit, use\"p4 submit\"to write a new description,"1741print"or\"p4 submit -i <%s\"to use the one prepared by" \1742"\"git p4\"."% fileName1743print"You can delete the file\"%s\"when finished."% fileName17441745if self.preserveUser and p4User and not self.p4UserIsMe(p4User):1746print"To preserve change ownership by user%s, you must\n" \1747"do\"p4 change -f <change>\"after submitting and\n" \1748"edit the User field."1749if pureRenameCopy:1750print"After submitting, renamed files must be re-synced."1751print"Invoke\"p4 sync -f\"on each of these files:"1752for f in pureRenameCopy:1753print" "+ f17541755print1756print"To revert the changes, use\"p4 revert ...\", and delete"1757print"the submit template file\"%s\""% fileName1758if filesToAdd:1759print"Since the commit adds new files, they must be deleted:"1760for f in filesToAdd:1761print" "+ f1762print1763return True17641765#1766# Let the user edit the change description, then submit it.1767#1768 submitted =False17691770try:1771if self.edit_template(fileName):1772# read the edited message and submit1773 tmpFile =open(fileName,"rb")1774 message = tmpFile.read()1775 tmpFile.close()1776if self.isWindows:1777 message = message.replace("\r\n","\n")1778 submitTemplate = message[:message.index(separatorLine)]1779p4_write_pipe(['submit','-i'], submitTemplate)17801781if self.preserveUser:1782if p4User:1783# Get last changelist number. Cannot easily get it from1784# the submit command output as the output is1785# unmarshalled.1786 changelist = self.lastP4Changelist()1787 self.modifyChangelistUser(changelist, p4User)17881789# The rename/copy happened by applying a patch that created a1790# new file. This leaves it writable, which confuses p4.1791for f in pureRenameCopy:1792p4_sync(f,"-f")1793 submitted =True17941795finally:1796# skip this patch1797if not submitted:1798print"Submission cancelled, undoing p4 changes."1799for f in editedFiles:1800p4_revert(f)1801for f in filesToAdd:1802p4_revert(f)1803 os.remove(f)1804for f in filesToDelete:1805p4_revert(f)18061807 os.remove(fileName)1808return submitted18091810# Export git tags as p4 labels. Create a p4 label and then tag1811# with that.1812defexportGitTags(self, gitTags):1813 validLabelRegexp =gitConfig("git-p4.labelExportRegexp")1814iflen(validLabelRegexp) ==0:1815 validLabelRegexp = defaultLabelRegexp1816 m = re.compile(validLabelRegexp)18171818for name in gitTags:18191820if not m.match(name):1821if verbose:1822print"tag%sdoes not match regexp%s"% (name, validLabelRegexp)1823continue18241825# Get the p4 commit this corresponds to1826 logMessage =extractLogMessageFromGitCommit(name)1827 values =extractSettingsGitLog(logMessage)18281829if not values.has_key('change'):1830# a tag pointing to something not sent to p4; ignore1831if verbose:1832print"git tag%sdoes not give a p4 commit"% name1833continue1834else:1835 changelist = values['change']18361837# Get the tag details.1838 inHeader =True1839 isAnnotated =False1840 body = []1841for l inread_pipe_lines(["git","cat-file","-p", name]):1842 l = l.strip()1843if inHeader:1844if re.match(r'tag\s+', l):1845 isAnnotated =True1846elif re.match(r'\s*$', l):1847 inHeader =False1848continue1849else:1850 body.append(l)18511852if not isAnnotated:1853 body = ["lightweight tag imported by git p4\n"]18541855# Create the label - use the same view as the client spec we are using1856 clientSpec =getClientSpec()18571858 labelTemplate ="Label:%s\n"% name1859 labelTemplate +="Description:\n"1860for b in body:1861 labelTemplate +="\t"+ b +"\n"1862 labelTemplate +="View:\n"1863for depot_side in clientSpec.mappings:1864 labelTemplate +="\t%s\n"% depot_side18651866if self.dry_run:1867print"Would create p4 label%sfor tag"% name1868elif self.prepare_p4_only:1869print"Not creating p4 label%sfor tag due to option" \1870" --prepare-p4-only"% name1871else:1872p4_write_pipe(["label","-i"], labelTemplate)18731874# Use the label1875p4_system(["tag","-l", name] +1876["%s@%s"% (depot_side, changelist)for depot_side in clientSpec.mappings])18771878if verbose:1879print"created p4 label for tag%s"% name18801881defrun(self, args):1882iflen(args) ==0:1883 self.master =currentGitBranch()1884eliflen(args) ==1:1885 self.master = args[0]1886if notbranchExists(self.master):1887die("Branch%sdoes not exist"% self.master)1888else:1889return False18901891if self.master:1892 allowSubmit =gitConfig("git-p4.allowSubmit")1893iflen(allowSubmit) >0and not self.master in allowSubmit.split(","):1894die("%sis not in git-p4.allowSubmit"% self.master)18951896[upstream, settings] =findUpstreamBranchPoint()1897 self.depotPath = settings['depot-paths'][0]1898iflen(self.origin) ==0:1899 self.origin = upstream19001901if self.preserveUser:1902if not self.canChangeChangelists():1903die("Cannot preserve user names without p4 super-user or admin permissions")19041905# if not set from the command line, try the config file1906if self.conflict_behavior is None:1907 val =gitConfig("git-p4.conflict")1908if val:1909if val not in self.conflict_behavior_choices:1910die("Invalid value '%s' for config git-p4.conflict"% val)1911else:1912 val ="ask"1913 self.conflict_behavior = val19141915if self.verbose:1916print"Origin branch is "+ self.origin19171918iflen(self.depotPath) ==0:1919print"Internal error: cannot locate perforce depot path from existing branches"1920 sys.exit(128)19211922 self.useClientSpec =False1923ifgitConfigBool("git-p4.useclientspec"):1924 self.useClientSpec =True1925if self.useClientSpec:1926 self.clientSpecDirs =getClientSpec()19271928# Check for the existance of P4 branches1929 branchesDetected = (len(p4BranchesInGit().keys()) >1)19301931if self.useClientSpec and not branchesDetected:1932# all files are relative to the client spec1933 self.clientPath =getClientRoot()1934else:1935 self.clientPath =p4Where(self.depotPath)19361937if self.clientPath =="":1938die("Error: Cannot locate perforce checkout of%sin client view"% self.depotPath)19391940print"Perforce checkout for depot path%slocated at%s"% (self.depotPath, self.clientPath)1941 self.oldWorkingDirectory = os.getcwd()19421943# ensure the clientPath exists1944 new_client_dir =False1945if not os.path.exists(self.clientPath):1946 new_client_dir =True1947 os.makedirs(self.clientPath)19481949chdir(self.clientPath, is_client_path=True)1950if self.dry_run:1951print"Would synchronize p4 checkout in%s"% self.clientPath1952else:1953print"Synchronizing p4 checkout..."1954if new_client_dir:1955# old one was destroyed, and maybe nobody told p41956p4_sync("...","-f")1957else:1958p4_sync("...")1959 self.check()19601961 commits = []1962if self.master:1963 commitish = self.master1964else:1965 commitish ='HEAD'19661967for line inread_pipe_lines(["git","rev-list","--no-merges","%s..%s"% (self.origin, commitish)]):1968 commits.append(line.strip())1969 commits.reverse()19701971if self.preserveUser orgitConfigBool("git-p4.skipUserNameCheck"):1972 self.checkAuthorship =False1973else:1974 self.checkAuthorship =True19751976if self.preserveUser:1977 self.checkValidP4Users(commits)19781979#1980# Build up a set of options to be passed to diff when1981# submitting each commit to p4.1982#1983if self.detectRenames:1984# command-line -M arg1985 self.diffOpts ="-M"1986else:1987# If not explicitly set check the config variable1988 detectRenames =gitConfig("git-p4.detectRenames")19891990if detectRenames.lower() =="false"or detectRenames =="":1991 self.diffOpts =""1992elif detectRenames.lower() =="true":1993 self.diffOpts ="-M"1994else:1995 self.diffOpts ="-M%s"% detectRenames19961997# no command-line arg for -C or --find-copies-harder, just1998# config variables1999 detectCopies =gitConfig("git-p4.detectCopies")2000if detectCopies.lower() =="false"or detectCopies =="":2001pass2002elif detectCopies.lower() =="true":2003 self.diffOpts +=" -C"2004else:2005 self.diffOpts +=" -C%s"% detectCopies20062007ifgitConfigBool("git-p4.detectCopiesHarder"):2008 self.diffOpts +=" --find-copies-harder"20092010#2011# Apply the commits, one at a time. On failure, ask if should2012# continue to try the rest of the patches, or quit.2013#2014if self.dry_run:2015print"Would apply"2016 applied = []2017 last =len(commits) -12018for i, commit inenumerate(commits):2019if self.dry_run:2020print" ",read_pipe(["git","show","-s",2021"--format=format:%h%s", commit])2022 ok =True2023else:2024 ok = self.applyCommit(commit)2025if ok:2026 applied.append(commit)2027else:2028if self.prepare_p4_only and i < last:2029print"Processing only the first commit due to option" \2030" --prepare-p4-only"2031break2032if i < last:2033 quit =False2034while True:2035# prompt for what to do, or use the option/variable2036if self.conflict_behavior =="ask":2037print"What do you want to do?"2038 response =raw_input("[s]kip this commit but apply"2039" the rest, or [q]uit? ")2040if not response:2041continue2042elif self.conflict_behavior =="skip":2043 response ="s"2044elif self.conflict_behavior =="quit":2045 response ="q"2046else:2047die("Unknown conflict_behavior '%s'"%2048 self.conflict_behavior)20492050if response[0] =="s":2051print"Skipping this commit, but applying the rest"2052break2053if response[0] =="q":2054print"Quitting"2055 quit =True2056break2057if quit:2058break20592060chdir(self.oldWorkingDirectory)20612062if self.dry_run:2063pass2064elif self.prepare_p4_only:2065pass2066eliflen(commits) ==len(applied):2067print"All commits applied!"20682069 sync =P4Sync()2070if self.branch:2071 sync.branch = self.branch2072 sync.run([])20732074 rebase =P4Rebase()2075 rebase.rebase()20762077else:2078iflen(applied) ==0:2079print"No commits applied."2080else:2081print"Applied only the commits marked with '*':"2082for c in commits:2083if c in applied:2084 star ="*"2085else:2086 star =" "2087print star,read_pipe(["git","show","-s",2088"--format=format:%h%s", c])2089print"You will have to do 'git p4 sync' and rebase."20902091ifgitConfigBool("git-p4.exportLabels"):2092 self.exportLabels =True20932094if self.exportLabels:2095 p4Labels =getP4Labels(self.depotPath)2096 gitTags =getGitTags()20972098 missingGitTags = gitTags - p4Labels2099 self.exportGitTags(missingGitTags)21002101# exit with error unless everything applied perfectly2102iflen(commits) !=len(applied):2103 sys.exit(1)21042105return True21062107classView(object):2108"""Represent a p4 view ("p4 help views"), and map files in a2109 repo according to the view."""21102111def__init__(self, client_name):2112 self.mappings = []2113 self.client_prefix ="//%s/"% client_name2114# cache results of "p4 where" to lookup client file locations2115 self.client_spec_path_cache = {}21162117defappend(self, view_line):2118"""Parse a view line, splitting it into depot and client2119 sides. Append to self.mappings, preserving order. This2120 is only needed for tag creation."""21212122# Split the view line into exactly two words. P4 enforces2123# structure on these lines that simplifies this quite a bit.2124#2125# Either or both words may be double-quoted.2126# Single quotes do not matter.2127# Double-quote marks cannot occur inside the words.2128# A + or - prefix is also inside the quotes.2129# There are no quotes unless they contain a space.2130# The line is already white-space stripped.2131# The two words are separated by a single space.2132#2133if view_line[0] =='"':2134# First word is double quoted. Find its end.2135 close_quote_index = view_line.find('"',1)2136if close_quote_index <=0:2137die("No first-word closing quote found:%s"% view_line)2138 depot_side = view_line[1:close_quote_index]2139# skip closing quote and space2140 rhs_index = close_quote_index +1+12141else:2142 space_index = view_line.find(" ")2143if space_index <=0:2144die("No word-splitting space found:%s"% view_line)2145 depot_side = view_line[0:space_index]2146 rhs_index = space_index +121472148# prefix + means overlay on previous mapping2149if depot_side.startswith("+"):2150 depot_side = depot_side[1:]21512152# prefix - means exclude this path, leave out of mappings2153 exclude =False2154if depot_side.startswith("-"):2155 exclude =True2156 depot_side = depot_side[1:]21572158if not exclude:2159 self.mappings.append(depot_side)21602161defconvert_client_path(self, clientFile):2162# chop off //client/ part to make it relative2163if not clientFile.startswith(self.client_prefix):2164die("No prefix '%s' on clientFile '%s'"%2165(self.client_prefix, clientFile))2166return clientFile[len(self.client_prefix):]21672168defupdate_client_spec_path_cache(self, files):2169""" Caching file paths by "p4 where" batch query """21702171# List depot file paths exclude that already cached2172 fileArgs = [f['path']for f in files if f['path']not in self.client_spec_path_cache]21732174iflen(fileArgs) ==0:2175return# All files in cache21762177 where_result =p4CmdList(["-x","-","where"], stdin=fileArgs)2178for res in where_result:2179if"code"in res and res["code"] =="error":2180# assume error is "... file(s) not in client view"2181continue2182if"clientFile"not in res:2183die("No clientFile in 'p4 where' output")2184if"unmap"in res:2185# it will list all of them, but only one not unmap-ped2186continue2187ifgitConfigBool("core.ignorecase"):2188 res['depotFile'] = res['depotFile'].lower()2189 self.client_spec_path_cache[res['depotFile']] = self.convert_client_path(res["clientFile"])21902191# not found files or unmap files set to ""2192for depotFile in fileArgs:2193ifgitConfigBool("core.ignorecase"):2194 depotFile = depotFile.lower()2195if depotFile not in self.client_spec_path_cache:2196 self.client_spec_path_cache[depotFile] =""21972198defmap_in_client(self, depot_path):2199"""Return the relative location in the client where this2200 depot file should live. Returns "" if the file should2201 not be mapped in the client."""22022203ifgitConfigBool("core.ignorecase"):2204 depot_path = depot_path.lower()22052206if depot_path in self.client_spec_path_cache:2207return self.client_spec_path_cache[depot_path]22082209die("Error:%sis not found in client spec path"% depot_path )2210return""22112212classP4Sync(Command, P4UserMap):2213 delete_actions = ("delete","move/delete","purge")22142215def__init__(self):2216 Command.__init__(self)2217 P4UserMap.__init__(self)2218 self.options = [2219 optparse.make_option("--branch", dest="branch"),2220 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),2221 optparse.make_option("--changesfile", dest="changesFile"),2222 optparse.make_option("--silent", dest="silent", action="store_true"),2223 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),2224 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),2225 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",2226help="Import into refs/heads/ , not refs/remotes"),2227 optparse.make_option("--max-changes", dest="maxChanges",2228help="Maximum number of changes to import"),2229 optparse.make_option("--changes-block-size", dest="changes_block_size",type="int",2230help="Internal block size to use when iteratively calling p4 changes"),2231 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',2232help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),2233 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',2234help="Only sync files that are included in the Perforce Client Spec"),2235 optparse.make_option("-/", dest="cloneExclude",2236 action="append",type="string",2237help="exclude depot path"),2238]2239 self.description ="""Imports from Perforce into a git repository.\n2240 example:2241 //depot/my/project/ -- to import the current head2242 //depot/my/project/@all -- to import everything2243 //depot/my/project/@1,6 -- to import only from revision 1 to 622442245 (a ... is not needed in the path p4 specification, it's added implicitly)"""22462247 self.usage +=" //depot/path[@revRange]"2248 self.silent =False2249 self.createdBranches =set()2250 self.committedChanges =set()2251 self.branch =""2252 self.detectBranches =False2253 self.detectLabels =False2254 self.importLabels =False2255 self.changesFile =""2256 self.syncWithOrigin =True2257 self.importIntoRemotes =True2258 self.maxChanges =""2259 self.changes_block_size =None2260 self.keepRepoPath =False2261 self.depotPaths =None2262 self.p4BranchesInGit = []2263 self.cloneExclude = []2264 self.useClientSpec =False2265 self.useClientSpec_from_options =False2266 self.clientSpecDirs =None2267 self.tempBranches = []2268 self.tempBranchLocation ="git-p4-tmp"2269 self.largeFileSystem =None22702271ifgitConfig('git-p4.largeFileSystem'):2272 largeFileSystemConstructor =globals()[gitConfig('git-p4.largeFileSystem')]2273 self.largeFileSystem =largeFileSystemConstructor(2274lambda git_mode, relPath, contents: self.writeToGitStream(git_mode, relPath, contents)2275)22762277ifgitConfig("git-p4.syncFromOrigin") =="false":2278 self.syncWithOrigin =False22792280# This is required for the "append" cloneExclude action2281defensure_value(self, attr, value):2282if nothasattr(self, attr)orgetattr(self, attr)is None:2283setattr(self, attr, value)2284returngetattr(self, attr)22852286# Force a checkpoint in fast-import and wait for it to finish2287defcheckpoint(self):2288 self.gitStream.write("checkpoint\n\n")2289 self.gitStream.write("progress checkpoint\n\n")2290 out = self.gitOutput.readline()2291if self.verbose:2292print"checkpoint finished: "+ out22932294defextractFilesFromCommit(self, commit):2295 self.cloneExclude = [re.sub(r"\.\.\.$","", path)2296for path in self.cloneExclude]2297 files = []2298 fnum =02299while commit.has_key("depotFile%s"% fnum):2300 path = commit["depotFile%s"% fnum]23012302if[p for p in self.cloneExclude2303ifp4PathStartsWith(path, p)]:2304 found =False2305else:2306 found = [p for p in self.depotPaths2307ifp4PathStartsWith(path, p)]2308if not found:2309 fnum = fnum +12310continue23112312file= {}2313file["path"] = path2314file["rev"] = commit["rev%s"% fnum]2315file["action"] = commit["action%s"% fnum]2316file["type"] = commit["type%s"% fnum]2317 files.append(file)2318 fnum = fnum +12319return files23202321defstripRepoPath(self, path, prefixes):2322"""When streaming files, this is called to map a p4 depot path2323 to where it should go in git. The prefixes are either2324 self.depotPaths, or self.branchPrefixes in the case of2325 branch detection."""23262327if self.useClientSpec:2328# branch detection moves files up a level (the branch name)2329# from what client spec interpretation gives2330 path = self.clientSpecDirs.map_in_client(path)2331if self.detectBranches:2332for b in self.knownBranches:2333if path.startswith(b +"/"):2334 path = path[len(b)+1:]23352336elif self.keepRepoPath:2337# Preserve everything in relative path name except leading2338# //depot/; just look at first prefix as they all should2339# be in the same depot.2340 depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])2341ifp4PathStartsWith(path, depot):2342 path = path[len(depot):]23432344else:2345for p in prefixes:2346ifp4PathStartsWith(path, p):2347 path = path[len(p):]2348break23492350 path =wildcard_decode(path)2351return path23522353defsplitFilesIntoBranches(self, commit):2354"""Look at each depotFile in the commit to figure out to what2355 branch it belongs."""23562357if self.clientSpecDirs:2358 files = self.extractFilesFromCommit(commit)2359 self.clientSpecDirs.update_client_spec_path_cache(files)23602361 branches = {}2362 fnum =02363while commit.has_key("depotFile%s"% fnum):2364 path = commit["depotFile%s"% fnum]2365 found = [p for p in self.depotPaths2366ifp4PathStartsWith(path, p)]2367if not found:2368 fnum = fnum +12369continue23702371file= {}2372file["path"] = path2373file["rev"] = commit["rev%s"% fnum]2374file["action"] = commit["action%s"% fnum]2375file["type"] = commit["type%s"% fnum]2376 fnum = fnum +123772378# start with the full relative path where this file would2379# go in a p4 client2380if self.useClientSpec:2381 relPath = self.clientSpecDirs.map_in_client(path)2382else:2383 relPath = self.stripRepoPath(path, self.depotPaths)23842385for branch in self.knownBranches.keys():2386# add a trailing slash so that a commit into qt/4.2foo2387# doesn't end up in qt/4.2, e.g.2388if relPath.startswith(branch +"/"):2389if branch not in branches:2390 branches[branch] = []2391 branches[branch].append(file)2392break23932394return branches23952396defwriteToGitStream(self, gitMode, relPath, contents):2397 self.gitStream.write('M%sinline%s\n'% (gitMode, relPath))2398 self.gitStream.write('data%d\n'%sum(len(d)for d in contents))2399for d in contents:2400 self.gitStream.write(d)2401 self.gitStream.write('\n')24022403# output one file from the P4 stream2404# - helper for streamP4Files24052406defstreamOneP4File(self,file, contents):2407 relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)2408if verbose:2409 size =int(self.stream_file['fileSize'])2410 sys.stdout.write('\r%s-->%s(%iMB)\n'% (file['depotFile'], relPath, size/1024/1024))2411 sys.stdout.flush()24122413(type_base, type_mods) =split_p4_type(file["type"])24142415 git_mode ="100644"2416if"x"in type_mods:2417 git_mode ="100755"2418if type_base =="symlink":2419 git_mode ="120000"2420# p4 print on a symlink sometimes contains "target\n";2421# if it does, remove the newline2422 data =''.join(contents)2423if not data:2424# Some version of p4 allowed creating a symlink that pointed2425# to nothing. This causes p4 errors when checking out such2426# a change, and errors here too. Work around it by ignoring2427# the bad symlink; hopefully a future change fixes it.2428print"\nIgnoring empty symlink in%s"%file['depotFile']2429return2430elif data[-1] =='\n':2431 contents = [data[:-1]]2432else:2433 contents = [data]24342435if type_base =="utf16":2436# p4 delivers different text in the python output to -G2437# than it does when using "print -o", or normal p4 client2438# operations. utf16 is converted to ascii or utf8, perhaps.2439# But ascii text saved as -t utf16 is completely mangled.2440# Invoke print -o to get the real contents.2441#2442# On windows, the newlines will always be mangled by print, so put2443# them back too. This is not needed to the cygwin windows version,2444# just the native "NT" type.2445#2446try:2447 text =p4_read_pipe(['print','-q','-o','-','%s@%s'% (file['depotFile'],file['change'])])2448exceptExceptionas e:2449if'Translation of file content failed'instr(e):2450 type_base ='binary'2451else:2452raise e2453else:2454ifp4_version_string().find('/NT') >=0:2455 text = text.replace('\r\n','\n')2456 contents = [ text ]24572458if type_base =="apple":2459# Apple filetype files will be streamed as a concatenation of2460# its appledouble header and the contents. This is useless2461# on both macs and non-macs. If using "print -q -o xx", it2462# will create "xx" with the data, and "%xx" with the header.2463# This is also not very useful.2464#2465# Ideally, someday, this script can learn how to generate2466# appledouble files directly and import those to git, but2467# non-mac machines can never find a use for apple filetype.2468print"\nIgnoring apple filetype file%s"%file['depotFile']2469return24702471# Note that we do not try to de-mangle keywords on utf16 files,2472# even though in theory somebody may want that.2473 pattern =p4_keywords_regexp_for_type(type_base, type_mods)2474if pattern:2475 regexp = re.compile(pattern, re.VERBOSE)2476 text =''.join(contents)2477 text = regexp.sub(r'$\1$', text)2478 contents = [ text ]24792480try:2481 relPath.decode('ascii')2482except:2483 encoding ='utf8'2484ifgitConfig('git-p4.pathEncoding'):2485 encoding =gitConfig('git-p4.pathEncoding')2486 relPath = relPath.decode(encoding,'replace').encode('utf8','replace')2487if self.verbose:2488print'Path with non-ASCII characters detected. Used%sto encode:%s'% (encoding, relPath)24892490if self.largeFileSystem:2491(git_mode, contents) = self.largeFileSystem.processContent(git_mode, relPath, contents)24922493 self.writeToGitStream(git_mode, relPath, contents)24942495defstreamOneP4Deletion(self,file):2496 relPath = self.stripRepoPath(file['path'], self.branchPrefixes)2497if verbose:2498 sys.stdout.write("delete%s\n"% relPath)2499 sys.stdout.flush()2500 self.gitStream.write("D%s\n"% relPath)25012502if self.largeFileSystem and self.largeFileSystem.isLargeFile(relPath):2503 self.largeFileSystem.removeLargeFile(relPath)25042505# handle another chunk of streaming data2506defstreamP4FilesCb(self, marshalled):25072508# catch p4 errors and complain2509 err =None2510if"code"in marshalled:2511if marshalled["code"] =="error":2512if"data"in marshalled:2513 err = marshalled["data"].rstrip()25142515if not err and'fileSize'in self.stream_file:2516 required_bytes =int((4*int(self.stream_file["fileSize"])) -calcDiskFree())2517if required_bytes >0:2518 err ='Not enough space left on%s! Free at least%iMB.'% (2519 os.getcwd(), required_bytes/1024/10242520)25212522if err:2523 f =None2524if self.stream_have_file_info:2525if"depotFile"in self.stream_file:2526 f = self.stream_file["depotFile"]2527# force a failure in fast-import, else an empty2528# commit will be made2529 self.gitStream.write("\n")2530 self.gitStream.write("die-now\n")2531 self.gitStream.close()2532# ignore errors, but make sure it exits first2533 self.importProcess.wait()2534if f:2535die("Error from p4 print for%s:%s"% (f, err))2536else:2537die("Error from p4 print:%s"% err)25382539if marshalled.has_key('depotFile')and self.stream_have_file_info:2540# start of a new file - output the old one first2541 self.streamOneP4File(self.stream_file, self.stream_contents)2542 self.stream_file = {}2543 self.stream_contents = []2544 self.stream_have_file_info =False25452546# pick up the new file information... for the2547# 'data' field we need to append to our array2548for k in marshalled.keys():2549if k =='data':2550if'streamContentSize'not in self.stream_file:2551 self.stream_file['streamContentSize'] =02552 self.stream_file['streamContentSize'] +=len(marshalled['data'])2553 self.stream_contents.append(marshalled['data'])2554else:2555 self.stream_file[k] = marshalled[k]25562557if(verbose and2558'streamContentSize'in self.stream_file and2559'fileSize'in self.stream_file and2560'depotFile'in self.stream_file):2561 size =int(self.stream_file["fileSize"])2562if size >0:2563 progress =100*self.stream_file['streamContentSize']/size2564 sys.stdout.write('\r%s %d%%(%iMB)'% (self.stream_file['depotFile'], progress,int(size/1024/1024)))2565 sys.stdout.flush()25662567 self.stream_have_file_info =True25682569# Stream directly from "p4 files" into "git fast-import"2570defstreamP4Files(self, files):2571 filesForCommit = []2572 filesToRead = []2573 filesToDelete = []25742575for f in files:2576 filesForCommit.append(f)2577if f['action']in self.delete_actions:2578 filesToDelete.append(f)2579else:2580 filesToRead.append(f)25812582# deleted files...2583for f in filesToDelete:2584 self.streamOneP4Deletion(f)25852586iflen(filesToRead) >0:2587 self.stream_file = {}2588 self.stream_contents = []2589 self.stream_have_file_info =False25902591# curry self argument2592defstreamP4FilesCbSelf(entry):2593 self.streamP4FilesCb(entry)25942595 fileArgs = ['%s#%s'% (f['path'], f['rev'])for f in filesToRead]25962597p4CmdList(["-x","-","print"],2598 stdin=fileArgs,2599 cb=streamP4FilesCbSelf)26002601# do the last chunk2602if self.stream_file.has_key('depotFile'):2603 self.streamOneP4File(self.stream_file, self.stream_contents)26042605defmake_email(self, userid):2606if userid in self.users:2607return self.users[userid]2608else:2609return"%s<a@b>"% userid26102611defstreamTag(self, gitStream, labelName, labelDetails, commit, epoch):2612""" Stream a p4 tag.2613 commit is either a git commit, or a fast-import mark, ":<p4commit>"2614 """26152616if verbose:2617print"writing tag%sfor commit%s"% (labelName, commit)2618 gitStream.write("tag%s\n"% labelName)2619 gitStream.write("from%s\n"% commit)26202621if labelDetails.has_key('Owner'):2622 owner = labelDetails["Owner"]2623else:2624 owner =None26252626# Try to use the owner of the p4 label, or failing that,2627# the current p4 user id.2628if owner:2629 email = self.make_email(owner)2630else:2631 email = self.make_email(self.p4UserId())2632 tagger ="%s %s %s"% (email, epoch, self.tz)26332634 gitStream.write("tagger%s\n"% tagger)26352636print"labelDetails=",labelDetails2637if labelDetails.has_key('Description'):2638 description = labelDetails['Description']2639else:2640 description ='Label from git p4'26412642 gitStream.write("data%d\n"%len(description))2643 gitStream.write(description)2644 gitStream.write("\n")26452646definClientSpec(self, path):2647if not self.clientSpecDirs:2648return True2649 inClientSpec = self.clientSpecDirs.map_in_client(path)2650if not inClientSpec and self.verbose:2651print('Ignoring file outside of client spec:{0}'.format(path))2652return inClientSpec26532654defhasBranchPrefix(self, path):2655if not self.branchPrefixes:2656return True2657 hasPrefix = [p for p in self.branchPrefixes2658ifp4PathStartsWith(path, p)]2659if hasPrefix and self.verbose:2660print('Ignoring file outside of prefix:{0}'.format(path))2661return hasPrefix26622663defcommit(self, details, files, branch, parent =""):2664 epoch = details["time"]2665 author = details["user"]26662667if self.verbose:2668print('commit into{0}'.format(branch))26692670if self.clientSpecDirs:2671 self.clientSpecDirs.update_client_spec_path_cache(files)26722673 files = [f for f in files2674if self.inClientSpec(f['path'])and self.hasBranchPrefix(f['path'])]26752676if not files and notgitConfigBool('git-p4.keepEmptyCommits'):2677print('Ignoring revision{0}as it would produce an empty commit.'2678.format(details['change']))2679return26802681 self.gitStream.write("commit%s\n"% branch)2682 self.gitStream.write("mark :%s\n"% details["change"])2683 self.committedChanges.add(int(details["change"]))2684 committer =""2685if author not in self.users:2686 self.getUserMapFromPerforceServer()2687 committer ="%s %s %s"% (self.make_email(author), epoch, self.tz)26882689 self.gitStream.write("committer%s\n"% committer)26902691 self.gitStream.write("data <<EOT\n")2692 self.gitStream.write(details["desc"])2693 self.gitStream.write("\n[git-p4: depot-paths =\"%s\": change =%s"%2694(','.join(self.branchPrefixes), details["change"]))2695iflen(details['options']) >0:2696 self.gitStream.write(": options =%s"% details['options'])2697 self.gitStream.write("]\nEOT\n\n")26982699iflen(parent) >0:2700if self.verbose:2701print"parent%s"% parent2702 self.gitStream.write("from%s\n"% parent)27032704 self.streamP4Files(files)2705 self.gitStream.write("\n")27062707 change =int(details["change"])27082709if self.labels.has_key(change):2710 label = self.labels[change]2711 labelDetails = label[0]2712 labelRevisions = label[1]2713if self.verbose:2714print"Change%sis labelled%s"% (change, labelDetails)27152716 files =p4CmdList(["files"] + ["%s...@%s"% (p, change)2717for p in self.branchPrefixes])27182719iflen(files) ==len(labelRevisions):27202721 cleanedFiles = {}2722for info in files:2723if info["action"]in self.delete_actions:2724continue2725 cleanedFiles[info["depotFile"]] = info["rev"]27262727if cleanedFiles == labelRevisions:2728 self.streamTag(self.gitStream,'tag_%s'% labelDetails['label'], labelDetails, branch, epoch)27292730else:2731if not self.silent:2732print("Tag%sdoes not match with change%s: files do not match."2733% (labelDetails["label"], change))27342735else:2736if not self.silent:2737print("Tag%sdoes not match with change%s: file count is different."2738% (labelDetails["label"], change))27392740# Build a dictionary of changelists and labels, for "detect-labels" option.2741defgetLabels(self):2742 self.labels = {}27432744 l =p4CmdList(["labels"] + ["%s..."% p for p in self.depotPaths])2745iflen(l) >0and not self.silent:2746print"Finding files belonging to labels in%s"% `self.depotPaths`27472748for output in l:2749 label = output["label"]2750 revisions = {}2751 newestChange =02752if self.verbose:2753print"Querying files for label%s"% label2754forfileinp4CmdList(["files"] +2755["%s...@%s"% (p, label)2756for p in self.depotPaths]):2757 revisions[file["depotFile"]] =file["rev"]2758 change =int(file["change"])2759if change > newestChange:2760 newestChange = change27612762 self.labels[newestChange] = [output, revisions]27632764if self.verbose:2765print"Label changes:%s"% self.labels.keys()27662767# Import p4 labels as git tags. A direct mapping does not2768# exist, so assume that if all the files are at the same revision2769# then we can use that, or it's something more complicated we should2770# just ignore.2771defimportP4Labels(self, stream, p4Labels):2772if verbose:2773print"import p4 labels: "+' '.join(p4Labels)27742775 ignoredP4Labels =gitConfigList("git-p4.ignoredP4Labels")2776 validLabelRegexp =gitConfig("git-p4.labelImportRegexp")2777iflen(validLabelRegexp) ==0:2778 validLabelRegexp = defaultLabelRegexp2779 m = re.compile(validLabelRegexp)27802781for name in p4Labels:2782 commitFound =False27832784if not m.match(name):2785if verbose:2786print"label%sdoes not match regexp%s"% (name,validLabelRegexp)2787continue27882789if name in ignoredP4Labels:2790continue27912792 labelDetails =p4CmdList(['label',"-o", name])[0]27932794# get the most recent changelist for each file in this label2795 change =p4Cmd(["changes","-m","1"] + ["%s...@%s"% (p, name)2796for p in self.depotPaths])27972798if change.has_key('change'):2799# find the corresponding git commit; take the oldest commit2800 changelist =int(change['change'])2801if changelist in self.committedChanges:2802 gitCommit =":%d"% changelist # use a fast-import mark2803 commitFound =True2804else:2805 gitCommit =read_pipe(["git","rev-list","--max-count=1",2806"--reverse",":/\[git-p4:.*change =%d\]"% changelist], ignore_error=True)2807iflen(gitCommit) ==0:2808print"importing label%s: could not find git commit for changelist%d"% (name, changelist)2809else:2810 commitFound =True2811 gitCommit = gitCommit.strip()28122813if commitFound:2814# Convert from p4 time format2815try:2816 tmwhen = time.strptime(labelDetails['Update'],"%Y/%m/%d%H:%M:%S")2817exceptValueError:2818print"Could not convert label time%s"% labelDetails['Update']2819 tmwhen =128202821 when =int(time.mktime(tmwhen))2822 self.streamTag(stream, name, labelDetails, gitCommit, when)2823if verbose:2824print"p4 label%smapped to git commit%s"% (name, gitCommit)2825else:2826if verbose:2827print"Label%shas no changelists - possibly deleted?"% name28282829if not commitFound:2830# We can't import this label; don't try again as it will get very2831# expensive repeatedly fetching all the files for labels that will2832# never be imported. If the label is moved in the future, the2833# ignore will need to be removed manually.2834system(["git","config","--add","git-p4.ignoredP4Labels", name])28352836defguessProjectName(self):2837for p in self.depotPaths:2838if p.endswith("/"):2839 p = p[:-1]2840 p = p[p.strip().rfind("/") +1:]2841if not p.endswith("/"):2842 p +="/"2843return p28442845defgetBranchMapping(self):2846 lostAndFoundBranches =set()28472848 user =gitConfig("git-p4.branchUser")2849iflen(user) >0:2850 command ="branches -u%s"% user2851else:2852 command ="branches"28532854for info inp4CmdList(command):2855 details =p4Cmd(["branch","-o", info["branch"]])2856 viewIdx =02857while details.has_key("View%s"% viewIdx):2858 paths = details["View%s"% viewIdx].split(" ")2859 viewIdx = viewIdx +12860# require standard //depot/foo/... //depot/bar/... mapping2861iflen(paths) !=2or not paths[0].endswith("/...")or not paths[1].endswith("/..."):2862continue2863 source = paths[0]2864 destination = paths[1]2865## HACK2866ifp4PathStartsWith(source, self.depotPaths[0])andp4PathStartsWith(destination, self.depotPaths[0]):2867 source = source[len(self.depotPaths[0]):-4]2868 destination = destination[len(self.depotPaths[0]):-4]28692870if destination in self.knownBranches:2871if not self.silent:2872print"p4 branch%sdefines a mapping from%sto%s"% (info["branch"], source, destination)2873print"but there exists another mapping from%sto%salready!"% (self.knownBranches[destination], destination)2874continue28752876 self.knownBranches[destination] = source28772878 lostAndFoundBranches.discard(destination)28792880if source not in self.knownBranches:2881 lostAndFoundBranches.add(source)28822883# Perforce does not strictly require branches to be defined, so we also2884# check git config for a branch list.2885#2886# Example of branch definition in git config file:2887# [git-p4]2888# branchList=main:branchA2889# branchList=main:branchB2890# branchList=branchA:branchC2891 configBranches =gitConfigList("git-p4.branchList")2892for branch in configBranches:2893if branch:2894(source, destination) = branch.split(":")2895 self.knownBranches[destination] = source28962897 lostAndFoundBranches.discard(destination)28982899if source not in self.knownBranches:2900 lostAndFoundBranches.add(source)290129022903for branch in lostAndFoundBranches:2904 self.knownBranches[branch] = branch29052906defgetBranchMappingFromGitBranches(self):2907 branches =p4BranchesInGit(self.importIntoRemotes)2908for branch in branches.keys():2909if branch =="master":2910 branch ="main"2911else:2912 branch = branch[len(self.projectName):]2913 self.knownBranches[branch] = branch29142915defupdateOptionDict(self, d):2916 option_keys = {}2917if self.keepRepoPath:2918 option_keys['keepRepoPath'] =129192920 d["options"] =' '.join(sorted(option_keys.keys()))29212922defreadOptions(self, d):2923 self.keepRepoPath = (d.has_key('options')2924and('keepRepoPath'in d['options']))29252926defgitRefForBranch(self, branch):2927if branch =="main":2928return self.refPrefix +"master"29292930iflen(branch) <=0:2931return branch29322933return self.refPrefix + self.projectName + branch29342935defgitCommitByP4Change(self, ref, change):2936if self.verbose:2937print"looking in ref "+ ref +" for change%susing bisect..."% change29382939 earliestCommit =""2940 latestCommit =parseRevision(ref)29412942while True:2943if self.verbose:2944print"trying: earliest%slatest%s"% (earliestCommit, latestCommit)2945 next =read_pipe("git rev-list --bisect%s %s"% (latestCommit, earliestCommit)).strip()2946iflen(next) ==0:2947if self.verbose:2948print"argh"2949return""2950 log =extractLogMessageFromGitCommit(next)2951 settings =extractSettingsGitLog(log)2952 currentChange =int(settings['change'])2953if self.verbose:2954print"current change%s"% currentChange29552956if currentChange == change:2957if self.verbose:2958print"found%s"% next2959return next29602961if currentChange < change:2962 earliestCommit ="^%s"% next2963else:2964 latestCommit ="%s"% next29652966return""29672968defimportNewBranch(self, branch, maxChange):2969# make fast-import flush all changes to disk and update the refs using the checkpoint2970# command so that we can try to find the branch parent in the git history2971 self.gitStream.write("checkpoint\n\n");2972 self.gitStream.flush();2973 branchPrefix = self.depotPaths[0] + branch +"/"2974range="@1,%s"% maxChange2975#print "prefix" + branchPrefix2976 changes =p4ChangesForPaths([branchPrefix],range, self.changes_block_size)2977iflen(changes) <=0:2978return False2979 firstChange = changes[0]2980#print "first change in branch: %s" % firstChange2981 sourceBranch = self.knownBranches[branch]2982 sourceDepotPath = self.depotPaths[0] + sourceBranch2983 sourceRef = self.gitRefForBranch(sourceBranch)2984#print "source " + sourceBranch29852986 branchParentChange =int(p4Cmd(["changes","-m","1","%s...@1,%s"% (sourceDepotPath, firstChange)])["change"])2987#print "branch parent: %s" % branchParentChange2988 gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)2989iflen(gitParent) >0:2990 self.initialParents[self.gitRefForBranch(branch)] = gitParent2991#print "parent git commit: %s" % gitParent29922993 self.importChanges(changes)2994return True29952996defsearchParent(self, parent, branch, target):2997 parentFound =False2998for blob inread_pipe_lines(["git","rev-list","--reverse",2999"--no-merges", parent]):3000 blob = blob.strip()3001iflen(read_pipe(["git","diff-tree", blob, target])) ==0:3002 parentFound =True3003if self.verbose:3004print"Found parent of%sin commit%s"% (branch, blob)3005break3006if parentFound:3007return blob3008else:3009return None30103011defimportChanges(self, changes):3012 cnt =13013for change in changes:3014 description =p4_describe(change)3015 self.updateOptionDict(description)30163017if not self.silent:3018 sys.stdout.write("\rImporting revision%s(%s%%)"% (change, cnt *100/len(changes)))3019 sys.stdout.flush()3020 cnt = cnt +130213022try:3023if self.detectBranches:3024 branches = self.splitFilesIntoBranches(description)3025for branch in branches.keys():3026## HACK --hwn3027 branchPrefix = self.depotPaths[0] + branch +"/"3028 self.branchPrefixes = [ branchPrefix ]30293030 parent =""30313032 filesForCommit = branches[branch]30333034if self.verbose:3035print"branch is%s"% branch30363037 self.updatedBranches.add(branch)30383039if branch not in self.createdBranches:3040 self.createdBranches.add(branch)3041 parent = self.knownBranches[branch]3042if parent == branch:3043 parent =""3044else:3045 fullBranch = self.projectName + branch3046if fullBranch not in self.p4BranchesInGit:3047if not self.silent:3048print("\nImporting new branch%s"% fullBranch);3049if self.importNewBranch(branch, change -1):3050 parent =""3051 self.p4BranchesInGit.append(fullBranch)3052if not self.silent:3053print("\nResuming with change%s"% change);30543055if self.verbose:3056print"parent determined through known branches:%s"% parent30573058 branch = self.gitRefForBranch(branch)3059 parent = self.gitRefForBranch(parent)30603061if self.verbose:3062print"looking for initial parent for%s; current parent is%s"% (branch, parent)30633064iflen(parent) ==0and branch in self.initialParents:3065 parent = self.initialParents[branch]3066del self.initialParents[branch]30673068 blob =None3069iflen(parent) >0:3070 tempBranch ="%s/%d"% (self.tempBranchLocation, change)3071if self.verbose:3072print"Creating temporary branch: "+ tempBranch3073 self.commit(description, filesForCommit, tempBranch)3074 self.tempBranches.append(tempBranch)3075 self.checkpoint()3076 blob = self.searchParent(parent, branch, tempBranch)3077if blob:3078 self.commit(description, filesForCommit, branch, blob)3079else:3080if self.verbose:3081print"Parent of%snot found. Committing into head of%s"% (branch, parent)3082 self.commit(description, filesForCommit, branch, parent)3083else:3084 files = self.extractFilesFromCommit(description)3085 self.commit(description, files, self.branch,3086 self.initialParent)3087# only needed once, to connect to the previous commit3088 self.initialParent =""3089exceptIOError:3090print self.gitError.read()3091 sys.exit(1)30923093defimportHeadRevision(self, revision):3094print"Doing initial import of%sfrom revision%sinto%s"% (' '.join(self.depotPaths), revision, self.branch)30953096 details = {}3097 details["user"] ="git perforce import user"3098 details["desc"] = ("Initial import of%sfrom the state at revision%s\n"3099% (' '.join(self.depotPaths), revision))3100 details["change"] = revision3101 newestRevision =031023103 fileCnt =03104 fileArgs = ["%s...%s"% (p,revision)for p in self.depotPaths]31053106for info inp4CmdList(["files"] + fileArgs):31073108if'code'in info and info['code'] =='error':3109 sys.stderr.write("p4 returned an error:%s\n"3110% info['data'])3111if info['data'].find("must refer to client") >=0:3112 sys.stderr.write("This particular p4 error is misleading.\n")3113 sys.stderr.write("Perhaps the depot path was misspelled.\n");3114 sys.stderr.write("Depot path:%s\n"%" ".join(self.depotPaths))3115 sys.exit(1)3116if'p4ExitCode'in info:3117 sys.stderr.write("p4 exitcode:%s\n"% info['p4ExitCode'])3118 sys.exit(1)311931203121 change =int(info["change"])3122if change > newestRevision:3123 newestRevision = change31243125if info["action"]in self.delete_actions:3126# don't increase the file cnt, otherwise details["depotFile123"] will have gaps!3127#fileCnt = fileCnt + 13128continue31293130for prop in["depotFile","rev","action","type"]:3131 details["%s%s"% (prop, fileCnt)] = info[prop]31323133 fileCnt = fileCnt +131343135 details["change"] = newestRevision31363137# Use time from top-most change so that all git p4 clones of3138# the same p4 repo have the same commit SHA1s.3139 res =p4_describe(newestRevision)3140 details["time"] = res["time"]31413142 self.updateOptionDict(details)3143try:3144 self.commit(details, self.extractFilesFromCommit(details), self.branch)3145exceptIOError:3146print"IO error with git fast-import. Is your git version recent enough?"3147print self.gitError.read()314831493150defrun(self, args):3151 self.depotPaths = []3152 self.changeRange =""3153 self.previousDepotPaths = []3154 self.hasOrigin =False31553156# map from branch depot path to parent branch3157 self.knownBranches = {}3158 self.initialParents = {}31593160if self.importIntoRemotes:3161 self.refPrefix ="refs/remotes/p4/"3162else:3163 self.refPrefix ="refs/heads/p4/"31643165if self.syncWithOrigin:3166 self.hasOrigin =originP4BranchesExist()3167if self.hasOrigin:3168if not self.silent:3169print'Syncing with origin first, using "git fetch origin"'3170system("git fetch origin")31713172 branch_arg_given =bool(self.branch)3173iflen(self.branch) ==0:3174 self.branch = self.refPrefix +"master"3175ifgitBranchExists("refs/heads/p4")and self.importIntoRemotes:3176system("git update-ref%srefs/heads/p4"% self.branch)3177system("git branch -D p4")31783179# accept either the command-line option, or the configuration variable3180if self.useClientSpec:3181# will use this after clone to set the variable3182 self.useClientSpec_from_options =True3183else:3184ifgitConfigBool("git-p4.useclientspec"):3185 self.useClientSpec =True3186if self.useClientSpec:3187 self.clientSpecDirs =getClientSpec()31883189# TODO: should always look at previous commits,3190# merge with previous imports, if possible.3191if args == []:3192if self.hasOrigin:3193createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)31943195# branches holds mapping from branch name to sha13196 branches =p4BranchesInGit(self.importIntoRemotes)31973198# restrict to just this one, disabling detect-branches3199if branch_arg_given:3200 short = self.branch.split("/")[-1]3201if short in branches:3202 self.p4BranchesInGit = [ short ]3203else:3204 self.p4BranchesInGit = branches.keys()32053206iflen(self.p4BranchesInGit) >1:3207if not self.silent:3208print"Importing from/into multiple branches"3209 self.detectBranches =True3210for branch in branches.keys():3211 self.initialParents[self.refPrefix + branch] = \3212 branches[branch]32133214if self.verbose:3215print"branches:%s"% self.p4BranchesInGit32163217 p4Change =03218for branch in self.p4BranchesInGit:3219 logMsg =extractLogMessageFromGitCommit(self.refPrefix + branch)32203221 settings =extractSettingsGitLog(logMsg)32223223 self.readOptions(settings)3224if(settings.has_key('depot-paths')3225and settings.has_key('change')):3226 change =int(settings['change']) +13227 p4Change =max(p4Change, change)32283229 depotPaths =sorted(settings['depot-paths'])3230if self.previousDepotPaths == []:3231 self.previousDepotPaths = depotPaths3232else:3233 paths = []3234for(prev, cur)inzip(self.previousDepotPaths, depotPaths):3235 prev_list = prev.split("/")3236 cur_list = cur.split("/")3237for i inrange(0,min(len(cur_list),len(prev_list))):3238if cur_list[i] <> prev_list[i]:3239 i = i -13240break32413242 paths.append("/".join(cur_list[:i +1]))32433244 self.previousDepotPaths = paths32453246if p4Change >0:3247 self.depotPaths =sorted(self.previousDepotPaths)3248 self.changeRange ="@%s,#head"% p4Change3249if not self.silent and not self.detectBranches:3250print"Performing incremental import into%sgit branch"% self.branch32513252# accept multiple ref name abbreviations:3253# refs/foo/bar/branch -> use it exactly3254# p4/branch -> prepend refs/remotes/ or refs/heads/3255# branch -> prepend refs/remotes/p4/ or refs/heads/p4/3256if not self.branch.startswith("refs/"):3257if self.importIntoRemotes:3258 prepend ="refs/remotes/"3259else:3260 prepend ="refs/heads/"3261if not self.branch.startswith("p4/"):3262 prepend +="p4/"3263 self.branch = prepend + self.branch32643265iflen(args) ==0and self.depotPaths:3266if not self.silent:3267print"Depot paths:%s"%' '.join(self.depotPaths)3268else:3269if self.depotPaths and self.depotPaths != args:3270print("previous import used depot path%sand now%swas specified. "3271"This doesn't work!"% (' '.join(self.depotPaths),3272' '.join(args)))3273 sys.exit(1)32743275 self.depotPaths =sorted(args)32763277 revision =""3278 self.users = {}32793280# Make sure no revision specifiers are used when --changesfile3281# is specified.3282 bad_changesfile =False3283iflen(self.changesFile) >0:3284for p in self.depotPaths:3285if p.find("@") >=0or p.find("#") >=0:3286 bad_changesfile =True3287break3288if bad_changesfile:3289die("Option --changesfile is incompatible with revision specifiers")32903291 newPaths = []3292for p in self.depotPaths:3293if p.find("@") != -1:3294 atIdx = p.index("@")3295 self.changeRange = p[atIdx:]3296if self.changeRange =="@all":3297 self.changeRange =""3298elif','not in self.changeRange:3299 revision = self.changeRange3300 self.changeRange =""3301 p = p[:atIdx]3302elif p.find("#") != -1:3303 hashIdx = p.index("#")3304 revision = p[hashIdx:]3305 p = p[:hashIdx]3306elif self.previousDepotPaths == []:3307# pay attention to changesfile, if given, else import3308# the entire p4 tree at the head revision3309iflen(self.changesFile) ==0:3310 revision ="#head"33113312 p = re.sub("\.\.\.$","", p)3313if not p.endswith("/"):3314 p +="/"33153316 newPaths.append(p)33173318 self.depotPaths = newPaths33193320# --detect-branches may change this for each branch3321 self.branchPrefixes = self.depotPaths33223323 self.loadUserMapFromCache()3324 self.labels = {}3325if self.detectLabels:3326 self.getLabels();33273328if self.detectBranches:3329## FIXME - what's a P4 projectName ?3330 self.projectName = self.guessProjectName()33313332if self.hasOrigin:3333 self.getBranchMappingFromGitBranches()3334else:3335 self.getBranchMapping()3336if self.verbose:3337print"p4-git branches:%s"% self.p4BranchesInGit3338print"initial parents:%s"% self.initialParents3339for b in self.p4BranchesInGit:3340if b !="master":33413342## FIXME3343 b = b[len(self.projectName):]3344 self.createdBranches.add(b)33453346 self.tz ="%+03d%02d"% (- time.timezone /3600, ((- time.timezone %3600) /60))33473348 self.importProcess = subprocess.Popen(["git","fast-import"],3349 stdin=subprocess.PIPE,3350 stdout=subprocess.PIPE,3351 stderr=subprocess.PIPE);3352 self.gitOutput = self.importProcess.stdout3353 self.gitStream = self.importProcess.stdin3354 self.gitError = self.importProcess.stderr33553356if revision:3357 self.importHeadRevision(revision)3358else:3359 changes = []33603361iflen(self.changesFile) >0:3362 output =open(self.changesFile).readlines()3363 changeSet =set()3364for line in output:3365 changeSet.add(int(line))33663367for change in changeSet:3368 changes.append(change)33693370 changes.sort()3371else:3372# catch "git p4 sync" with no new branches, in a repo that3373# does not have any existing p4 branches3374iflen(args) ==0:3375if not self.p4BranchesInGit:3376die("No remote p4 branches. Perhaps you never did\"git p4 clone\"in here.")33773378# The default branch is master, unless --branch is used to3379# specify something else. Make sure it exists, or complain3380# nicely about how to use --branch.3381if not self.detectBranches:3382if notbranch_exists(self.branch):3383if branch_arg_given:3384die("Error: branch%sdoes not exist."% self.branch)3385else:3386die("Error: no branch%s; perhaps specify one with --branch."%3387 self.branch)33883389if self.verbose:3390print"Getting p4 changes for%s...%s"% (', '.join(self.depotPaths),3391 self.changeRange)3392 changes =p4ChangesForPaths(self.depotPaths, self.changeRange, self.changes_block_size)33933394iflen(self.maxChanges) >0:3395 changes = changes[:min(int(self.maxChanges),len(changes))]33963397iflen(changes) ==0:3398if not self.silent:3399print"No changes to import!"3400else:3401if not self.silent and not self.detectBranches:3402print"Import destination:%s"% self.branch34033404 self.updatedBranches =set()34053406if not self.detectBranches:3407if args:3408# start a new branch3409 self.initialParent =""3410else:3411# build on a previous revision3412 self.initialParent =parseRevision(self.branch)34133414 self.importChanges(changes)34153416if not self.silent:3417print""3418iflen(self.updatedBranches) >0:3419 sys.stdout.write("Updated branches: ")3420for b in self.updatedBranches:3421 sys.stdout.write("%s"% b)3422 sys.stdout.write("\n")34233424ifgitConfigBool("git-p4.importLabels"):3425 self.importLabels =True34263427if self.importLabels:3428 p4Labels =getP4Labels(self.depotPaths)3429 gitTags =getGitTags()34303431 missingP4Labels = p4Labels - gitTags3432 self.importP4Labels(self.gitStream, missingP4Labels)34333434 self.gitStream.close()3435if self.importProcess.wait() !=0:3436die("fast-import failed:%s"% self.gitError.read())3437 self.gitOutput.close()3438 self.gitError.close()34393440# Cleanup temporary branches created during import3441if self.tempBranches != []:3442for branch in self.tempBranches:3443read_pipe("git update-ref -d%s"% branch)3444 os.rmdir(os.path.join(os.environ.get("GIT_DIR",".git"), self.tempBranchLocation))34453446# Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow3447# a convenient shortcut refname "p4".3448if self.importIntoRemotes:3449 head_ref = self.refPrefix +"HEAD"3450if notgitBranchExists(head_ref)andgitBranchExists(self.branch):3451system(["git","symbolic-ref", head_ref, self.branch])34523453return True34543455classP4Rebase(Command):3456def__init__(self):3457 Command.__init__(self)3458 self.options = [3459 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),3460]3461 self.importLabels =False3462 self.description = ("Fetches the latest revision from perforce and "3463+"rebases the current work (branch) against it")34643465defrun(self, args):3466 sync =P4Sync()3467 sync.importLabels = self.importLabels3468 sync.run([])34693470return self.rebase()34713472defrebase(self):3473if os.system("git update-index --refresh") !=0:3474die("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.");3475iflen(read_pipe("git diff-index HEAD --")) >0:3476die("You have uncommitted changes. Please commit them before rebasing or stash them away with git stash.");34773478[upstream, settings] =findUpstreamBranchPoint()3479iflen(upstream) ==0:3480die("Cannot find upstream branchpoint for rebase")34813482# the branchpoint may be p4/foo~3, so strip off the parent3483 upstream = re.sub("~[0-9]+$","", upstream)34843485print"Rebasing the current branch onto%s"% upstream3486 oldHead =read_pipe("git rev-parse HEAD").strip()3487system("git rebase%s"% upstream)3488system("git diff-tree --stat --summary -M%sHEAD --"% oldHead)3489return True34903491classP4Clone(P4Sync):3492def__init__(self):3493 P4Sync.__init__(self)3494 self.description ="Creates a new git repository and imports from Perforce into it"3495 self.usage ="usage: %prog [options] //depot/path[@revRange]"3496 self.options += [3497 optparse.make_option("--destination", dest="cloneDestination",3498 action='store', default=None,3499help="where to leave result of the clone"),3500 optparse.make_option("--bare", dest="cloneBare",3501 action="store_true", default=False),3502]3503 self.cloneDestination =None3504 self.needsGit =False3505 self.cloneBare =False35063507defdefaultDestination(self, args):3508## TODO: use common prefix of args?3509 depotPath = args[0]3510 depotDir = re.sub("(@[^@]*)$","", depotPath)3511 depotDir = re.sub("(#[^#]*)$","", depotDir)3512 depotDir = re.sub(r"\.\.\.$","", depotDir)3513 depotDir = re.sub(r"/$","", depotDir)3514return os.path.split(depotDir)[1]35153516defrun(self, args):3517iflen(args) <1:3518return False35193520if self.keepRepoPath and not self.cloneDestination:3521 sys.stderr.write("Must specify destination for --keep-path\n")3522 sys.exit(1)35233524 depotPaths = args35253526if not self.cloneDestination andlen(depotPaths) >1:3527 self.cloneDestination = depotPaths[-1]3528 depotPaths = depotPaths[:-1]35293530 self.cloneExclude = ["/"+p for p in self.cloneExclude]3531for p in depotPaths:3532if not p.startswith("//"):3533 sys.stderr.write('Depot paths must start with "//":%s\n'% p)3534return False35353536if not self.cloneDestination:3537 self.cloneDestination = self.defaultDestination(args)35383539print"Importing from%sinto%s"% (', '.join(depotPaths), self.cloneDestination)35403541if not os.path.exists(self.cloneDestination):3542 os.makedirs(self.cloneDestination)3543chdir(self.cloneDestination)35443545 init_cmd = ["git","init"]3546if self.cloneBare:3547 init_cmd.append("--bare")3548 retcode = subprocess.call(init_cmd)3549if retcode:3550raiseCalledProcessError(retcode, init_cmd)35513552if not P4Sync.run(self, depotPaths):3553return False35543555# create a master branch and check out a work tree3556ifgitBranchExists(self.branch):3557system(["git","branch","master", self.branch ])3558if not self.cloneBare:3559system(["git","checkout","-f"])3560else:3561print'Not checking out any branch, use ' \3562'"git checkout -q -b master <branch>"'35633564# auto-set this variable if invoked with --use-client-spec3565if self.useClientSpec_from_options:3566system("git config --bool git-p4.useclientspec true")35673568return True35693570classP4Branches(Command):3571def__init__(self):3572 Command.__init__(self)3573 self.options = [ ]3574 self.description = ("Shows the git branches that hold imports and their "3575+"corresponding perforce depot paths")3576 self.verbose =False35773578defrun(self, args):3579iforiginP4BranchesExist():3580createOrUpdateBranchesFromOrigin()35813582 cmdline ="git rev-parse --symbolic "3583 cmdline +=" --remotes"35843585for line inread_pipe_lines(cmdline):3586 line = line.strip()35873588if not line.startswith('p4/')or line =="p4/HEAD":3589continue3590 branch = line35913592 log =extractLogMessageFromGitCommit("refs/remotes/%s"% branch)3593 settings =extractSettingsGitLog(log)35943595print"%s<=%s(%s)"% (branch,",".join(settings["depot-paths"]), settings["change"])3596return True35973598classHelpFormatter(optparse.IndentedHelpFormatter):3599def__init__(self):3600 optparse.IndentedHelpFormatter.__init__(self)36013602defformat_description(self, description):3603if description:3604return description +"\n"3605else:3606return""36073608defprintUsage(commands):3609print"usage:%s<command> [options]"% sys.argv[0]3610print""3611print"valid commands:%s"%", ".join(commands)3612print""3613print"Try%s<command> --help for command specific help."% sys.argv[0]3614print""36153616commands = {3617"debug": P4Debug,3618"submit": P4Submit,3619"commit": P4Submit,3620"sync": P4Sync,3621"rebase": P4Rebase,3622"clone": P4Clone,3623"rollback": P4RollBack,3624"branches": P4Branches3625}362636273628defmain():3629iflen(sys.argv[1:]) ==0:3630printUsage(commands.keys())3631 sys.exit(2)36323633 cmdName = sys.argv[1]3634try:3635 klass = commands[cmdName]3636 cmd =klass()3637exceptKeyError:3638print"unknown command%s"% cmdName3639print""3640printUsage(commands.keys())3641 sys.exit(2)36423643 options = cmd.options3644 cmd.gitdir = os.environ.get("GIT_DIR",None)36453646 args = sys.argv[2:]36473648 options.append(optparse.make_option("--verbose","-v", dest="verbose", action="store_true"))3649if cmd.needsGit:3650 options.append(optparse.make_option("--git-dir", dest="gitdir"))36513652 parser = optparse.OptionParser(cmd.usage.replace("%prog","%prog "+ cmdName),3653 options,3654 description = cmd.description,3655 formatter =HelpFormatter())36563657(cmd, args) = parser.parse_args(sys.argv[2:], cmd);3658global verbose3659 verbose = cmd.verbose3660if cmd.needsGit:3661if cmd.gitdir ==None:3662 cmd.gitdir = os.path.abspath(".git")3663if notisValidGitDir(cmd.gitdir):3664 cmd.gitdir =read_pipe("git rev-parse --git-dir").strip()3665if os.path.exists(cmd.gitdir):3666 cdup =read_pipe("git rev-parse --show-cdup").strip()3667iflen(cdup) >0:3668chdir(cdup);36693670if notisValidGitDir(cmd.gitdir):3671ifisValidGitDir(cmd.gitdir +"/.git"):3672 cmd.gitdir +="/.git"3673else:3674die("fatal: cannot locate git repository at%s"% cmd.gitdir)36753676 os.environ["GIT_DIR"] = cmd.gitdir36773678if not cmd.run(args):3679 parser.print_help()3680 sys.exit(2)368136823683if __name__ =='__main__':3684main()