-
Notifications
You must be signed in to change notification settings - Fork 19
/
P4Transfer.py
executable file
·2733 lines (2452 loc) · 126 KB
/
P4Transfer.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) 2011-2021 Sven Erik Knop/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:
P4Transfer.py
DESCRIPTION:
This python script (2.7/3.6+ compatible) will transfer Perforce changelists with all contents
between independent servers when no remote depots are possible, and P4 DVCS commands
(such as p4 clone/fetch/zip/unzip) are not an option.
This script transfers changes in one direction - from a source server to a target server.
Usage:
python3 P4Transfer.py -h
The script requires a config file, by default transfer.yaml,
that provides the Perforce connection information for both servers.
An initial example can be generated, e.g.
P4Transfer.py --sample-config > transfer.yaml
For full documentation/usage, see project doc:
https://github.com/perforce/p4transfer/blob/main/doc/P4Transfer.adoc
"""
from __future__ import print_function, division
import sys
import re
import hashlib
import stat
import pprint
import errno
from string import Template
import argparse
import textwrap
import os.path
from datetime import datetime
import logging
import time
# Non-standard modules
import P4
import logutils
# Import yaml which will roundtrip comments
from ruamel.yaml import YAML
yaml = YAML()
VERSION = """$Id$"""
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.Revision.__repr__ = logrepr
P4.Integration.__repr__ = logrepr
P4.DepotFile.__repr__ = logrepr
# Old to new typemaps
canonicalTypes = {
"xtext": "text+x",
"ktext": "text+k",
"kxtext": "text+kx",
"xbinary": "binary+x",
"ctext": "text+C",
"cxtext": "text+Cx",
"ltext": "text+F",
"xltext": "text+Fx",
"ubinary": "binary+F",
"uxbinary": "binary+Fx",
"tempobj": "binary+FSw",
"ctempobj": "binary+Sw",
"xtempobj": "binary+FSwx",
"xunicode": "unicode+x",
"xutf16": "utf16+x"
}
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.")
# 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 = "P4Transfer"
CHANGE_MAP_DESC = "Updated change_map_file"
# This is for writing to sample config file
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: p4transfer_counter
# case_sensitive: Set this to True if source/target servers are both case sensitive.
# Otherwise case inconsistencies can cause problems when conversion runs on Linux
case_sensitive: True
# historical_start_change: Set this if you require P4Transfer to start with this changelist.
# A historical start is useful if you have 100,000 changelists in source server and want to only
# transfer the last 10,000. Set this value to the first change to be transferred.
# Once you have set this value and started a transfer DO NOT MODIFY IT or you will potentially
# mess up integration history etc!!!!!
# IMPORTANT NOTE: setting this value causes extra work to be done for every integration to adjust
# revision ranges - thus slowing down transfers.
# If not set, or 0 then transfer starts from the value of counter_name above, and assumes that ALL HISTORY
# of included files is transferred.
historical_start_change:
# instance_name: Name of the instance of P4Transfer - for emails etc. Spaces allowed.
instance_name: "Perforce 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 <[email protected]>"
# mail_to:
# - "[email protected]"
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
mail_to:
# mail_from: Email address of sender of emails, E.g. [email protected]
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"
# sync_progress_size_interval (Integer): Size in bytes controlling when syncs are reported to log file.
# Useful for keeping an eye on progress for large syncs over slow network links.
sync_progress_size_interval: "500 * 1000 * 1000"
# 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, $sourcePort, $sourceUser
change_description_format: \"$sourceDescription\\n\\nTransferred from p4://$sourcePort@$sourceChange\"
# change_map_file: Name of an (optional) CSV file listing mappings of source/target changelists.
# If this is blank (DEFAULT) then no mapping file is created.
# If non-blank, then a file with this name in the target workspace is appended to
# and will be submitted after every sequence (batch_size) of changes is made.
# Default type of this file is text+CS32 to avoid storing too many revisions.
# File must be mapped into target client workspace.
# File can contain a sub-directory, e.g. change_map/change_map.csv
# Note that due to the way client workspace views are created the local filename
# should include a valid source path including depot name, e.g.
# //depot/export/... -> depot/export/change_map.csv
change_map_file:
# superuser: Set to n if not a superuser (so can't update change times - can just transfer them).
superuser: "y"
# ignore_files: An array of regex patterns which are used to ingore any matching files.
# Allows you to ignore some issues which cause transfer problems.
# E.g.
# ignore_files:
# - "some/files/to/*ignore$"
ignore_files:
source:
# 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:
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:
# workspace_root: Root directory to use for both client workspaces.
# This will be used to update the client workspace Root: field for both source/target workspaces
# They must be the same.
# Make sure there is enough space to hold the largest single changelist that will be transferred!
workspace_root: /work/transfer
# views: An array of source/target view mappings
# You are not allowed to specify both 'views' and 'stream_views' - leave one or other blank!!
# Each value is a string - normally quote. Standard p4 wildcards are valid.
# These values are used to construct the appropriate View: fields for source/target client workspaces
# It is allowed to have exclusion mappings - by specifying the '-' as first character in 'src'
# entry - see last example below.
views:
- src: "//depot/source_path1/..."
targ: "//import/target_path1/..."
- src: "//depot/source_path2/..."
targ: "//import/target_path2/..."
- src: "-//depot/source_path2/exclude/*.tgz"
targ: "//import/target_path2/exclude/*.tgz"
# transfer_target_stream: The name of a special target stream to use - IT SHOULD NOT CONTAIN FILES!!
# This will be setup as a mainline stream, with no sharing and with import+ mappings
# It is in standard stream name format, e.g. //<depot>/<name> or //<depot>/<mid>/<name>
# e.g. transfer_target_stream: //targ_streams/transfer_target
transfer_target_stream:
# stream_views: An array of source/target stream view mappings and other record fields.
# You are not allowed to specify both 'views' and 'stream_views' - leave one or other blank
# Each src/targ value is a string with '*' p4 wildcards to match stream names (like 'p4 streams //depot/rel*')
# Multiple wildcards are allowed, but make sure the number of wildcards matches between source and target.
# Please note that target depots must exist.
# Target streams will be created as required using the specified type/parent fields.
# Field 'type:' has allowed values: mainline, development, release
# Field 'parent:' should specify a suitable parent if you are creating development or release streams.
stream_views:
- src: "//streams_src/main"
targ: "//streams_targ/main"
type: mainline
parent: ""
- src: "//streams_src2/release*"
targ: "//streams_targ2/rel*"
type: mainline
parent: "//streams_targ2/main"
- src: "//src3_streams/*rel*"
targ: "//targ3_streams/*release*"
type: mainline
parent: "//targ3_streams/main"
""")
class SourceTargetTextComparison(object):
"""Decide if source and target servers are similar OS so that text
files can be compared by size and digest (no line ending differences)"""
sourceVersion = None
targetVersion = None
sourceP4DVersion = None
targetP4DVersion = None
caseSensitive = False
def _getServerString(self, server):
return server.p4cmd("info", "-s")[0]["serverVersion"]
def _getOS(self, serverString):
parts = serverString.split("/")
return parts[1]
def _getP4DVersion(self, serverString):
parts = serverString.split("/")
return parts[2]
def setup(self, src, targ, caseSensitive=True):
self.caseSensitive = caseSensitive
svrString = self._getServerString(src)
self.sourceVersion = self._getOS(svrString)
self.sourceP4DVersion = self._getP4DVersion(svrString)
svrString = self._getServerString(targ)
self.targetVersion = self._getOS(svrString)
self.targetP4DVersion = self._getP4DVersion(svrString)
def compatible(self):
if self.sourceVersion:
# TODO: compare different architectures better - e.g. allow 32 vs 64 bit
return self.sourceVersion == self.targetVersion
return False
sourceTargetTextComparison = SourceTargetTextComparison()
def specialMovesSupported():
# Minor new functionality in 2021.1 (2021.1/2126753)
# #2095201 (Job #95658, #101217) **
return sourceTargetTextComparison.sourceP4DVersion > "2021.0"
class UTCTimeFromSource(object):
"""Return offset in minutes to be added to source server timestamp to get valid target server timestamp"""
utcOffset = 0
reDate = re.compile(r"([\+\-]*)([0-9]{2})([0-9]{2})")
def _getOffsetString(self, server):
# Server date: 2015/07/13 14:52:59 -0700 PDT
# Server date: 2015/07/13 14:52:59 +0100 BST
try:
dt = server.p4cmd("info", "-s")[0]["serverDate"]
return dt.split()[2]
except:
return "0000"
def _getOffsetValue(self, offsetStr):
try:
m = self.reDate.match(offsetStr)
if m:
result = int(m.group(2)) * 60 + int(m.group(3))
if m.group(1) and m.group(1) == '-':
result = -result
return result
except:
return 0
def setup(self, src, offsetString=None):
if offsetString:
srcOffset = offsetString
else:
srcOffset = self._getOffsetString(src)
self.utcOffset = -self._getOffsetValue(srcOffset)
def offsetMins(self):
return self.utcOffset
def offsetSeconds(self):
return self.utcOffset * 60
utcTimeFromSource = UTCTimeFromSource()
def stop_file_exists(filepath):
"""Checks if a stop file exists at the given filepath."""
return os.path.exists(filepath)
STOP_FILE_NAME = "__stopfile"
STOP_FILE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), STOP_FILE_NAME)
def controlled_sleep(minutes):
start_time = time.time()
end_time = start_time + (minutes * 60)
while time.time() < end_time:
if stop_file_exists(STOP_FILE_PATH):
# Log or print that we detected the stop file and are breaking out of sleep
return True # Indicates sleep was interrupted by stop file
time.sleep(30) # Sleep for 30 seconds before checking again
return False # Indicates full sleep was completed without interruption
def isText(ftype):
"If filetype is not text - binary or unicode"
if re.search("text", ftype):
return True
return False
def isKeyTextFile(ftype):
return isText(ftype) and "k" in ftype
alreadyEscaped = re.compile(r"%25|%23|%40|%2A")
def escapeWildCards(fname):
m = alreadyEscaped.findall(fname)
if not m:
fname = fname.replace("%", "%25")
fname = fname.replace("#", "%23")
fname = fname.replace("@", "%40")
fname = fname.replace("*", "%2A")
return fname
def fileContentComparisonPossible(ftype):
"Decides if it is possible to compare size/digest for text files"
if not isText(ftype):
return True
if "k" in ftype:
return False
return sourceTargetTextComparison.compatible()
def readContents(fname):
"Reads file contents appropriate according to type"
if os.name == "posix" and os.path.islink(fname):
linktarget = os.readlink(fname)
linktarget += "\n"
return linktarget
flags = "rb"
with open(fname, flags) as fh:
contents = fh.read()
return contents
def writeContents(fname, contents):
flags = "wb"
ensureDirectory(os.path.dirname(fname))
if os.path.exists(fname):
makeWritable(fname)
with open(fname, flags) as fh:
try:
fh.write(contents)
except TypeError:
fh.write(contents.encode())
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 getLocalDigest(fname, blocksize=2**20):
"Return MD5 digest of file on disk"
m = hashlib.md5()
if os.name == "posix" and os.path.islink(fname):
linktarget = os.readlink(fname)
linktarget += "\n"
m.update(linktarget)
return m.hexdigest()
with open(fname, "rb") as f:
while True:
buf = f.read(blocksize)
if not buf:
break
m.update(buf)
return m.hexdigest()
# All possible p4 keywords (or at least their prefix - there are various $Date* ones
re_rcs_keywords = re.compile(r"\$Id|\$Header|\$Date|\$Change|\$File|\$Revision|\$Author")
def getKTextDigest(fname):
"Special calculation for ktext files - ignores lines with keywords in them"
contents = readContents(fname)
if python3:
contents = contents.decode()
m = hashlib.md5()
# Optimisation to search on whole file
if not re_rcs_keywords.search(contents):
if python3:
m.update(contents.encode())
else:
m.update(contents)
fileSize = os.path.getsize(fname)
return fileSize, m.hexdigest()
lines = contents.split("\n")
fileSize = 0
for line in lines:
if not re_rcs_keywords.search(line):
if python3:
m.update(line.encode())
else:
m.update(line)
fileSize += len(line)
return fileSize, m.hexdigest()
def diskFileContentModified(file):
fileSize = 0
digest = ""
if "symlink" in file.type:
if os.name == "posix":
assert(os.path.islink(file.fixedLocalFile))
linktarget = os.readlink(file.fixedLocalFile)
linktarget += "\n"
m = hashlib.md5()
if python3:
m.update(linktarget.encode())
else:
m.update(linktarget)
fileSize = len(linktarget)
digest = m.hexdigest()
else:
fileSize = os.path.getsize(file.fixedLocalFile)
digest = getLocalDigest(file.fixedLocalFile)
elif fileContentComparisonPossible(file.type):
try:
fileSize = os.path.getsize(file.fixedLocalFile)
digest = getLocalDigest(file.fixedLocalFile)
except EnvironmentError as e:
if e.errno == errno.ENOENT:
return False
else:
raise
elif isKeyTextFile(file.type):
fileSize, digest = getKTextDigest(file.fixedLocalFile)
return (fileSize, digest.lower()) != (int(file.fileSize), file.digest.lower())
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 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
self._integrations = []
if self.action not in ['delete', 'move/delete']:
if 'fileSize' in change:
try:
self.fileSize = change['fileSize'][n]
except IndexError:
self.fileSize = None
if 'digest' in change:
try:
self.digest = change['digest'][n]
except IndexError:
self.digest = None
def updateDigest(self):
"Update values for ktext files if required - assumes file on disk"
if not isKeyTextFile(self.type) or not self.fixedLocalFile:
return # Leave values as default
if self.action not in ['delete', 'move/delete']:
self.fileSize, self.digest = getKTextDigest(self.fixedLocalFile)
def addIntegrationInfo(self, integ):
"Add what could be more than one integration"
self._integrations.append(integ)
def hasIntegrations(self):
return len(self._integrations)
def deleteIntegrations(self, integsToDelete):
"Delete specified indexes - which are in reverse order"
for ind in integsToDelete:
del self._integrations[ind]
def numIntegrations(self):
return len(self._integrations)
def hasMoveIntegrations(self):
for integ in self._integrations:
if integ.how in ["moved from", "moved into"]:
return True
return False
def hasOnlyMovedFromIntegrations(self):
for integ in self._integrations:
if integ.how not in ["moved from"]:
return False
return True
def hasOnlyIgnoreIntegrations(self):
for integ in self._integrations:
if integ.how not in ["ignored"]:
return False
return True
def integrations(self):
"Yield in reverse order so that we replay correctly"
for ind, integ in reversed(list(enumerate(self._integrations))):
yield ind, integ
def getIntegration(self, index=0):
"Latest integration"
return self._integrations[index]
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 localIntegSourceFile(self, index=0):
"Local file without rev specifier"
return self._integrations[index].localFile
def localIntegSource(self, index=0):
"Fully specify local source with start/end of revisions"
if self._integrations[index].srev == 0:
return "%s#%d" % (self._integrations[index].localFile, self._integrations[index].erev)
return "%s#%d,%d" % (self._integrations[index].localFile, self._integrations[index].srev + 1,
self._integrations[index].erev)
def localIntegSyncSource(self, index=0):
"Fully specify local source with end rev for syncing"
return "%s#%d" % (self._integrations[index].localFile, self._integrations[index].erev)
def integSyncSource(self, index=0):
"Integration source with end rev"
return "%s#%d" % (self._integrations[index].file, self._integrations[index].erev)
def integSyncSourceWithoutRev(self, index=0):
"Integration source without env rev"
return "%s" % (self._integrations[index].file)
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,
)
def __hash__(self):
return hash(self.localFile)
def canonicalType(self):
"Translate between old style type and new canonical type"
if self.type in canonicalTypes:
return canonicalTypes[self.type]
return self.type
def __eq__(self, other, caseSensitive=True):
"For comparisons between source and target after transfer"
if caseSensitive:
if self.localFile != other.localFile: # Check filename
return False
else:
if self.localFile.lower() != other.localFile.lower():
return False
# Purge means filetype +Sn - so no comparison possible
if self.action == 'purge' or other.action == 'purge':
return True
# Can't compare branches of purged files - content is "purged file" so size 11 with fixed digest!
purgedDigest = "08F48C3930677CB9C7F42E5248D560D4"
if (self.fileSize == '11' and self.digest == purgedDigest) or (other.fileSize == '11' and other.digest == purgedDigest):
return True
if fileContentComparisonPossible(self.type):
if (self.fileSize, self.digest, self.canonicalType()) != (other.fileSize, other.digest, other.canonicalType()):
if self.type == 'utf16':
if abs(int(self.fileSize) - int(other.fileSize)) < 5:
return True
return False
return True
class ChangelistComparer(object):
"Compare two lists of filerevisions"
def __init__(self, logger, caseSensitive=True):
self.logger = logger
self.caseSensitive = caseSensitive
def listsEqual(self, srclist, targlist, filesToIgnore):
"Compare two lists of changes, with an ignore list"
srcfiles = set([chRev.localFile for chRev in srclist if chRev.localFile not in filesToIgnore])
targfiles = set([chRev.localFile for chRev in targlist])
if not self.caseSensitive:
srcfiles = set([escapeWildCards(x.lower()) for x in srcfiles])
targfiles = set([x.lower() for x in targfiles])
diffs = srcfiles.difference(targfiles)
if diffs:
return (False, "Replication failure: missing elements in target changelist:\n%s" % "\n ".join([str(r) for r in diffs]))
srcfiles = set(chRev for chRev in srclist if chRev.localFile not in filesToIgnore)
targfiles = set(chRev for chRev in targlist)
diffs = srcfiles.difference(targfiles)
if diffs:
# Check for no filesize or digest present - indicating "p4 verify -qu" should be run
new_diffs = [r for r in diffs if r.fileSize and r.digest]
if not new_diffs:
self.logger.debug("Ignoring differences due to lack of fileSize/digest or purged files")
debugDiffs = [r for r in diffs if not r.fileSize or not r.digest]
self.logger.debug("Missing deleted elements in target changelist:\n%s" % "\n ".join([str(r) for r in debugDiffs]))
return (True, "")
targlookup = {}
# Cross check again for case insensitive servers - note that this will update the lists!
if not self.caseSensitive:
for chRev in srcfiles:
chRev.localFile = chRev.localFile.lower()
for chRev in targfiles:
chRev.localFile = chRev.localFile.lower()
new_diffs = [r for r in diffs if r.fileSize and r.digest]
diffs2 = srcfiles.difference(targfiles)
if not diffs2:
return (True, "")
for chRev in targlist:
targlookup[chRev.localFile] = chRev
# For case insenstive, focus on digest rather than fileSize
new_diffs = [r for r in diffs2 if r != targlookup[escapeWildCards(r.localFile)] and r.digest != targlookup[escapeWildCards(r.localFile)].digest]
if not new_diffs:
return (True, "")
return (False, "Replication failure (case insensitive): src/target content differences found\nsrc:%s\ntarg:%s" % (
"\n ".join([str(r) for r in diffs]),
"\n ".join([str(targlookup[r.localFile]) for r in diffs])))
for chRev in targlist:
targlookup[chRev.localFile] = chRev
return (False, "Replication failure: src/target content differences found\nsrc:%s\ntarg:%s" % (
"\n ".join([str(r) for r in diffs]),
"\n ".join([str(targlookup[r.localFile]) for r in diffs])))
return (True, "")
class ReportProgress(object):
"Report overall progress"
def __init__(self, p4, changes, logger, workspace):
self.logger = logger
self.filesToSync = 0
self.changesToSync = len(changes)
self.sizeToSync = 0
self.filesSynced = 0
self.changesSynced = 0
self.sizeSynced = 0
self.previousSizeSynced = 0
self.sync_progress_size_interval = None # Set to integer value to get reports
self.logger.info("Syncing %d changes" % (len(changes)))
self.logger.info("Finding change sizes")
self.changeSizes = {}
for chg in changes:
sizes = p4.run('sizes', '-s', '//%s/...@%s,%s' % (workspace, chg['change'], chg['change']))
fcount = int(sizes[0]['fileCount'])
fsize = int(sizes[0]['fileSize'])
self.sizeToSync += fsize
self.filesToSync += fcount
self.changeSizes[chg['change']] = (fcount, fsize)
self.logger.info("Syncing filerevs %d, size %s" % (self.filesToSync, fmtsize(self.sizeToSync)))
def SetSyncProgressSizeInterval(self, interval):
"Set appropriate"
if interval:
self.sync_progress_size_interval = int(interval)
def ReportChangeSync(self):
self.changesSynced += 1
def ReportFileSync(self, fileSize):
self.filesSynced += 1
self.sizeSynced += fileSize
if not self.sync_progress_size_interval:
return
if self.sizeSynced > self.previousSizeSynced + self.sync_progress_size_interval:
self.previousSizeSynced = self.sizeSynced
syncPercent = 100 * float(self.filesSynced) / float(self.filesToSync)
sizePercent = 100 * float(self.sizeSynced) / float(self.sizeToSync)
self.logger.info("Synced %d/%d changes, files %d/%d (%2.1f %%), size %s/%s (%2.1f %%)" % (
self.changesSynced, self.changesToSync,
self.filesSynced, self.filesToSync, syncPercent,
fmtsize(self.sizeSynced), fmtsize(self.sizeToSync),
sizePercent))
class P4Base(object):
"Processes a config"
section = None
P4PORT = None
P4CLIENT = None
P4CHARSET = None
P4USER = None
P4PASSWD = None
counter = 0
clientLogged = 0
matchingStreams = []
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 streamMatches(self, srcName, streamName):
"Decides if stream matches the source view (which may contain wildcards)"
if "*" not in srcName:
return srcName == streamName
reSrc = srcName.replace(r"*", r"(.*)")
m = re.search(reSrc, streamName)
if m:
return True
return False
def matchingSourceStreams(self, view):
"Search for any streams matching the source view expanding p4 wildcards *"
streams = self.p4.run_streams(view['src']) # Valid with wildcards
if not streams:
raise P4TConfigException("No source streams found matching: '%s'" % view['src'])
return [x['Stream'] for x in streams]
def matchSourceTargetStreams(self, views):
"Search for any target streams matching the source view - only valid if called on p4 source"
self.matchingStreams = []
for v in views:
if "*" not in v['src']:
self.matchingStreams.append((v['src'], v['targ']))
continue
srcStreams = self.matchingSourceStreams(v)
reSrc = v['src'].replace(r"*", r"(.*)")
numStars = v['src'].count("*")
reTarg = v['targ'].replace(r"*", r"\1", 1)
i = 2
while i <= numStars:
reTarg = reTarg.replace(r"*", r"\%d" % i, 1)
i += 1
for s in srcStreams:
targ = re.sub(reSrc, reTarg, s)
self.matchingStreams.append((s, targ))
return self.matchingStreams
def createClientWorkspace(self, isSource, matchingStreams=None):
"Create or adjust client workspace for source or 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.options.workspace_root
clientspec._root = self.root
clientspec["Options"] = clientspec["Options"].replace("noclobber", "clobber")
clientspec["Options"] = clientspec["Options"].replace("normdir", "rmdir")
clientspec["LineEnd"] = "unix"
clientspec._view = []
# We create/update our special target stream, and also create any required target streams that don't exist
if self.options.stream_views:
if isSource:
self.matchSourceTargetStreams(self.options.stream_views)
if self.matchingStreams is None:
raise P4TConfigException("No matching src/target streams found: %s" % str(self.options.stream_views))
for s in self.matchingStreams:
src = s[0]
srcPath = src.replace('//', '')
line = "%s/... //%s/%s/..." % (src, self.p4.client, srcPath)
clientspec._view.append(line)
else:
transferStream = self.p4.fetch_stream(self.options.transfer_target_stream)
origStream = dict(transferStream)
transferStream["Type"] = "mainline"
transferStream["Paths"] = []
targStreamsUpdated = False
for v in self.options.stream_views:
for s in matchingStreams: # Array of tuples passed in
src = s[0]
targ = s[1]
if not self.streamMatches(v['src'], src):
continue
srcPath = src.replace('//', '')
line = "import+ %s/... %s/..." % (srcPath, targ)
transferStream["Paths"].append(line)
targStream = self.p4.fetch_stream('-t', v['type'], targ)
origTargStream = dict(targStream)
targStream['Type'] = v['type']
if v['parent']: