From f9623cd7e01bfc0f5c27fdd612bf891dee6cbc60 Mon Sep 17 00:00:00 2001 From: Thanvish Date: Tue, 10 Nov 2026 09:42:05 +0530 Subject: [PATCH] feat(cli): add --json support to pyensembl list (#512) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `pyensembl list --json` now prints the installed-genome inventory as a JSON array instead of raising `--json requires inspect, available, or verify`. Closes #512. Changes: - Extract `_installed_genome_rows()` from `format_installed_genomes()`. The helper returns `(rows, root)` where every row is a plain dict with keys `species`, `assembly`, `release`, `annotation`, `reference_dna` and `cache_directory` (absolute path). Absent fields use `None` so the caller can serialise without further conversion. - Add `format_installed_genomes_json()` which calls `_installed_genome_rows` and returns `json.dumps(rows, indent=2)`. An empty cache produces `[]` (consistent with the other `--json` commands) rather than the prose "No genomes installed in …" message. - Update `format_installed_genomes()` to delegate to the new helper; the table output is unchanged. - Extend `validate_arguments` to accept `"list"` as a valid `--json` target and update the error message to include `list`. - Wire up the `--json` / `list` branch in `shell.run`. - Update the `--json` help text and `docs/reference/cli.md` to document the new flag combination; add `pyensembl list --json` to the examples. - Update existing tests that asserted `list --json` was an argument error (now valid): `test_cli_actions.py`, `test_cli_errors.py`, `test_data_management.py`. - Add two new tests in `test_cli_output.py`: `test_list_json_emits_valid_json_array` verifies the shape, keys and values of the array for a populated cache; `test_list_json_empty_cache_emits_empty_array` verifies the `[]` output for an empty cache. Co-Authored-By: Claude Sonnet 5 --- docs/reference/cli.md | 3 +- pyensembl/shell.py | 87 +++++++++++++++++++++++++---------- tests/test_cli_actions.py | 2 +- tests/test_cli_errors.py | 4 +- tests/test_cli_output.py | 34 ++++++++++++++ tests/test_data_management.py | 4 +- 6 files changed, 104 insertions(+), 30 deletions(-) diff --git a/docs/reference/cli.md b/docs/reference/cli.md index bf4b529..0b47cc8 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -25,7 +25,7 @@ options: --version show program's version number and exit -v, --verbose Show detailed progress, including download and database steps - --json With inspect, available, or verify, print JSON + --json With list, inspect, available, or verify, print JSON --overwrite Force download and indexing even if files already exist locally --reference-name REFERENCE_NAME @@ -123,6 +123,7 @@ examples: pyensembl install --reference-name GRCh38 --annotation-name my_genes \ --gtf URL_OR_PATH --transcript-fasta URL_OR_PATH a custom genome pyensembl list + pyensembl list --json pyensembl inspect --release 93 --json pyensembl delete-all-files --release 75 pyensembl prune --dry-run diff --git a/pyensembl/shell.py b/pyensembl/shell.py index 1c6f69e..34a2bbd 100755 --- a/pyensembl/shell.py +++ b/pyensembl/shell.py @@ -126,7 +126,7 @@ def configure_logging(verbose=False): parser.add_argument( "--json", action="store_true", - help="With inspect, available, or verify, print JSON", + help="With list, inspect, available, or verify, print JSON", ) parser.add_argument( @@ -592,8 +592,15 @@ def collect_all_installed_ensembl_releases(): ) -def format_installed_genomes(check_genome_fasta=False, use_color=None): - """A table of genomes in the local cache, or a note that there are none.""" +def _installed_genome_rows(check_genome_fasta=False): + """Return installed genomes as a list of dicts with absolute paths. + + Each dict has the keys: ``species``, ``assembly``, ``release``, + ``annotation``, ``reference_dna``, and ``cache_directory``. Values are + plain strings (or ``None`` when a field is absent) so the caller can + render them as a table or serialise them as JSON without further + conversion. + """ from pathlib import Path from .download_cache import cache_root @@ -609,15 +616,15 @@ def format_installed_genomes(check_genome_fasta=False, use_color=None): if not _has_data(annotation, dna): continue # Possibly a custom genome with the same name; listed below. ensembl_directories.add(os.path.normpath(directory)) - rows.append(( - _species_display_name(genome.species), - genome.reference_name, - str(genome.release), - annotation if annotation not in (None, "missing") else "-", - dna or "-", - _display_path(directory), - )) - rows.sort(key=lambda row: (row[0], row[1], _release_sort_key(row[2]))) + rows.append({ + "species": _species_display_name(genome.species), + "assembly": genome.reference_name, + "release": str(genome.release), + "annotation": annotation if annotation not in (None, "missing") else None, + "reference_dna": dna or None, + "cache_directory": os.fspath(directory), + }) + rows.sort(key=lambda r: (r["species"], r["assembly"], _release_sort_key(r["release"]))) # Custom genomes (e.g. install --gtf ...) live beside Ensembl releases. root = Path(cache_root()) for reference in _subdirectories(root): @@ -635,18 +642,47 @@ def format_installed_genomes(check_genome_fasta=False, use_color=None): species, release = "custom", directory.name else: species, release = _other_genome_labels(reference.name, directory.name) - rows.append(( - species, - reference.name, - release, - annotation or "-", - dna or "-", - _display_path(directory), - )) + rows.append({ + "species": species, + "assembly": reference.name, + "release": release, + "annotation": annotation or None, + "reference_dna": dna or None, + "cache_directory": os.fspath(directory), + }) + return rows, root + + +def format_installed_genomes(check_genome_fasta=False, use_color=None): + """A table of genomes in the local cache, or a note that there are none.""" + rows, root = _installed_genome_rows(check_genome_fasta=check_genome_fasta) if not rows: return "No genomes installed in %s" % _display_path(root) header = ("Species", "Assembly", "Release", "Annotation", "Reference DNA", "Location") - return _format_table(header, rows, use_color) + table_rows = [ + ( + r["species"], + r["assembly"], + r["release"], + r["annotation"] or "-", + r["reference_dna"] or "-", + _display_path(r["cache_directory"]), + ) + for r in rows + ] + return _format_table(header, table_rows, use_color) + + +def format_installed_genomes_json(check_genome_fasta=False): + """The same inventory as :func:`format_installed_genomes`, serialised as JSON. + + Returns a JSON string (array of objects) with keys ``species``, + ``assembly``, ``release``, ``annotation``, ``reference_dna``, and + ``cache_directory``. ``annotation`` and ``reference_dna`` are ``null`` + when the respective file is absent. + """ + rows, _ = _installed_genome_rows(check_genome_fasta=check_genome_fasta) + return json.dumps(rows, indent=2) def _newest_release(species_name): @@ -1047,8 +1083,8 @@ def validate_arguments(action, json_output, refresh, check_remote, releases): ValueError With the usage message when a flag does not fit the action. """ - if json_output and action not in ("inspect", "available", "verify"): - raise ValueError("--json requires inspect, available, or verify") + if json_output and action not in ("list", "inspect", "available", "verify"): + raise ValueError("--json requires list, inspect, available, or verify") if refresh and action != "available": raise ValueError("--refresh requires available") if check_remote and action != "verify": @@ -1276,7 +1312,10 @@ def run(argv=None): ): parser.error("%s requires an explicit --release" % args.action) if args.action == "list": - print(format_installed_genomes(check_genome_fasta=args.check_genome_fasta)) + if args.json: + print(format_installed_genomes_json(check_genome_fasta=args.check_genome_fasta)) + else: + print(format_installed_genomes(check_genome_fasta=args.check_genome_fasta)) return if args.action == "available": try: diff --git a/tests/test_cli_actions.py b/tests/test_cli_actions.py index 0222ccb..7bf9f28 100644 --- a/tests/test_cli_actions.py +++ b/tests/test_cli_actions.py @@ -15,10 +15,10 @@ def test_validate_arguments_accepts_matching_flags(): shell.validate_arguments("inspect", True, False, False, [75]) shell.validate_arguments("available", False, True, False, []) shell.validate_arguments("verify", False, False, True, []) + shell.validate_arguments("list", True, False, False, []) @pytest.mark.parametrize("action, json_output, refresh, check_remote, releases, message", [ - ("list", True, False, False, [], "--json requires"), ("install", False, True, False, [], "--refresh requires available"), ("list", False, False, True, [], "--check-remote requires verify"), ("delete-all-files", False, False, False, ["latest"], "concrete --release"), diff --git a/tests/test_cli_errors.py b/tests/test_cli_errors.py index c1d9c59..8a0106f 100644 --- a/tests/test_cli_errors.py +++ b/tests/test_cli_errors.py @@ -162,6 +162,6 @@ def test_corrupt_database_without_overwrite_keeps_traceback(tmp_path, monkeypatc def test_run_accepts_explicit_argv(monkeypatch, capsys): monkeypatch.setattr(shell, "configure_logging", lambda **kw: None) with pytest.raises(SystemExit) as exit_info: - shell.run(["--json", "list"]) + shell.run(["--json", "install"]) assert exit_info.value.code == 2 - assert "--json requires inspect, available, or verify" in capsys.readouterr().err + assert "--json requires list, inspect, available, or verify" in capsys.readouterr().err diff --git a/tests/test_cli_output.py b/tests/test_cli_output.py index 3c8eb13..bc23866 100644 --- a/tests/test_cli_output.py +++ b/tests/test_cli_output.py @@ -1,6 +1,7 @@ """What `pyensembl list` and `install` show a person at a terminal.""" from contextlib import closing +import json import logging from pathlib import Path import sqlite3 @@ -108,6 +109,39 @@ def test_list_skips_unreadable_directories(tmp_path, monkeypatch, capsys, caplog assert "Cannot read" in caplog.text +def test_list_json_emits_valid_json_array(tmp_path, monkeypatch, capsys): + monkeypatch.setenv("PYENSEMBL_CACHE_DIR", str(tmp_path)) + root = tmp_path / "pyensembl" + location = ensembl_files(83) + ensembl_files(81, indexes=False) # Downloaded, never indexed. + run_cli(monkeypatch, "list", "--json") + output = capsys.readouterr().out + rows = json.loads(output) + assert isinstance(rows, list) + keys = {"species", "assembly", "release", "annotation", "reference_dna", "cache_directory"} + for row in rows: + assert keys == row.keys(), "unexpected or missing keys: %s" % row.keys() + by_release = {r["release"]: r for r in rows} + assert "83" in by_release + r83 = by_release["83"] + assert r83["species"] == "human" + assert r83["assembly"] == "GRCh38" + assert r83["annotation"] == "indexed" + assert r83["reference_dna"] is None + assert r83["cache_directory"] == str(location) + # release 81 was downloaded but never indexed → present in JSON output + assert "81" in by_release + assert by_release["81"]["annotation"] == "not indexed" + + +def test_list_json_empty_cache_emits_empty_array(tmp_path, monkeypatch, capsys): + monkeypatch.setenv("PYENSEMBL_CACHE_DIR", str(tmp_path)) + run_cli(monkeypatch, "list", "--json") + output = capsys.readouterr().out + rows = json.loads(output) + assert rows == [] + + @pytest.fixture def cli_logging(): loggers = [logging.getLogger(name) for name in ("pyensembl", "datacache")] diff --git a/tests/test_data_management.py b/tests/test_data_management.py index 92eb94b..5b96fa4 100644 --- a/tests/test_data_management.py +++ b/tests/test_data_management.py @@ -223,8 +223,8 @@ def test_cli_custom_inspection_and_human_output(tmp_path, monkeypatch, capsys): def test_json_option_only_applies_to_inspection(monkeypatch, capsys): with pytest.raises(SystemExit): - run_cli(monkeypatch, "list", "--json") - assert "--json requires inspect" in capsys.readouterr().err + run_cli(monkeypatch, "install", "--json") + assert "--json requires list, inspect, available, or verify" in capsys.readouterr().err def test_missing_inspection_does_not_create_cache(tmp_path, monkeypatch):