Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

fix: centralize airline parsing; raise on empty; refresh stale docs (#151)

Punit Araniea8863a38488
diff --git a/README.md b/README.md
index ae5b509..9e33028 100644
--- a/README.md
+++ b/README.md
@@ -139,7 +139,7 @@ fli flights JFK LHR 2026-10-25
# Advanced search with filters
fli flights JFK LHR 2026-10-25 \
--time 6-20 \ # Departure time window (6 AM - 8 PM)
- --airlines BA KL \ # Airlines (British Airways, KLM)
+ --airlines BA,KL \ # Airlines (British Airways, KLM)
--class BUSINESS \ # Cabin class
--stops NON_STOP \ # Non-stop flights only
--sort DURATION # Sort by duration
@@ -197,7 +197,7 @@ fli multi \
|------------------|-----------------------|------------------------|
| `--return, -r` | Return date | `2026-10-30` |
| `--time, -t` | Departure time window | `6-20` |
-| `--airlines, -a` | Airline IATA codes | `BA KL` |
+| `--airlines, -a` | Airline IATA codes | `BA,KL` |
| `--class, -c` | Cabin class | `ECONOMY`, `BUSINESS` |
| `--stops, -s` | Maximum stops | `NON_STOP`, `ONE_STOP` |
| `--sort, -o` | Sort results by | `CHEAPEST`, `DURATION` |
@@ -211,7 +211,7 @@ fli multi \
| `--to` | End date | `2026-02-01` |
| `--duration, -d` | Trip duration in days | `3` |
| `--round, -R` | Round-trip search | (flag) |
-| `--airlines, -a` | Airline IATA codes | `BA KL` |
+| `--airlines, -a` | Airline IATA codes | `BA,KL` |
| `--class, -c` | Cabin class | `ECONOMY`, `BUSINESS` |
| `--stops, -s` | Maximum stops | `NON_STOP`, `ONE_STOP` |
| `--time` | Departure time window | `6-20` |
diff --git a/docs/guides/quickstart.md b/docs/guides/quickstart.md
index 4b67f15..1539fdb 100644
--- a/docs/guides/quickstart.md
+++ b/docs/guides/quickstart.md
@@ -37,7 +37,7 @@ fli flights JFK LHR 2026-06-01 --return 2026-06-15
```bash
fli flights JFK LHR 2026-06-01 \
--time 6-20 \ # Departure window (6 AM - 8 PM)
- --airlines BA KL \ # Airlines (British Airways, KLM)
+ --airlines BA,KL \ # Airlines (British Airways, KLM)
--class BUSINESS \ # Cabin class
--stops NON_STOP # Non-stop flights only
```
diff --git a/fli/cli/commands/dates.py b/fli/cli/commands/dates.py
index 3576cb4..9e7314d 100644
--- a/fli/cli/commands/dates.py
+++ b/fli/cli/commands/dates.py
@@ -1,6 +1,5 @@
"""Date search CLI command for finding cheapest travel dates."""
-import re
from datetime import datetime, timedelta
from typing import Annotated
@@ -219,14 +218,6 @@ def dates(
trip_type = TripType.ROUND_TRIP if is_round_trip else TripType.ONE_WAY
stops = parse_max_stops(max_stops)
seat_type = parse_cabin_class(cabin_class)
- # Normalize airlines: split each element on commas to support "BA,KL" in a single flag
- if airlines:
- airlines = [
- code.strip().upper()
- for item in airlines
- for code in re.split(r"[,\s]+", item)
- if code.strip()
- ]
parsed_airlines = parse_airlines(airlines)
selected_days = _build_selected_days(
monday=monday,
diff --git a/fli/cli/commands/flights.py b/fli/cli/commands/flights.py
index 59b11ae..311e651 100644
--- a/fli/cli/commands/flights.py
+++ b/fli/cli/commands/flights.py
@@ -1,6 +1,5 @@
"""Flight search CLI command."""
-import re
from typing import Annotated, Any
import typer
@@ -55,21 +54,13 @@ def _search_flights_core(
currency: str = "USD",
) -> None:
"""Core flight search functionality."""
- # Normalize airlines: split each element on commas/spaces to support "BA,KL" in a single flag
- if airlines:
- airlines = [
- code.strip().upper()
- for item in airlines
- for code in re.split(r"[,\s]+", item)
- if code.strip()
- ]
query: dict[str, Any] = {
"origin": origin.upper(),
"destination": destination.upper(),
"departure_date": departure_date,
"return_date": return_date,
"departure_window": None,
- "airlines": [airline.upper() for airline in airlines] if airlines else None,
+ "airlines": None,
"cabin_class": cabin_class.upper(),
"max_stops": max_stops.upper(),
"sort_by": sort_by.upper(),
@@ -91,6 +82,9 @@ def _search_flights_core(
seat_type = parse_cabin_class(cabin_class)
stops = parse_max_stops(max_stops)
parsed_airlines = parse_airlines(airlines)
+ query["airlines"] = (
+ [airline.name.lstrip("_") for airline in parsed_airlines] if parsed_airlines else None
+ )
sort = parse_sort_by(sort_by)
emissions_filter = parse_emissions(emissions)
@@ -326,12 +320,12 @@ def flights(
"""Search for flights on a specific date.
Example:
- fli flights JFK LHR 2025-10-25 --time 6-20 --airlines BA KL --stops NON_STOP
- fli flights JFK LHR 2025-10-25 --format json
- fli flights JFK LHR 2025-10-25 --exclude-basic
- fli flights JFK LAX 2025-10-25 --bags 1 --carry-on
- fli flights JFK LAX 2025-10-25 --emissions LESS
- fli flights JFK LAX 2025-10-25 --all
+ fli flights JFK LHR 2026-10-25 --time 6-20 --airlines BA,KL --stops NON_STOP
+ fli flights JFK LHR 2026-10-25 --format json
+ fli flights JFK LHR 2026-10-25 --exclude-basic
+ fli flights JFK LAX 2026-10-25 --bags 1 --carry-on
+ fli flights JFK LAX 2026-10-25 --emissions LESS
+ fli flights JFK LAX 2026-10-25 --all
"""
_search_flights_core(
diff --git a/fli/cli/commands/multi.py b/fli/cli/commands/multi.py
index 36c6fae..88c7e2a 100644
--- a/fli/cli/commands/multi.py
+++ b/fli/cli/commands/multi.py
@@ -67,7 +67,7 @@ def multi(
typer.Option(
"--airlines",
"-a",
- help="List of airline IATA codes (e.g., BA KL)",
+ help="Airline IATA codes (e.g., BA,KL or repeated --airlines BA --airlines KL)",
),
] = None,
cabin_class: Annotated[
diff --git a/fli/core/parsers.py b/fli/core/parsers.py
index 1ca7d9b..8aacbe9 100644
--- a/fli/core/parsers.py
+++ b/fli/core/parsers.py
@@ -4,11 +4,14 @@ This module provides parsing functions used by both the CLI and MCP interfaces
to convert user input into domain model objects.
"""
+import re
from enum import Enum
from typing import TypeVar
from fli.models import Airline, Airport, EmissionsFilter, MaxStops, SeatType, SortBy
+_AIRLINE_SEPARATORS = re.compile(r"[,\s]+")
+
T = TypeVar("T", bound=Enum)
@@ -63,24 +66,38 @@ def resolve_airport(code: str) -> Airport:
def parse_airlines(codes: list[str] | None) -> list[Airline] | None:
"""Parse a list of airline codes into Airline enums.
+ Each item may itself contain multiple codes separated by commas or whitespace,
+ so callers can pass either ``["BA", "KL"]`` (one code per item) or
+ ``["BA,KL"]`` / ``["BA KL"]`` (combined). This lets the CLI accept the
+ documented ``--airlines BA,KL`` and ``--airlines "BA KL"`` forms in addition
+ to the repeated-flag form Typer collects natively.
+
Args:
- codes: List of IATA airline codes (e.g., ['BA', 'KL'])
+ codes: List of IATA airline codes; entries may be combined with commas or
+ whitespace (e.g., ['BA', 'KL'] or ['BA,KL'] or ['BA KL']).
Returns:
- List of Airline enums, or None if input is empty
+ List of Airline enums, or None if ``codes`` is None or an empty list.
Raises:
- ParseError: If any code is not a valid airline
+ ParseError: If any code is not a valid airline, or if ``codes`` was
+ non-empty but contained no parsable codes (e.g., [","]).
"""
if not codes:
return None
+ expanded = [
+ token.strip().upper()
+ for item in codes
+ for token in _AIRLINE_SEPARATORS.split(item)
+ if token.strip()
+ ]
+ if not expanded:
+ raise ParseError(f"No valid airline codes found in: {codes!r}")
+
airlines = []
- for code in codes:
- code = code.strip().upper()
- if not code:
- continue
+ for code in expanded:
# Airline codes starting with a digit need an underscore prefix
# to match the Airline enum member names (e.g., "3F" -> "_3F")
enum_key = f"_{code}" if code[0].isdigit() else code
@@ -90,7 +107,7 @@ def parse_airlines(codes: list[str] | None) -> list[Airline] | None:
except AttributeError as e:
raise ParseError(f"Invalid airline code: '{code}'") from e
- return airlines if airlines else None
+ return airlines
def parse_max_stops(stops: str) -> MaxStops:
diff --git a/skills/fli/SKILL.md b/skills/fli/SKILL.md
index 13cb79d..46795b6 100644
--- a/skills/fli/SKILL.md
+++ b/skills/fli/SKILL.md
@@ -123,7 +123,7 @@ Use filters like these when the user asks for them:
```bash
fli flights JFK LHR 2026-10-25 \
--time 6-20 \
- --airlines BA KL \
+ --airlines BA,KL \
--class BUSINESS \
--stops NON_STOP \
--sort DURATION
diff --git a/tests/cli/test_dates.py b/tests/cli/test_dates.py
index 22ba94d..202ad7c 100644
--- a/tests/cli/test_dates.py
+++ b/tests/cli/test_dates.py
@@ -7,6 +7,7 @@ import pytest
from typer.testing import CliRunner
from fli.cli.main import app
+from fli.models import Airline
from fli.models.google_flights.base import TripType
from fli.search import DatePrice
@@ -72,7 +73,7 @@ def test_dates_with_days(runner, mock_search_dates, mock_console):
def test_dates_with_airlines(runner, mock_search_dates, mock_console):
- """Test dates search with airline filter."""
+ """Repeated -a flags resolve to the matching Airline enums on the filter."""
mock_search_dates.search.return_value = [
DatePrice(
date=(datetime.now() + timedelta(days=1),),
@@ -84,7 +85,25 @@ def test_dates_with_airlines(runner, mock_search_dates, mock_console):
["dates", "JFK", "LAX", "-a", "DL", "-a", "UA"],
)
assert result.exit_code == 0
- mock_search_dates.search.assert_called_once()
+ args, _ = mock_search_dates.search.call_args
+ assert args[0].airlines == [Airline.DL, Airline.UA]
+
+
+def test_dates_with_comma_separated_airlines(runner, mock_search_dates, mock_console):
+ """Single -a flag with comma-joined codes splits into multiple airlines."""
+ mock_search_dates.search.return_value = [
+ DatePrice(
+ date=(datetime.now() + timedelta(days=1),),
+ price=299.99,
+ ),
+ ]
+ result = runner.invoke(
+ app,
+ ["dates", "JFK", "LAX", "-a", "DL,UA"],
+ )
+ assert result.exit_code == 0
+ args, _ = mock_search_dates.search.call_args
+ assert args[0].airlines == [Airline.DL, Airline.UA]
def test_dates_with_cabin_class(runner, mock_search_dates, mock_console):
diff --git a/tests/cli/test_flights.py b/tests/cli/test_flights.py
index 3418a9c..662368f 100644
--- a/tests/cli/test_flights.py
+++ b/tests/cli/test_flights.py
@@ -42,7 +42,7 @@ def test_flights_with_time_filter(runner, mock_search_flights, mock_console):
def test_flights_with_airlines(runner, mock_search_flights, mock_console):
- """Test flights search with airline filter."""
+ """Repeated -a flags resolve to the matching Airline enums on the filter."""
result = runner.invoke(
app,
[
@@ -57,7 +57,46 @@ def test_flights_with_airlines(runner, mock_search_flights, mock_console):
],
)
assert result.exit_code == 0
- mock_search_flights.search.assert_called_once()
+ args, _ = mock_search_flights.search.call_args
+ assert args[0].airlines == [Airline.DL, Airline.UA]
+
+
+def test_flights_with_comma_separated_airlines(runner, mock_search_flights, mock_console):
+ """Single -a flag with comma-joined codes splits into multiple airlines."""
+ result = runner.invoke(
+ app,
+ [
+ "flights",
+ "JFK",
+ "LAX",
+ datetime.now().strftime("%Y-%m-%d"),
+ "-a",
+ "DL,UA",
+ ],
+ )
+ assert result.exit_code == 0
+ args, _ = mock_search_flights.search.call_args
+ assert args[0].airlines == [Airline.DL, Airline.UA]
+
+
+def test_flights_json_query_echoes_split_airlines(runner, mock_search_flights, mock_console):
+ """JSON query echo reflects the parsed, split airline list — not the raw input."""
+ result = runner.invoke(
+ app,
+ [
+ "flights",
+ "JFK",
+ "LAX",
+ datetime.now().strftime("%Y-%m-%d"),
+ "-a",
+ "DL,UA",
+ "--format",
+ "json",
+ ],
+ )
+ assert result.exit_code == 0
+ payload = json.loads(result.stdout)
+ assert payload["query"]["airlines"] == ["DL", "UA"]
def test_flights_with_cabin_class(runner, mock_search_flights, mock_console):
diff --git a/tests/core/test_parsers.py b/tests/core/test_parsers.py
index 87ff132..1ddb681 100644
--- a/tests/core/test_parsers.py
+++ b/tests/core/test_parsers.py
@@ -49,6 +49,78 @@ class TestParseAirlinesWithAlliances:
assert Airline.AA in result
+class TestParseAirlinesSplitting:
+ """Tests for parse_airlines accepting comma- and whitespace-separated codes per item.
+
+ Motivated by the documented `--airlines BA,KL` (single token) and
+ `--airlines "BA KL"` (quoted) CLI forms, plus the same tolerance now extended
+ to MCP callers passing combined strings.
+ """
+
+ def test_comma_separated_in_one_item(self):
+ result = parse_airlines(["BA,KL"])
+ assert result == [Airline.BA, Airline.KL]
+
+ def test_space_separated_in_one_item(self):
+ result = parse_airlines(["BA KL"])
+ assert result == [Airline.BA, Airline.KL]
+
+ def test_tab_separator(self):
+ result = parse_airlines(["BA\tKL"])
+ assert result == [Airline.BA, Airline.KL]
+
+ def test_collapses_consecutive_separators(self):
+ result = parse_airlines(["BA,,KL", "AA UA"])
+ assert result == [Airline.BA, Airline.KL, Airline.AA, Airline.UA]
+
+ def test_strips_leading_and_trailing_separators(self):
+ result = parse_airlines([",BA,", " KL "])
+ assert result == [Airline.BA, Airline.KL]
+
+ def test_mixed_forms(self):
+ result = parse_airlines(["BA,KL", "LH"])
+ assert result == [Airline.BA, Airline.KL, Airline.LH]
+
+ def test_repeated_items_still_work(self):
+ # Backwards compat: `--airlines BA --airlines KL` arrives as ["BA", "KL"].
+ result = parse_airlines(["BA", "KL"])
+ assert result == [Airline.BA, Airline.KL]
+
+ def test_lowercase_in_split_is_uppercased(self):
+ result = parse_airlines(["ba,kl"])
+ assert result == [Airline.BA, Airline.KL]
+
+ def test_numeric_prefix_in_split(self):
+ result = parse_airlines(["BA,3F"])
+ assert result == [Airline.BA, Airline._3F]
+
+ def test_invalid_code_in_split_propagates(self):
+ with pytest.raises(ParseError, match="Invalid airline code: 'XXX'"):
+ parse_airlines(["BA,XXX"])
+
+ def test_raises_when_only_commas(self):
+ with pytest.raises(ParseError, match="No valid airline codes"):
+ parse_airlines([","])
+
+ def test_raises_when_only_whitespace(self):
+ with pytest.raises(ParseError, match="No valid airline codes"):
+ parse_airlines([" "])
+
+ def test_raises_when_only_empty_string(self):
+ with pytest.raises(ParseError, match="No valid airline codes"):
+ parse_airlines([""])
+
+ def test_raises_when_only_separators_across_items(self):
+ with pytest.raises(ParseError, match="No valid airline codes"):
+ parse_airlines(["", " ", ","])
+
+ def test_none_input_still_returns_none(self):
+ assert parse_airlines(None) is None
+
+ def test_empty_list_still_returns_none(self):
+ assert parse_airlines([]) is None
+
+
class TestParseSortBy:
"""Tests for parse_sort_by with updated enum values."""