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
72 changes: 72 additions & 0 deletions autotest/test_programs.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@

import argparse
import json
import shutil
import subprocess
import sys
import warnings
import zipfile
from datetime import UTC, datetime
from pathlib import Path
from unittest import mock

import pytest
from flaky import flaky
Expand Down Expand Up @@ -734,6 +736,7 @@ def test_cmd_install_at_version_syntax_and_list_and_uninstall(
owner="MODFLOW-ORG",
version=None,
bindir=str(bindir),
libdir=None,
platform=None,
subset=None,
force=False,
Expand Down Expand Up @@ -924,3 +927,72 @@ def test_latest_only_offered_with_a_full_release(self, monkeypatch):
assert get_releases(repo="x") == ["2.0rc1"]
with pytest.raises(ProgramInstallationError, match=r"'latest' not found.*: 2\.0rc1$"):
get_release(repo="x")


class TestLibdir:
@staticmethod
def _offline_release(monkeypatch, tmp_path, ostag="linux"):
suffix = ".dll" if ostag == "win64" else ".so"
exe = "mf6.exe" if ostag == "win64" else "mf6"
archive = _make_zip(
tmp_path / f"{ostag}.zip",
{f"mf6/bin/{exe}": b"fake-mf6", f"mf6/bin/libmf6{suffix}": b"fake-lib"},
)
release = {
"tag_name": "6.8.0",
"assets": [{"name": f"{ostag}.zip", "browser_download_url": "https://example/x"}],
}
monkeypatch.setattr("modflow_devtools.programs.get_release", lambda *a, **k: release)

def _download(url, dest, **kwargs):
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(archive, dest)

monkeypatch.setattr("modflow_devtools.programs.download_archive", _download)

def test_extract_puts_shared_libraries_in_libdir(self, tmp_path):
archive = _make_zip(
tmp_path / "linux.zip",
{"bin/mf6": b"fake-mf6", "bin/libmf6.so": b"fake-lib"},
)
bindir, libdir = tmp_path / "bin", tmp_path / "lib"
extracted = extract_release_archive(
archive, bindir, release_tag="6.8.0", ostag="linux", libdir=libdir
)
paths = {p.name: p.path for p in extracted}
assert paths["mf6"] == bindir / "mf6"
assert paths["libmf6"] == libdir / "libmf6.so"
assert not (bindir / "libmf6.so").exists()

def test_install_libdir_true_is_lib_beside_bindir(self, isolated_cache, tmp_path, monkeypatch):
self._offline_release(monkeypatch, tmp_path)
bindir = tmp_path / "env" / "bin"
install_program(repo="modflow6", bindir=bindir, platform="linux", libdir=True)
assert (bindir / "mf6").exists()
assert (tmp_path / "env" / "lib" / "libmf6.so").exists()
assert not (bindir / "libmf6.so").exists()

def test_uninstall_removes_library_from_libdir(self, isolated_cache, tmp_path, monkeypatch):
self._offline_release(monkeypatch, tmp_path)
bindir, libdir = tmp_path / "bin", tmp_path / "lib"
install_program(repo="modflow6", bindir=bindir, platform="linux", libdir=libdir)
assert get_executable("libmf6") == libdir / "libmf6.so"
uninstall_program("libmf6", version="6.8.0", bindir=bindir)
assert not (libdir / "libmf6.so").exists()
assert list_installed("libmf6") == {}

def test_libdir_ignored_on_windows(self, isolated_cache, tmp_path, monkeypatch):
self._offline_release(monkeypatch, tmp_path, ostag="win64")
bindir = tmp_path / "bin"
install_program(repo="modflow6", bindir=bindir, platform="win64", libdir=True)
assert (bindir / "libmf6.dll").exists()
assert not (tmp_path / "lib").exists()

def test_cli_libdir_flag(self):
with mock.patch("modflow_devtools.programs.__main__.cmd_install") as cmd:
with mock.patch.object(sys, "argv", ["mf", "install", "mf6", "--libdir"]):
main()
assert cmd.call_args.args[0].libdir is True
with mock.patch.object(sys, "argv", ["mf", "install", "mf6", "--libdir", "/x/lib"]):
main()
assert cmd.call_args.args[0].libdir == "/x/lib"
8 changes: 7 additions & 1 deletion docs/md/programs.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ mf programs install mf6 --repo modflow6 --version 6.8.0 --bindir /usr/local/bin
mf programs install --repo executables --subset mfnwt,mf2005 --bindir /usr/local/bin
```

Shared libraries (e.g. `libmf6`) are installed beside the executables by default. On Linux and macOS, `libdir` (`--libdir`) installs them in a given directory instead, or with no value, in `lib` beside the bindir. On Windows they always go in the bindir.

```bash
mf programs install mf6 --repo modflow6 --bindir /usr/local/bin --libdir
```

## Program sources

`repo` is **not** restricted to a fixed list - any repo under `owner` (default `MODFLOW-ORG`) with a GitHub release and a platform-matching asset works, including installing a single program directly from its own repo:
Expand Down Expand Up @@ -165,7 +171,7 @@ Platform is auto-detected as a MODFLOW ostag - `linux`, `mac`, `macarm`, or `win
└── metadata/{program}.json # per-program installation ledger
```

The ledger is a flat list of installations per program name - version, platform, bindir, install time, source, and the executable filename(s) - independent of how the archive was cached or discovered.
The ledger is a flat list of installations per program name - version, platform, bindir, install time, source, and the executable filename(s), or absolute paths for files outside the bindir - independent of how the archive was cached or discovered.

## Relationship to get-modflow and conda-forge

Expand Down
24 changes: 22 additions & 2 deletions modflow_devtools/programs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,7 @@ def extract_release_archive(
release_tag: str,
ostag: str,
subset: set[str] | None = None,
libdir: Path | None = None,
verbose: bool = False,
) -> list["_ExtractedProgram"]:
"""
Expand All @@ -357,8 +358,12 @@ def extract_release_archive(

`subset` items may be program names or file names. Raises
`ProgramInstallationError` if any is not in the archive.

Shared libraries go in `libdir` if given, otherwise in `dest_dir`.
"""
dest_dir.mkdir(parents=True, exist_ok=True)
if libdir is not None:
libdir.mkdir(parents=True, exist_ok=True)
exe_suffix, lib_suffix = get_binary_suffixes(ostag)
tag_version = _normalize_version(release_tag)

Expand Down Expand Up @@ -412,7 +417,7 @@ def extract_release_archive(
extracted: list[_ExtractedProgram] = []
for name in sorted(selected):
info, version, is_so = available[name]
target = dest_dir / Path(info.filename).name
target = (libdir if is_so and libdir else dest_dir) / Path(info.filename).name
# write beside the target and swap it in, so an existing (possibly
# running, or code-signed and cached by the OS) binary is replaced
# rather than modified in place
Expand Down Expand Up @@ -644,6 +649,8 @@ class ProgramInstallation:
"""Free-form provenance, e.g. {'repo': 'MODFLOW-ORG/modflow6', 'tag': '6.8.0'}
or {'origin': 'conda-forge'} - not a registry reference."""
executables: list[str]
"""File names in `bindir`, or absolute paths for files elsewhere (e.g. a
shared library installed in a separate libdir)."""


class InstallationMetadata:
Expand Down Expand Up @@ -733,6 +740,7 @@ def install_program(
owner: str = DEFAULT_OWNER,
version: str = "latest",
bindir: str | Path | None = None,
libdir: str | Path | bool | None = None,
platform: str | None = None,
subset: str | list[str] | set[str] | None = None,
force: bool = False,
Expand Down Expand Up @@ -764,6 +772,10 @@ def install_program(
bindir : str | Path, optional
Installation directory. Auto-selected (see `get_bindir_options`) if
omitted.
libdir : str | Path | bool, optional
Directory to install shared libraries on Linux and macOS, created if
needed. True selects `lib` beside `bindir`. Default is `bindir`. On
Windows, shared libraries are always installed in `bindir`.
platform : str, optional
Ostag override; auto-detected if omitted.
subset : str | list[str] | set[str], optional
Expand Down Expand Up @@ -795,6 +807,13 @@ def install_program(
bindir = Path(bindir)
bindir.mkdir(parents=True, exist_ok=True)

if not libdir or ostag.startswith("win"):
libdir = None
elif libdir is True:
libdir = bindir.parent / "lib"
else:
libdir = Path(libdir)

archive_path = _DEFAULT_CACHE.get_archive_dir(repo, tag, ostag) / asset["name"]
download_archive(
url=asset["browser_download_url"],
Expand All @@ -811,6 +830,7 @@ def install_program(
release_tag=tag,
ostag=ostag,
subset=subset,
libdir=libdir,
verbose=verbose,
)

Expand All @@ -824,7 +844,7 @@ def install_program(
bindir=bindir,
installed_at=installed_at,
source=dict(source),
executables=[prog.path.name],
executables=[str(prog.path) if prog.path.parent != bindir else prog.path.name],
)
InstallationMetadata(prog.name).add_installation(installation)
installations.append(installation)
Expand Down
11 changes: 10 additions & 1 deletion modflow_devtools/programs/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import argparse
import sys
from pathlib import Path

from . import (
DEFAULT_OWNER,
Expand Down Expand Up @@ -43,6 +44,7 @@ def cmd_install(args):
owner=args.owner,
version=version or "latest",
bindir=bindir,
libdir=args.libdir,
platform=args.platform,
subset=args.subset,
force=args.force,
Expand All @@ -51,7 +53,7 @@ def cmd_install(args):
print("\nInstalled:")
for inst in installations:
for exe in inst.executables:
print(f" {exe} {inst.version} -> {inst.bindir / exe}")
print(f" {Path(exe).name} {inst.version} -> {inst.bindir / exe}")
except Exception as e:
print(f"Installation failed: {e}", file=sys.stderr)
sys.exit(1)
Expand Down Expand Up @@ -142,6 +144,13 @@ def main():
"Default: auto-select."
),
)
install_parser.add_argument(
"--libdir",
nargs="?",
const=True,
help="Directory to install shared libraries on Linux and macOS; "
"default is the bindir. Without a value, 'lib' beside the bindir.",
)
install_parser.add_argument("--platform", help="Ostag override; default is to auto-detect.")
install_parser.add_argument(
"--subset",
Expand Down
Loading