Skip to content

Commit

Permalink
Remove passenger store (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
maxmouchet committed Jan 30, 2020
1 parent 9ec6d6d commit 8755268
Show file tree
Hide file tree
Showing 5 changed files with 6 additions and 171 deletions.
11 changes: 1 addition & 10 deletions locomotive/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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)
63 changes: 0 additions & 63 deletions locomotive/cli/commands/passengers.py

This file was deleted.

11 changes: 2 additions & 9 deletions locomotive/cli/commands/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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"]),
Expand All @@ -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)

Expand All @@ -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(
Expand Down
10 changes: 0 additions & 10 deletions locomotive/exceptions.py
Original file line number Diff line number Diff line change
@@ -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))
82 changes: 3 additions & 79 deletions locomotive/stores.py
Original file line number Diff line number Diff line change
@@ -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:
Expand Down

0 comments on commit 8755268

Please sign in to comment.