-
Notifications
You must be signed in to change notification settings - Fork 4
feat: add station contributor commands #35
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,3 @@ | ||
| """Meteostat CLI — Access weather and climate data through the terminal.""" | ||
|
|
||
| __version__ = "0.3.0" | ||
| __version__ = "0.4.0" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| """Contributor commands for the weather stations repository.""" | ||
|
|
||
| from typing import Any | ||
|
|
||
| import typer | ||
|
|
||
| from meteo.contrib.validation import Report | ||
|
|
||
| REPO_HELP = "Path to the stations repository (overrides stations_repo)." | ||
|
|
||
|
|
||
| def echo_report(report: Report, quiet: bool = False) -> None: | ||
| """Print the validation result of a station.""" | ||
| for error in report.errors: | ||
| typer.echo(f"{typer.style('✗', fg='red')} {report.station_id} {error}") | ||
| for warning in report.warnings: | ||
| typer.echo(f"{typer.style('!', fg='yellow')} {report.station_id} {warning}") | ||
| if report.valid and not report.warnings and not quiet: | ||
| typer.echo(f"{typer.style('✓', fg='green')} {report.station_id}") | ||
|
|
||
|
|
||
| def plural(count: int, word: str) -> str: | ||
| return f"{count} {word}" if count == 1 else f"{count} {word}s" | ||
|
|
||
|
|
||
| def print_station(data: dict[str, Any]) -> None: | ||
| """Print a station record in the same way as `meteo station ID`.""" | ||
| from meteo.commands.station import print_metadata | ||
|
|
||
| location = data.get("location") or {} | ||
| names = data.get("name") or {} | ||
| print_metadata( | ||
| { | ||
| "id": data.get("id"), | ||
| "name": names.get("en"), | ||
| "country": data.get("country"), | ||
| "region": data.get("region"), | ||
| "latitude": location.get("latitude"), | ||
| "longitude": location.get("longitude"), | ||
| "elevation": location.get("elevation"), | ||
| "timezone": data.get("timezone"), | ||
| **(data.get("identifiers") or {}), | ||
| } | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,171 @@ | ||
| """Add station command for the Meteostat CLI.""" | ||
|
|
||
| import re | ||
| from typing import Any | ||
|
|
||
| import typer | ||
|
|
||
| from meteo.commands.contrib import REPO_HELP, echo_report | ||
| from meteo.contrib.duplicates import find_duplicates | ||
| from meteo.contrib.repo import ( | ||
| generate_id, | ||
| load_stations, | ||
| resolve_repo, | ||
| serialize, | ||
| station_path, | ||
| write_station, | ||
| ) | ||
| from meteo.contrib.validation import Validator | ||
|
|
||
| LOCALIZED_NAME = re.compile(r"^([a-z]{2})=(.+)$") | ||
|
|
||
|
|
||
| def parse_names(values: list[str]) -> dict[str, str]: | ||
| """Parse --name values. `LANG=NAME` sets a localized name, anything else English.""" | ||
| names = {} | ||
| for value in values: | ||
| match = LOCALIZED_NAME.match(value) | ||
| lang, name = match.groups() if match else ("en", value) | ||
| names[lang] = name.strip() | ||
| return names | ||
|
|
||
|
|
||
| def parse_identifiers(values: list[str]) -> dict[str, str]: | ||
| """Parse KEY=VALUE identifiers.""" | ||
| identifiers = {} | ||
| for value in values: | ||
| key, sep, ident = value.partition("=") | ||
| if not sep or not key.strip() or not ident.strip(): | ||
| raise typer.BadParameter( | ||
| f"Identifiers must be KEY=VALUE, got '{value}'.", param_hint="--id" | ||
| ) | ||
| identifiers[key.strip().lower()] = ident.strip() | ||
| return identifiers | ||
|
|
||
|
|
||
| def add_cmd( | ||
| name: list[str] | None = typer.Option( | ||
| None, | ||
| "--name", | ||
| "-n", | ||
| help="Station name. Use LANG=NAME for a localized name (repeatable).", | ||
| ), | ||
| country: str | None = typer.Option( | ||
| None, "--country", "-c", help="ISO 3166-1 alpha-2 country code." | ||
| ), | ||
| region: str | None = typer.Option( | ||
| None, "--region", help="ISO 3166-2 state or region code." | ||
| ), | ||
| lat: float | None = typer.Option(None, "--lat", help="Latitude."), | ||
| lon: float | None = typer.Option(None, "--lon", help="Longitude."), | ||
| elevation: int | None = typer.Option( | ||
| None, "--elevation", "-e", help="Elevation in meters." | ||
| ), | ||
| timezone: str | None = typer.Option( | ||
| None, "--timezone", "-t", help="IANA time zone (e.g. Europe/Berlin)." | ||
| ), | ||
| identifier: list[str] | None = typer.Option( | ||
| None, | ||
| "--id", | ||
| "-i", | ||
| help="Station identifier as KEY=VALUE, e.g. wmo=10637 (repeatable).", | ||
| ), | ||
| yes: bool = typer.Option( | ||
| False, | ||
| "--yes", | ||
| "-y", | ||
| help="Don't prompt. Fail on missing properties and skip duplicate confirmation.", | ||
| ), | ||
| dry_run: bool = typer.Option( | ||
| False, "--dry-run", help="Print the resulting JSON without writing any file." | ||
| ), | ||
| repo: str | None = typer.Option(None, "--repo", help=REPO_HELP), | ||
| ) -> None: | ||
| """Add a new weather station.""" | ||
| repo_path = resolve_repo(repo) | ||
|
|
||
| names = parse_names(name or []) | ||
| identifiers = parse_identifiers(identifier or []) | ||
|
|
||
| if yes: | ||
| missing = [ | ||
| option | ||
| for option, value in ( | ||
| ("--name", names.get("en")), | ||
| ("--country", country), | ||
| ("--lat", lat), | ||
| ("--lon", lon), | ||
| ("--elevation", elevation), | ||
| ("--timezone", timezone), | ||
| ) | ||
| if value is None | ||
| ] | ||
| if missing: | ||
| typer.echo(f"Error: Missing option(s): {', '.join(missing)}", err=True) | ||
| raise typer.Exit(2) | ||
| else: | ||
| if "en" not in names: | ||
| names["en"] = typer.prompt("Name (English)").strip() | ||
| if country is None: | ||
| country = typer.prompt("Country (ISO 3166-1 alpha-2)") | ||
| if region is None: | ||
| region = typer.prompt( | ||
| "Region (ISO 3166-2, optional)", default="", show_default=False | ||
| ) | ||
| if lat is None: | ||
| lat = typer.prompt("Latitude", type=float) | ||
| if lon is None: | ||
| lon = typer.prompt("Longitude", type=float) | ||
| if elevation is None: | ||
| elevation = typer.prompt("Elevation (m)", type=int) | ||
| if timezone is None: | ||
| timezone = typer.prompt("Time zone (e.g. Europe/Berlin)") | ||
| if not identifier: | ||
| value = typer.prompt( | ||
| "Identifiers (KEY=VALUE, comma-separated, optional)", | ||
| default="", | ||
| show_default=False, | ||
| ) | ||
| identifiers = parse_identifiers( | ||
| [item for item in value.split(",") if item.strip()] | ||
| ) | ||
|
|
||
| station_id = generate_id(repo_path) | ||
| data: dict[str, Any] = { | ||
| "id": station_id, | ||
| "name": dict(sorted(names.items())), | ||
| "country": (country or "").strip().upper(), | ||
| "region": region.strip().upper() if region and region.strip() else None, | ||
| "identifiers": identifiers, | ||
| "location": {"latitude": lat, "longitude": lon, "elevation": elevation}, | ||
| "timezone": (timezone or "").strip(), | ||
| } | ||
|
|
||
| stations = load_stations(repo_path) | ||
| report = Validator(stations).validate(station_id, data) | ||
| if not report.valid: | ||
| echo_report(report) | ||
| raise typer.Exit(1) | ||
|
|
||
| stations[station_id] = data | ||
| duplicates = find_duplicates(stations, ids={station_id}) | ||
| if duplicates: | ||
| typer.echo("Potential duplicates:", err=True) | ||
| for dup in duplicates: | ||
| other = dup.station_b if dup.station_a == station_id else dup.station_a | ||
| other_name = stations[other].get("name", {}).get("en", "") | ||
| dist = f"{dup.distance} m, " if dup.distance is not None else "" | ||
| typer.echo( | ||
| f" {other} {other_name} ({dist}{', '.join(dup.reasons)})", | ||
| err=True, | ||
| ) | ||
| if not yes and not dry_run: | ||
| typer.confirm("Create station anyway?", abort=True, err=True) | ||
|
|
||
| if dry_run: | ||
| typer.echo(serialize(data)) | ||
| return | ||
|
|
||
| path = station_path(repo_path, station_id) | ||
| write_station(path, data) | ||
| typer.echo(f"Created station {station_id} ({path.relative_to(repo_path)})") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| """Build station database command for the Meteostat CLI.""" | ||
|
|
||
| from pathlib import Path | ||
|
|
||
| import typer | ||
|
|
||
| from meteo.commands.contrib import REPO_HELP, echo_report, plural | ||
| from meteo.contrib.database import build_database | ||
| from meteo.contrib.repo import load_stations, resolve_repo, station_files | ||
| from meteo.contrib.validation import Validator | ||
|
|
||
|
|
||
| def build_cmd( | ||
| output: str | None = typer.Option( | ||
| None, | ||
| "--output", | ||
| "-o", | ||
| help="Output file path (default: stations.db in the repository root).", | ||
| ), | ||
| skip_validation: bool = typer.Option( | ||
| False, "--skip-validation", help="Don't validate stations before building." | ||
| ), | ||
| repo: str | None = typer.Option(None, "--repo", help=REPO_HELP), | ||
| ) -> None: | ||
| """Build a SQLite database from the station files.""" | ||
| repo_path = resolve_repo(repo) | ||
| output_path = Path(output).expanduser() if output else repo_path / "stations.db" | ||
| stations = load_stations(repo_path) | ||
|
|
||
| skipped = 0 | ||
| if not skip_validation: | ||
| validator = Validator(stations) | ||
| for path in station_files(repo_path): | ||
| report = validator.validate_file(path) | ||
| if not report.valid: | ||
| echo_report(report, quiet=True) | ||
| stations.pop(path.stem, None) | ||
| skipped += 1 | ||
|
|
||
| count, failed = build_database(stations, output_path) | ||
| for station_id, reason in failed: | ||
| typer.echo(f"{typer.style('✗', fg='red')} {station_id} {reason}") | ||
|
|
||
| skipped += len(failed) | ||
| summary = f"Built {output_path} with {plural(count, 'station')}" | ||
| if skipped: | ||
| summary += f" ({skipped} skipped)" | ||
| typer.echo(summary) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| """Delete station command for the Meteostat CLI.""" | ||
|
|
||
| import typer | ||
|
|
||
| from meteo.commands.contrib import REPO_HELP, print_station | ||
| from meteo.contrib.repo import read_station, require_station, resolve_repo | ||
|
|
||
|
|
||
| def delete_cmd( | ||
| station_id: str = typer.Argument(..., help="Meteostat station ID."), | ||
| yes: bool = typer.Option( | ||
| False, "--yes", "-y", help="Skip the confirmation prompt." | ||
| ), | ||
| repo: str | None = typer.Option(None, "--repo", help=REPO_HELP), | ||
| ) -> None: | ||
| """Remove a weather station.""" | ||
| repo_path = resolve_repo(repo) | ||
| path = require_station(repo_path, station_id) | ||
|
|
||
| if not yes: | ||
| try: | ||
| print_station(read_station(path)) | ||
| except ValueError: | ||
| typer.echo(f"Warning: {path.name} contains invalid JSON.", err=True) | ||
| typer.confirm(f"Delete station {path.stem}?", abort=True) | ||
|
|
||
| path.unlink() | ||
| typer.echo(f"Deleted station {path.stem} ({path.relative_to(repo_path)})") |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.