From e45cd30c2132aa8f6564cde4f4edac1e6c3f55d2 Mon Sep 17 00:00:00 2001 From: salt-die <53280662+salt-die@users.noreply.github.com> Date: Tue, 12 Dec 2023 08:16:51 -0600 Subject: [PATCH] Use argparse for command line. --- aoc_lube/__init__.py | 19 +++++++++---------- aoc_lube/__main__.py | 27 +++++++++++++-------------- 2 files changed, 22 insertions(+), 24 deletions(-) diff --git a/aoc_lube/__init__.py b/aoc_lube/__init__.py index 14cc8ea..5b089df 100644 --- a/aoc_lube/__init__.py +++ b/aoc_lube/__init__.py @@ -4,7 +4,7 @@ import subprocess import time import webbrowser -from datetime import datetime, timedelta, timezone +from datetime import date, datetime, timedelta, timezone from pathlib import Path from typing import Callable, Literal @@ -62,24 +62,23 @@ ) -def setup_dir(year: int | None = None, template: str | Path | None = None) -> None: +def setup_dir(year: int | None = None, template: Path | None = None) -> None: r"""Run once to setup directory with templates for daily solutions. - A file or text can be provided as a template. The template must be a format - string with `year` and `day` keyword arguments, e.g.:: - - "import aoc_lube\ntodays_input = aoc_lube.fetch({year}, {day})" - - If no template is provided, the default one is used instead. + A file can be provided as a template. The file's text should be able to be formatted + with `year` and `day` keyword arguments. See `code_template.txt` (the default + template) as an example. """ + if year is None: + year = date.today().year + if template is None: template = TEMPLATE_FILE.read_text() - elif isinstance(template, Path): + else: template = template.read_text() for day in range(1, 26): file = Path(f"day_{day:02}.py") - if not file.exists(): file.write_text(template.format(year=year, day=day)) diff --git a/aoc_lube/__main__.py b/aoc_lube/__main__.py index ae74240..bb4953c 100644 --- a/aoc_lube/__main__.py +++ b/aoc_lube/__main__.py @@ -1,17 +1,16 @@ -"""Setup directory from command line with `python -m aoc_lube [YYYY]`.""" -import datetime -import sys +"""Setup directory from command line with +`python -m aoc_lube [-y YEAR] [-t TEMPLATE]`. +""" +import argparse +from pathlib import Path from . import setup_dir -try: - _, year, *rest = sys.argv -except ValueError: - setup_dir(datetime.date.today().year) -else: - if not year.isdigit(): - print(f"What is year {year}?") - elif rest: - print(f"Extra argument(s) not recognized: {rest}") - else: - setup_dir(int(year)) +parser = argparse.ArgumentParser( + prog="python -m aoc_lube", description="Setup a directory for Advent of Code." +) +parser.add_argument("-y", "--year", help="Advent of Code year.", default=None) +parser.add_argument("-t", "--template", help="A code template file.", default=None) +args = parser.parse_args() + +setup_dir(args.year, args.template if args.template is None else Path(args.template))