Coverage for pattern_lens/server.py: 69%

26 statements  

« prev     ^ index     » next       coverage.py v7.6.12, created at 2025-04-06 15:09 -0600

1"""cli for starting the server to show the web ui. 

2 

3can also run with --rewrite-index to update the index.html file. 

4this is useful for working on the ui. 

5""" 

6 

7import argparse 

8import http.server 

9import os 

10import socketserver 

11import sys 

12from pathlib import Path 

13 

14from pattern_lens.indexes import write_html_index 

15 

16 

17def main(path: str | None = None, port: int = 8000) -> None: 

18 "move to the given path and start the server" 

19 if path is not None: 

20 os.chdir(path) 

21 try: 

22 with socketserver.TCPServer( 

23 ("", port), 

24 http.server.SimpleHTTPRequestHandler, 

25 ) as httpd: 

26 print(f"Serving at http://localhost:{port}") 

27 httpd.serve_forever() 

28 except KeyboardInterrupt: 

29 print("Server stopped") 

30 sys.exit(0) 

31 

32 

33if __name__ == "__main__": 

34 arg_parser: argparse.ArgumentParser = argparse.ArgumentParser() 

35 arg_parser.add_argument( 

36 "--path", 

37 type=str, 

38 required=False, 

39 help="The path to serve, defaults to the current directory", 

40 default=None, 

41 ) 

42 arg_parser.add_argument( 

43 "--port", 

44 type=int, 

45 required=False, 

46 help="The port to serve on, defaults to 8000", 

47 default=8000, 

48 ) 

49 arg_parser.add_argument( 

50 "--rewrite-index", 

51 action="store_true", 

52 help="Whether to write the latest index.html file", 

53 ) 

54 args: argparse.Namespace = arg_parser.parse_args() 

55 

56 if args.rewrite_index: 

57 write_html_index(path=Path(args.path)) 

58 

59 main(path=args.path, port=args.port)