Debian Codegraph @

third_party/python/python-hglib/hglib/client.py

raw
1 import struct, re, datetime
2 import hglib
3 from hglib import error, util, templates, merge, context
4
5 from hglib.util import b, cmdbuilder, BytesIO, strtobytes
6
7 class revision(tuple):
8 def __new__(cls, rev, node, tags, branch, author, desc, date):
9 return tuple.__new__(cls, (rev, node, tags, branch, author, desc, date))
10
11 @property
12 def rev(self):
13 return self[0]
14
15 @property
16 def node(self):
17 return self[1]
18
19 @property
20 def tags(self):
21 return self[2]
22
23 @property
24 def branch(self):
25 return self[3]
26
27 @property
28 def author(self):
29 return self[4]
30
31 @property
32 def desc(self):
33 return self[5]
34
35 @property
36 def date(self):
37 return self[6]
38
39 class hgclient(object):
40 inputfmt = '>I'
41 outputfmt = '>cI'
42 outputfmtsize = struct.calcsize(outputfmt)
43 retfmt = '>i'
44
45 def __init__(self, path, encoding, configs, connect=True):
46 self._args = [hglib.HGPATH, 'serve', '--cmdserver', 'pipe',
47 '--config', 'ui.interactive=True']
48 if path:
49 self._args += ['-R', path]
50 if configs:
51 for config in configs:
52 self._args += ['--config', config]
53 self._env = {'HGPLAIN': '1'}
54 if encoding:
55 self._env['HGENCODING'] = encoding
56
57 self.server = None
58 self._version = None
59 # include the hidden changesets if True
60 self.hidden = None
61
62 self._cbout = None
63 self._cberr = None
64 self._cbprompt = None
65
66 if connect:
67 self.open()
68
69 self._protocoltracefn = None
70
71 def setcbout(self, cbout):
72 """
73 cbout is a function that will be called with the stdout data of
74 the command as it runs. Call with None to stop getting call backs.
75 """
76 self._cbout = cbout
77
78 def setcberr(self, cberr):
79 """
80 cberr is a function that will be called with the stderr data of
81 the command as it runs.Call with None to stop getting call backs.
82 """
83 self._cberr = cberr
84
85 def setcbprompt(self, cbprompt):
86 """
87 cbprompt is used to reply to prompts by the server
88 It receives the max number of bytes to return and the
89 contents of stdout received so far.
90
91 Call with None to stop getting call backs.
92
93 cbprompt is never called from merge() or import_()
94 which already handle the prompt.
95 """
96 self._cbprompt = cbprompt
97
98 def setprotocoltrace(self, tracefn=None):
99 """
100 if tracefn is None no trace calls will be made.
101 Otherwise tracefn is call as tracefn( direction, channel, data )
102 direction is 'r' for read from server and 'w' for write to server
103 channel is always None when direction is 'w'
104 and the channel-identified when the direction is 'r'
105 """
106 self._protocoltracefn = tracefn
107
108 def __enter__(self):
109 if self.server is None:
110 self.open()
111 return self
112
113 def __exit__(self, exc_type, exc_val, exc_tb):
114 self.close()
115
116 def _readhello(self):
117 """ read the hello message the server sends when started """
118 ch, msg = self._readchannel()
119 assert ch == b('o')
120
121 msg = msg.split(b('\n'))
122
123 self.capabilities = msg[0][len(b('capabilities: ')):]
124 if not self.capabilities:
125 raise error.ResponseError(
126 "bad hello message: expected 'capabilities: '"
127 ", got %r" % msg[0])
128
129 self.capabilities = set(self.capabilities.split())
130
131 # at the very least the server should be able to run commands
132 assert b('runcommand') in self.capabilities
133
134 self._encoding = msg[1][len(b('encoding: ')):]
135 if not self._encoding:
136 raise error.ResponseError("bad hello message: expected 'encoding: '"
137 ", got %r" % msg[1])
138
139 def _readchannel(self):
140 data = self.server.stdout.read(hgclient.outputfmtsize)
141 if not data:
142 raise error.ServerError()
143 channel, length = struct.unpack(hgclient.outputfmt, data)
144 if channel in b('IL'):
145 return channel, length
146 else:
147 return channel, self.server.stdout.read(length)
148
149 @staticmethod
150 def _parserevs(splitted):
151 '''splitted is a list of fields according to our rev.style, where
152 each 6 fields compose one revision.
153 '''
154 revs = []
155 for rev in util.grouper(7, splitted):
156 # truncate the timezone and convert to a local datetime
157 posixtime = float(rev[6].split(b('.'), 1)[0])
158 dt = datetime.datetime.fromtimestamp(posixtime)
159 revs.append(revision(rev[0], rev[1], rev[2], rev[3],
160 rev[4], rev[5], dt))
161 return revs
162
163 def runcommand(self, args, inchannels, outchannels):
164 def writeblock(data):
165 if self._protocoltracefn is not None:
166 self._protocoltracefn('w', None, data)
167 self.server.stdin.write(struct.pack(self.inputfmt, len(data)))
168 self.server.stdin.write(data)
169 self.server.stdin.flush()
170
171 if not self.server:
172 raise ValueError("server not connected")
173
174 self.server.stdin.write(b('runcommand\n'))
175 writeblock(b('\0').join(args))
176
177 while True:
178 channel, data = self._readchannel()
179 if self._protocoltracefn is not None:
180 self._protocoltracefn('r', channel, data)
181
182 # input channels
183 if channel in inchannels:
184 writeblock(inchannels[channel](data))
185 # output channels
186 elif channel in outchannels:
187 outchannels[channel](data)
188 # result channel, command finished
189 elif channel == b('r'):
190 return struct.unpack(hgclient.retfmt, data)[0]
191 # a channel that we don't know and can't ignore
192 elif channel.isupper():
193 raise error.ResponseError(
194 "unexpected data on required channel '%s'" % channel)
195 # optional channel
196 else:
197 pass
198
199 def rawcommand(self, args, eh=None, prompt=None, input=None):
200 """
201 args is the cmdline (usually built using util.cmdbuilder)
202
203 eh is an error handler that is passed the return code, stdout and stderr
204 If no eh is given, we raise a CommandError if ret != 0
205
206 prompt is used to reply to prompts by the server
207 It receives the max number of bytes to return and the contents of stdout
208 received so far
209
210 input is used to reply to bulk data requests by the server
211 It receives the max number of bytes to return
212 """
213 out, err = BytesIO(), BytesIO()
214 outchannels = {}
215 if self._cbout is None:
216 outchannels[b('o')] = out.write
217 else:
218 def out_handler(data):
219 out.write(data)
220 self._cbout(data)
221 outchannels[b('o')] = out_handler
222 if self._cberr is None:
223 outchannels[b('e')] = err.write
224 else:
225 def err_handler(data):
226 err.write(data)
227 self._cberr(data)
228 outchannels[b('e')] = err_handler
229
230 inchannels = {}
231 if prompt is None:
232 prompt = self._cbprompt
233 if prompt is not None:
234 def func(size):
235 reply = prompt(size, out.getvalue())
236 return reply
237 inchannels[b('L')] = func
238 if input is not None:
239 inchannels[b('I')] = input
240
241 ret = self.runcommand(args, inchannels, outchannels)
242 out, err = out.getvalue(), err.getvalue()
243
244 if ret:
245 if eh is None:
246 raise error.CommandError(args, ret, out, err)
247 else:
248 return eh(ret, out, err)
249 return out
250
251 def open(self):
252 if self.server is not None:
253 raise ValueError('server already open')
254
255 self.server = util.popen(self._args, self._env)
256 try:
257 self._readhello()
258 except error.ServerError:
259 ret, serr = self._close()
260 raise error.ServerError('server exited with status %d: %s'
261 % (ret, serr.strip()))
262 return self
263
264 def close(self):
265 """Closes the command server instance and waits for it to exit,
266 returns the exit code.
267
268 Attempting to call any function afterwards that needs to
269 communicate with the server will raise a ValueError.
270 """
271 return self._close()[0]
272
273 def _close(self):
274 _sout, serr = self.server.communicate()
275 ret = self.server.returncode
276 self.server = None
277 return ret, serr
278
279 def add(self, files=[], dryrun=False, subrepos=False, include=None,
280 exclude=None):
281 """
282 Add the specified files on the next commit.
283 If no files are given, add all files to the repository.
284
285 dryrun - do no perform actions
286 subrepos - recurse into subrepositories
287 include - include names matching the given patterns
288 exclude - exclude names matching the given patterns
289
290 Return whether all given files were added.
291 """
292 if not isinstance(files, list):
293 files = [files]
294
295 args = cmdbuilder(b('add'), n=dryrun, S=subrepos, I=include, X=exclude,
296 *files)
297
298 eh = util.reterrorhandler(args)
299 self.rawcommand(args, eh=eh)
300
301 return bool(eh)
302
303 def addremove(self, files=[], similarity=None, dryrun=False, include=None,
304 exclude=None):
305 """Add all new files and remove all missing files from the repository.
306
307 New files are ignored if they match any of the patterns in
308 ".hgignore". As with add, these changes take effect at the
309 next commit.
310
311 similarity - used to detect renamed files. With a parameter
312 greater than 0, this compares every removed file with every
313 added file and records those similar enough as renames. This
314 option takes a percentage between 0 (disabled) and 100 (files
315 must be identical) as its parameter. Detecting renamed files
316 this way can be expensive. After using this option, "hg status
317 -C" can be used to check which files were identified as moved
318 or renamed.
319
320 dryrun - do no perform actions
321 include - include names matching the given patterns
322 exclude - exclude names matching the given patterns
323
324 Return True if all files are successfully added.
325
326 """
327 if not isinstance(files, list):
328 files = [files]
329
330 args = cmdbuilder(b('addremove'), s=similarity, n=dryrun, I=include,
331 X=exclude, *files)
332
333 eh = util.reterrorhandler(args)
334 self.rawcommand(args, eh=eh)
335
336 return bool(eh)
337
338 def annotate(self, files, rev=None, nofollow=False, text=False, user=False,
339 file=False, date=False, number=False, changeset=False,
340 line=False, verbose=False, include=None, exclude=None):
341 """
342 Show changeset information by line for each file in files.
343
344 rev - annotate the specified revision
345 nofollow - don't follow copies and renames
346 text - treat all files as text
347 user - list the author (long with -v)
348 file - list the filename
349 date - list the date
350 number - list the revision number (default)
351 changeset - list the changeset
352 line - show line number at the first appearance
353 include - include names matching the given patterns
354 exclude - exclude names matching the given patterns
355
356 Yields a (info, contents) tuple for each line in a file. Info is a space
357 separated string according to the given options.
358 """
359 if not isinstance(files, list):
360 files = [files]
361
362 args = cmdbuilder(b('annotate'), r=rev, no_follow=nofollow, a=text,
363 u=user, f=file, d=date, n=number, c=changeset,
364 l=line, v=verbose, I=include, X=exclude,
365 hidden=self.hidden, *files)
366
367 out = self.rawcommand(args)
368
369 for line in out.splitlines():
370 yield tuple(line.split(b(': '), 1))
371
372 def archive(self, dest, rev=None, nodecode=False, prefix=None, type=None,
373 subrepos=False, include=None, exclude=None):
374 """Create an unversioned archive of a repository revision.
375
376 The exact name of the destination archive or directory is given using a
377 format string; see export for details.
378
379 Each member added to an archive file has a directory prefix
380 prepended. Use prefix to specify a format string for the
381 prefix. The default is the basename of the archive, with
382 suffixes removed.
383
384 dest - destination path
385 rev - revision to distribute. The revision used is the parent of the
386 working directory if one isn't given.
387
388 nodecode - do not pass files through decoders
389 prefix - directory prefix for files in archive
390 type - type of distribution to create. The archive type is automatically
391 detected based on file extension if one isn't given.
392
393 Valid types are:
394
395 "files" a directory full of files (default)
396 "tar" tar archive, uncompressed
397 "tbz2" tar archive, compressed using bzip2
398 "tgz" tar archive, compressed using gzip
399 "uzip" zip archive, uncompressed
400 "zip" zip archive, compressed using deflate
401
402 subrepos - recurse into subrepositories
403 include - include names matching the given patterns
404 exclude - exclude names matching the given patterns
405
406 """
407 args = cmdbuilder(b('archive'), dest, r=rev,
408 no_decode=nodecode, p=prefix,
409 t=type, S=subrepos, I=include, X=exclude,
410 hidden=self.hidden)
411
412 self.rawcommand(args)
413
414 def backout(self, rev, merge=False, parent=None, tool=None, message=None,
415 logfile=None, date=None, user=None):
416 """Prepare a new changeset with the effect of rev undone in the current
417 working directory.
418
419 If rev is the parent of the working directory, then this new
420 changeset is committed automatically. Otherwise, hg needs to
421 merge the changes and the merged result is left uncommitted.
422
423 rev - revision to backout
424 merge - merge with old dirstate parent after backout
425 parent - parent to choose when backing out merge
426 tool - specify merge tool
427 message - use text as commit message
428 logfile - read commit message from file
429 date - record the specified date as commit date
430 user - record the specified user as committer
431
432 """
433 if message and logfile:
434 raise ValueError("cannot specify both a message and a logfile")
435
436 args = cmdbuilder(b('backout'), r=rev, merge=merge, parent=parent,
437 t=tool, m=message, l=logfile, d=date, u=user,
438 hidden=self.hidden)
439
440 self.rawcommand(args)
441
442 def bookmark(self, name, rev=None, force=False, delete=False,
443 inactive=False, rename=None):
444 """
445 Set a bookmark on the working directory's parent revision or rev,
446 with the given name.
447
448 name - bookmark name
449 rev - revision to bookmark
450 force - bookmark even if another bookmark with the same name exists
451 delete - delete the given bookmark
452 inactive - do not mark the new bookmark active
453 rename - rename the bookmark given by rename to name
454 """
455 args = cmdbuilder(b('bookmark'), name, r=rev, f=force, d=delete,
456 i=inactive, m=rename)
457
458 self.rawcommand(args)
459
460 def bookmarks(self):
461 """
462 Return the bookmarks as a list of (name, rev, node) and the index of the
463 current one.
464
465 If there isn't a current one, -1 is returned as the index.
466 """
467 args = cmdbuilder(b('bookmarks'), hidden=self.hidden)
468 out = self.rawcommand(args)
469
470 bms = []
471 current = -1
472 if out.rstrip() != b('no bookmarks set'):
473 for line in out.splitlines():
474 iscurrent, line = line[0:3], line[3:]
475 if b('*') in iscurrent:
476 current = len(bms)
477 name, line = line.split(b(' '), 1)
478 rev, node = line.split(b(':'))
479 bms.append((name, int(rev), node))
480 return bms, current
481
482 def branch(self, name=None, clean=False, force=False):
483 """When name isn't given, return the current branch name. Otherwise
484 set the working directory branch name (the branch will not
485 exist in the repository until the next commit). Standard
486 practice recommends that primary development take place on the
487 'default' branch.
488
489 When clean is True, reset and return the working directory
490 branch to that of the parent of the working directory,
491 negating a previous branch change.
492
493 name - new branch name
494 clean - reset branch name to parent branch name
495 force - set branch name even if it shadows an existing branch
496
497 """
498 if name and clean:
499 raise ValueError('cannot use both name and clean')
500
501 args = cmdbuilder(b('branch'), name, f=force, C=clean)
502 out = self.rawcommand(args).rstrip()
503
504 if name:
505 return name
506 elif not clean:
507 return out
508 else:
509 # len('reset working directory to branch ') == 34
510 return out[34:]
511
512 def branches(self, active=False, closed=False):
513 """
514 Returns the repository's named branches as a list of (name, rev, node).
515
516 active - show only branches that have unmerged heads
517 closed - show normal and closed branches
518 """
519 args = cmdbuilder(b('branches'), a=active, c=closed, hidden=self.hidden)
520 out = self.rawcommand(args)
521
522 branches = []
523 for line in out.rstrip().splitlines():
524 namerev, node = line.rsplit(b(':'), 1)
525 name, rev = namerev.rsplit(b(' '), 1)
526 name = name.rstrip()
527 node = node.split()[0] # get rid of ' (inactive)'
528 branches.append((name, int(rev), node))
529 return branches
530
531 def bundle(self, file, destrepo=None, rev=[], branch=[], base=[], all=False,
532 force=False, type=None, ssh=None, remotecmd=None,
533 insecure=False):
534 """Generate a compressed changegroup file collecting changesets not
535 known to be in another repository.
536
537 If destrepo isn't given, then hg assumes the destination will have all
538 the nodes you specify with base. To create a bundle containing all
539 changesets, use all (or set base to 'null').
540
541 file - destination file name
542 destrepo - repository to look for changes
543 rev - a changeset intended to be added to the destination
544 branch - a specific branch you would like to bundle
545 base - a base changeset assumed to be available at the destination
546 all - bundle all changesets in the repository
547 type - bundle compression type to use, available compression
548 methods are: none, bzip2, and gzip (default: bzip2)
549
550 force - run even when the destrepo is unrelated
551 ssh - specify ssh command to use
552 remotecmd - specify hg command to run on the remote side
553 insecure - do not verify server certificate (ignoring
554 web.cacerts config)
555
556 Return True if a bundle was created, False if no changes were found.
557
558 """
559 args = cmdbuilder(b('bundle'), file, destrepo, f=force, r=rev, b=branch,
560 base=base, a=all, t=type, e=ssh, remotecmd=remotecmd,
561 insecure=insecure, hidden=self.hidden)
562
563 eh = util.reterrorhandler(args)
564 self.rawcommand(args, eh=eh)
565
566 return bool(eh)
567
568 def cat(self, files, rev=None, output=None):
569 """Return a string containing the specified files as they were at the
570 given revision. If no revision is given, the parent of the working
571 directory is used, or tip if no revision is checked out.
572
573 If output is given, writes the contents to the specified file.
574 The name of the file is given using a format string. The
575 formatting rules are the same as for the export command, with
576 the following additions:
577
578 "%s" basename of file being printed
579 "%d" dirname of file being printed, or '.' if in repository root
580 "%p" root-relative path name of file being printed
581
582 """
583 args = cmdbuilder(b('cat'), r=rev, o=output, hidden=self.hidden, *files)
584 out = self.rawcommand(args)
585
586 if not output:
587 return out
588
589 def clone(self, source=b('.'), dest=None, branch=None, updaterev=None,
590 revrange=None):
591 """
592 Create a copy of an existing repository specified by source in a new
593 directory dest.
594
595 If dest isn't specified, it defaults to the basename of source.
596
597 branch - clone only the specified branch
598 updaterev - revision, tag or branch to check out
599 revrange - include the specified changeset
600 """
601 args = cmdbuilder(b('clone'), source, dest, b=branch,
602 u=updaterev, r=revrange)
603 self.rawcommand(args)
604
605 def init(self, dest, ssh=None, remotecmd=None, insecure=False):
606 args = util.cmdbuilder('init', dest, e=ssh, remotecmd=remotecmd,
607 insecure=insecure)
608 self.rawcommand(args)
609
610 def commit(self, message=None, logfile=None, addremove=False,
611 closebranch=False, date=None, user=None, include=None,
612 exclude=None, amend=False):
613 """
614 Commit changes reported by status into the repository.
615
616 message - the commit message
617 logfile - read commit message from file
618 addremove - mark new/missing files as added/removed before committing
619 closebranch - mark a branch as closed, hiding it from the branch list
620 date - record the specified date as commit date
621 user - record the specified user as committer
622 include - include names matching the given patterns
623 exclude - exclude names matching the given patterns
624 amend - amend the parent of the working dir
625 """
626 if amend and message is None and logfile is None:
627 # retrieve current commit message
628 message = self.log(b('.'))[0][5]
629 if message is None and logfile is None and not amend:
630 raise ValueError("must provide at least a message or a logfile")
631 elif message and logfile:
632 raise ValueError("cannot specify both a message and a logfile")
633
634 # --debug will print the committed cset
635 args = cmdbuilder(b('commit'), debug=True, m=message, A=addremove,
636 close_branch=closebranch, d=date, u=user, l=logfile,
637 I=include, X=exclude, amend=amend)
638 out = self.rawcommand(args)
639 m = re.search(b(r'^committed changeset (\d+):([0-9a-f]+)'), out,
640 re.MULTILINE)
641 if not m:
642 raise ValueError('revision and node not found in hg output: %r'
643 % out)
644 rev, node = m.groups()
645 return int(rev), node
646
647 def config(self, names=[], untrusted=False, showsource=False):
648 """Return a list of (section, key, value) config settings from all
649 hgrc files
650
651 When showsource is specified, return (source, section, key, value) where
652 source is of the form filename:[line]
653
654 """
655 def splitline(s):
656 k, value = s.rstrip().split(b('='), 1)
657 section, key = k.split(b('.'), 1)
658 return section, key, value
659
660 if not isinstance(names, list):
661 names = [names]
662
663 args = cmdbuilder(b('showconfig'), u=untrusted, debug=showsource,
664 *names)
665 out = self.rawcommand(args)
666
667 conf = []
668 if showsource:
669 out = util.skiplines(out, b('read config from: '))
670 for line in out.splitlines():
671 m = re.match(b(r"(.+?:(?:\d+:)?) (.*)"), line)
672 t = splitline(m.group(2))
673 conf.append((m.group(1)[:-1], t[0], t[1], t[2]))
674 else:
675 for line in out.splitlines():
676 conf.append(splitline(line))
677
678 return conf
679
680 @property
681 def encoding(self):
682 """
683 Return the server's encoding (as reported in the hello message).
684 """
685 if not b('getencoding') in self.capabilities:
686 raise CapabilityError('getencoding')
687
688 if not self._encoding:
689 self.server.stdin.write(b('getencoding\n'))
690 self._encoding = self._readfromchannel('r')
691
692 return self._encoding
693
694 def copy(self, source, dest, after=False, force=False, dryrun=False,
695 include=None, exclude=None):
696 """Mark dest as having copies of source files. If dest is a
697 directory, copies are put in that directory. If dest is a
698 file, then source must be a string.
699
700 Returns True on success, False if errors are encountered.
701
702 source - a file or a list of files
703 dest - a destination file or directory
704 after - record a copy that has already occurred
705 force - forcibly copy over an existing managed file
706 dryrun - do not perform actions, just print output
707 include - include names matching the given patterns
708 exclude - exclude names matching the given patterns
709
710 """
711 if not isinstance(source, list):
712 source = [source]
713
714 source.append(dest)
715 args = cmdbuilder(b('copy'), A=after, f=force, n=dryrun,
716 I=include, X=exclude, *source)
717
718 eh = util.reterrorhandler(args)
719 self.rawcommand(args, eh=eh)
720
721 return bool(eh)
722
723 def diff(self, files=[], revs=[], change=None, text=False,
724 git=False, nodates=False, showfunction=False,
725 reverse=False, ignoreallspace=False,
726 ignorespacechange=False, ignoreblanklines=False,
727 unified=None, stat=False, subrepos=False, include=None,
728 exclude=None):
729 """
730 Return differences between revisions for the specified files.
731
732 revs - a revision or a list of two revisions to diff
733 change - change made by revision
734 text - treat all files as text
735 git - use git extended diff format
736 nodates - omit dates from diff headers
737 showfunction - show which function each change is in
738 reverse - produce a diff that undoes the changes
739 ignoreallspace - ignore white space when comparing lines
740 ignorespacechange - ignore changes in the amount of white space
741 ignoreblanklines - ignore changes whose lines are all blank
742 unified - number of lines of context to show
743 stat - output diffstat-style summary of changes
744 subrepos - recurse into subrepositories
745 include - include names matching the given patterns
746 exclude - exclude names matching the given patterns
747 """
748 if change and revs:
749 raise ValueError('cannot specify both change and rev')
750
751 args = cmdbuilder(b('diff'), r=list(map(strtobytes, revs)), c=change,
752 a=text, g=git, nodates=nodates,
753 p=showfunction, reverse=reverse,
754 w=ignoreallspace, b=ignorespacechange,
755 B=ignoreblanklines, U=unified, stat=stat,
756 S=subrepos, I=include, X=exclude, hidden=self.hidden,
757 *files)
758
759 return self.rawcommand(args)
760
761 def export(self, revs, output=None, switchparent=False,
762 text=False, git=False, nodates=False):
763 """Return the header and diffs for one or more changesets. When
764 output is given, dumps to file. The name of the file is given
765 using a format string. The formatting rules are as follows:
766
767 "%%" literal "%" character
768 "%H" changeset hash (40 hexadecimal digits)
769 "%N" number of patches being generated
770 "%R" changeset revision number
771 "%b" basename of the exporting repository
772 "%h" short-form changeset hash (12 hexadecimal digits)
773 "%n" zero-padded sequence number, starting at 1
774 "%r" zero-padded changeset revision number
775
776 output - print output to file with formatted name
777 switchparent - diff against the second parent
778 rev - a revision or list of revisions to export
779 text - treat all files as text
780 git - use git extended diff format
781 nodates - omit dates from diff headers
782
783 """
784 if not isinstance(revs, list):
785 revs = [revs]
786 args = cmdbuilder(b('export'), o=output, switch_parent=switchparent,
787 a=text, g=git, nodates=nodates, hidden=self.hidden,
788 *revs)
789
790 out = self.rawcommand(args)
791
792 if output is None:
793 return out
794
795 def forget(self, files, include=None, exclude=None):
796 """Mark the specified files so they will no longer be tracked after
797 the next commit.
798
799 This only removes files from the current branch, not from the entire
800 project history, and it does not delete them from the working directory.
801
802 Returns True on success.
803
804 include - include names matching the given patterns
805 exclude - exclude names matching the given patterns
806
807 """
808 if not isinstance(files, list):
809 files = [files]
810
811 args = cmdbuilder(b('forget'), I=include, X=exclude, *files)
812
813 eh = util.reterrorhandler(args)
814 self.rawcommand(args, eh=eh)
815
816 return bool(eh)
817
818 def grep(self, pattern, files=[], all=False, text=False, follow=False,
819 ignorecase=False, fileswithmatches=False, line=False, user=False,
820 date=False, include=None, exclude=None):
821 """Search for a pattern in specified files and revisions.
822
823 This behaves differently than Unix grep. It only accepts Python/Perl
824 regexps. It searches repository history, not the working directory.
825 It always prints the revision number in which a match appears.
826
827 Yields (filename, revision, [line, [match status, [user,
828 [date, [match]]]]]) per match depending on the given options.
829
830 all - print all revisions that match
831 text - treat all files as text
832 follow - follow changeset history, or file history across
833 copies and renames
834 ignorecase - ignore case when matching
835 fileswithmatches - return only filenames and revisions that match
836 line - return line numbers in the result tuple
837 user - return the author in the result tuple
838 date - return the date in the result tuple
839 include - include names matching the given patterns
840 exclude - exclude names matching the given patterns
841
842 """
843 if not isinstance(files, list):
844 files = [files]
845
846 args = cmdbuilder(b('grep'), all=all, a=text, f=follow, i=ignorecase,
847 l=fileswithmatches, n=line, u=user, d=date,
848 I=include, X=exclude, hidden=self.hidden,
849 *[pattern] + files)
850 args.append(b('-0'))
851
852 def eh(ret, out, err):
853 if ret != 1:
854 raise error.CommandError(args, ret, out, err)
855 return b('')
856
857 out = self.rawcommand(args, eh=eh).split(b('\0'))
858
859 fieldcount = 3
860 if user:
861 fieldcount += 1
862 if date:
863 fieldcount += 1
864 if line:
865 fieldcount += 1
866 if all:
867 fieldcount += 1
868 if fileswithmatches:
869 fieldcount -= 1
870
871 return util.grouper(fieldcount, out)
872
873 def heads(self, rev=[], startrev=[], topological=False, closed=False):
874 """Return a list of current repository heads or branch heads.
875
876 rev - return only branch heads on the branches associated with
877 the specified changesets.
878
879 startrev - return only heads which are descendants of the given revs.
880 topological - named branch mechanics will be ignored and only changesets
881 without children will be shown.
882
883 closed - normal and closed branch heads.
884
885 """
886 if not isinstance(rev, list):
887 rev = [rev]
888
889 args = cmdbuilder(b('heads'), r=startrev, t=topological, c=closed,
890 template=templates.changeset, hidden=self.hidden,
891 *rev)
892
893 def eh(ret, out, err):
894 if ret != 1:
895 raise error.CommandError(args, ret, out, err)
896 return b('')
897
898 out = self.rawcommand(args, eh=eh).split(b('\0'))[:-1]
899 return self._parserevs(out)
900
901 def identify(self, rev=None, source=None, num=False, id=False, branch=False,
902 tags=False, bookmarks=False):
903 """Return a summary string identifying the repository state at rev
904 using one or two parent hash identifiers, followed by a "+" if
905 the working directory has uncommitted changes, the branch name
906 (if not default), a list of tags, and a list of bookmarks.
907
908 When rev is not given, return a summary string of the current
909 state of the repository.
910
911 Specifying source as a repository root or Mercurial bundle will cause
912 lookup to operate on that repository/bundle.
913
914 num - show local revision number
915 id - show global revision id
916 branch - show branch
917 tags - show tags
918 bookmarks - show bookmarks
919
920 """
921 args = cmdbuilder(b('identify'), source, r=rev, n=num, i=id,
922 b=branch, t=tags, B=bookmarks,
923 hidden=self.hidden)
924
925 return self.rawcommand(args)
926
927 def import_(self, patches, strip=None, force=False, nocommit=False,
928 bypass=False, exact=False, importbranch=False, message=None,
929 date=None, user=None, similarity=None):
930 """Import the specified patches which can be a list of file names or a
931 file-like object and commit them individually (unless nocommit is
932 specified).
933
934 strip - directory strip option for patch. This has the same
935 meaning as the corresponding patch option (default: 1)
936
937 force - skip check for outstanding uncommitted changes
938 nocommit - don't commit, just update the working directory
939 bypass - apply patch without touching the working directory
940 exact - apply patch to the nodes from which it was generated
941 importbranch - use any branch information in patch (implied by exact)
942 message - the commit message
943 date - record the specified date as commit date
944 user - record the specified user as committer
945 similarity - guess renamed files by similarity (0<=s<=100)
946
947 """
948 if hasattr(patches, 'read') and hasattr(patches, 'readline'):
949 patch = patches
950
951 def readline(size, output):
952 return patch.readline(size)
953
954 stdin = True
955 patches = ()
956 prompt = readline
957 input = patch.read
958 else:
959 stdin = False
960 prompt = None
961 input = None
962
963 args = cmdbuilder(b('import'), strip=strip, force=force,
964 no_commit=nocommit, bypass=bypass, exact=exact,
965 import_branch=importbranch, message=message,
966 date=date, user=user, similarity=similarity, _=stdin,
967 *patches)
968
969 self.rawcommand(args, prompt=prompt, input=input)
970
971 def incoming(self, revrange=None, path=None, force=False, newest=False,
972 bundle=None, bookmarks=False, branch=None, limit=None,
973 nomerges=False, subrepos=False):
974 """Return new changesets found in the specified path or the default pull
975 location.
976
977 When bookmarks=True, return a list of (name, node) of incoming
978 bookmarks.
979
980 revrange - a remote changeset or list of changesets intended to be added
981 force - run even if remote repository is unrelated
982 newest - show newest record first
983 bundle - avoid downloading the changesets twice and store the
984 bundles into the specified file.
985
986 bookmarks - compare bookmarks (this changes the return value)
987 branch - a specific branch you would like to pull
988 limit - limit number of changes returned
989 nomerges - do not show merges
990 ssh - specify ssh command to use
991 remotecmd - specify hg command to run on the remote side
992 insecure- do not verify server certificate (ignoring web.cacerts config)
993 subrepos - recurse into subrepositories
994
995 """
996 args = cmdbuilder(b('incoming'), path,
997 template=templates.changeset, r=revrange,
998 f=force, n=newest, bundle=bundle,
999 B=bookmarks, b=branch, l=limit, M=nomerges,
1000 S=subrepos)
1001
1002 def eh(ret, out, err):
1003 if ret != 1:
1004 raise error.CommandError(args, ret, out, err)
1005
1006 out = self.rawcommand(args, eh=eh)
1007 if not out:
1008 return []
1009
1010 out = util.eatlines(out, 2)
1011 if bookmarks:
1012 bms = []
1013 for line in out.splitlines():
1014 bms.append(tuple(line.split()))
1015 return bms
1016 else:
1017 out = out.split(b('\0'))[:-1]
1018 return self._parserevs(out)
1019
1020 def log(self, revrange=None, files=[], follow=False,
1021 followfirst=False, date=None, copies=False, keyword=None,
1022 removed=False, onlymerges=False, user=None, branch=None,
1023 prune=None, hidden=None, limit=None, nomerges=False,
1024 include=None, exclude=None):
1025 """Return the revision history of the specified files or the entire
1026 project.
1027
1028 File history is shown without following rename or copy history of files.
1029 Use follow with a filename to follow history across renames and copies.
1030 follow without a filename will only show ancestors or descendants of the
1031 starting revision. followfirst only follows the first parent of merge
1032 revisions.
1033
1034 If revrange isn't specified, the default is "tip:0" unless
1035 follow is set, in which case the working directory parent is
1036 used as the starting revision.
1037
1038 The returned changeset is a named tuple with the following
1039 string fields:
1040
1041 - rev
1042 - node
1043 - tags (space delimited)
1044 - branch
1045 - author
1046 - desc
1047
1048 follow - follow changeset history, or file history across
1049 copies and renames
1050 followfirst - only follow the first parent of merge changesets
1051 date - show revisions matching date spec
1052 copies - show copied files
1053 keyword - do case-insensitive search for a given text
1054 removed - include revisions where files were removed
1055 onlymerges - show only merges
1056 user - revisions committed by user
1057 branch - show changesets within the given named branch
1058 prune - do not display revision or any of its ancestors
1059 hidden - show hidden changesets
1060 limit - limit number of changes displayed
1061 nomerges - do not show merges
1062 include - include names matching the given patterns
1063 exclude - exclude names matching the given patterns
1064
1065 """
1066 if hidden is None:
1067 hidden = self.hidden
1068 args = cmdbuilder(b('log'), template=templates.changeset,
1069 r=revrange, f=follow, follow_first=followfirst,
1070 d=date, C=copies, k=keyword, removed=removed,
1071 m=onlymerges, u=user, b=branch, P=prune,
1072 l=limit, M=nomerges, I=include, X=exclude,
1073 hidden=hidden, *files)
1074
1075 out = self.rawcommand(args)
1076 out = out.split(b('\0'))[:-1]
1077
1078 return self._parserevs(out)
1079
1080 def manifest(self, rev=None, all=False):
1081 """Yields (nodeid, permission, executable, symlink, file path) tuples
1082 for version controlled files for the given revision. If no
1083 revision is given, the first parent of the working directory
1084 is used, or the null revision if no revision is checked out.
1085
1086 When all is True, all files from all revisions are yielded
1087 (just the name). This includes deleted and renamed files.
1088
1089 """
1090 args = cmdbuilder(b('manifest'), r=rev, all=all, debug=True,
1091 hidden=self.hidden)
1092
1093 out = self.rawcommand(args)
1094
1095 if all:
1096 for line in out.splitlines():
1097 yield line
1098 else:
1099 for line in out.splitlines():
1100 node = line[0:40]
1101 perm = line[41:44]
1102 symlink = line[45:46] == b('@')
1103 executable = line[45:46] == b('*')
1104 yield node, perm, executable, symlink, line[47:]
1105
1106 def merge(self, rev=None, force=False, tool=None, cb=merge.handlers.abort):
1107 """Merge working directory with rev. If no revision is specified, the
1108 working directory's parent is a head revision, and the current
1109 branch contains exactly one other head, the other head is
1110 merged with by default.
1111
1112 The current working directory is updated with all changes made in the
1113 requested revision since the last common predecessor revision.
1114
1115 Files that changed between either parent are marked as changed for the
1116 next commit and a commit must be performed before any further updates to
1117 the repository are allowed. The next commit will have two parents.
1118
1119 force - force a merge with outstanding changes
1120 tool - can be used to specify the merge tool used for file merges. It
1121 overrides the HGMERGE environment variable and your configuration files.
1122
1123 cb - controls the behaviour when Mercurial prompts what to do
1124 with regard to a specific file, e.g. when one parent modified
1125 a file and the other removed it. It can be one of
1126 merge.handlers, or a function that gets a single argument
1127 which are the contents of stdout. It should return one of the
1128 expected choices (a single character).
1129
1130 """
1131 # we can't really use --preview since merge doesn't support --template
1132 args = cmdbuilder(b('merge'), r=rev, f=force, t=tool)
1133
1134 prompt = None
1135 if cb is merge.handlers.abort:
1136 prompt = cb
1137 elif cb is merge.handlers.noninteractive:
1138 args.append(b('-y'))
1139 else:
1140 prompt = lambda size, output: cb(output) + b('\n')
1141
1142 self.rawcommand(args, prompt=prompt)
1143
1144 def move(self, source, dest, after=False, force=False, dryrun=False,
1145 include=None, exclude=None):
1146 """Mark dest as copies of source; mark source for deletion. If dest
1147 is a directory, copies are put in that directory. If dest is a
1148 file, then source must be a string.
1149
1150 Returns True on success, False if errors are encountered.
1151
1152 source - a file or a list of files
1153 dest - a destination file or directory
1154 after - record a rename that has already occurred
1155 force - forcibly copy over an existing managed file
1156 dryrun - do not perform actions, just print output
1157 include - include names matching the given patterns
1158 exclude - exclude names matching the given patterns
1159
1160 """
1161 if not isinstance(source, list):
1162 source = [source]
1163
1164 source.append(dest)
1165 args = cmdbuilder(b('move'), A=after, f=force, n=dryrun,
1166 I=include, X=exclude, *source)
1167
1168 eh = util.reterrorhandler(args)
1169 self.rawcommand(args, eh=eh)
1170
1171 return bool(eh)
1172
1173 def outgoing(self, revrange=None, path=None, force=False, newest=False,
1174 bookmarks=False, branch=None, limit=None, nomerges=False,
1175 subrepos=False):
1176 """Return changesets not found in the specified path or the default push
1177 location.
1178
1179 When bookmarks=True, return a list of (name, node) of
1180 bookmarks that will be pushed.
1181
1182 revrange - a (list of) changeset intended to be included in
1183 the destination force - run even when the destination is
1184 unrelated newest - show newest record first branch - a
1185 specific branch you would like to push limit - limit number of
1186 changes displayed nomerges - do not show merges ssh - specify
1187 ssh command to use remotecmd - specify hg command to run on
1188 the remote side insecure - do not verify server certificate
1189 (ignoring web.cacerts config) subrepos - recurse into
1190 subrepositories
1191
1192 """
1193 args = cmdbuilder(b('outgoing'),
1194 path,
1195 template=templates.changeset, r=revrange,
1196 f=force, n=newest, B=bookmarks,
1197 b=branch, S=subrepos)
1198
1199 def eh(ret, out, err):
1200 if ret != 1:
1201 raise error.CommandError(args, ret, out, err)
1202
1203 out = self.rawcommand(args, eh=eh)
1204 if not out:
1205 return []
1206
1207 out = util.eatlines(out, 2)
1208 if bookmarks:
1209 bms = []
1210 for line in out.splitlines():
1211 bms.append(tuple(line.split()))
1212 return bms
1213 else:
1214 out = out.split(b('\0'))[:-1]
1215 return self._parserevs(out)
1216
1217 def parents(self, rev=None, file=None):
1218 """Return the working directory's parent revisions. If rev is given,
1219 the parent of that revision will be printed. If file is given,
1220 the revision in which the file was last changed (before the
1221 working directory revision or the revision specified by rev)
1222 is returned.
1223
1224 """
1225 args = cmdbuilder(b('parents'), file, template=templates.changeset,
1226 r=rev, hidden=self.hidden)
1227
1228 out = self.rawcommand(args)
1229 if not out:
1230 return
1231
1232 out = out.split(b('\0'))[:-1]
1233
1234 return self._parserevs(out)
1235
1236 def paths(self, name=None):
1237 """
1238 Return the definition of given symbolic path name. If no name is given,
1239 return a dictionary of pathname : url of all available names.
1240
1241 Path names are defined in the [paths] section of your configuration file
1242 and in "/etc/mercurial/hgrc". If run inside a repository, ".hg/hgrc" is
1243 used, too.
1244 """
1245 if not name:
1246 out = self.rawcommand([b('paths')])
1247 if not out:
1248 return {}
1249
1250 return dict([s.split(b(' = '))
1251 for s in out.rstrip().split(b('\n'))])
1252 else:
1253 args = cmdbuilder(b('paths'), name)
1254 out = self.rawcommand(args)
1255 return out.rstrip()
1256
1257 def pull(self, source=None, rev=None, update=False, force=False,
1258 bookmark=None, branch=None, ssh=None, remotecmd=None,
1259 insecure=False, tool=None):
1260 """Pull changes from a remote repository.
1261
1262 This finds all changes from the repository specified by source
1263 and adds them to this repository. If source is omitted, the
1264 'default' path will be used. By default, this does not update
1265 the copy of the project in the working directory.
1266
1267 Returns True on success, False if update was given and there were
1268 unresolved files.
1269
1270 update - update to new branch head if changesets were pulled
1271 force - run even when remote repository is unrelated
1272 rev - a (list of) remote changeset intended to be added
1273 bookmark - (list of) bookmark to pull
1274 branch - a (list of) specific branch you would like to pull
1275 ssh - specify ssh command to use
1276 remotecmd - specify hg command to run on the remote side
1277 insecure - do not verify server certificate (ignoring
1278 web.cacerts config)
1279 tool - specify merge tool for rebase
1280
1281 """
1282 args = cmdbuilder(b('pull'), source, r=rev, u=update, f=force,
1283 B=bookmark, b=branch, e=ssh,
1284 remotecmd=remotecmd, insecure=insecure,
1285 t=tool)
1286
1287 eh = util.reterrorhandler(args)
1288 self.rawcommand(args, eh=eh)
1289
1290 return bool(eh)
1291
1292 def push(self, dest=None, rev=None, force=False, bookmark=None, branch=None,
1293 newbranch=False, ssh=None, remotecmd=None, insecure=False):
1294 """Push changesets from this repository to the specified destination.
1295
1296 This operation is symmetrical to pull: it is identical to a pull in the
1297 destination repository from the current one.
1298
1299 Returns True if push was successful, False if nothing to push.
1300
1301 rev - the (list of) specified revision and all its ancestors
1302 will be pushed to the remote repository.
1303
1304 force - override the default behavior and push all changesets on all
1305 branches.
1306
1307 bookmark - (list of) bookmark to push
1308 branch - a (list of) specific branch you would like to push
1309 newbranch - allows push to create a new named branch that is
1310 not present at the destination. This allows you to only create
1311 a new branch without forcing other changes.
1312
1313 ssh - specify ssh command to use
1314 remotecmd - specify hg command to run on the remote side
1315 insecure - do not verify server certificate (ignoring
1316 web.cacerts config)
1317
1318 """
1319 args = cmdbuilder(b('push'), dest, r=rev, f=force, B=bookmark, b=branch,
1320 new_branch=newbranch, e=ssh, remotecmd=remotecmd,
1321 insecure=insecure)
1322
1323 eh = util.reterrorhandler(args)
1324 self.rawcommand(args, eh=eh)
1325
1326 return bool(eh)
1327
1328 def remove(self, files, after=False, force=False, include=None,
1329 exclude=None):
1330 """Schedule the indicated files for removal from the repository. This
1331 only removes files from the current branch, not from the
1332 entire project history.
1333
1334 Returns True on success, False if any warnings encountered.
1335
1336 after - used to remove only files that have already been deleted
1337 force - remove (and delete) file even if added or modified
1338 include - include names matching the given patterns
1339 exclude - exclude names matching the given patterns
1340
1341 """
1342 if not isinstance(files, list):
1343 files = [files]
1344
1345 args = cmdbuilder(b('remove'), A=after, f=force, I=include, X=exclude,
1346 *files)
1347
1348 eh = util.reterrorhandler(args)
1349 self.rawcommand(args, eh=eh)
1350
1351 return bool(eh)
1352
1353 def resolve(self, file=[], all=False, listfiles=False, mark=False,
1354 unmark=False, tool=None, include=None, exclude=None):
1355 """
1356 Redo merges or set/view the merge status of given files.
1357
1358 Returns True on success, False if any files fail a resolve attempt.
1359
1360 When listfiles is True, returns a list of (code, file path) of resolved
1361 and unresolved files. Code will be 'R' or 'U' accordingly.
1362
1363 all - select all unresolved files
1364 mark - mark files as resolved
1365 unmark - mark files as unresolved
1366 tool - specify merge tool
1367 include - include names matching the given patterns
1368 exclude - exclude names matching the given patterns
1369 """
1370 if not isinstance(file, list):
1371 file = [file]
1372
1373 args = cmdbuilder(b('resolve'), a=all, l=listfiles, m=mark, u=unmark,
1374 t=tool, I=include, X=exclude, *file)
1375
1376 out = self.rawcommand(args)
1377
1378 if listfiles:
1379 l = []
1380 for line in out.splitlines():
1381 l.append(tuple(line.split(b(' '), 1)))
1382 return l
1383
1384 def revert(self, files, rev=None, all=False, date=None, nobackup=False,
1385 dryrun=False, include=None, exclude=None):
1386 """With no revision specified, revert the specified files or
1387 directories to the contents they had in the parent of the
1388 working directory. This restores the contents of files to an
1389 unmodified state and unschedules adds, removes, copies, and
1390 renames. If the working directory has two parents, you must
1391 explicitly specify a revision.
1392
1393 Specifying rev or date will revert the given files or
1394 directories to their states as of a specific revision. Because
1395 revert does not change the working directory parents, this
1396 will cause these files to appear modified. This can be helpful
1397 to "back out" some or all of an earlier change.
1398
1399 Modified files are saved with a .orig suffix before reverting.
1400 To disable these backups, use nobackup.
1401
1402 Returns True on success.
1403
1404 all - revert all changes when no arguments given
1405 date - tipmost revision matching date
1406 rev - revert to the specified revision
1407 nobackup - do not save backup copies of files
1408 include - include names matching the given patterns
1409 exclude - exclude names matching the given patterns
1410 dryrun - do not perform actions, just print output
1411
1412 """
1413 if not isinstance(files, list):
1414 files = [files]
1415
1416 args = cmdbuilder(b('revert'), r=rev, a=all, d=date,
1417 no_backup=nobackup, n=dryrun, I=include, X=exclude,
1418 hidden=self.hidden, *files)
1419
1420 eh = util.reterrorhandler(args)
1421 self.rawcommand(args, eh=eh)
1422
1423 return bool(eh)
1424
1425 def root(self):
1426 """
1427 Return the root directory of the current repository.
1428 """
1429 return self.rawcommand([b('root')]).rstrip()
1430
1431 def status(self, rev=None, change=None, all=False, modified=False,
1432 added=False, removed=False, deleted=False, clean=False,
1433 unknown=False, ignored=False, copies=False,
1434 subrepos=False, include=None, exclude=None):
1435 """
1436 Return status of files in the repository as a list of (code, file path)
1437 where code can be:
1438
1439 M = modified
1440 A = added
1441 R = removed
1442 C = clean
1443 ! = missing (deleted by non-hg command, but still tracked)
1444 ? = untracked
1445 I = ignored
1446 = origin of the previous file listed as A (added)
1447
1448 rev - show difference from (list of) revision
1449 change - list the changed files of a revision
1450 all - show status of all files
1451 modified - show only modified files
1452 added - show only added files
1453 removed - show only removed files
1454 deleted - show only deleted (but tracked) files
1455 clean - show only files without changes
1456 unknown - show only unknown (not tracked) files
1457 ignored - show only ignored files
1458 copies - show source of copied files
1459 subrepos - recurse into subrepositories
1460 include - include names matching the given patterns
1461 exclude - exclude names matching the given patterns
1462 """
1463 if rev and change:
1464 raise ValueError('cannot specify both rev and change')
1465
1466 args = cmdbuilder(b('status'), rev=rev, change=change, A=all,
1467 m=modified, a=added, r=removed, d=deleted, c=clean,
1468 u=unknown, i=ignored, C=copies, S=subrepos, I=include,
1469 X=exclude, hidden=self.hidden)
1470
1471 args.append(b('-0'))
1472
1473 out = self.rawcommand(args)
1474 l = []
1475
1476 for entry in out.split(b('\0')):
1477 if entry:
1478 if entry[0:1] == b(' '):
1479 l.append((b(' '), entry[2:]))
1480 else:
1481 l.append(tuple(entry.split(b(' '), 1)))
1482
1483 return l
1484
1485 def tag(self, names, rev=None, message=None, force=False, local=False,
1486 remove=False, date=None, user=None):
1487 """Add one or more tags specified by names for the current or given
1488 revision.
1489
1490 Changing an existing tag is normally disallowed; use force to override.
1491
1492 Tag commits are usually made at the head of a branch. If the
1493 parent of the working directory is not a branch head, a
1494 CommandError will be raised. force can be specified to force
1495 the tag commit to be based on a non-head changeset.
1496
1497 local - make the tag local
1498 rev - revision to tag
1499 remove - remove a tag
1500 message - set commit message
1501 date - record the specified date as commit date
1502 user - record the specified user as committer
1503
1504 """
1505 if not isinstance(names, list):
1506 names = [names]
1507
1508 args = cmdbuilder(b('tag'), r=rev, m=message, f=force, l=local,
1509 remove=remove, d=date, u=user, hidden=self.hidden,
1510 *names)
1511
1512 self.rawcommand(args)
1513
1514 def tags(self):
1515 """
1516 Return a list of repository tags as: (name, rev, node, islocal)
1517 """
1518 args = cmdbuilder(b('tags'), v=True)
1519
1520 out = self.rawcommand(args)
1521
1522 t = []
1523 for line in out.splitlines():
1524 taglocal = line.endswith(b(' local'))
1525 if taglocal:
1526 line = line[:-6]
1527 name, rev = line.rsplit(b(' '), 1)
1528 rev, node = rev.split(b(':'))
1529 t.append((name.rstrip(), int(rev), node, taglocal))
1530 return t
1531
1532 def phase(self, revs=(), secret=False, draft=False, public=False,
1533 force=False):
1534 '''Set or show the current phase name.
1535
1536 revs - target revision(s)
1537 public - set changeset phase to public
1538 draft - set changeset phase to draft
1539 secret - set changeset phase to secret
1540 force - allow to move boundary backward
1541
1542 output format: [(id, phase) ...] for each changeset
1543
1544 The arguments match the mercurial API.
1545 '''
1546 if not isinstance(revs, (list, tuple)):
1547 revs = [revs]
1548 args = util.cmdbuilder(b('phase'), secret=secret, draft=draft,
1549 public=public, force=force,
1550 hidden=self.hidden, *revs)
1551 out = self.rawcommand(args)
1552 if draft or public or secret:
1553 return
1554 else:
1555 output = [i.split(b(': '))for i in out.strip().split(b('\n'))]
1556 return [(int(num), phase) for (num, phase) in output]
1557
1558 def summary(self, remote=False):
1559 """
1560 Return a dictionary with a brief summary of the working directory state,
1561 including parents, branch, commit status, and available updates.
1562
1563 'parent' : a list of (rev, node, tags, message)
1564 'branch' : the current branch
1565 'commit' : True if the working directory is clean, False otherwise
1566 'update' : number of available updates,
1567 ['remote' : (in, in bookmarks, out, out bookmarks),]
1568 ['mq': (applied, unapplied) mq patches,]
1569
1570 unparsed entries will be of them form key : value
1571 """
1572 args = cmdbuilder(b('summary'), remote=remote, hidden=self.hidden)
1573
1574 out = self.rawcommand(args).splitlines()
1575
1576 d = {}
1577 while out:
1578 line = out.pop(0)
1579 name, value = line.split(b(': '), 1)
1580
1581 if name == b('parent'):
1582 parent, tags = value.split(b(' '), 1)
1583 rev, node = parent.split(b(':'))
1584
1585 if tags:
1586 tags = tags.replace(b(' (empty repository)'), b(''))
1587 else:
1588 tags = None
1589
1590 value = d.get(name, [])
1591
1592 if rev == b('-1'):
1593 value.append((int(rev), node, tags, None))
1594 else:
1595 message = out.pop(0)[1:]
1596 value.append((int(rev), node, tags, message))
1597 elif name == b('branch'):
1598 pass
1599 elif name == b('commit'):
1600 value = value == b('(clean)')
1601 elif name == b('update'):
1602 if value == b('(current)'):
1603 value = 0
1604 else:
1605 value = int(value.split(b(' '), 1)[0])
1606 elif remote and name == b('remote'):
1607 if value == b('(synced)'):
1608 value = 0, 0, 0, 0
1609 else:
1610 inc = incb = out_ = outb = 0
1611
1612 for v in value.split(b(', ')):
1613 count, v = v.split(b(' '), 1)
1614 if v == b('outgoing'):
1615 out_ = int(count)
1616 elif v.endswith(b('incoming')):
1617 inc = int(count)
1618 elif v == b('incoming bookmarks'):
1619 incb = int(count)
1620 elif v == b('outgoing bookmarks'):
1621 outb = int(count)
1622
1623 value = inc, incb, out_, outb
1624 elif name == b('mq'):
1625 applied = unapplied = 0
1626 for v in value.split(b(', ')):
1627 count, v = v.split(b(' '), 1)
1628 if v == b('applied'):
1629 applied = int(count)
1630 elif v == b('unapplied'):
1631 unapplied = int(count)
1632 value = applied, unapplied
1633
1634 d[name] = value
1635
1636 return d
1637
1638 def tip(self):
1639 """
1640 Return the tip revision (usually just called the tip) which is the
1641 changeset most recently added to the repository (and therefore the most
1642 recently changed head).
1643 """
1644 args = cmdbuilder(b('tip'), template=templates.changeset,
1645 hidden=self.hidden)
1646 out = self.rawcommand(args)
1647 out = out.split(b('\0'))
1648
1649 return self._parserevs(out)[0]
1650
1651 def update(self, rev=None, clean=False, check=False, date=None):
1652 """
1653 Update the repository's working directory to changeset specified by rev.
1654 If rev isn't specified, update to the tip of the current named branch.
1655
1656 Return the number of files (updated, merged, removed, unresolved)
1657
1658 clean - discard uncommitted changes (no backup)
1659 check - update across branches if no uncommitted changes
1660 date - tipmost revision matching date
1661 """
1662 if clean and check:
1663 raise ValueError('clean and check cannot both be True')
1664
1665 args = cmdbuilder(b('update'), r=rev, C=clean, c=check, d=date,
1666 hidden=self.hidden)
1667
1668 def eh(ret, out, err):
1669 if ret == 1:
1670 return out
1671
1672 raise error.CommandError(args, ret, out, err)
1673
1674
1675 out = self.rawcommand(args, eh=eh)
1676
1677 m = re.search(b(r'^(\d+).+, (\d+).+, (\d+).+, (\d+)'), out,
1678 re.MULTILINE)
1679 return tuple(map(int, list(m.groups())))
1680
1681 @property
1682 def version(self):
1683 """Return hg version that runs the command server as a 4 fielded
1684 tuple: major, minor, micro and local build info. e.g. (1, 9,
1685 1, '+4-3095db9f5c2c')
1686 """
1687 if self._version is None:
1688 v = self.rawcommand(cmdbuilder(b('version'), q=True))
1689 v = list(re.match(b(r'.*?(\d+)\.(\d+)\.?(\d+)?(\+[0-9a-f-]+)?'),
1690 v).groups())
1691
1692 for i in range(3):
1693 try:
1694 v[i] = int(v[i])
1695 except TypeError:
1696 v[i] = 0
1697
1698 self._version = tuple(v)
1699
1700 return self._version
1701
1702 def __getitem__(self, changeid):
1703 try:
1704 return context.changectx(self, changeid)
1705 except ValueError as e:
1706 raise KeyError(*e.args)
1707
1708 def __contains__(self, changeid):
1709 """
1710 check if changeid, which can be either a local revision number or a
1711 changeset id, matches a changeset in the client.
1712 """
1713 try:
1714 context.changectx(self, changeid)
1715 return True
1716 except ValueError:
1717 return False