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
14 changes: 14 additions & 0 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,20 @@
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.38.0

Harmonize cache resolution, offline mode, and cache inspection with `datacache>=1.34.0` (#545):

- Honor `OPENVAX_DATA_CACHE` as a shared fallback behind `PYENSEMBL_CACHE_DIR`
(resolving to `$OPENVAX_DATA_CACHE/pyensembl`) while keeping existing
platform cache directories unchanged.
- Add `pyensembl dirs [--json]` to report the resolved cache root, why it was
chosen (`origin`/`detail`), offline status, and per-subdirectory disk usage
without creating directories or touching the network.
- Add `--offline` CLI flag (and respect `OPENVAX_OFFLINE` / `DATACACHE_OFFLINE`)
to fail fast on remote download attempts while serving cached data, and honor
`OPENVAX_NO_PROGRESS` / `DATACACHE_NO_PROGRESS` via `datacache.should_show_progress`.

## 2.37.0

Add `--json` output support to `pyensembl list` (#512, #526):
Expand Down
45 changes: 38 additions & 7 deletions pyensembl/cache_location.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

CACHE_BASE_SUBDIR = "pyensembl"
CACHE_DIR_ENV_KEY = "PYENSEMBL_CACHE_DIR"
SHARED_CACHE_DIR_ENV_KEY = "OPENVAX_DATA_CACHE"

# Directories PyEnsembl itself creates under the cache root which hold no
# genome: shared reference DNA (``genome_fasta_cache``), gene-name alias
Expand All @@ -31,12 +32,37 @@
NON_GENOME_CACHE_DIRECTORIES = frozenset({"dna_cache", "aliases", "dated_releases"})


def resolve_cache_location():
"""Resolve PyEnsembl's cache directory and why it was chosen; nothing is created.

Precedence:
1. ``$PYENSEMBL_CACHE_DIR/pyensembl`` when ``PYENSEMBL_CACHE_DIR`` is set.
2. ``$OPENVAX_DATA_CACHE/pyensembl`` when ``OPENVAX_DATA_CACHE`` is set.
3. The platform cache directory for ``pyensembl`` from datacache.

Returns
-------
datacache.CacheLocation
The resolved ``path``, ``origin``, and ``detail``.
"""
import datacache

return datacache.resolve_cache_dir(
CACHE_BASE_SUBDIR,
CACHE_DIR_ENV_KEY,
shared_envkey=SHARED_CACHE_DIR_ENV_KEY,
shared_subdir=None,
append_package_to_env=True,
)


def cache_root():
"""Return the directory holding all of PyEnsembl's data; nothing is created.

``$PYENSEMBL_CACHE_DIR/pyensembl`` when that variable is set, otherwise
the platform cache directory from datacache, e.g. ``~/.cache/pyensembl``,
``~/Library/Caches/pyensembl``, or
``$PYENSEMBL_CACHE_DIR/pyensembl`` when that variable is set, else
``$OPENVAX_DATA_CACHE/pyensembl`` when ``OPENVAX_DATA_CACHE`` is set,
otherwise the platform cache directory from datacache, e.g.
``~/.cache/pyensembl``, ``~/Library/Caches/pyensembl``, or
``%LOCALAPPDATA%\\pyensembl\\pyensembl\\Cache``. Every genome's directory
is ``<root>/<reference>/<annotation><version>``.

Expand All @@ -45,9 +71,14 @@ def cache_root():
str
The cache root path.
"""
environment_root = environ.get(CACHE_DIR_ENV_KEY)
environment_root = environ.get(CACHE_DIR_ENV_KEY, "").strip()
if environment_root:
return join(environment_root, CACHE_BASE_SUBDIR)
import datacache
from os.path import expanduser

return join(expanduser(environment_root), CACHE_BASE_SUBDIR)
shared_root = environ.get(SHARED_CACHE_DIR_ENV_KEY, "").strip()
if shared_root:
from os.path import expanduser

return datacache.get_cache_root(CACHE_BASE_SUBDIR)
return join(expanduser(shared_root), CACHE_BASE_SUBDIR)
return resolve_cache_location().path
4 changes: 3 additions & 1 deletion pyensembl/download_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@
CACHE_BASE_SUBDIR,
CACHE_DIR_ENV_KEY,
NON_GENOME_CACHE_DIRECTORIES,
SHARED_CACHE_DIR_ENV_KEY,
cache_root,
resolve_cache_location,
)
from .common import file_digest

Expand Down Expand Up @@ -88,7 +90,7 @@ def cache_subdirectory(
def _default_cache_directory(reference_name, annotation_name, annotation_version):
subdirectory = cache_subdirectory(reference_name, annotation_name, annotation_version)
directory = join(cache_root(), subdirectory[len(CACHE_BASE_SUBDIR) + 1:])
if not environ.get(CACHE_DIR_ENV_KEY):
if not environ.get(CACHE_DIR_ENV_KEY) and not environ.get(SHARED_CACHE_DIR_ENV_KEY):
# Before 2.17, each genome asked appdirs for its own directory. That
# matches the layout above on Linux and macOS, but on Windows gave
# unrelated paths; keep using a genome already installed there.
Expand Down
135 changes: 128 additions & 7 deletions pyensembl/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
functions that run an action.
"""

from contextlib import contextmanager
import argparse
import json
import logging
Expand Down Expand Up @@ -81,6 +82,7 @@ def configure_logging(verbose=False):
actions:
install download and index genome data (skips what is already done)
list show installed genomes, whether they are indexed, and their DNA
dirs show where PyEnsembl's cache lives, why it resolved there, and disk usage
inspect inspect selected source files, indexes, and download provenance offline
verify verify recorded dated-annotation checksums without repair
available show supported species, assemblies, and Ensembl releases
Expand All @@ -97,6 +99,7 @@ def configure_logging(verbose=False):
pyensembl install --reference-name GRCh38 --annotation-name my_genes \\
--gtf URL_OR_PATH --transcript-fasta URL_OR_PATH a custom genome
pyensembl list
pyensembl dirs --json
pyensembl inspect --release 93 --json
pyensembl delete-all-files --release 75
pyensembl prune --dry-run
Expand Down Expand Up @@ -126,7 +129,13 @@ def configure_logging(verbose=False):
parser.add_argument(
"--json",
action="store_true",
help="With list, inspect, available, or verify, print JSON",
help="With list, dirs, inspect, available, or verify, print JSON",
)

parser.add_argument(
"--offline",
action="store_true",
help="Forbid remote downloads (equivalent to OPENVAX_OFFLINE=1)",
)

parser.add_argument(
Expand Down Expand Up @@ -368,6 +377,7 @@ def complete_species(prefix, **kwargs):
choices=(
"install",
"list",
"dirs",
"inspect",
"verify",
"available",
Expand Down Expand Up @@ -1108,8 +1118,84 @@ def _directory_size(path):


def _progress_available():
"""Show progress bars when someone is watching stderr."""
return sys.stderr.isatty()
"""Show progress bars when stderr is interactive and progress is not disabled by env."""
import datacache

return datacache.should_show_progress("auto")


def _directory_stats(path):
"""Return (exists, total_bytes, file_count) without following symlinks or creating anything."""
if not os.path.exists(path):
return False, 0, 0
total_bytes = 0
file_count = 0
for root, _dirs, files in os.walk(path, followlinks=False):
for name in files:
try:
st = os.lstat(os.path.join(root, name))
except OSError:
continue
total_bytes += st.st_size
file_count += 1
return True, total_bytes, file_count


def format_cache_dirs(json_output=False):
"""Describe where PyEnsembl's cache lives, why it resolved there, and disk usage (read-only)."""
import datacache
from .cache_location import resolve_cache_location

loc = resolve_cache_location()
exists, total_bytes, file_count = _directory_stats(loc.path)
offline = datacache.offline_source()
entries = []
if os.path.isdir(loc.path):
try:
children = sorted(os.scandir(loc.path), key=lambda e: e.name)
except OSError:
children = []
for entry in children:
if not entry.is_dir(follow_symlinks=False):
continue
_, sub_bytes, sub_files = _directory_stats(entry.path)
entries.append(dict(
name=entry.name,
path=entry.path,
size_bytes=sub_bytes,
file_count=sub_files,
))
payload = dict(
cache_root=loc.path,
origin=loc.origin,
detail=loc.detail,
exists=exists,
size_bytes=total_bytes,
file_count=file_count,
offline=offline is not None,
offline_source=offline,
subdirectories=entries,
)
if json_output:
return json.dumps(payload, indent=2)
lines = [
"Cache root: %s" % loc.path,
"Origin: %s (%s)" % (loc.detail, loc.origin),
"Size: %s (%d file(s))" % (datacache.format_bytes(total_bytes), file_count)
if exists else "Size: not created yet",
]
if offline:
lines.append("Offline: enabled (%s)" % offline)
if entries:
lines.append("")
lines.append(_format_table(
("Directory", "Size", "Files", "Path"),
[
(e["name"], datacache.format_bytes(e["size_bytes"]), str(e["file_count"]), e["path"])
for e in entries
],
))
return "\n".join(lines)


def _install(genome, only_genome_fasta=False, overwrite=False, show_progress=False):
Expand Down Expand Up @@ -1178,8 +1264,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 ("list", "inspect", "available", "verify"):
raise ValueError("--json requires list, inspect, available, or verify")
if json_output and action not in ("list", "dirs", "inspect", "available", "verify"):
raise ValueError("--json requires list, dirs, inspect, available, or verify")
if refresh and action != "available":
raise ValueError("--refresh requires available")
if check_remote and action != "verify":
Expand Down Expand Up @@ -1372,6 +1458,23 @@ def run_install(genome, only_genome_fasta=False, overwrite=False):
raise InstallError(message) from error


@contextmanager
def _offline_override(offline):
"""Temporarily set DATACACHE_OFFLINE=1 for the duration of a CLI call."""
if not offline:
yield
return
previous = os.environ.get("DATACACHE_OFFLINE")
os.environ["DATACACHE_OFFLINE"] = "1"
try:
yield
finally:
if previous is None:
os.environ.pop("DATACACHE_OFFLINE", None)
else:
os.environ["DATACACHE_OFFLINE"] = previous


def run(argv=None):
"""Command-line entry point (console script ``pyensembl``).

Expand All @@ -1390,6 +1493,11 @@ def run(argv=None):
)
except ValueError as error:
parser.error(str(error))
with _offline_override(args.offline):
_run_action(args)


def _run_action(args):
if args.action == "prune":
try:
print(run_prune(args.dry_run))
Expand All @@ -1405,15 +1513,22 @@ def run(argv=None):
(args.genome_fasta_path and args.annotation_name))
):
parser.error("%s requires an explicit --release" % args.action)
if args.action == "dirs":
print(format_cache_dirs(json_output=args.json))
return
if args.action == "list":
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":
from datacache import OfflineError

try:
print(run_available(args))
except OfflineError as error:
parser.exit(1, "%s: error: %s\n" % (parser.prog, error))
except ValueError as error:
# Conflicting selectors are argument errors; failures while
# reading release listings keep their tracebacks.
Expand All @@ -1430,12 +1545,17 @@ def run(argv=None):
parser.error("No genomes selected")

if args.action == "verify":
from datacache import OfflineError

try:
require_ensembl_releases(genomes)
except ValueError as error:
parser.error(str(error))
# Checksum and manifest errors keep their tracebacks.
text, ok = run_verify(genomes, args.check_remote, args.json)
try:
text, ok = run_verify(genomes, args.check_remote, args.json)
except OfflineError as error:
parser.exit(1, "%s: error: %s\n" % (parser.prog, error))
print(text)
if not ok:
raise SystemExit(1)
Expand All @@ -1445,14 +1565,15 @@ def run(argv=None):
for genome in genomes:
_delete_genome_files(genome, args.action)
elif args.action == "install":
from datacache import OfflineError
from .dated_releases import UnpublishedDateError

for genome in genomes:
try:
run_install(genome, args.only_genome_fasta, args.overwrite)
except UnpublishedDateError as error:
parser.error(str(error))
except InstallError as error:
except (InstallError, OfflineError) as error:
parser.exit(1, "%s: error: %s\n" % (parser.prog, error))
else:
raise ValueError("Invalid action: %s" % args.action)
2 changes: 1 addition & 1 deletion pyensembl/version.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__version__ = "2.37.0"
__version__ = "2.38.0"


def print_version():
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ dependencies = [
"argcomplete>=3,<4",
# [progress] brings tqdm: progress bars are part of pyensembl. 1.30 makes
# `import datacache` lazy, which keeps `--release` tab completion fast.
"datacache[progress]>=1.30.0,<2.0.0",
"datacache[progress]>=1.34.0,<2.0.0",
"gtfparse>=2.9.0,<4.0.0",
"serializable>=0.2.1,<2.0.0",
"pyfaidx>=0.8.1,<1.0.0",
Expand Down
Loading
Loading