Skip to content

Instantly share code, notes, and snippets.

@osharaki
Last active May 3, 2021 17:18
Show Gist options
  • Save osharaki/763b4c1b303b7d762c9fe6aff5bb56e7 to your computer and use it in GitHub Desktop.
Save osharaki/763b4c1b303b7d762c9fe6aff5bb56e7 to your computer and use it in GitHub Desktop.
Unogs API miner: command-line interface
"""
Functions to set up the command line interface.
Raises:
argparse.ArgumentTypeError: Raised if request buffer is out of range
argparse.ArgumentTypeError: Raised if time is neither "now" nor HH:mm
argparse.ArgumentTypeError: Raised if time is out of correct range
argparse.ArgumentTypeError: Raised if offset is negative or not multiple
of 100
Returns:
argparse.Namespace: Populated argument namespace
"""
import argparse
import re
# Allows for more control over the error message in the case of invalid arguments
def buffer_type(value, min=0, max=100):
value = int(value)
if min <= value <= max:
return value
else:
raise argparse.ArgumentTypeError(
f"Buffer must be in the inclusive range {min} to {max}"
)
def time_type(value):
match = re.match("^[0-9]{2}:[0-9]{2}$|^now$", value)
if match is None:
raise argparse.ArgumentTypeError(f"Execution time must be either now or HH:mm")
if match[0] != "now":
# Check for correct time values
hrs, mins = match[0].split(":")
if not (0 <= int(hrs) < 24 and 0 <= int(mins) < 60):
raise argparse.ArgumentTypeError(
f"Time must follow HH:mm format. Hours and minutes must be in the range [0-24) and [0-60), respectively"
)
return match[0]
def offset_type(value):
value = int(value)
if value >= 0 and value % 100 == 0:
return value
raise argparse.ArgumentTypeError("Offset must be non-negative multiple of 100")
def init_cli(default_buffer, default_time):
parser = argparse.ArgumentParser()
parser.add_argument(
"-b",
dest="buffer",
type=buffer_type,
default=default_buffer,
metavar="[0-100]",
help=f"The number of requests [{0}-{100}] from the daily quota to leave remaining (i.e. unconsumed). Defaults to {default_buffer}",
)
parser.add_argument(
"-t",
dest="exec_time",
type=time_type,
default=default_time,
metavar="now|HH:mm",
help="When to start making API requests. Accepts either now (for immediate execution) or HH:mm (i.e. hours followed by minutes in the 24-hour time format). Defaults to 21:35 machine time.",
)
parser.add_argument(
"-o",
dest="offset",
type=offset_type,
default=0,
metavar="Non-negative multiple of 100, e.g. 0, 100, 200, etc.",
help="Where to start retrieving results. For example, an offset of 200 will yield results starting at the show with index 200 (i.e. the third 100 results). Defaults to 0.",
)
return parser.parse_args()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment