-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.py
1717 lines (1385 loc) · 63.6 KB
/
client.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
import struct, re, datetime
import hglib
from hglib import error, util, templates, merge, context
from hglib.util import b, cmdbuilder, BytesIO, strtobytes
class revision(tuple):
def __new__(cls, rev, node, tags, branch, author, desc, date):
return tuple.__new__(cls, (rev, node, tags, branch, author, desc, date))
@property
def rev(self):
return self[0]
@property
def node(self):
return self[1]
@property
def tags(self):
return self[2]
@property
def branch(self):
return self[3]
@property
def author(self):
return self[4]
@property
def desc(self):
return self[5]
@property
def date(self):
return self[6]
class hgclient(object):
inputfmt = '>I'
outputfmt = '>cI'
outputfmtsize = struct.calcsize(outputfmt)
retfmt = '>i'
def __init__(self, path, encoding, configs, connect=True):
self._args = [hglib.HGPATH, 'serve', '--cmdserver', 'pipe',
'--config', 'ui.interactive=True']
if path:
self._args += ['-R', path]
if configs:
for config in configs:
self._args += ['--config', config]
self._env = {'HGPLAIN': '1'}
if encoding:
self._env['HGENCODING'] = encoding
self.server = None
self._version = None
# include the hidden changesets if True
self.hidden = None
self._cbout = None
self._cberr = None
self._cbprompt = None
if connect:
self.open()
self._protocoltracefn = None
def setcbout(self, cbout):
"""
cbout is a function that will be called with the stdout data of
the command as it runs. Call with None to stop getting call backs.
"""
self._cbout = cbout
def setcberr(self, cberr):
"""
cberr is a function that will be called with the stderr data of
the command as it runs.Call with None to stop getting call backs.
"""
self._cberr = cberr
def setcbprompt(self, cbprompt):
"""
cbprompt is used to reply to prompts by the server
It receives the max number of bytes to return and the
contents of stdout received so far.
Call with None to stop getting call backs.
cbprompt is never called from merge() or import_()
which already handle the prompt.
"""
self._cbprompt = cbprompt
def setprotocoltrace(self, tracefn=None):
"""
if tracefn is None no trace calls will be made.
Otherwise tracefn is call as tracefn( direction, channel, data )
direction is 'r' for read from server and 'w' for write to server
channel is always None when direction is 'w'
and the channel-identified when the direction is 'r'
"""
self._protocoltracefn = tracefn
def __enter__(self):
if self.server is None:
self.open()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def _readhello(self):
""" read the hello message the server sends when started """
ch, msg = self._readchannel()
assert ch == b('o')
msg = msg.split(b('\n'))
self.capabilities = msg[0][len(b('capabilities: ')):]
if not self.capabilities:
raise error.ResponseError(
"bad hello message: expected 'capabilities: '"
", got %r" % msg[0])
self.capabilities = set(self.capabilities.split())
# at the very least the server should be able to run commands
assert b('runcommand') in self.capabilities
self._encoding = msg[1][len(b('encoding: ')):]
if not self._encoding:
raise error.ResponseError("bad hello message: expected 'encoding: '"
", got %r" % msg[1])
def _readchannel(self):
data = self.server.stdout.read(hgclient.outputfmtsize)
if not data:
raise error.ServerError()
channel, length = struct.unpack(hgclient.outputfmt, data)
if channel in b('IL'):
return channel, length
else:
return channel, self.server.stdout.read(length)
@staticmethod
def _parserevs(splitted):
'''splitted is a list of fields according to our rev.style, where
each 6 fields compose one revision.
'''
revs = []
for rev in util.grouper(7, splitted):
# truncate the timezone and convert to a local datetime
posixtime = float(rev[6].split(b('.'), 1)[0])
dt = datetime.datetime.fromtimestamp(posixtime)
revs.append(revision(rev[0], rev[1], rev[2], rev[3],
rev[4], rev[5], dt))
return revs
def runcommand(self, args, inchannels, outchannels):
def writeblock(data):
if self._protocoltracefn is not None:
self._protocoltracefn('w', None, data)
self.server.stdin.write(struct.pack(self.inputfmt, len(data)))
self.server.stdin.write(data)
self.server.stdin.flush()
if not self.server:
raise ValueError("server not connected")
self.server.stdin.write(b('runcommand\n'))
writeblock(b('\0').join(args))
while True:
channel, data = self._readchannel()
if self._protocoltracefn is not None:
self._protocoltracefn('r', channel, data)
# input channels
if channel in inchannels:
writeblock(inchannels[channel](data))
# output channels
elif channel in outchannels:
outchannels[channel](data)
# result channel, command finished
elif channel == b('r'):
return struct.unpack(hgclient.retfmt, data)[0]
# a channel that we don't know and can't ignore
elif channel.isupper():
raise error.ResponseError(
"unexpected data on required channel '%s'" % channel)
# optional channel
else:
pass
def rawcommand(self, args, eh=None, prompt=None, input=None):
"""
args is the cmdline (usually built using util.cmdbuilder)
eh is an error handler that is passed the return code, stdout and stderr
If no eh is given, we raise a CommandError if ret != 0
prompt is used to reply to prompts by the server
It receives the max number of bytes to return and the contents of stdout
received so far
input is used to reply to bulk data requests by the server
It receives the max number of bytes to return
"""
out, err = BytesIO(), BytesIO()
outchannels = {}
if self._cbout is None:
outchannels[b('o')] = out.write
else:
def out_handler(data):
out.write(data)
self._cbout(data)
outchannels[b('o')] = out_handler
if self._cberr is None:
outchannels[b('e')] = err.write
else:
def err_handler(data):
err.write(data)
self._cberr(data)
outchannels[b('e')] = err_handler
inchannels = {}
if prompt is None:
prompt = self._cbprompt
if prompt is not None:
def func(size):
reply = prompt(size, out.getvalue())
return reply
inchannels[b('L')] = func
if input is not None:
inchannels[b('I')] = input
ret = self.runcommand(args, inchannels, outchannels)
out, err = out.getvalue(), err.getvalue()
if ret:
if eh is None:
raise error.CommandError(args, ret, out, err)
else:
return eh(ret, out, err)
return out
def open(self):
if self.server is not None:
raise ValueError('server already open')
self.server = util.popen(self._args, self._env)
try:
self._readhello()
except error.ServerError:
ret, serr = self._close()
raise error.ServerError('server exited with status %d: %s'
% (ret, serr.strip()))
return self
def close(self):
"""Closes the command server instance and waits for it to exit,
returns the exit code.
Attempting to call any function afterwards that needs to
communicate with the server will raise a ValueError.
"""
return self._close()[0]
def _close(self):
_sout, serr = self.server.communicate()
ret = self.server.returncode
self.server = None
return ret, serr
def add(self, files=[], dryrun=False, subrepos=False, include=None,
exclude=None):
"""
Add the specified files on the next commit.
If no files are given, add all files to the repository.
dryrun - do no perform actions
subrepos - recurse into subrepositories
include - include names matching the given patterns
exclude - exclude names matching the given patterns
Return whether all given files were added.
"""
if not isinstance(files, list):
files = [files]
args = cmdbuilder(b('add'), n=dryrun, S=subrepos, I=include, X=exclude,
*files)
eh = util.reterrorhandler(args)
self.rawcommand(args, eh=eh)
return bool(eh)
def addremove(self, files=[], similarity=None, dryrun=False, include=None,
exclude=None):
"""Add all new files and remove all missing files from the repository.
New files are ignored if they match any of the patterns in
".hgignore". As with add, these changes take effect at the
next commit.
similarity - used to detect renamed files. With a parameter
greater than 0, this compares every removed file with every
added file and records those similar enough as renames. This
option takes a percentage between 0 (disabled) and 100 (files
must be identical) as its parameter. Detecting renamed files
this way can be expensive. After using this option, "hg status
-C" can be used to check which files were identified as moved
or renamed.
dryrun - do no perform actions
include - include names matching the given patterns
exclude - exclude names matching the given patterns
Return True if all files are successfully added.
"""
if not isinstance(files, list):
files = [files]
args = cmdbuilder(b('addremove'), s=similarity, n=dryrun, I=include,
X=exclude, *files)
eh = util.reterrorhandler(args)
self.rawcommand(args, eh=eh)
return bool(eh)
def annotate(self, files, rev=None, nofollow=False, text=False, user=False,
file=False, date=False, number=False, changeset=False,
line=False, verbose=False, include=None, exclude=None):
"""
Show changeset information by line for each file in files.
rev - annotate the specified revision
nofollow - don't follow copies and renames
text - treat all files as text
user - list the author (long with -v)
file - list the filename
date - list the date
number - list the revision number (default)
changeset - list the changeset
line - show line number at the first appearance
include - include names matching the given patterns
exclude - exclude names matching the given patterns
Yields a (info, contents) tuple for each line in a file. Info is a space
separated string according to the given options.
"""
if not isinstance(files, list):
files = [files]
args = cmdbuilder(b('annotate'), r=rev, no_follow=nofollow, a=text,
u=user, f=file, d=date, n=number, c=changeset,
l=line, v=verbose, I=include, X=exclude,
hidden=self.hidden, *files)
out = self.rawcommand(args)
for line in out.splitlines():
yield tuple(line.split(b(': '), 1))
def archive(self, dest, rev=None, nodecode=False, prefix=None, type=None,
subrepos=False, include=None, exclude=None):
"""Create an unversioned archive of a repository revision.
The exact name of the destination archive or directory is given using a
format string; see export for details.
Each member added to an archive file has a directory prefix
prepended. Use prefix to specify a format string for the
prefix. The default is the basename of the archive, with
suffixes removed.
dest - destination path
rev - revision to distribute. The revision used is the parent of the
working directory if one isn't given.
nodecode - do not pass files through decoders
prefix - directory prefix for files in archive
type - type of distribution to create. The archive type is automatically
detected based on file extension if one isn't given.
Valid types are:
"files" a directory full of files (default)
"tar" tar archive, uncompressed
"tbz2" tar archive, compressed using bzip2
"tgz" tar archive, compressed using gzip
"uzip" zip archive, uncompressed
"zip" zip archive, compressed using deflate
subrepos - recurse into subrepositories
include - include names matching the given patterns
exclude - exclude names matching the given patterns
"""
args = cmdbuilder(b('archive'), dest, r=rev,
no_decode=nodecode, p=prefix,
t=type, S=subrepos, I=include, X=exclude,
hidden=self.hidden)
self.rawcommand(args)
def backout(self, rev, merge=False, parent=None, tool=None, message=None,
logfile=None, date=None, user=None):
"""Prepare a new changeset with the effect of rev undone in the current
working directory.
If rev is the parent of the working directory, then this new
changeset is committed automatically. Otherwise, hg needs to
merge the changes and the merged result is left uncommitted.
rev - revision to backout
merge - merge with old dirstate parent after backout
parent - parent to choose when backing out merge
tool - specify merge tool
message - use text as commit message
logfile - read commit message from file
date - record the specified date as commit date
user - record the specified user as committer
"""
if message and logfile:
raise ValueError("cannot specify both a message and a logfile")
args = cmdbuilder(b('backout'), r=rev, merge=merge, parent=parent,
t=tool, m=message, l=logfile, d=date, u=user,
hidden=self.hidden)
self.rawcommand(args)
def bookmark(self, name, rev=None, force=False, delete=False,
inactive=False, rename=None):
"""
Set a bookmark on the working directory's parent revision or rev,
with the given name.
name - bookmark name
rev - revision to bookmark
force - bookmark even if another bookmark with the same name exists
delete - delete the given bookmark
inactive - do not mark the new bookmark active
rename - rename the bookmark given by rename to name
"""
args = cmdbuilder(b('bookmark'), name, r=rev, f=force, d=delete,
i=inactive, m=rename)
self.rawcommand(args)
def bookmarks(self):
"""
Return the bookmarks as a list of (name, rev, node) and the index of the
current one.
If there isn't a current one, -1 is returned as the index.
"""
args = cmdbuilder(b('bookmarks'), hidden=self.hidden)
out = self.rawcommand(args)
bms = []
current = -1
if out.rstrip() != b('no bookmarks set'):
for line in out.splitlines():
iscurrent, line = line[0:3], line[3:]
if b('*') in iscurrent:
current = len(bms)
name, line = line.split(b(' '), 1)
rev, node = line.split(b(':'))
bms.append((name, int(rev), node))
return bms, current
def branch(self, name=None, clean=False, force=False):
"""When name isn't given, return the current branch name. Otherwise
set the working directory branch name (the branch will not
exist in the repository until the next commit). Standard
practice recommends that primary development take place on the
'default' branch.
When clean is True, reset and return the working directory
branch to that of the parent of the working directory,
negating a previous branch change.
name - new branch name
clean - reset branch name to parent branch name
force - set branch name even if it shadows an existing branch
"""
if name and clean:
raise ValueError('cannot use both name and clean')
args = cmdbuilder(b('branch'), name, f=force, C=clean)
out = self.rawcommand(args).rstrip()
if name:
return name
elif not clean:
return out
else:
# len('reset working directory to branch ') == 34
return out[34:]
def branches(self, active=False, closed=False):
"""
Returns the repository's named branches as a list of (name, rev, node).
active - show only branches that have unmerged heads
closed - show normal and closed branches
"""
args = cmdbuilder(b('branches'), a=active, c=closed, hidden=self.hidden)
out = self.rawcommand(args)
branches = []
for line in out.rstrip().splitlines():
namerev, node = line.rsplit(b(':'), 1)
name, rev = namerev.rsplit(b(' '), 1)
name = name.rstrip()
node = node.split()[0] # get rid of ' (inactive)'
branches.append((name, int(rev), node))
return branches
def bundle(self, file, destrepo=None, rev=[], branch=[], base=[], all=False,
force=False, type=None, ssh=None, remotecmd=None,
insecure=False):
"""Generate a compressed changegroup file collecting changesets not
known to be in another repository.
If destrepo isn't given, then hg assumes the destination will have all
the nodes you specify with base. To create a bundle containing all
changesets, use all (or set base to 'null').
file - destination file name
destrepo - repository to look for changes
rev - a changeset intended to be added to the destination
branch - a specific branch you would like to bundle
base - a base changeset assumed to be available at the destination
all - bundle all changesets in the repository
type - bundle compression type to use, available compression
methods are: none, bzip2, and gzip (default: bzip2)
force - run even when the destrepo is unrelated
ssh - specify ssh command to use
remotecmd - specify hg command to run on the remote side
insecure - do not verify server certificate (ignoring
web.cacerts config)
Return True if a bundle was created, False if no changes were found.
"""
args = cmdbuilder(b('bundle'), file, destrepo, f=force, r=rev, b=branch,
base=base, a=all, t=type, e=ssh, remotecmd=remotecmd,
insecure=insecure, hidden=self.hidden)
eh = util.reterrorhandler(args)
self.rawcommand(args, eh=eh)
return bool(eh)
def cat(self, files, rev=None, output=None):
"""Return a string containing the specified files as they were at the
given revision. If no revision is given, the parent of the working
directory is used, or tip if no revision is checked out.
If output is given, writes the contents to the specified file.
The name of the file is given using a format string. The
formatting rules are the same as for the export command, with
the following additions:
"%s" basename of file being printed
"%d" dirname of file being printed, or '.' if in repository root
"%p" root-relative path name of file being printed
"""
args = cmdbuilder(b('cat'), r=rev, o=output, hidden=self.hidden, *files)
out = self.rawcommand(args)
if not output:
return out
def clone(self, source=b('.'), dest=None, branch=None, updaterev=None,
revrange=None):
"""
Create a copy of an existing repository specified by source in a new
directory dest.
If dest isn't specified, it defaults to the basename of source.
branch - clone only the specified branch
updaterev - revision, tag or branch to check out
revrange - include the specified changeset
"""
args = cmdbuilder(b('clone'), source, dest, b=branch,
u=updaterev, r=revrange)
self.rawcommand(args)
def init(self, dest, ssh=None, remotecmd=None, insecure=False):
args = util.cmdbuilder('init', dest, e=ssh, remotecmd=remotecmd,
insecure=insecure)
self.rawcommand(args)
def commit(self, message=None, logfile=None, addremove=False,
closebranch=False, date=None, user=None, include=None,
exclude=None, amend=False):
"""
Commit changes reported by status into the repository.
message - the commit message
logfile - read commit message from file
addremove - mark new/missing files as added/removed before committing
closebranch - mark a branch as closed, hiding it from the branch list
date - record the specified date as commit date
user - record the specified user as committer
include - include names matching the given patterns
exclude - exclude names matching the given patterns
amend - amend the parent of the working dir
"""
if amend and message is None and logfile is None:
# retrieve current commit message
message = self.log(b('.'))[0][5]
if message is None and logfile is None and not amend:
raise ValueError("must provide at least a message or a logfile")
elif message and logfile:
raise ValueError("cannot specify both a message and a logfile")
# --debug will print the committed cset
args = cmdbuilder(b('commit'), debug=True, m=message, A=addremove,
close_branch=closebranch, d=date, u=user, l=logfile,
I=include, X=exclude, amend=amend)
out = self.rawcommand(args)
m = re.search(b(r'^committed changeset (\d+):([0-9a-f]+)'), out,
re.MULTILINE)
if not m:
raise ValueError('revision and node not found in hg output: %r'
% out)
rev, node = m.groups()
return int(rev), node
def config(self, names=[], untrusted=False, showsource=False):
"""Return a list of (section, key, value) config settings from all
hgrc files
When showsource is specified, return (source, section, key, value) where
source is of the form filename:[line]
"""
def splitline(s):
k, value = s.rstrip().split(b('='), 1)
section, key = k.split(b('.'), 1)
return section, key, value
if not isinstance(names, list):
names = [names]
args = cmdbuilder(b('showconfig'), u=untrusted, debug=showsource,
*names)
out = self.rawcommand(args)
conf = []
if showsource:
out = util.skiplines(out, b('read config from: '))
for line in out.splitlines():
m = re.match(b(r"(.+?:(?:\d+:)?) (.*)"), line)
t = splitline(m.group(2))
conf.append((m.group(1)[:-1], t[0], t[1], t[2]))
else:
for line in out.splitlines():
conf.append(splitline(line))
return conf
@property
def encoding(self):
"""
Return the server's encoding (as reported in the hello message).
"""
if not b('getencoding') in self.capabilities:
raise CapabilityError('getencoding')
if not self._encoding:
self.server.stdin.write(b('getencoding\n'))
self._encoding = self._readfromchannel('r')
return self._encoding
def copy(self, source, dest, after=False, force=False, dryrun=False,
include=None, exclude=None):
"""Mark dest as having copies of source files. If dest is a
directory, copies are put in that directory. If dest is a
file, then source must be a string.
Returns True on success, False if errors are encountered.
source - a file or a list of files
dest - a destination file or directory
after - record a copy that has already occurred
force - forcibly copy over an existing managed file
dryrun - do not perform actions, just print output
include - include names matching the given patterns
exclude - exclude names matching the given patterns
"""
if not isinstance(source, list):
source = [source]
source.append(dest)
args = cmdbuilder(b('copy'), A=after, f=force, n=dryrun,
I=include, X=exclude, *source)
eh = util.reterrorhandler(args)
self.rawcommand(args, eh=eh)
return bool(eh)
def diff(self, files=[], revs=[], change=None, text=False,
git=False, nodates=False, showfunction=False,
reverse=False, ignoreallspace=False,
ignorespacechange=False, ignoreblanklines=False,
unified=None, stat=False, subrepos=False, include=None,
exclude=None):
"""
Return differences between revisions for the specified files.
revs - a revision or a list of two revisions to diff
change - change made by revision
text - treat all files as text
git - use git extended diff format
nodates - omit dates from diff headers
showfunction - show which function each change is in
reverse - produce a diff that undoes the changes
ignoreallspace - ignore white space when comparing lines
ignorespacechange - ignore changes in the amount of white space
ignoreblanklines - ignore changes whose lines are all blank
unified - number of lines of context to show
stat - output diffstat-style summary of changes
subrepos - recurse into subrepositories
include - include names matching the given patterns
exclude - exclude names matching the given patterns
"""
if change and revs:
raise ValueError('cannot specify both change and rev')
args = cmdbuilder(b('diff'), r=list(map(strtobytes, revs)), c=change,
a=text, g=git, nodates=nodates,
p=showfunction, reverse=reverse,
w=ignoreallspace, b=ignorespacechange,
B=ignoreblanklines, U=unified, stat=stat,
S=subrepos, I=include, X=exclude, hidden=self.hidden,
*files)
return self.rawcommand(args)
def export(self, revs, output=None, switchparent=False,
text=False, git=False, nodates=False):
"""Return the header and diffs for one or more changesets. When
output is given, dumps to file. The name of the file is given
using a format string. The formatting rules are as follows:
"%%" literal "%" character
"%H" changeset hash (40 hexadecimal digits)
"%N" number of patches being generated
"%R" changeset revision number
"%b" basename of the exporting repository
"%h" short-form changeset hash (12 hexadecimal digits)
"%n" zero-padded sequence number, starting at 1
"%r" zero-padded changeset revision number
output - print output to file with formatted name
switchparent - diff against the second parent
rev - a revision or list of revisions to export
text - treat all files as text
git - use git extended diff format
nodates - omit dates from diff headers
"""
if not isinstance(revs, list):
revs = [revs]
args = cmdbuilder(b('export'), o=output, switch_parent=switchparent,
a=text, g=git, nodates=nodates, hidden=self.hidden,
*revs)
out = self.rawcommand(args)
if output is None:
return out
def forget(self, files, include=None, exclude=None):
"""Mark the specified files so they will no longer be tracked after
the next commit.
This only removes files from the current branch, not from the entire
project history, and it does not delete them from the working directory.
Returns True on success.
include - include names matching the given patterns
exclude - exclude names matching the given patterns
"""
if not isinstance(files, list):
files = [files]
args = cmdbuilder(b('forget'), I=include, X=exclude, *files)
eh = util.reterrorhandler(args)
self.rawcommand(args, eh=eh)
return bool(eh)
def grep(self, pattern, files=[], all=False, text=False, follow=False,
ignorecase=False, fileswithmatches=False, line=False, user=False,
date=False, include=None, exclude=None):
"""Search for a pattern in specified files and revisions.
This behaves differently than Unix grep. It only accepts Python/Perl
regexps. It searches repository history, not the working directory.
It always prints the revision number in which a match appears.
Yields (filename, revision, [line, [match status, [user,
[date, [match]]]]]) per match depending on the given options.
all - print all revisions that match
text - treat all files as text
follow - follow changeset history, or file history across
copies and renames
ignorecase - ignore case when matching
fileswithmatches - return only filenames and revisions that match
line - return line numbers in the result tuple
user - return the author in the result tuple
date - return the date in the result tuple
include - include names matching the given patterns
exclude - exclude names matching the given patterns
"""
if not isinstance(files, list):
files = [files]
args = cmdbuilder(b('grep'), all=all, a=text, f=follow, i=ignorecase,
l=fileswithmatches, n=line, u=user, d=date,
I=include, X=exclude, hidden=self.hidden,
*[pattern] + files)
args.append(b('-0'))
def eh(ret, out, err):
if ret != 1:
raise error.CommandError(args, ret, out, err)
return b('')
out = self.rawcommand(args, eh=eh).split(b('\0'))
fieldcount = 3
if user:
fieldcount += 1
if date:
fieldcount += 1
if line:
fieldcount += 1
if all:
fieldcount += 1
if fileswithmatches:
fieldcount -= 1
return util.grouper(fieldcount, out)
def heads(self, rev=[], startrev=[], topological=False, closed=False):
"""Return a list of current repository heads or branch heads.
rev - return only branch heads on the branches associated with
the specified changesets.
startrev - return only heads which are descendants of the given revs.
topological - named branch mechanics will be ignored and only changesets
without children will be shown.
closed - normal and closed branch heads.
"""
if not isinstance(rev, list):
rev = [rev]
args = cmdbuilder(b('heads'), r=startrev, t=topological, c=closed,
template=templates.changeset, hidden=self.hidden,
*rev)
def eh(ret, out, err):
if ret != 1:
raise error.CommandError(args, ret, out, err)
return b('')
out = self.rawcommand(args, eh=eh).split(b('\0'))[:-1]
return self._parserevs(out)
def identify(self, rev=None, source=None, num=False, id=False, branch=False,
tags=False, bookmarks=False):
"""Return a summary string identifying the repository state at rev
using one or two parent hash identifiers, followed by a "+" if
the working directory has uncommitted changes, the branch name
(if not default), a list of tags, and a list of bookmarks.
When rev is not given, return a summary string of the current
state of the repository.
Specifying source as a repository root or Mercurial bundle will cause
lookup to operate on that repository/bundle.
num - show local revision number
id - show global revision id
branch - show branch
tags - show tags
bookmarks - show bookmarks
"""
args = cmdbuilder(b('identify'), source, r=rev, n=num, i=id,
b=branch, t=tags, B=bookmarks,
hidden=self.hidden)
return self.rawcommand(args)
def import_(self, patches, strip=None, force=False, nocommit=False,
bypass=False, exact=False, importbranch=False, message=None,
date=None, user=None, similarity=None):
"""Import the specified patches which can be a list of file names or a
file-like object and commit them individually (unless nocommit is
specified).
strip - directory strip option for patch. This has the same
meaning as the corresponding patch option (default: 1)
force - skip check for outstanding uncommitted changes
nocommit - don't commit, just update the working directory
bypass - apply patch without touching the working directory
exact - apply patch to the nodes from which it was generated
importbranch - use any branch information in patch (implied by exact)
message - the commit message
date - record the specified date as commit date
user - record the specified user as committer
similarity - guess renamed files by similarity (0<=s<=100)
"""
if hasattr(patches, 'read') and hasattr(patches, 'readline'):
patch = patches
def readline(size, output):
return patch.readline(size)
stdin = True
patches = ()
prompt = readline
input = patch.read
else:
stdin = False
prompt = None
input = None
args = cmdbuilder(b('import'), strip=strip, force=force,
no_commit=nocommit, bypass=bypass, exact=exact,
import_branch=importbranch, message=message,
date=date, user=user, similarity=similarity, _=stdin,
*patches)
self.rawcommand(args, prompt=prompt, input=input)
def incoming(self, revrange=None, path=None, force=False, newest=False,
bundle=None, bookmarks=False, branch=None, limit=None,
nomerges=False, subrepos=False):
"""Return new changesets found in the specified path or the default pull
location.
When bookmarks=True, return a list of (name, node) of incoming
bookmarks.
revrange - a remote changeset or list of changesets intended to be added
force - run even if remote repository is unrelated
newest - show newest record first
bundle - avoid downloading the changesets twice and store the
bundles into the specified file.
bookmarks - compare bookmarks (this changes the return value)
branch - a specific branch you would like to pull
limit - limit number of changes returned
nomerges - do not show merges
ssh - specify ssh command to use
remotecmd - specify hg command to run on the remote side
insecure- do not verify server certificate (ignoring web.cacerts config)
subrepos - recurse into subrepositories
"""
args = cmdbuilder(b('incoming'), path,
template=templates.changeset, r=revrange,
f=force, n=newest, bundle=bundle,
B=bookmarks, b=branch, l=limit, M=nomerges,
S=subrepos)