forked from asottile/reorder-python-imports
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreorder-python-server
executable file
·53 lines (45 loc) · 1.67 KB
/
reorder-python-server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/env python
import os
import time
from http.server import BaseHTTPRequestHandler
from http.server import HTTPServer
from pathlib import Path
from reorder_python_imports import fix_file_contents
HOST_NAME = "localhost"
PORT_NUMBER = 31338
def contains_git(p: Path) -> bool:
return bool(list(x for x in p.iterdir() if x.name == ".git"))
class MyHandler(BaseHTTPRequestHandler):
def do_POST(self):
self.send_response(200)
self.end_headers()
project_root = Path(self.path)
while not contains_git(project_root) and not project_root.parent == project_root:
project_root = project_root.parent
os.chdir(str(project_root))
content_raw = self.rfile.read(int(self.headers["content-length"]))
content = content_raw.decode()
try:
new_contents = fix_file_contents(
content,
imports_to_add=[],
imports_to_remove=[],
imports_to_replace=[],
separate_relative=False,
separate_from_import=False,
application_directories=[str(project_root)],
)
self.wfile.write(new_contents.encode())
except:
print("OH NO: " + content_raw.decode())
self.wfile.write(content_raw)
if __name__ == "__main__":
server_class = HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
print(time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER))
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print(time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER))