forked from rghe/perfarce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
perfarce.py
1914 lines (1585 loc) · 65.9 KB
/
perfarce.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
# Mercurial extension to push to and pull from Perforce depots.
#
# Copyright 2009-16 Frank Kingswood <[email protected]>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2, incorporated herein by reference.
'''Push to or pull from Perforce depots
This extension modifies the remote repository handling so that repository
paths that resemble
p4://p4server[:port]/clientname[/path/to/directory]
cause operations on the named p4 client specification on the p4 server.
The client specification must already exist on the server before using
this extension. Making changes to the client specification Views causes
problems when synchronizing the repositories, and should be avoided.
If a /path/to/directory is given then only a subset of the p4 view
will be operated on. Multiple partial p4 views can use the same p4
client specification.
Five built-in commands are overridden:
outgoing If the destination repository name starts with p4:// then
this reports files affected by the revision(s) that are
in the local repository but not in the p4 depot.
push If the destination repository name starts with p4:// then
this exports changes from the local repository to the p4
depot. If no revision is specified then all changes since
the last p4 changelist are pushed. In either case, all
revisions to be pushed are folded into a single p4 changelist.
Optionally the resulting changelist is submitted to the p4
server, controlled by the --submit option to push, or by
setting
--config perfarce.submit=True
If the option
--config perfarce.keep=False
is False then after a successful submit the files in the
p4 workarea will be deleted.
pull If the source repository name starts with p4:// then this
imports changes from the p4 depot, automatically creating
merges of changelists submitted by hg push.
If the option
--config perfarce.keep=False
is False then the import does not leave files in the p4
workarea, otherwise the p4 workarea will be updated
with the new files.
The option
--config perfarce.tags=False
can be used to disable pulling p4 tags (a.k.a. labels).
The option
--config perfarce.pull_trim_log=False
can be used to remove the {{mercurial}} node IDs from both
p4 and the imported changes. Use with care as this is a
non-reversible operation.
--config perfarce.clientuser=script_or_regex
can be used to enable quasi-multiuser operation, where
several users submit changes to p4 with the same user name
and have their real user name in the p4 client spec.
If the value of this parameter contains at least one space
then it is split into a search regular expression and
replacement string. The search and replace regular expressions
describe the substitution to be made to turn a client spec name
into a user name. If the search regex does not match then the
username is left unchanged.
If the value of this parameter has no spaces then it is
taken as the name of a script to run. The script is run
with the client and user names as arguments. If the script
produces output then this is taken as the user name,
otherwise the username is left unchanged.
incoming If the source repository name starts with p4:// then this
reports changes in the p4 depot that are not yet in the
local repository.
clone If the source repository name starts with p4:// then this
creates the destination repository and pulls all changes
from the p4 depot into it.
If the option
--config perfarce.lowercasepaths=False
is True then the import forces all paths in lowercase,
otherwise paths are recorded unchanged. Filename case is
preserved.
If the option
--config perfarce.ignorecase=False
is True then the import ignores all case differences in
the p4 depot. Directory and filename case is preserved.
These two setting are workarounds to handle Perforce depots
containing a path spelled differently from file to file
(e.g. path/foo and PAth/bar are in the same directory),
or where the same file may be spelled differently from time
to time (e.g. path/foo and path/FOO are the same object).
'''
from mercurial import cmdutil, commands, context, copies, encoding, error, extensions, hg, node, phases, scmutil, util, url
from mercurial.node import hex, short
from mercurial.i18n import _
from mercurial.error import ConfigError
try:
from mercurial import registrar
except ImportError:
registrar=None
try:
from mercurial.interfaces.repository import peer as peerrepository
except ImportError:
try:
from mercurial.repository import peer as peerrepository
except ImportError:
try:
from mercurial.repo import repository as peerrepository
except ImportError:
from mercurial.peer import peerrepository
import marshal, os, re, string, sys
propertycache=util.propertycache
try:
from mercurial.utils.procutil import shellquote, popen
except ImportError:
from mercurial.util import shellquote
try:
from mercurial.utils.dateutil import datestr
except ImportError:
from mercurial.util import datestr
try:
from mercurial.scmutil import revsymbol
except ImportError:
def revsymbol(repo, symbol):
return symbol
file = open
cmdtable = {}
if registrar is not None:
command = registrar.command(cmdtable)
else:
command = cmdutil.command(cmdtable)
if tuple(util.version().split(b".",2)) < (b"4",b"6"):
def revpairnodes(repo, rev):
return scmutil.revpair(repo, rev)
else:
# Mercurial 4.6: revpair started returning ctx objects instead of node
def revpairnodes(repo, rev):
ctx1, ctx2 = scmutil.revpair(repo, rev)
return ctx1.node(), ctx2.node()
def uisetup(ui):
'''monkeypatch pull and push for p4:// support'''
extensions.wrapcommand(commands.table, b'pull', pull)
p = extensions.wrapcommand(commands.table, b'push', push)
p[1].append((b'', b'submit', None, 'for p4:// destination submit new changelist to server'))
p[1].append((b'', b'job', [], b'for p4:// destination set job id(s)'))
extensions.wrapcommand(commands.table, b'incoming', incoming)
extensions.wrapcommand(commands.table, b'outgoing', outgoing)
p = extensions.wrapcommand(commands.table, b'clone', clone)
p[1].append((b'', b'startrev', b'', b'for p4:// source set initial revisions for clone'))
p[1].append((b'', b'encoding', b'', b'for p4:// source set encoding used by server'))
hg.schemes['p4'] = p4repo
# --------------------------------------------------------------------------
class p4repo(peerrepository):
'Dummy repository class so we can use -R for p4submit and p4revert'
def __init__(self, ui, path):
self.path = path
self.ui = ui
self.root = None
@staticmethod
def instance(ui, path, create):
return p4repo(ui, path)
def local(self):
return True
def __getattr__(self, a):
raise error.Abort(_('%s not supported for p4') % a)
def loaditer(f):
"Yield the dictionary objects generated by p4"
try:
while True:
d = marshal.load(f)
if not d:
break
yield d
except EOFError:
pass
class p4notclient(error.Abort):
"Exception raised when a path is not a p4 client or invalid"
pass
class p4badclient(error.Abort):
"Exception raised when a path is an invalid p4 client"
pass
class TempFile:
"Temporary file"
def __init__(self, mode):
import tempfile
fd, self.Name = tempfile.mkstemp(prefix='hg-p4-')
if mode:
self.File = os.fdopen(fd, mode)
else:
os.close(fd)
self.File = None
def close(self):
if self.File:
self.File.close()
self.File=None
def __del__(self):
self.close()
try:
os.unlink(self.Name)
except Exception:
pass
def int_to_bytes(x: int) -> bytes:
if isinstance(x, bytes):
return x
return str(x).encode()
def encode_bool(b):
if isinstance(b, bytes):
return b
if b:
return b"true"
return b"false"
class p4client(object):
def __init__(self, ui, repo, path):
'initialize a p4client class from the remote path'
if not path.startswith(b'p4:'):
raise p4notclient(_('%s not a p4 repository') % path)
if not path.startswith(b'p4://'):
raise p4badclient(_('%s not a p4 repository') % path)
self.ui = ui
self.repo = repo
self.server = None # server name:port
self.client = None # client spec name
self.root = None # root directory of client workspace
self.partial = None # tail of path for partial checkouts (ending in /), or empty string
self.rootpart = None # root+partial directory in client workspace (ending in /)
self.keep = ui.configbool(b'perfarce', b'keep', True)
self.lowercasepaths = ui.configbool(b'perfarce', b'lowercasepaths', False)
self.ignorecase = ui.configbool(b'perfarce', b'ignorecase', False)
# caches
self.clientspec = {}
self.usercache = {}
self.p4stat = None
self.p4pending = None
if tuple(util.version().split(b".",2)) < (b"3",b"2"):
self.getfile_none=self.getfile_none_ioerr
else:
self.getfile_none=self.getfile_none_none
s, c = path[5:].split(b'/', 1)
if b':' not in s:
s = '%s:1666' % s
self.server = s
if c:
if b'/' in c:
c, p = c.split(b'/', 1)
p = b'/'.join(q for q in p.split(b'/') if q)
if p:
p += b'/'
else:
p = b''
d = self.runone(b'client -o %s' % shellquote(c), abort=False)
if not isinstance(d, dict):
raise p4badclient(_('%s is not a valid p4 client') % path)
code = d.get(b'code')
if code == b'error':
data=d[b'data'].strip()
ui.warn('%s\n' % data)
raise p4badclient(_('%s is not a valid p4 client: %s') % (path, data))
if sys.platform.startswith("cygwin"):
re_dospath = re.compile('[a-z]:\\\\',re.I)
def isdir(d):
return os.path.isdir(d) and not re_dospath.match(d)
else:
isdir=os.path.isdir
for n in [b'Root'] + [b'AltRoots%d' % i for i in range(9)]:
if n in d and isdir(d[n]):
self.root = util.pconvert(d[n])
break
if not self.root:
ui.note(_('the p4 client root must exist\n'))
raise p4badclient(_('the p4 client root must exist\n'))
self.clientspec = d
self.client = c
self.partial = p
if p:
if self.lowercasepaths:
p = self.normcase(p)
p = os.path.join(self.root, p)
else:
p = self.root
self.rootpart = util.pconvert(p)
if not self.rootpart.endswith(b'/'):
self.rootpart += b'/'
if self.root.endswith(b'/'):
self.root = self.root[:-1]
def find(self, rev=None, base=False, p4rev=None, abort=True):
'''Find the most recent revision which has the p4 extra data which
gives the p4 changelist it was converted from. If base is True then
return the most recent child of that revision where the only changes
between it and the p4 changelist are to .hg files.
Returns the revision and p4 changelist number'''
def dothgonly(ctx):
'returns True if only .hg files in this context'
if not ctx.files():
# no files means this must have been a merge
return False
for f in ctx.files():
if not f.startswith(b'.hg'):
return False
return True
try:
mqnode = [self.repo[revsymbol(self.repo, b'qbase')].node()]
except Exception:
mqnode = None
if rev is None:
rev = revsymbol(self.repo, b'default')
current = self.repo[rev]
current = [(current,())]
seen = set()
while current:
next = []
self.ui.debug(b"find: %s\n" % (b" ".join(hex(c[0].node()) for c in current)))
for ctx,path in current:
extra = ctx.extra()
if b'p4' in extra:
if base:
while path:
if dothgonly(path[0]) and not (mqnode and
self.repo.changelog.nodesbetween(mqnode, [ctx.node()])[0]):
ctx = path[0]
path = path[1:]
else:
path = []
p4 = int(extra[b'p4'])
if not p4rev or p4==p4rev:
return ctx.node(), p4
for p in ctx.parents():
if p and p not in seen:
seen.add(p)
next.append((p, (ctx,) + path))
current = next
if abort:
raise error.Abort(_('no p4 changelist revision found'))
return node.nullid, 0
@propertycache
def re_type(self): return re.compile(b'([a-z]+)?(text|binary|symlink|apple|resource|unicode|utf\d+)(\+\w+)?$')
@propertycache
def re_keywords(self): return re.compile(rb'\$(Id|Header|Date|DateTime|Change|File|Revision|Author):[^$\n]*\$')
@propertycache
def re_keywords_old(self): return re.compile(b'\$(Id|Header):[^$\n]*\$')
def decodetype(self, p4type):
'decode p4 type name into mercurial mode string and keyword substitution regex'
base = mode = b''
keywords = None
utf16 = False
p4type = self.re_type.match(p4type)
if p4type:
base = p4type.group(2)
flags = (p4type.group(1) or b'') + (p4type.group(3) or b'')
if b'x' in flags:
mode = b'x'
if base == b'symlink':
mode = b'l'
if base == b'utf16':
utf16 = True
if b'ko' in flags:
keywords = self.re_keywords_old
elif b'k' in flags:
keywords = self.re_keywords
return base, mode, keywords, utf16
@propertycache
def encoding(self):
# work out character set for p4 text (but not filenames)
emap = { 'none': 'ascii',
'utf8-bom': 'utf_8_sig',
'macosroman': 'mac-roman',
'winansi': 'cp1252' }
e = os.environ.get("P4CHARSET")
if e:
return emap.get(e,e)
return self.ui.config(b'perfarce', b'encoding', None)
def decode(self, text):
'decode text in p4 character set as utf-8'
if self.encoding:
try:
return text.decode(self.encoding).encode(encoding.encoding)
except LookupError as e:
raise error.Abort("%s, please check your locale settings" % e)
return text
def encode(self, text):
'encode utf-8 text to p4 character set'
if self.encoding:
try:
return text.decode(encoding.encoding).encode(self.encoding)
except LookupError as e:
raise error.Abort("%s, please check your locale settings" % e)
return text
@staticmethod
def encodename(name):
'escape @ # % * characters in a p4 filename'
return name.replace(b'%',b'%25').replace(b'@',b'%40').replace(b'#',b'%23').replace(b'*',b'%2A')
@staticmethod
def normcase(name):
'convert path name to lower case'
return os.path.normpath(name).lower()
@propertycache
def re_hgid(self): return re.compile(b'{{mercurial (([0-9a-f]{40})(:([0-9a-f]{40}))?)}}')
def parsenodes(self, desc):
'find revisions in p4 changelist description'
m = self.re_hgid.search(desc)
nodes = []
if m:
try:
nodes = self.repo.changelog.nodesbetween(
[self.repo[m.group(2)].node()], [self.repo[m.group(4) or m.group(2)].node()])[0]
except Exception:
if self.ui.traceback:self.ui.traceback()
self.ui.note(_(b'ignoring hg revision range %s from p4\n' % m.group(1)))
return nodes, m
def configint(self, section, name, default=None):
'helper for configint which is missing before Mercurial 1.9'
try:
return self.ui.configint(section, name, default)
except AttributeError:
return int(self.ui.config(section, name, default))
@propertycache
def maxargs(self):
try:
r = self.configint(b'perfarce', b'maxargs', 0)
except ConfigError:
r = 0
if r<1:
if os.name == 'posix':
r = 250
else:
r = 25
return r
def run(self, cmd, files=[], abort=True, client=None):
'Run a P4 command and yield the objects returned'
c = [b'p4', b'-G']
if self.server:
c.append(b'-p')
c.append(self.server)
if client or self.client:
c.append(b'-c')
c.append(client or self.client)
if self.root:
c.append(b'-d')
c.append(shellquote(self.root))
if files and len(files)>self.maxargs:
tmp = TempFile('w')
for f in files:
if self.ui.debugflag: self.ui.debug(b'> -x %s\n' % f)
print(f, file=tmp.File)
tmp.close()
c.append(b'-x')
c.append(tmp.Name)
files = []
c.append(cmd)
cs = b' '.join(c + [shellquote(f) for f in files])
if self.ui.debugflag: self.ui.debug(b'> %s\n' % cs)
for d in loaditer(popen(cs, b'rb')):
if self.ui.debugflag: self.ui.debug(b'< %r\n' % d)
code = d.get(b'code')
data = d.get(b'data')
if code is not None and data is not None:
data = data.strip()
if abort and code == b'error':
raise error.Abort(b'p4: %s' % data)
elif code == b'info':
self.ui.note(b'p4: %s\n' % data)
yield d
def runs(self, cmd, **args):
'''Run a P4 command, discarding any output (except errors)'''
for d in self.run(cmd, **args):
pass
def runone(self, cmd, **args):
'''Run a P4 command and return the object returned'''
value=None
for d in self.run(cmd, **args):
if value is None:
value = d
else:
raise error.Abort(_('p4 %s returned more than one object') % cmd)
if value is None:
raise error.Abort(_('p4 %s returned no objects') % cmd)
return value
def getpending(self, node):
'''returns True if node is pending in p4 or has been submitted to p4'''
if self.p4stat is None:
self._readp4stat()
return node.node() in self.p4stat
def getpendinglist(self):
'return p4 submission state dictionary'
if self.p4stat is None:
self._readp4stat()
return self.p4pending
def _readp4stat(self):
'''read pending and submitted changelists into pending cache'''
self.p4stat = set()
self.p4pending = []
p4rev, p4id = self.find(abort=False)
def helper(self,d,p4id):
c = int(d[b'change'])
if c == p4id:
return
desc = d[b'desc']
nodes, match = self.parsenodes(desc)
entry = (c, d[b'status'] == b'submitted', nodes, desc, d[b'client'])
self.p4pending.append(entry)
for n in nodes:
self.p4stat.add(n)
change = b'%s...@%d,#head' % (self.partial, p4id)
for d in self.run(b'changes -l -c %s %s' %
(shellquote(self.client), shellquote(change))):
helper(self,d,p4id)
for d in self.run(b'changes -l -c %s -s pending' %
(shellquote(self.client))):
helper(self,d,p4id)
self.p4pending.sort()
def repopath(self, path):
'Convert a p4 client path to a path relative to the hg root'
if self.lowercasepaths:
pathname, fname = os.path.split(path)
path = os.path.join(self.normcase(pathname), fname)
path = util.pconvert(path)
if not path.startswith(self.rootpart):
raise error.Abort(_('invalid p4 local path %s') % path)
return path[len(self.rootpart):]
def localpath(self, path):
'Convert a path relative to the hg root to a path in the p4 workarea'
return util.localpath(os.path.join(self.rootpart, path))
def getuser(self, user, client=None):
'get full name and email address of user (and optionally client spec name)'
r = self.usercache.get((user,None)) or self.usercache.get((user,client))
if r:
return r
# allow mapping the client name into a user name
cu = self.ui.config(b"perfarce",b"clientuser")
if cu and b" " in cu:
cus, cur = cu.split(b" ", 1)
u, f = re.subn(cus, cur, client)
if f:
r = string.capwords(u)
self.usercache[(user, client)] = r
return r
elif cu:
cmd = b"%s %s %s" % (util.expandpath(cu), shellquote(client), shellquote(user))
self.ui.debug(b'> %s\n' % cmd)
old = os.getcwd()
try:
os.chdir(self.root)
r = None
for r in util.popen(cmd):
r = r.strip()
self.ui.debug(b'< %r\n' % r)
if r:
self.usercache[(user, client)] = r
return r
finally:
os.chdir(old)
else:
d = self.runone(b'user -o %s' % shellquote(user), abort=False)
if b'Update' in d:
try:
r = b'%s <%s>' % (d[b'FullName'], d[b'Email'])
self.usercache[(user, None)] = r
return r
except Exception:
pass
return user
@propertycache
def re_changeno(self): return re.compile(b'Change ([0-9]+) created.+')
def change(self, change=None, description=None, update=False, jobs=None):
'''Create a new p4 changelist or update an existing changelist with
the given description. Returns the changelist number as a string.'''
# get changelist data, and update it
changelist = self.runone(b'change -o %s' % (change or b''))
if jobs:
for i,j in enumerate(jobs):
changelist[b'Jobs%d'%i] = self.encode(j)
if description is not None:
changelist[b'Description'] = self.encode(description)
# write changelist data to a temporary file
tmp = TempFile('wb')
marshal.dump(changelist, tmp.File, 0)
tmp.close()
# update p4 changelist
d = self.runone(b'change -i%s <%s' % (update and b" -u" or b"", shellquote(tmp.Name.encode('utf-8'))))
data = d[b'data']
if d[b'code'] == b'info':
if not self.ui.verbose:
self.ui.status(b'p4: %s\n' % data)
if not change:
m = self.re_changeno.match(data)
if m:
change = m.group(1)
else:
raise error.Abort(_('error creating p4 change: %s') % data)
if not change:
raise error.Abort(_('did not get changelist number from p4'))
# invalidate cache
self.p4stat = None
return change
class description:
'Changelist description'
def __init__(self, **args):
self.__dict__.update(args)
def __repr__(self):
return "%s(%s)"%(self.__class__.__name__,
", ".join("%s=%r"%(k,getattr(self,k)) for k in sorted(self.__dict__.keys())))
actions = { b'add':b'A', b'branch':b'A', b'move/add':b'A',
b'edit':b'M', b'integrate':b'M', b'import':b'A',
b'delete':b'R', b'move/delete':b'R', b'purge':b'R',
}
def describe(self, change, local=None, shelve=False):
'''Return p4 changelist description object with user name and date.
If the local is true, then also collect a list of 5-tuples
(depotname, revision, type, action, localname)
If local is false then the files list returned holds 4-tuples
(depotname, revision, type, action)
Retrieving the local filenames is potentially very slow, even more
so when this is used on pending changelists.
'''
d = self.runone(b'describe -%s %s' % (b"S" if shelve else b"s", int_to_bytes(change)))
client = d[b'client']
status = d[b'status']
r = self.description(change=d[b'change'],
desc=self.decode(d[b'desc']),
user=self.getuser(self.decode(d[b'user']), client),
date=(int(d[b'time']), 0), # p4 uses UNIX epoch
status=status,
client=client)
files = {}
if local and status=='submitted':
r.files = self.fstat(change)
else:
r.files = []
i = 0
while True:
df = b'depotFile%d' % i
if df not in d:
break
df = d[df]
rv = d[b'rev%d' % i]
tp = d[b'type%d' % i]
ac = d[b'action%d' % i]
files[df] = item = (df, int(rv), tp, self.actions[ac])
r.files.append(item)
i += 1
r.jobs = []
i = 0
while True:
jn = b'job%d' % i
if jn not in d:
break
r.jobs.append(d[jn])
i += 1
if local and files:
r.files = []
for d in self.run(b'where', files=[f for f in files]):
r.files.append(files[d[b'depotFile']] + (self.repopath(d[b'path']),))
return r
def fstat(self, change=None, all=False, files=[]):
'''Find local names for all the files belonging to a changelist.
Returns a list of tuples
(depotname, revision, type, action, localname)
with only entries for files that appear in the workspace.
If all is unset considers only files modified by the
changelist, otherwise returns all files *at* that changelist.
'''
result = []
if files:
p4cmd = b'fstat'
elif all:
p4cmd = b'fstat %s' % shellquote(b'%s...@%d' % (self.partial, change))
else:
p4cmd = b'fstat -e %d %s' % (change, shellquote(b'%s...' % self.partial))
for d in self.run(p4cmd, files=files):
if len(result) % 250 == 0:
if hasattr(self.ui, 'progress'):
self.ui.progress(b'p4 fstat', len(result), unit=b'entries')
else:
self.ui.note(_(b'%d files\r') % len(result))
self.ui.flush()
if b'desc' in d or d[b'clientFile'].startswith(b'.hg'):
continue
else:
lf = self.repopath(d[b'clientFile'])
df = d[b'depotFile']
rv = d[b'headRev']
tp = d[b'headType']
ac = d[b'headAction']
result.append((df, int(rv), tp, self.actions[ac], lf))
if hasattr(self.ui, 'progress'):
self.ui.progress('p4 fstat', None)
self.ui.note(_(b'%d files \n') % len(result))
return result
def sync(self, change, fake=False, force=False, all=False, files=[]):
'''Synchronize the client with the depot at the given change.
Setting fake adds -k, force adds -f option. The all option is
not used here, but indicates that the caller wants all the files
at that revision, not just the files affected by the change.'''
cmd = b'sync'
if fake:
cmd += b' -k'
elif force:
cmd += b' -f'
if not files:
cmd += b' ' + shellquote(b'%s...@%d' % (self.partial, change))
n = 0
for d in self.run(cmd, files=[(b"%s@%d" % (os.path.join(self.partial, f), change)) for f in files], abort=False):
n += 1
if n % 250 == 0:
if hasattr(self.ui, 'progress'):
self.ui.progress('p4 sync', n, unit='files')
code = d.get(b'code')
if code == b'error':
data = d[b'data'].strip()
if d[b'generic'] == 17 or d[b'severity'] == 2:
self.ui.note(b'p4: %s\n' % data)
else:
raise error.Abort(b'p4: %s' % data)
if hasattr(self.ui, 'progress'):
self.ui.progress('p4 sync', None)
if files and n < len(files):
raise error.Abort(_('incomplete reply from p4, reduce maxargs'))
def getfile_none_ioerr(self, entry):
"Mercurial up to 3.1 uses IOError to signal removed files"
self.ui.debug(b'getfile ioerror on %r\n'%(entry,))
raise IOError()
def getfile_none_none(self, entry):
"Mercurial from 3.2 uses None,None to signal removed files"
return None, None
def getfile(self, entry):
'''Return contents of a file in the p4 depot at the given revision number.
Entry is a tuple
(depotname, revision, type, action, localname)
If self.keep is set, assumes that the client is in sync.
Raises IOError or returns None,None if the file is deleted (depending on version).
'''
if entry[3] == b'R':
return self.getfile_none(entry)
try:
basetype, mode, keywords, utf16 = self.decodetype(entry[2])
if self.keep:
fn = self.localpath(entry[4])
if mode == b'l':
try:
contents = os.readlink(fn)
except AttributeError:
contents = file(fn, 'rb').read()
if contents.endswith('\n'):
contents = contents[:-1]
else:
contents = file(fn, 'rb').read()
else:
cmd = b'print'
if utf16:
tmp = TempFile(None)
tmp.close()
cmd += b' -o %s'%shellquote(tmp.Name)
cmd += b' %s#%d' % (shellquote(entry[0]), entry[1])
contents = []
for d in self.run(cmd):
code = d[b'code']
if code == b'text' or code == b'binary':
contents.append(d[b'data'])
if utf16:
contents = file(tmp.Name, 'rb').read()
else:
contents = b''.join(contents)
if mode == b'l' and contents.endswith('\n'):
contents = contents[:-1]
if keywords:
contents = keywords.sub('$\\1$', contents)
return mode, contents
except Exception as e:
if self.ui.traceback:self.ui.traceback()
raise error.Abort(_('file %s missing in p4 workspace') % entry[4])
@propertycache
def tags(self):
try:
t = self.configint(b'perfarce', b'tags', -1)
except (ConfigError,ValueError) as e:
t = -1
if t<0 or t>2:
t = self.ui.configbool(b'perfarce', b'tags', True)
return t
def labels(self, change):
'Return p4 labels a.k.a. tags at the given changelist'
tags = []
if self.tags:
change = b'%s...@%d,%d' % (self.partial, change, change)
for d in self.run(b'labels %s' % shellquote(change)):
l = d.get(b'label')
if l:
tags.append(l)
return tags
def submit(self, change):
'''submit one changelist to p4 and optionally delete the files added
or modified in the p4 workarea'''
cl = None
for d in self.run(b'submit -c %s' % int_to_bytes(change)):
if d[b'code'] == b'error':
raise error.Abort(_('error submitting p4 change %s: %s') % (int_to_bytes(change), d['data']))
cl = d.get(b'submittedChange', cl)
self.ui.note(_(b'submitted changelist %s\n') % cl)
if not self.keep:
# delete the files in the p4 client directory
self.sync(0)
# invalidate cache
self.p4stat = None
def hasmovecopy(self):
'''detect whether p4 move and p4 copy are supported.
these advanced features are available since about 2009.1 or so.'''
mc = []
for op in b'move',b'copy':
v = self.ui.configbool(b'perfarce', op, None)
if v is None:
self.ui.note(_(b'checking if p4 %s is supported, set perfarce.%s to skip this test\n') % (op, op))
d = self.runone(b'help %s' % op, abort=False)
v = d[b'code']==b'info'
self.ui.debug(_(b'p4 %s is %ssupported\n') % (op, [b"not ",b""][v]))
mc.append(v)
return tuple(mc)
@staticmethod
def pullcommon(original, ui, repo, source, **opts):
'Shared code for pull and incoming'
if opts.get(b'mq',None):
return True, original(ui, repo, *(source and [source] or []), **opts)
source = ui.expandpath(source or b'default')
try:
client = p4client(ui, repo, source)
except p4notclient:
if ui.traceback:ui.traceback()
return True, original(ui, repo, *(source and [source] or []), **opts)
except p4badclient as e:
if ui.traceback:ui.traceback()
raise error.Abort(str(e))
# if present, --rev will be the last Perforce changeset number to get
stoprev = opts.get(b'rev')
stoprev = stoprev and max(int(r) for r in stoprev) or 0
# for clone we support a --startrev option to fold initial changelists
startrev = opts.get(b'startrev')
startrev = startrev and int(startrev) or 0
# for clone we support an --encoding option to set server character set
if opts.get(b'encoding'):