-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGitP4Transfer.py
executable file
·1509 lines (1300 loc) · 61.4 KB
/
GitP4Transfer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2021-22 Robert Cowham, Perforce Software Ltd
# ========================================
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PERFORCE
# SOFTWARE, INC. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
"""
NAME:
GitP4Transfer.py
DESCRIPTION:
This python script (3.8+ compatible) will transfer Git changes into a Perforce
Helix Core Repository, somewhat similar to 'git p4' (not historical) and also GitFusion (now deprecated).
This script transfers changes in one direction - from a source Git server to a target p4 server.
It handles LFS files in the source server (assuming git LFS is suitably installed and enabled)
Requires Git version 2.7+ due to use of formatting flags
Usage:
python3 GitP4Transfer.py -h
The script requires a config file, by default transfer.yaml. An initial example can be generated, e.g.
GitP4Transfer.py --sample-config > transfer.yaml
For full documentation/usage, see project doc:
https://github.com/rcowham/gitp4transfer/blob/main/doc/GitP4Transfer.adoc
"""
# Notes:
# Scan all commits for diffs
# Scan all commits for other key info
# Find start commit
# Process in reverse order
from __future__ import print_function, division
from os import error
import sys
import re
import subprocess
import stat
import pprint
from string import Template
import argparse
import textwrap
import os.path
from datetime import datetime
import logging
import time
import platform
import collections
# Non-standard modules
import P4
import logutils
# Import yaml which will roundtrip comments
from ruamel.yaml import YAML
yaml = YAML()
subproc = subprocess # Could have a wrapper for use on Windows
VERSION = """$Id: 74939df934a7a660e6beff62870f65635918300b $"""
ANON_BRANCH_PREFIX = "_anon"
if bytes is not str:
# For python3, always encode and decode as appropriate
def decode_text_stream(s):
return s.decode() if isinstance(s, bytes) else s
else:
# For python2.7, pass read strings as-is
def decode_text_stream(s):
return s
def anonymousBranch(branch):
return branch.startswith(ANON_BRANCH_PREFIX)
def logrepr(self):
return pprint.pformat(self.__dict__, width=240)
alreadyLogged = {}
# Log messages just once per run
def logOnce(logger, *args):
global alreadyLogged
msg = ", ".join([str(x) for x in args])
if msg not in alreadyLogged:
alreadyLogged[msg] = 1
logger.debug(msg)
#
# P4 wildcards are not allowed in filenames. P4 complains
# if you simply add them, but you can force it with "-f", in
# which case it translates them into %xx encoding internally.
#
def wildcard_decode(path):
# Search for and fix just these four characters. Do % last so
# that fixing it does not inadvertently create new %-escapes.
# Cannot have * in a filename in windows; untested as to
# what p4 would do in such a case.
if not platform.system() == "Windows":
path = path.replace("%2A", "*")
path = path.replace("%23", "#") \
.replace("%40", "@") \
.replace("%25", "%")
return path
def wildcard_encode(path):
# do % first to avoid double-encoding the %s introduced here
path = path.replace("%", "%25") \
.replace("*", "%2A") \
.replace("#", "%23") \
.replace("@", "%40")
return path
def wildcard_present(path):
m = re.search("[*#@%]", path)
return m is not None
def isModeExec(mode):
# Returns True if the given git mode represents an executable file,
# otherwise False.
return mode[-3:] == "755"
def isModeExecChanged(src_mode, dst_mode):
return isModeExec(src_mode) != isModeExec(dst_mode)
_diff_tree_pattern = None
def parseDiffTreeEntry(entry):
"""Parses a single diff tree entry into its component elements.
See git-diff-tree(1) manpage for details about the format of the diff
output. This method returns a dictionary with the following elements:
src_mode - The mode of the source file
dst_mode - The mode of the destination file
src_sha1 - The sha1 for the source file
dst_sha1 - The sha1 fr the destination file
status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc)
status_score - The score for the status (applicable for 'C' and 'R'
statuses). This is None if there is no score.
src - The path for the source file.
dst - The path for the destination file. This is only present for
copy or renames. If it is not present, this is None.
If the pattern is not matched, None is returned."""
global _diff_tree_pattern
if not _diff_tree_pattern:
_diff_tree_pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)')
match = _diff_tree_pattern.match(entry)
if match:
return {
'src_mode': match.group(1),
'dst_mode': match.group(2),
'src_sha1': match.group(3),
'dst_sha1': match.group(4),
'status': match.group(5),
'status_score': match.group(6),
'src': PathQuoting.dequote(match.group(7)),
'dst': PathQuoting.dequote(match.group(10))
}
return None
P4.Revision.__repr__ = logrepr
P4.Integration.__repr__ = logrepr
P4.DepotFile.__repr__ = logrepr
python3 = sys.version_info[0] >= 3
if sys.hexversion < 0x02070000 or (0x0300000 <= sys.hexversion < 0x0303000):
sys.exit("Python 2.7 or 3.3 or newer is required to run this program.")
reFetchMoveError = re.compile("Files are missing as a result of one or more move operations")
# Although this should work with Python 3, it doesn't currently handle Windows Perforce servers
# with filenames containing charaters such as umlauts etc: åäö
class P4TException(Exception):
pass
class P4TLogicException(P4TException):
pass
class P4TConfigException(P4TException):
pass
CONFIG_FILE = 'transfer.yaml'
GENERAL_SECTION = 'general'
SOURCE_SECTION = 'source'
TARGET_SECTION = 'target'
LOGGER_NAME = "GitP4Transfer"
CHANGE_MAP_DESC = "Updated change_map_file"
# This is for writing to sample config file
yaml.preserve_quotes = True
DEFAULT_CONFIG = yaml.load(r"""
# counter_name: Unique counter on target server to use for recording source changes processed. No spaces.
# Name sensibly if you have multiple instances transferring into the same target p4 repository.
# The counter value represents the last transferred change number - script will start from next change.
# If not set, or 0 then transfer will start from first change.
counter_name: GitP4Transfer_counter
# instance_name: Name of the instance of GitP4Transfer - for emails etc. Spaces allowed.
instance_name: "Git LFS Transfer from XYZ"
# For notification - if smtp not available - expects a pre-configured nms FormMail script as a URL
# E.g. expects to post using 2 fields: subject, message
# Alternatively, use the following entries (suitable adjusted) to use Mailgun for notifications
# api: "<Mailgun API key"
# url: "https://api.mailgun.net/v3/<domain or sandbox>"
# mail_from: "Fred <fred@example.com>"
# mail_to:
# - "fred@example.com"
mail_form_url:
# The mail_* parameters must all be valid (non-blank) to receive email updates during processing.
# mail_to: One or more valid email addresses - comma separated for multiple values
# E.g. somebody@example.com,somebody-else@example.com
mail_to:
# mail_from: Email address of sender of emails, E.g. p4transfer@example.com
mail_from:
# mail_server: The SMTP server to connect to for email sending, E.g. smtpserver.example.com
mail_server:
# ===============================================================================
# Note that for any of the following parameters identified as (Integer) you can specify a
# valid python expression which evaluates to integer value, e.g.
# "24 * 60"
# "7 * 24 * 60"
# Such values should be quoted (in order to be treated as strings)
# -------------------------------------------------------------------------------
# sleep_on_error_interval (Integer): How long (in minutes) to sleep when error is encountered in the script
sleep_on_error_interval: 60
# poll_interval (Integer): How long (in minutes) to wait between polling source server for new changes
poll_interval: 60
# change_batch_size (Integer): changelists are processed in batches of this size
change_batch_size: 1000
# The following *_interval values result in reports, but only if mail_* values are specified
# report_interval (Integer): Interval (in minutes) between regular update emails being sent
report_interval: 30
# error_report_interval (Integer): Interval (in minutes) between error emails being sent e.g. connection error
# Usually some value less than report_interval. Useful if transfer being run with --repeat option.
error_report_interval: 15
# summary_report_interval (Integer): Interval (in minutes) between summary emails being sent e.g. changes processed
# Typically some value such as 1 week (10080 = 7 * 24 * 60). Useful if transfer being run with --repeat option.
summary_report_interval: "7 * 24 * 60"
# max_logfile_size (Integer): Max size of file to (in bytes) after which it should be rotated
# Typically some value such as 20MB = 20 * 1024 * 1024. Useful if transfer being run with --repeat option.
max_logfile_size: "20 * 1024 * 1024"
# change_description_format: The standard format for transferred changes.
# Keywords prefixed with $. Use \\n for newlines. Keywords allowed:
# $sourceDescription, $sourceChange, $sourceRepo, $sourceUser
change_description_format: "$sourceDescription\\n\\nTransferred from git://$sourceRepo@$sourceChange"
# superuser: Set to n if not a superuser (so can't update change times - can just transfer them).
superuser: "y"
source:
# git_repo: root directory for git repo
# This will be used to update the client workspace Root: field for target workspace
git_repo:
target:
# P4PORT to connect to, e.g. some-server:1666 - if this is on localhost and you just
# want to specify port number, then use quotes: "1666"
p4port:
# P4USER to use
p4user:
# P4CLIENT to use, e.g. p4-transfer-client
p4client:
# P4PASSWD for the user - valid password. If blank then no login performed.
# Recommended to make sure user is in a group with a long password timeout!
# Make sure your P4TICKETS file is correctly found in the environment
p4passwd:
# P4CHARSET to use, e.g. none, utf8, etc - leave blank for non-unicode p4d instance
p4charset:
# branch_maps: An array of git branches to migrate and where to.
# Note that other branches encountered will be given temp names under anon_branches_root
# Entries specify 'git_branch' and 'targ'. No wildcards.
branch_maps:
- git_branch: "master"
targ: "//git_import/master"
# import_anon_branches: Set this to 'y' to import anonymous branches - NOT YET FUNCTIONAL!!!
# Any other value means they will not be imported.
import_anon_branches: n
# anon_branches_root: A depot path used for anonymous git branches (names automatically generated).
# NOT YET FUNCTIONAL
# Such branches only contain files modified on git branch.
# Name of branch under this root is _anonNNNN with a unique ID.
# If this field is empty, then no anonymous branches will be created/imported.
#anon_branches_root: //git_import/temp_branches
anon_branches_root:
""")
def ensureDirectory(directory):
if not os.path.isdir(directory):
os.makedirs(directory)
def makeWritable(fpath):
"Make file writable"
os.chmod(fpath, stat.S_IWRITE + stat.S_IREAD)
def p4time(unixtime):
"Convert time to Perforce format time"
return time.strftime("%Y/%m/%d:%H:%M:%S", time.localtime(unixtime))
def printSampleConfig():
"Print defaults from above dictionary for saving as a base file"
print("")
print("# Save this output to a file to e.g. transfer.yaml and edit it for your configuration")
print("")
yaml.dump(DEFAULT_CONFIG, sys.stdout)
sys.stdout.flush()
def fmtsize(num):
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0
class PathQuoting:
"""From git-filter-repo.py - great for python2 - but needs conversion to bytes for python3"""
_unescape = {b'a': b'\a',
b'b': b'\b',
b'f': b'\f',
b'n': b'\n',
b'r': b'\r',
b't': b'\t',
b'v': b'\v',
b'"': b'"',
b'\\':b'\\'}
_unescape_re = re.compile(br'\\([a-z"\\]|[0-9]{3})')
_escape = [bytes([x]) for x in range(127)]+[
b'\\'+bytes(ord(c) for c in oct(x)[2:]) for x in range(127,256)]
_reverse = dict(map(reversed, _unescape.items()))
for x in _reverse:
_escape[ord(x)] = b'\\'+_reverse[x]
_special_chars = [len(x) > 1 for x in _escape]
@staticmethod
def unescape_sequence(orig):
seq = orig.group(1)
return PathQuoting._unescape[seq] if len(seq) == 1 else bytes([int(seq, 8)])
@staticmethod
def dequote(quoted_string):
if quoted_string and quoted_string.startswith('"'):
assert quoted_string.endswith('"')
# Python3 - convert to bytes for magic above
quoted_string = quoted_string.encode()
result = PathQuoting._unescape_re.sub(PathQuoting.unescape_sequence,
quoted_string[1:-1])
return result.decode()
return quoted_string
class GitFileChanges():
"Convenience class for file changes as part of a git commit"
def __init__(self, modes, shas, changeTypes, filenames) -> None:
self.modes = modes
self.shas = shas
self.changeTypes = changeTypes
self.filenames = filenames
class GitCommit():
"Convenience class for a git commit"
def __init__(self, commitID, name, email, description) -> None:
self.commitID = commitID
self.name = name
self.email = email
self.description = description
self.parents = []
self.fileChanges = []
self.branch = None
self.parentBranch = None
self.firstOnBranch = False
def userID(self):
parts = self.email.split("@")
if parts and len(parts) > 1:
return parts[0]
return self.name.replace(" ", "_")
class GitInfo:
"Extract info about Git repo"
def __init__(self, logger) -> None:
self.logger = logger
self.anonBranchInd = 0
def read_pipe_lines(self, c):
self.logger.debug('Reading pipe: %s\n' % str(c))
expand = not isinstance(c, list)
p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)
pipe = p.stdout
val = [decode_text_stream(line) for line in pipe.readlines()]
if pipe.close() or p.wait():
raise Exception('Command failed: %s' % str(c))
return val
def getCommitDiffs(self, refs):
"Return array of commits in reverse order for processing, together with dict of commits"
# Setup the rev-list/diff-tree process and read info about file diffs
# Learned from git-filter-repo
cmd = ('git rev-list --first-parent --reverse {}'.format(' '.join(refs)) +
' | git diff-tree --stdin --always --root --format=%H%n%P%n%cn%n%ce%n%B%n"__END_OF_DESC__"%n%cd' +
' --date=iso-local -M -t -c --raw --combined-all-paths')
if self.logger:
self.logger.debug(cmd)
dtp = subproc.Popen(cmd, shell=True, bufsize=-1, stdout=subprocess.PIPE)
f = dtp.stdout
commitList = []
commits = {}
line = decode_text_stream(f.readline())
if not line:
return commitList, commits
cont = bool(line)
while cont:
commitID = decode_text_stream(line).rstrip()
parents = decode_text_stream(f.readline()).split()
name = decode_text_stream(f.readline()).rstrip()
email = decode_text_stream(f.readline()).rstrip()
desc = []
in_desc = True
while in_desc:
line = decode_text_stream(f.readline()).rstrip()
if line.startswith('__END_OF_DESC__'):
in_desc = False
elif line:
desc.append(line)
date = decode_text_stream(f.readline()).rstrip()
# We expect a blank line next; if we get a non-blank line then
# this commit modified no files and we need to move on to the next.
# If there is no line, we've reached end-of-input.
line = decode_text_stream(f.readline())
if not line:
cont = False
line = line.rstrip()
# If we haven't reached end of input, and we got a blank line meaning
# a commit that has modified files, then get the file changes associated
# with this commit.
fileChanges = []
if cont and not line:
cont = False
for line in f:
line = decode_text_stream(line)
if not line.startswith(':'):
cont = True
break
n = 1 + max(1, len(parents))
assert line.startswith(':'*(n-1))
relevant = line[n-1:-1]
splits = relevant.split(None, n)
modes = splits[0:n]
splits = splits[n].split(None, n)
shas = splits[0:n]
splits = splits[n].split('\t')
change_types = splits[0]
filenames = [PathQuoting.dequote(x) for x in splits[1:]]
fileChanges.append(GitFileChanges(modes, shas, change_types, filenames))
commits[commitID] = GitCommit(commitID, name, email, '\n'.join(desc))
commits[commitID].parents = parents
commits[commitID].fileChanges = fileChanges
commitList.append(commitID)
# Close the output, ensure rev-list|diff-tree pipeline completed successfully
dtp.stdout.close()
if dtp.wait():
raise SystemExit(("Error: rev-list|diff-tree pipeline failed; see above.")) # pragma: no cover
return commitList, commits
def getFileChanges(self, commit):
"Return file changes for a commit which is a merge - thus itself against its first parent"
cmd = ('git diff-tree -r {} {}'.format(commit.commitID, commit.parents[0]))
if self.logger:
self.logger.debug(cmd)
dtp = subproc.Popen(cmd, shell=True, bufsize=-1, stdout=subprocess.PIPE)
f = dtp.stdout
fileChanges = []
for line in f:
line = decode_text_stream(line)
if not line.startswith(':'):
continue
n = 2 # 1 + max(1, len(commit.parents))
assert line.startswith(':'*(n-1))
relevant = line[n-1:-1]
splits = relevant.split(None, n)
modes = splits[0:n]
splits = splits[n].split(None, n)
shas = splits[0:n]
splits = splits[n].split('\t')
change_types = splits[0]
filenames = [PathQuoting.dequote(x) for x in splits[1:]]
fileChanges.append(GitFileChanges(modes, shas, change_types, filenames))
dtp.stdout.close()
if dtp.wait():
raise SystemExit(("Error: {} failed; see above.".format(cmd))) # pragma: no cover
return fileChanges
def getBranchCommits(self, branchRefs):
"Returns a list of commit ids on the referenced branches"
branchCommits = {}
for b in branchRefs:
branchCommits[b] = []
cmd = ('git rev-list --first-parent {}'.format(b))
if self.logger:
self.logger.debug(cmd)
dtp = subproc.Popen(cmd, shell=True, bufsize=-1, stdout=subprocess.PIPE)
f = dtp.stdout
line = decode_text_stream(f.readline())
if not line:
return
cont = bool(line)
while cont:
commit = decode_text_stream(line).rstrip()
branchCommits[b].append(commit)
line = decode_text_stream(f.readline())
if not line:
break
dtp.stdout.close()
if dtp.wait():
raise SystemExit("Error: {} failed; see above.".format(cmd)) # pragma: no cover
return branchCommits
# def updateBranchInfo(self, branchRefs, commitList, commits):
# "Updates the branch details for every commit"
# branchCommits = self.getBranchCommits(branchRefs)
# for b in branchRefs:
# for id in branchCommits[b]:
# if not id in commitList:
# raise P4TException("Failed to find commit: %s" % id)
# commits[id].branch = b
# # Now update anonymous branches - in commit order (so parents first)
# for id in commitList:
# if not commits[id].branch:
# firstParent = commits[id].parents[0]
# assert(commits[firstParent].branch is not None)
# if not commits[firstParent].branch.startswith(ANON_BRANCH_PREFIX):
# self.anonBranchInd += 1
# anonBranch = "%s%04d" % (ANON_BRANCH_PREFIX, self.anonBranchInd)
# commits[id].branch = anonBranch
# commits[id].parentBranch = commits[firstParent].branch
# commits[id].firstOnBranch = True
# else:
# commits[id].branch = commits[firstParent].branch
class ChangeRevision:
"Represents a change - created from P4API supplied information and thus encoding"
def __init__(self, rev, change, n):
self.rev = rev
self.action = change['action'][n]
self.type = change['type'][n]
self.depotFile = change['depotFile'][n]
self.localFile = None
self.fileSize = 0
self.digest = ""
self.fixedLocalFile = None
def depotFileRev(self):
"Fully specify depot file with rev number"
return "%s#%s" % (self.depotFile, self.rev)
def localFileRev(self):
"Fully specify local file with rev number"
return "%s#%s" % (self.localFile, self.rev)
def setLocalFile(self, localFile):
self.localFile = localFile
localFile = localFile.replace("%40", "@")
localFile = localFile.replace("%23", "#")
localFile = localFile.replace("%2A", "*")
localFile = localFile.replace("%25", "%")
localFile = localFile.replace("/", os.sep)
self.fixedLocalFile = localFile
def __repr__(self):
return 'rev={rev} action={action} type={type} size={size} digest={digest} depotFile={depotfile}' .format(
rev=self.rev,
action=self.action,
type=self.type,
size=self.fileSize,
digest=self.digest,
depotfile=self.depotFile,
)
class P4Base(object):
"Processes a config"
section = None
P4PORT = None
P4CLIENT = None
P4CHARSET = None
P4USER = None
P4PASSWD = None
counter = 0
clientLogged = 0
def __init__(self, section, options, p4id):
self.section = section
self.options = options
self.logger = logging.getLogger(LOGGER_NAME)
self.p4id = p4id
self.p4 = None
self.client_logged = 0
def __str__(self):
return '[section = {} P4PORT = {} P4CLIENT = {} P4USER = {} P4PASSWD = {} P4CHARSET = {}]'.format(
self.section,
self.P4PORT,
self.P4CLIENT,
self.P4USER,
self.P4PASSWD,
self.P4CHARSET,
)
def connect(self, progname):
self.p4 = P4.P4()
self.p4.port = self.P4PORT
self.p4.client = self.P4CLIENT
self.p4.user = self.P4USER
self.p4.prog = progname
self.p4.exception_level = P4.P4.RAISE_ERROR
self.p4.connect()
if self.P4CHARSET is not None:
self.p4.charset = self.P4CHARSET
if self.P4PASSWD is not None:
self.p4.password = self.P4PASSWD
self.p4.run_login()
def p4cmd(self, *args, **kwargs):
"Execute p4 cmd while logging arguments and results"
self.logger.debug(self.p4id, args)
output = self.p4.run(args, **kwargs)
self.logger.debug(self.p4id, output)
self.checkWarnings()
return output
def disconnect(self):
if self.p4:
self.p4.disconnect()
def checkWarnings(self):
if self.p4 and self.p4.warnings:
self.logger.warning('warning result: {}'.format(str(self.p4.warnings)))
# def resetWorkspace(self):
# self.p4cmd('sync', '//%s/...#none' % self.p4.P4CLIENT)
def createClientWorkspace(self):
"""Create or adjust client workspace for target
"""
clientspec = self.p4.fetch_client(self.p4.client)
logOnce(self.logger, "orig %s:%s:%s" % (self.p4id, self.p4.client, pprint.pformat(clientspec)))
self.root = self.source.git_repo
clientspec._root = self.root
clientspec["Options"] = clientspec["Options"].replace("normdir", "rmdir")
clientspec["Options"] = clientspec["Options"].replace("noallwrite", "allwrite")
clientspec["LineEnd"] = "unix"
clientView = []
v = self.options.branch_maps[0] # Start with first one - assume to be equivalent of master
line = "%s/... //%s/..." % (v['targ'], self.p4.client)
clientView.append(line)
for exclude in ['.git/...']:
line = "-%s/%s //%s/%s" % (v['targ'], exclude, self.p4.client, exclude)
clientView.append(line)
clientspec._view = clientView
self.clientmap = P4.Map(clientView)
self.clientspec = clientspec
self.p4.save_client(clientspec)
logOnce(self.logger, "updated %s:%s:%s" % (self.p4id, self.p4.client, pprint.pformat(clientspec)))
self.p4.cwd = self.root
ctr = P4.Map('//"'+clientspec._client+'/..." "' + clientspec._root + '/..."')
self.localmap = P4.Map.join(self.clientmap, ctr)
self.depotmap = self.localmap.reverse()
def updateClientWorkspace(self, branch):
""" Adjust client workspace for new branch"""
clientspec = self.p4.fetch_client(self.p4.client)
logOnce(self.logger, "orig %s:%s:%s" % (self.p4id, self.p4.client, pprint.pformat(clientspec)))
clientView = []
if anonymousBranch(branch):
targ = "%s/%s" % (self.options.anon_branches_root, branch)
else:
for v in self.options.branch_maps:
if v['git_branch'] == branch:
targ = v['targ']
break
line = "%s/... //%s/..." % (targ, self.p4.client)
clientView.append(line)
for exclude in ['.git/...']:
line = "-%s/%s //%s/%s" % (targ, exclude, self.p4.client, exclude)
clientView.append(line)
clientspec._view = clientView
self.clientmap = P4.Map(clientView)
self.clientspec = clientspec
self.p4.save_client(clientspec)
logOnce(self.logger, "updated %s:%s:%s" % (self.p4id, self.p4.client, pprint.pformat(clientspec)))
self.logger.debug("Updated client view for branch: %s" % branch)
ctr = P4.Map('//"'+clientspec._client+'/..." "' + clientspec._root + '/..."')
self.localmap = P4.Map.join(self.clientmap, ctr)
self.depotmap = self.localmap.reverse()
def getBranchMap(self, origBranch, newBranch):
"""Create a mapping between original and new branches"""
src = ""
targ = ""
if anonymousBranch(origBranch):
src = "%s/%s" % (self.options.anon_branches_root, origBranch)
else:
for v in self.options.branch_maps:
if v['git_branch'] == origBranch:
src = v['targ']
if anonymousBranch(newBranch):
targ = "%s/%s" % (self.options.anon_branches_root, newBranch)
else:
for v in self.options.branch_maps:
if v['git_branch'] == newBranch:
targ = v['targ']
line = "%s/... %s/..." % (src, targ)
self.logger.debug("Map: %s" % line)
branchMap = P4.Map(line)
return branchMap
tempBranch = "p4_exportBranch"
class GitSource(P4Base):
"Functionality for reading from source Perforce repository"
def __init__(self, section, options):
super(GitSource, self).__init__(section, options, 'src')
self.gitinfo = GitInfo(self.logger)
def run_cmd(self, cmd, dir=".", get_output=True, timeout=2*60*60, stop_on_error=True):
"Run cmd logging input and output"
output = ""
try:
self.logger.debug("Running: %s" % cmd)
if get_output:
p = subprocess.Popen(cmd, cwd=dir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, shell=True)
if python3:
output, _ = p.communicate(timeout=timeout)
else:
output, _ = p.communicate()
# rc = p.returncode
self.logger.debug("Output:\n%s" % output)
else:
result = subprocess.run(cmd, shell=True, check=True, capture_output=True)
self.logger.debug('Result: %s' % str(result))
except subprocess.CalledProcessError as e:
self.logger.debug("Output: %s" % e.output)
if stop_on_error:
msg = 'Failed run_cmd: %d %s' % (e.returncode, str(e))
self.logger.debug(msg)
raise e
except Exception as e:
self.logger.debug("Output: %s" % output)
if stop_on_error:
msg = 'Failed run_cmd: %s' % str(e)
self.logger.debug(msg)
raise e
return output
def missingCommits(self, counter):
# self.gather_commits()
branchRefs = [t['git_branch'] for t in self.options.branch_maps]
self.gitinfo = GitInfo(self.logger)
commitList, commits = self.gitinfo.getCommitDiffs(branchRefs)
try:
ind = commitList.index(counter)
commitList = commitList[ind+1:]
except ValueError:
pass
# self.gitinfo.updateBranchInfo(branchRefs, commitList, commits)
self.logger.debug("commits: %s" % ' '.join(commitList))
maxChanges = 0
if self.options.change_batch_size:
maxChanges = self.options.change_batch_size
if self.options.maximum and self.options.maximum < maxChanges:
maxChanges = self.options.maximum
if maxChanges > 0:
commitList = commitList[:maxChanges]
self.logger.debug('processing %d commits' % len(commitList))
self.commitList = commitList
self.commits = commits
return commitList, commits
def fileModified(self, filename):
"Returns true if git thinks file has changed on disk"
args = ['git', 'status', '-z', filename]
result = self.run_cmd(' '.join(args))
return len(result) > 0
def checkoutCommit(self, commitID):
"""Expects change number as a string, and returns list of filerevs"""
args = ['git', 'switch', '-C', tempBranch, commitID]
self.run_cmd(' '.join(args), get_output=False)
class P4Target(P4Base):
"Functionality for transferring changes to target Perforce repository"
def __init__(self, section, options, source):
super(P4Target, self).__init__(section, options, 'targ')
self.source = source
self.filesToIgnore = []
self.currentBranch = ""
def formatChangeDescription(self, **kwargs):
"""Format using specified format options - see call in replicateCommit"""
format = self.options.change_description_format
format = format.replace("\\n", "\n")
t = Template(format)
result = t.safe_substitute(**kwargs)
return result
def ignoreFile(self, fname):
"Returns True if file is to be ignored"
if not self.options.re_ignore_files:
return False
for exp in self.options.re_ignore_files:
if exp.search(fname):
return True
return False
def p4_integrate(self, src, dest):
self.p4cmd("integrate", "-Dt", wildcard_encode(src), wildcard_encode(dest))
# def p4_sync(f, *options):
# p4_system(["sync"] + list(options) + [wildcard_encode(f)])
def p4_add(self, f):
# forcibly add file names with wildcards
if wildcard_present(f):
self.p4cmd("add", "-f", f)
else:
self.p4cmd("add", f)
def p4_delete(self, f):
self.p4cmd("delete", wildcard_encode(f))
def p4_edit(self, f, *options):
self.p4cmd("edit", options, wildcard_encode(f))
def p4_revert(self, f):
self.p4cmd("revert", wildcard_encode(f))
def p4_reopen(self, type, f):
self.p4cmd("reopen", "-t", type, wildcard_encode(f))
# def p4_reopen_in_change(changelist, files):
# cmd = ["reopen", "-c", str(changelist)] + files
# p4_system(cmd)
def p4_move(self, src, dest):
self.p4cmd("move", "-k", wildcard_encode(src), wildcard_encode(dest))
def replicateCommit(self, commit):
"""This is the heart of it all. Replicate a single commit/change"""
self.filesToIgnore = []
# Branch processing currently removed for now.
# if self.currentBranch == "":
# self.currentBranch = commit.branch
# if self.currentBranch != commit.branch:
# self.updateClientWorkspace(commit.branch)
# if commit.firstOnBranch:
# self.p4cmd('sync', '-k')
# fileChanges = commit.fileChanges
# if len(commit.parents) > 1:
# # merge commit
# parentBranch = self.source.commits[commit.parents[1]].branch
# branchMap = self.getBranchMap(parentBranch, commit.branch)
# else:
# branchMap = self.getBranchMap(commit.parentBranch, commit.branch)
# if len(fileChanges) == 0:
# # Do a git diff-tree to make sure we detect files changed on the target branch.
# fileChanges = self.source.gitinfo.getFileChanges(commit)
# for fc in fileChanges:
# self.logger.debug("fileChange: %s %s" % (fc.changeTypes, fc.filenames[0]))
# if fc.changeTypes == 'A':
# self.p4cmd('rec', '-af', fc.filenames[0])
# elif fc.changeTypes == 'M' or fc.changeTypes == 'MM':
# # Translate target depot to source via client map and branch map
# depotFile = self.depotmap.translate(os.path.join(self.source.git_repo, fc.filenames[0]))
# src = branchMap.translate(depotFile, 0)
# self.p4cmd('sync', '-k', fc.filenames[0])
# self.p4cmd('integrate', src, fc.filenames[0])
# self.p4cmd('resolve', '-at')
# # After whatever p4 has done to the file contents we ensure it is as per git
# if self.source.fileModified(fc.filenames[0]):
# self.p4cmd('edit', fc.filenames[0])
# args = ['git', 'restore', fc.filenames[0]]
# self.source.run_cmd(' '.join(args))
# elif fc.changeTypes == 'D':
# self.p4cmd('rec', '-d', fc.filenames[0])
# else: # Better safe than sorry! Various known actions not yet implemented
# raise P4TLogicException('Action not yet implemented: %s', fc.changeTypes)
# self.currentBranch = commit.branch
# else:
self.p4cmd('sync', '-k')
fileChanges = commit.fileChanges
if not fileChanges or (0 < len([f for f in fileChanges if f.changeTypes == 'MM'])):
# Do a git diff-tree to make sure we detect files changed on the target branch rather than just dirs
fileChanges = self.source.gitinfo.getFileChanges(commit)
if not commit.parents:
for fc in fileChanges:
self.logger.debug("fileChange: %s %s" % (fc.changeTypes, fc.filenames[0]))
if fc.filenames[0]:
filename = PathQuoting.dequote(fc.filenames[0])
if fc.changeTypes == 'A':
self.p4cmd('rec', '-af', filename)
elif fc.changeTypes == 'M':
self.p4cmd('rec', '-e', filename)
elif fc.changeTypes == 'D':