From 8755268dd6fa477934050568abbd06a516fde1e8 Mon Sep 17 00:00:00 2001 From: Maxime Mouchet Date: Thu, 30 Jan 2020 13:32:45 +0100 Subject: [PATCH] Remove passenger store (#9) --- locomotive/cli/__init__.py | 11 +--- locomotive/cli/commands/passengers.py | 63 -------------------- locomotive/cli/commands/search.py | 11 +--- locomotive/exceptions.py | 10 ---- locomotive/stores.py | 82 +-------------------------- 5 files changed, 6 insertions(+), 171 deletions(-) delete mode 100644 locomotive/cli/commands/passengers.py diff --git a/locomotive/cli/__init__.py b/locomotive/cli/__init__.py index 7d17e10..b1cd554 100644 --- a/locomotive/cli/__init__.py +++ b/locomotive/cli/__init__.py @@ -7,19 +7,12 @@ import click -from ..stores import Passengers, Stations -from .commands.passengers import passengers +from ..stores import Stations from .commands.search import search @click.group() @click.option("--debug", is_flag=True) -@click.option( - "--passengers-file", - metavar="PATH", - default=Passengers.default_path(), - show_default=True, -) @click.option( "--stations-file", metavar="PATH", @@ -39,9 +32,7 @@ def cli(ctx: click.Context, **args: Any) -> None: logging.basicConfig(level=logging.DEBUG) ctx.ensure_object(dict) - ctx.obj["passengers"] = Passengers(path=args["passengers_file"]) ctx.obj["stations"] = Stations(path=args["stations_file"]) -cli.add_command(passengers) cli.add_command(search) diff --git a/locomotive/cli/commands/passengers.py b/locomotive/cli/commands/passengers.py deleted file mode 100644 index dff3808..0000000 --- a/locomotive/cli/commands/passengers.py +++ /dev/null @@ -1,63 +0,0 @@ -""" -CLI command for managing passenger profiles. -""" - -import datetime as dt -from typing import Optional - -import click -import dateparser as dp -from attr import NOTHING - -from ...models.passenger import Passenger - - -@click.group() -def passengers() -> None: - """ - Manage passenger profiles. - """ - - -@passengers.command() -@click.pass_context -def add(ctx: click.Context) -> None: - """ - Add a passenger profile. - """ - passengers_ = ctx.obj["passengers"] - attrs = {} - # TODO: Move this generic logic outside - for attr in Passenger.__attrs_attrs__: - text = attr.name.replace("_", " ").capitalize() - default = None - value_proc = None - if attr.default != NOTHING: - default = attr.default - if attr.type is dt.date: - value_proc = __parse_if_present - attrs[attr.name] = click.prompt(text, default=default, value_proc=value_proc) - passenger = Passenger(**attrs) - passengers_.add(passenger) - passengers_.save() - click.echo("Passenger saved to {}".format(passengers_.path)) - - -@passengers.command() -@click.pass_context -def show(ctx: click.Context) -> None: - """ - Show passengers profiles. - """ - passengers_ = ctx.obj["passengers"] - for passenger in passengers_: - click.echo(passenger) - - -def __parse_if_present(date_string: Optional[str]) -> Optional[dt.date]: - if date_string: - datetime = dp.parse(date_string) - if datetime: - date: dt.date = datetime.date() - return date - return None diff --git a/locomotive/cli/commands/search.py b/locomotive/cli/commands/search.py index 2fd32e9..30801bb 100644 --- a/locomotive/cli/commands/search.py +++ b/locomotive/cli/commands/search.py @@ -8,6 +8,7 @@ from ...api.abstract import TravelRequest from ...api.oui_v3 import Client +from ...models import Passenger from ..formatters import Formatter, JSONFormatter, PrettyFormatter # We use click.echo because: @@ -34,9 +35,6 @@ default="second", help="Travel class.", ) -@click.option( - "--passenger", metavar="NAME", help="Passenger profile (see `sncf-cli passengers`)." -) @click.option( "--format", type=click.Choice(["pretty", "json"]), @@ -57,7 +55,6 @@ def search(ctx: click.Context, **args: str) -> None: sncf-cli search Brest Paris sncf-cli search Brest Paris --class second --date 2019-06-01 """ - passengers = ctx.obj["passengers"] stations = ctx.obj["stations"] client = Client(stations) @@ -75,11 +72,7 @@ def search(ctx: click.Context, **args: str) -> None: departure_station = stations.find_or_raise(args["origin"]) arrival_station = stations.find_or_raise(args["destination"]) - - if args["passenger"]: - passenger = passengers.find_or_raise(args["passenger"]) - else: - passenger = passengers.default() + passenger = Passenger.dummy() click.echo( "{} → {} ({:.0f}km) on {}".format( diff --git a/locomotive/exceptions.py b/locomotive/exceptions.py index f0ff634..8da48cd 100644 --- a/locomotive/exceptions.py +++ b/locomotive/exceptions.py @@ -1,16 +1,6 @@ import click -class PassengerAlreadyExistsException(click.ClickException): - def __init__(self, passenger: str) -> None: - super().__init__("Passenger {} already exists".format(passenger)) - - -class PassengerNotFoundException(click.ClickException): - def __init__(self, passenger: str) -> None: - super().__init__("Passenger {} not found".format(passenger)) - - class StationNotFoundException(click.ClickException): def __init__(self, station: str) -> None: super().__init__("Train station for {} not found".format(station)) diff --git a/locomotive/stores.py b/locomotive/stores.py index 8d51d8a..8874d0e 100644 --- a/locomotive/stores.py +++ b/locomotive/stores.py @@ -1,89 +1,13 @@ import contextlib -import datetime as dt import difflib -import json import sqlite3 from pathlib import Path -from typing import Any, Iterator, List, Optional, Union +from typing import Optional import attr -from .exceptions import ( - PassengerAlreadyExistsException, - PassengerNotFoundException, - StationNotFoundException, -) -from .models import Passenger, Station - - -class Passengers: - """ - Passengers store. - """ - - path: Path - passengers: List[Passenger] - - def __init__(self, path: Optional[Path] = None) -> None: - if path is None: - path = self.default_path() - - self.path = Path(path).expanduser().absolute() - - if self.path.exists(): - self.passengers = self.__passengers_from_json(self.path) - else: - self.passengers = [Passenger.dummy()] - - def __iter__(self) -> Iterator[Passenger]: - return self.passengers.__iter__() - - @classmethod - def default_path(cls) -> Path: - return Path.home().joinpath(".locomotive", "passengers.json") - - @classmethod - def __passengers_from_json(cls, path: Path) -> List[Passenger]: - passengers = [] - for obj in json.load(open(path)): - obj["birthday"] = dt.datetime.strptime(obj["birthday"], "%Y-%m-%d").date() - passengers.append(Passenger(**obj)) - return passengers - - @classmethod - def __serialize(cls, obj: Any) -> Union[dict, str]: - if hasattr(obj, "__attrs_attrs__"): - return attr.asdict(obj) - elif isinstance(obj, dt.datetime) or isinstance(obj, dt.date): - return obj.isoformat() - raise TypeError - - def add(self, passenger: Passenger) -> None: - if self.find(passenger.name): - raise PassengerAlreadyExistsException(passenger.name) - self.passengers.append(passenger) - - def default(self) -> Passenger: - return Passenger.dummy() - - def find(self, query: str) -> Optional[Passenger]: - # TODO: Optimize - for passenger in self.passengers: - if str(passenger.name).lower() == query.lower(): - return passenger - return None - - def find_or_raise(self, query: str) -> Passenger: - passenger = self.find(query) - if passenger: - return passenger - raise PassengerNotFoundException(query) - - def save(self) -> Path: - self.path.parent.mkdir(parents=True, exist_ok=True) - obj = list(map(attr.asdict, self.passengers)) - json.dump(obj, open(self.path, "w"), default=self.__serialize, indent=4) - return self.path +from .exceptions import StationNotFoundException +from .models import Station class Stations: