Debian Codegraph @

tests/dumbhttp.py

raw
1 #!/usr/bin/env python3
2
3
4 """
5 Small and dumb HTTP server for use in tests.
6 """
7
8 import io
9 import optparse
10 import os
11 import signal
12 import socket
13 import sys
14
15 from mercurial import (
16 encoding,
17 pycompat,
18 server,
19 util,
20 )
21
22 httpserver = util.httpserver
23 OptionParser = optparse.OptionParser
24
25 if pycompat.iswindows:
26 sys.stdout = io.TextIOWrapper(
27 sys.stdout.buffer,
28 sys.stdout.encoding,
29 sys.stdout.errors,
30 newline="\n",
31 )
32 sys.stderr = io.TextIOWrapper(
33 sys.stderr.buffer,
34 sys.stderr.encoding,
35 sys.stderr.errors,
36 newline="\n",
37 )
38
39 if os.environ.get('HGIPV6', '0') == '1':
40
41 class simplehttpserver(httpserver.httpserver):
42 address_family = socket.AF_INET6
43
44 else:
45 simplehttpserver = httpserver.httpserver
46
47
48 class _httprequesthandler(httpserver.simplehttprequesthandler):
49 def log_message(self, format, *args):
50 httpserver.simplehttprequesthandler.log_message(self, format, *args)
51 sys.stderr.flush()
52
53
54 class simplehttpservice:
55 def __init__(self, host, port):
56 self.address = (host, port)
57
58 def init(self):
59 self.httpd = simplehttpserver(self.address, _httprequesthandler)
60
61 def run(self):
62 self.httpd.serve_forever()
63
64
65 if __name__ == '__main__':
66 parser = OptionParser()
67 parser.add_option(
68 '-p',
69 '--port',
70 dest='port',
71 type='int',
72 default=8000,
73 help='TCP port to listen on',
74 metavar='PORT',
75 )
76 parser.add_option(
77 '-H',
78 '--host',
79 dest='host',
80 default='localhost',
81 help='hostname or IP to listen on',
82 metavar='HOST',
83 )
84 parser.add_option('--logfile', help='file name of access/error log')
85 parser.add_option(
86 '--pid',
87 dest='pid',
88 help='file name where the PID of the server is stored',
89 )
90 parser.add_option(
91 '-f',
92 '--foreground',
93 dest='foreground',
94 action='store_true',
95 help='do not start the HTTP server in the background',
96 )
97 parser.add_option('--daemon-postexec', action='append')
98
99 (options, args) = parser.parse_args()
100
101 signal.signal(signal.SIGTERM, lambda x, y: sys.exit(0))
102
103 if options.foreground and options.logfile:
104 parser.error(
105 "options --logfile and --foreground are mutually " "exclusive"
106 )
107 if options.foreground and options.pid:
108 parser.error("options --pid and --foreground are mutually exclusive")
109
110 opts = {
111 b'pid_file': options.pid,
112 b'daemon': not options.foreground,
113 b'daemon_postexec': pycompat.rapply(
114 encoding.strtolocal, options.daemon_postexec
115 ),
116 }
117 service = simplehttpservice(options.host, options.port)
118 runargs = [sys.executable, __file__] + sys.argv[1:]
119 runargs = [pycompat.fsencode(a) for a in runargs]
120 server.runservice(
121 opts,
122 initfn=service.init,
123 runfn=service.run,
124 logfile=options.logfile,
125 runargs=runargs,
126 )