Debian Codegraph @

ansible_collections/community/general/tests/integration/targets/flatpak/files/serve.py

raw
1 #!/usr/bin/env python
2 # Copyright (c) Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 import os
9 import posixpath
10 import sys
11 from http.server import HTTPServer, SimpleHTTPRequestHandler
12 from urllib.parse import unquote
13
14 # Argument parsing
15 if len(sys.argv) != 4:
16 print(f"Syntax: {sys.argv[0]} <bind> <port> <path>")
17 sys.exit(-1)
18
19 HOST, PORT_str, PATH = sys.argv[1:4]
20 PORT = int(PORT_str)
21
22
23 # The HTTP request handler
24 class Handler(SimpleHTTPRequestHandler):
25 def translate_path(self, path):
26 # Modified from Python 3.6's version of SimpleHTTPRequestHandler
27 # to support using another base directory than CWD.
28
29 # abandon query parameters
30 path = path.split("?", 1)[0]
31 path = path.split("#", 1)[0]
32 # Don't forget explicit trailing slash when normalizing. Issue17324
33 trailing_slash = path.rstrip().endswith("/")
34 try:
35 path = unquote(path, errors="surrogatepass")
36 except (UnicodeDecodeError, TypeError):
37 path = unquote(path)
38 path = posixpath.normpath(path)
39 words = path.split("/")
40 words = filter(None, words)
41 path = PATH
42 for word in words:
43 if os.path.dirname(word) or word in (os.curdir, os.pardir):
44 # Ignore components that are not a simple file/directory name
45 continue
46 path = os.path.join(path, word)
47 if trailing_slash:
48 path += "/"
49 return path
50
51
52 # Run simple HTTP server
53 httpd = HTTPServer((HOST, PORT), Handler)
54
55 try:
56 httpd.serve_forever()
57 except KeyboardInterrupt:
58 pass
59
60 httpd.server_close()