Debian Codegraph @

tests/printenv.py

raw
1 #!/usr/bin/env python3
2 #
3 # simple script to be used in hooks
4 #
5 # put something like this in the repo .hg/hgrc:
6 #
7 # [hooks]
8 # changegroup = python "$TESTDIR/printenv.py" <hookname> [exit] [output]
9 #
10 # - <hookname> is a mandatory argument (e.g. "changegroup")
11 # - [exit] is the exit code of the hook (default: 0)
12 # - [output] is the name of the output file (default: use sys.stdout)
13 # the file will be opened in append mode.
14 #
15 import argparse
16 import os
17 import sys
18
19 try:
20 import msvcrt
21
22 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
23 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
24 msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)
25 except ImportError:
26 pass
27
28 parser = argparse.ArgumentParser()
29 parser.add_argument("name", help="the hook name, used for display")
30 parser.add_argument(
31 "exitcode",
32 nargs="?",
33 default=0,
34 type=int,
35 help="the exit code for the hook",
36 )
37 parser.add_argument(
38 "out", nargs="?", default=None, help="where to write the output"
39 )
40 parser.add_argument(
41 "--line",
42 action="store_true",
43 help="print environment variables one per line instead of on a single line",
44 )
45 args = parser.parse_args()
46
47 if args.out is None:
48 out = sys.stdout
49 out = getattr(out, "buffer", out)
50 else:
51 out = open(args.out, "ab")
52
53 # variables with empty values may not exist on all platforms, filter
54 # them now for portability sake.
55 env = [(k, v) for k, v in os.environ.items() if k.startswith("HG_") and v]
56 env.sort()
57
58 out.write(b"%s hook: " % args.name.encode('ascii'))
59 if os.name == 'nt':
60 filter = lambda x: x.replace('\\', '/')
61 else:
62 filter = lambda x: x
63
64 vars = [
65 b"%s=%s" % (k.encode('ascii'), filter(v).encode('ascii')) for k, v in env
66 ]
67
68 # Print variables on out
69 if not args.line:
70 out.write(b" ".join(vars))
71 else:
72 for var in vars:
73 out.write(var)
74 out.write(b"\n")
75
76 out.write(b"\n")
77 out.close()
78
79 sys.exit(args.exitcode)