pferd/PFERD/__main__.py

93 lines
2.5 KiB
Python
Raw Normal View History

2021-05-13 23:52:46 +02:00
import argparse
import asyncio
2021-05-15 21:33:51 +02:00
import configparser
2021-05-13 23:52:46 +02:00
from pathlib import Path
from .cli import PARSER, load_default_section
2021-05-13 23:52:46 +02:00
from .config import Config, ConfigDumpException, ConfigLoadException
from .logging import log
2021-05-13 23:52:46 +02:00
from .pferd import Pferd
2021-05-19 17:32:23 +02:00
from .version import NAME, VERSION
2021-05-13 23:52:46 +02:00
2021-05-15 21:33:51 +02:00
def load_parser(
args: argparse.Namespace,
) -> configparser.ConfigParser:
2021-05-19 18:10:17 +02:00
log.explain_topic("Loading config")
2021-05-15 21:33:51 +02:00
parser = configparser.ConfigParser()
if args.command is None:
2021-05-19 18:10:17 +02:00
log.explain("No CLI command specified, loading config from file")
2021-05-15 21:33:51 +02:00
Config.load_parser(parser, path=args.config)
2021-05-19 18:10:17 +02:00
else:
log.explain(f"CLI command specified, creating config for {args.command!r}")
if args.command:
args.command(args, parser)
2021-05-15 21:33:51 +02:00
load_default_section(args, parser)
2021-05-15 21:33:51 +02:00
prune_crawlers(args, parser)
return parser
def prune_crawlers(
args: argparse.Namespace,
parser: configparser.ConfigParser,
) -> None:
if not args.crawler:
return
for section in parser.sections():
if section.startswith("crawl:"):
# TODO Use removeprefix() when switching to 3.9
name = section[len("crawl:"):]
if name not in args.crawler:
parser.remove_section(section)
# TODO Check if crawlers actually exist
2021-05-13 23:52:46 +02:00
def main() -> None:
2021-05-15 21:33:51 +02:00
args = PARSER.parse_args()
2021-05-13 23:52:46 +02:00
# Configure log levels set by command line arguments
if args.explain is not None:
log.output_explain = args.explain
2021-05-19 18:10:17 +02:00
if args.dump_config:
log.output_explain = False
2021-05-19 17:32:23 +02:00
if args.version:
print(f"{NAME} {VERSION}")
exit()
2021-05-13 23:52:46 +02:00
try:
2021-05-15 21:33:51 +02:00
config = Config(load_parser(args))
2021-05-19 18:10:17 +02:00
except ConfigLoadException as e:
log.error(f"Failed to load config file at path {str(e.path)!r}")
log.error_contd(f"Reason: {e.reason}")
2021-05-13 23:52:46 +02:00
exit(1)
# Configure log levels set in the config file
# TODO Catch config section exceptions
if args.explain is None:
log.output_explain = config.default_section.explain()
2021-05-15 21:33:51 +02:00
if args.dump_config is not None:
2021-05-13 23:52:46 +02:00
try:
2021-05-15 21:33:51 +02:00
if args.dump_config is True:
config.dump()
elif args.dump_config == "-":
config.dump_to_stdout()
else:
config.dump(Path(args.dump_config))
2021-05-13 23:52:46 +02:00
except ConfigDumpException:
exit(1)
exit()
pferd = Pferd(config)
2021-05-22 14:45:32 +02:00
try:
asyncio.run(pferd.run())
except KeyboardInterrupt:
# TODO Clean up tmp files
pass