1#!/usr/bin/env python3
2#
3# Dumps output generated by Mercurial's command server in a formatted style to a
4# given file or stderr if '-' is specified. Output is also written in its raw
5# format to stdout.
6#
7# $ ./hg serve --cmds pipe | ./contrib/debugcmdserver.py -
8# o, 52   -> 'capabilities: getencoding runcommand\nencoding: UTF-8'
9
10from __future__ import absolute_import, print_function
11import struct
12import sys
13
14if len(sys.argv) != 2:
15    print('usage: debugcmdserver.py FILE')
16    sys.exit(1)
17
18outputfmt = '>cI'
19outputfmtsize = struct.calcsize(outputfmt)
20
21if sys.argv[1] == '-':
22    log = sys.stderr
23else:
24    log = open(sys.argv[1], 'a')
25
26
27def read(size):
28    data = sys.stdin.read(size)
29    if not data:
30        raise EOFError
31    sys.stdout.write(data)
32    sys.stdout.flush()
33    return data
34
35
36try:
37    while True:
38        header = read(outputfmtsize)
39        channel, length = struct.unpack(outputfmt, header)
40        log.write('%s, %-4d' % (channel, length))
41        if channel in 'IL':
42            log.write(' -> waiting for input\n')
43        else:
44            data = read(length)
45            log.write(' -> %r\n' % data)
46        log.flush()
47except EOFError:
48    pass
49finally:
50    if log != sys.stderr:
51        log.close()
52