Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@
Changes in each published version, newest first. These notes start at 2.27.2;
earlier versions are available as [Git tags](https://github.com/openvax/pyensembl/tags).

## 2.37.0

Add `--json` output support to `pyensembl list` (#512, #526):

- `pyensembl list --json` prints installed Ensembl, pinned, and custom genomes
as a deterministically sorted JSON array (`[]` when no genomes are installed),
with keys `species`, `assembly`, `release`, `annotation`, `reference_dna`,
and `cache_directory`.

## 2.36.1

Test-only change. The tests that rewrite a source file with the same size
Expand Down
3 changes: 2 additions & 1 deletion docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
87 changes: 63 additions & 24 deletions pyensembl/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -593,8 +593,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 NON_GENOME_CACHE_DIRECTORIES, cache_root
Expand All @@ -610,15 +617,14 @@ 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),
})
# Custom genomes (e.g. install --gtf ...) live beside Ensembl releases.
root = Path(cache_root())
for reference in _subdirectories(root):
Expand All @@ -636,18 +642,48 @@ 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),
})
rows.sort(key=lambda r: (r["species"], r["assembly"], _release_sort_key(r["release"])))
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):
Expand Down Expand Up @@ -1142,8 +1178,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":
Expand Down Expand Up @@ -1370,7 +1406,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:
Expand Down
4 changes: 3 additions & 1 deletion pyensembl/version.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
__version__ = "2.36.1"
__version__ = "2.37.0"


def print_version():
print(f"v{__version__}")


if __name__ == "__main__":
print_version()
2 changes: 1 addition & 1 deletion tests/test_cli_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
4 changes: 2 additions & 2 deletions tests/test_cli_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,9 @@ 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


@pytest.mark.parametrize("action", [
Expand Down
33 changes: 33 additions & 0 deletions tests/test_cli_output.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -125,6 +126,38 @@ 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))
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")]
Expand Down
4 changes: 2 additions & 2 deletions tests/test_data_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading