uv-stack 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
uv_stack/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """uv-stack: formalized uv + micromamba environment management."""
2
+
3
+ __version__ = "0.1.2"
@@ -0,0 +1,114 @@
1
+ """uv-stack command-line interface (rich-click).
2
+
3
+ Defines the root group, the shared ``--root`` option (stored on the Click
4
+ context), version output, and the error wrapper that renders
5
+ :class:`UvStackError` as a panel and exits non-zero.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+
12
+ import rich_click as click
13
+ from rich_click.rich_help_formatter import RichHelpFormatter
14
+ from rich_click.rich_panel import RichCommandPanel
15
+
16
+ from uv_stack import __version__
17
+ from uv_stack.cli._render import render_error
18
+ from uv_stack.config import ConfigRoot
19
+ from uv_stack.errors import UvStackError
20
+
21
+ # Width of the command-name column in every command-group panel. rich-click
22
+ # renders the Options and Commands panels as independent tables, so their
23
+ # description columns only align if the command-name column is pinned to a
24
+ # fixed width (the built-in ratio option scales with terminal width and cannot
25
+ # match the content-sized Options panel). 15 aligns the command descriptions
26
+ # with the Options descriptions for the current option set; widen it if a
27
+ # longer option name or metavar pushes the Options column further right.
28
+ _COMMAND_NAME_COLUMN_WIDTH = 15
29
+
30
+
31
+ class _AlignedCommandPanel(RichCommandPanel):
32
+ """Command-group panel with a fixed-width name column.
33
+
34
+ Pinning the first column to a constant width aligns the description column
35
+ both across command groups and with the Options panel above them.
36
+ """
37
+
38
+ def get_table(self, command, ctx, formatter): # type: ignore[no-untyped-def]
39
+ table = super().get_table(command, ctx, formatter)
40
+ if len(table.columns) >= 2:
41
+ name_column, help_column = table.columns[0], table.columns[1]
42
+ name_column.width = _COMMAND_NAME_COLUMN_WIDTH
43
+ name_column.ratio = None
44
+ # The table expands to the panel width, so give the help column the
45
+ # flexible ratio; otherwise the name column absorbs the slack in
46
+ # groups whose rows do not wrap and the descriptions misalign.
47
+ help_column.ratio = 1
48
+ return table
49
+
50
+
51
+ RichHelpFormatter.command_panel_class = _AlignedCommandPanel
52
+
53
+ click.rich_click.TEXT_MARKUP = "rich"
54
+ click.rich_click.SHOW_ARGUMENTS = True
55
+ click.rich_click.COMMAND_GROUPS = {
56
+ "stack": [
57
+ {"name": "Environments", "commands": ["upgrade", "create"]},
58
+ {"name": "Inspection", "commands": ["list", "show", "resolve"]},
59
+ {"name": "Maintenance", "commands": ["doctor", "config"]},
60
+ ]
61
+ }
62
+
63
+
64
+ class UvStackGroup(click.RichGroup):
65
+ """Custom group that catches UvStackError and renders it as a panel."""
66
+
67
+ def invoke(self, ctx: click.Context) -> None:
68
+ try:
69
+ super().invoke(ctx)
70
+ except UvStackError as error:
71
+ render_error(error)
72
+ sys.exit(1)
73
+
74
+
75
+ @click.group(cls=UvStackGroup)
76
+ @click.version_option(__version__, prog_name="stack")
77
+ @click.option(
78
+ "--root",
79
+ "root",
80
+ default=None,
81
+ help="Config root. Defaults to $UV_ENV_ROOT or ~/.config/python-envs.",
82
+ )
83
+ @click.pass_context
84
+ def cli(ctx: click.Context, root: str | None) -> None:
85
+ """stack — formalized uv + micromamba environment management."""
86
+ ctx.obj = ConfigRoot.discover(root)
87
+
88
+
89
+ def _register() -> None:
90
+ from uv_stack.cli import (
91
+ config_cmd,
92
+ create,
93
+ doctor,
94
+ list_cmd,
95
+ resolve,
96
+ show,
97
+ upgrade,
98
+ )
99
+
100
+ cli.add_command(upgrade.upgrade)
101
+ cli.add_command(create.create)
102
+ cli.add_command(list_cmd.list_resources)
103
+ cli.add_command(show.show)
104
+ cli.add_command(resolve.resolve)
105
+ cli.add_command(doctor.doctor)
106
+ cli.add_command(config_cmd.config)
107
+
108
+
109
+ _register()
110
+
111
+
112
+ def main() -> None:
113
+ """Console-script entry point."""
114
+ cli()
@@ -0,0 +1,42 @@
1
+ """Shared rich rendering helpers for the CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+ from pathlib import Path
7
+
8
+ import rich_click as click
9
+ from rich.console import Console
10
+ from rich.panel import Panel
11
+ from rich.table import Table
12
+
13
+ from uv_stack.errors import UvStackError
14
+
15
+ console = Console()
16
+ error_console = Console(stderr=True)
17
+
18
+
19
+ def render_error(error: UvStackError) -> None:
20
+ """Print a :class:`UvStackError` as a red panel with an optional hint."""
21
+ body = error.message
22
+ if error.hint:
23
+ body += f"\n\n[dim]Hint:[/dim] {error.hint}"
24
+ error_console.print(Panel(body, title="uv-stack error", border_style="red"))
25
+
26
+
27
+ def render_list(title: str, items: Iterable[str], directory: Path | None = None) -> None:
28
+ """Print a simple single-column table, optionally headed by its directory."""
29
+ if directory is not None:
30
+ # A full-width line, not a table caption: captions wrap to the
31
+ # content-sized table width and mangle long absolute paths.
32
+ console.print(f"[dim]{title} in {directory}[/dim]")
33
+ table = Table(title=title)
34
+ table.add_column(title.rstrip("s").capitalize())
35
+ for item in items:
36
+ table.add_row(item)
37
+ console.print(table)
38
+
39
+
40
+ def echo(message: str) -> None:
41
+ """Print a plain line to stdout (kept here so commands avoid importing rich)."""
42
+ click.echo(message)
@@ -0,0 +1,27 @@
1
+ """``stack config`` commands (init)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import rich_click as click
6
+
7
+ from uv_stack.cli._render import echo
8
+ from uv_stack.config import ConfigRoot
9
+ from uv_stack.operations.init import init_config_root
10
+
11
+
12
+ @click.group()
13
+ def config() -> None:
14
+ """Initialize the config tree."""
15
+
16
+
17
+ @config.command("init")
18
+ @click.pass_obj
19
+ def config_init(config_root: ConfigRoot) -> None:
20
+ """Create missing config directories (profiles/, bundles/, envs/)."""
21
+ created = init_config_root(config_root)
22
+ if not created:
23
+ echo("Nothing to do — all config directories already exist.")
24
+ return
25
+ echo(f"Created {len(created)} directories under {config_root.root}:")
26
+ for path in created:
27
+ echo(f" {path}")
uv_stack/cli/create.py ADDED
@@ -0,0 +1,50 @@
1
+ """``stack create``: create a new environment or project."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import rich_click as click
8
+
9
+ from uv_stack.cli._render import console
10
+ from uv_stack.cli.upgrade import _run_upgrade
11
+ from uv_stack.config import ConfigRoot
12
+ from uv_stack.operations.project import ProjectOptions, init_project
13
+ from uv_stack.operations.upgrade import UpgradeOptions
14
+ from uv_stack.runner import SubprocessRunner
15
+
16
+
17
+ @click.group("create")
18
+ def create() -> None:
19
+ """Create a new environment or project."""
20
+
21
+
22
+ @create.command("env")
23
+ @click.argument("name")
24
+ @click.option("--recreate", is_flag=True, help="Remove and recreate the env first.")
25
+ @click.pass_obj
26
+ def create_env(config: ConfigRoot, name: str, recreate: bool) -> None:
27
+ """Create environment NAME, then upgrade it (``--recreate`` wipes it first)."""
28
+ options = UpgradeOptions(recreate=True) if recreate else UpgradeOptions(create=True)
29
+ _run_upgrade(config, [name], options)
30
+
31
+
32
+ @create.command("project")
33
+ @click.argument("tokens", nargs=-1, required=True)
34
+ @click.option("--python", "python", default="3.12", help="Python version to pin.")
35
+ @click.option("--name", "name", default=None, help="Project name for uv init.")
36
+ @click.option("--no-sync", is_flag=True, help="Add dependencies but do not sync.")
37
+ @click.option("--force", is_flag=True, help="Add to an existing pyproject.toml.")
38
+ @click.pass_obj
39
+ def create_project(
40
+ config: ConfigRoot,
41
+ tokens: tuple[str, ...],
42
+ python: str,
43
+ name: str | None,
44
+ no_sync: bool,
45
+ force: bool,
46
+ ) -> None:
47
+ """Create a uv project from the resolved stack TOKENS."""
48
+ options = ProjectOptions(python=python, name=name, no_sync=no_sync, force=force)
49
+ init_project(config, SubprocessRunner(), list(tokens), options, cwd=Path.cwd())
50
+ console.print("[green]Project initialized.[/green]")
uv_stack/cli/doctor.py ADDED
@@ -0,0 +1,24 @@
1
+ """``stack doctor``: detect layout/config problems and print suggested fixes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import rich_click as click
6
+
7
+ from uv_stack.cli._render import console
8
+ from uv_stack.config import ConfigRoot
9
+ from uv_stack.operations.doctor import diagnose
10
+
11
+
12
+ @click.command("doctor")
13
+ @click.pass_obj
14
+ def doctor(config_root: ConfigRoot) -> None:
15
+ """Detect layout/config problems and print suggested fixes."""
16
+ findings = diagnose(config_root)
17
+ if not findings:
18
+ console.print("[green]No problems detected.[/green]")
19
+ return
20
+ for finding in findings:
21
+ color = "red" if finding.level == "error" else "yellow"
22
+ console.print(f"[{color}]{finding.level.upper()}[/{color}] {finding.message}")
23
+ if finding.fix:
24
+ console.print(f" [dim]fix:[/dim] {finding.fix}")
@@ -0,0 +1,23 @@
1
+ """``stack list KIND``: list environments, profiles, or bundles."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import rich_click as click
6
+
7
+ from uv_stack.cli._render import render_list
8
+ from uv_stack.config import ConfigRoot
9
+
10
+ _KINDS = ("env", "profile", "bundle")
11
+
12
+
13
+ @click.command("list")
14
+ @click.argument("kind", type=click.Choice(_KINDS))
15
+ @click.pass_obj
16
+ def list_resources(config: ConfigRoot, kind: str) -> None:
17
+ """List resources of KIND (env, profile, or bundle)."""
18
+ if kind == "env":
19
+ render_list("envs", config.list_envs(), config.envs_dir)
20
+ elif kind == "profile":
21
+ render_list("profiles", config.list_profiles(), config.profiles_dir)
22
+ else:
23
+ render_list("bundles", config.list_bundles(), config.bundles_dir)
@@ -0,0 +1,33 @@
1
+ """``stack resolve`` command (resolver debugging)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import rich_click as click
6
+
7
+ from uv_stack.cli._render import echo
8
+ from uv_stack.config import ConfigRoot
9
+ from uv_stack.resolver import Resolver
10
+
11
+
12
+ @click.command()
13
+ @click.option(
14
+ "--full",
15
+ is_flag=True,
16
+ help="Expand bundles and profiles to a flat package list (requirements.txt-compatible).",
17
+ )
18
+ @click.argument("tokens", nargs=-1, required=True)
19
+ @click.pass_obj
20
+ def resolve(config: ConfigRoot, tokens: tuple[str, ...], full: bool) -> None:
21
+ """Resolve TOKENS and print the result.
22
+
23
+ By default each token is classified as ``bundle:``, ``profile:``, or
24
+ ``package:`` without expansion. With ``--full``, bundles and profiles are
25
+ expanded to a raw package list with no prefixes.
26
+ """
27
+ resolver = Resolver(config)
28
+ if full:
29
+ lines = resolver.resolve_packages(list(tokens))
30
+ else:
31
+ lines = resolver.classify(list(tokens))
32
+ for line in lines:
33
+ echo(line)
uv_stack/cli/show.py ADDED
@@ -0,0 +1,68 @@
1
+ """``stack show KIND [NAME]``: show an environment, profile, or bundle."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import rich_click as click
6
+
7
+ from uv_stack.cli._render import echo
8
+ from uv_stack.config import ConfigRoot
9
+ from uv_stack.render import render_requirements_in
10
+ from uv_stack.resolver import Resolver
11
+
12
+ _KINDS = ("env", "profile", "bundle")
13
+
14
+
15
+ @click.command("show")
16
+ @click.argument("kind", type=click.Choice(_KINDS))
17
+ @click.argument("name", required=False)
18
+ @click.pass_obj
19
+ def show(config: ConfigRoot, kind: str, name: str | None) -> None:
20
+ """Show details of KIND NAME. NAME defaults to ``main`` for ``env``."""
21
+ if kind == "env":
22
+ _show_env(config, name or "main")
23
+ elif name is None:
24
+ raise click.UsageError(f"'show {kind}' requires a NAME.")
25
+ elif kind == "profile":
26
+ _show_profile(config, name)
27
+ else:
28
+ _show_bundle(config, name)
29
+
30
+
31
+ def _show_env(config: ConfigRoot, name: str) -> None:
32
+ cfg = config.load_env(name)
33
+ echo(f"Environment: {cfg.name}")
34
+ echo(f"Python: {cfg.python}")
35
+ echo("Stack:")
36
+ for token in cfg.stack:
37
+ echo(f" {token}")
38
+ echo("Channels:")
39
+ echo(" conda-forge")
40
+ for channel in cfg.channels:
41
+ if channel != "conda-forge":
42
+ echo(f" {channel}")
43
+ echo("Micromamba packages:")
44
+ for pkg in cfg.micromamba:
45
+ echo(f" {pkg}")
46
+ stack = Resolver(config).resolve(cfg.stack)
47
+ echo("Resolved profiles:")
48
+ for profile_name in stack.profiles:
49
+ echo(f" {profile_name}")
50
+ echo("Resolved inline requirements:")
51
+ for req in stack.inline:
52
+ echo(f" {req}")
53
+ # Touch render to validate it produces text without error.
54
+ render_requirements_in(stack, config, name)
55
+
56
+
57
+ def _show_profile(config: ConfigRoot, name: str) -> None:
58
+ prof = config.load_profile(name)
59
+ echo(f"Profile: {prof.name}")
60
+ for req in prof.requirements:
61
+ echo(f" {req}")
62
+
63
+
64
+ def _show_bundle(config: ConfigRoot, name: str) -> None:
65
+ b = config.load_bundle(name)
66
+ echo(f"Bundle: {b.name}")
67
+ for token in b.tokens:
68
+ echo(f" {token}")
@@ -0,0 +1,125 @@
1
+ """``stack upgrade``: upgrade existing environments (render → compile → install → check)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ import rich_click as click
8
+
9
+ from uv_stack.cli._render import console, echo, render_error
10
+ from uv_stack.config import ConfigRoot
11
+ from uv_stack.errors import UvStackError
12
+ from uv_stack.operations.upgrade import UpgradeOptions, upgrade_env
13
+ from uv_stack.runner import SubprocessRunner
14
+
15
+
16
+ def _run_upgrade(
17
+ config: ConfigRoot,
18
+ names: list[str],
19
+ options: UpgradeOptions,
20
+ *,
21
+ stop_on_error: bool = False,
22
+ ) -> None:
23
+ """Upgrade each environment, continuing past failures by default.
24
+
25
+ Each environment's outcome is recorded and printed in a final summary.
26
+ With ``stop_on_error`` the batch aborts at the first failing environment.
27
+ A non-empty failure set exits the process with status 1.
28
+
29
+ :param config: Configuration root.
30
+ :param names: Environment names to upgrade.
31
+ :param options: Upgrade options.
32
+ :param stop_on_error: Abort the batch on the first failure.
33
+ """
34
+ runner = SubprocessRunner()
35
+ failed: list[str] = []
36
+
37
+ for name in names:
38
+ console.rule(f"Upgrading {name}")
39
+ try:
40
+ result = upgrade_env(config, runner, name, options)
41
+ except UvStackError as error:
42
+ render_error(error)
43
+ failed.append(name)
44
+ if stop_on_error:
45
+ break
46
+ continue
47
+ if options.dry_run:
48
+ echo("Planned commands:")
49
+ for command in result.planned:
50
+ echo(" " + " ".join(command.args))
51
+
52
+ if options.dry_run:
53
+ return
54
+
55
+ _print_summary(names, failed)
56
+ if failed:
57
+ sys.exit(1)
58
+
59
+
60
+ def _print_summary(names: list[str], failed: list[str]) -> None:
61
+ """Print a per-environment ✓/✗ summary of an upgrade batch."""
62
+ failed_set = set(failed)
63
+ console.rule("Summary")
64
+ for name in names:
65
+ if name in failed_set:
66
+ console.print(f" [red]✗[/red] {name}")
67
+ else:
68
+ console.print(f" [green]✓[/green] {name}")
69
+ if failed:
70
+ console.print(f"[red]{len(failed)} of {len(names)} environment(s) failed.[/red]")
71
+ else:
72
+ console.print("[green]All requested environments upgraded.[/green]")
73
+
74
+
75
+ @click.command("upgrade")
76
+ @click.argument("names", nargs=-1)
77
+ @click.option("-y", "--yes", is_flag=True, help="Confirm bulk upgrade of all envs.")
78
+ @click.option("--dry-run", is_flag=True, help="Print the command plan; change nothing.")
79
+ @click.option(
80
+ "--stop-on-error",
81
+ is_flag=True,
82
+ help="Abort the batch at the first failing environment.",
83
+ )
84
+ @click.option("--no-upgrade", is_flag=True, help="Recompile without forcing upgrades.")
85
+ @click.option(
86
+ "--upgrade-package",
87
+ "upgrade_packages",
88
+ multiple=True,
89
+ help="Upgrade only this package (repeatable).",
90
+ )
91
+ @click.pass_obj
92
+ def upgrade(
93
+ config: ConfigRoot,
94
+ names: tuple[str, ...],
95
+ yes: bool,
96
+ dry_run: bool,
97
+ stop_on_error: bool,
98
+ no_upgrade: bool,
99
+ upgrade_packages: tuple[str, ...],
100
+ ) -> None:
101
+ """Render, compile, install, and check one or more existing environments.
102
+
103
+ With no NAMES, all discovered environments are upgraded (with confirmation
104
+ unless -y is given). By default the batch continues past a failing
105
+ environment and reports a ``✓``/``✗`` summary; ``--stop-on-error`` aborts at
106
+ the first failure. To create a missing environment, use ``stack create env``.
107
+ """
108
+ options = UpgradeOptions(
109
+ dry_run=dry_run,
110
+ no_upgrade=no_upgrade,
111
+ upgrade_packages=list(upgrade_packages),
112
+ )
113
+ targets = list(names)
114
+ if not targets:
115
+ targets = config.list_envs()
116
+ if not targets:
117
+ console.print("[yellow]No environments discovered.[/yellow]")
118
+ return
119
+ echo("Discovered environments:")
120
+ for name in targets:
121
+ echo(f" - {name}")
122
+ if not yes and not click.confirm("Upgrade all of these?"):
123
+ echo("Aborted.")
124
+ return
125
+ _run_upgrade(config, targets, options, stop_on_error=stop_on_error)
uv_stack/commands.py ADDED
@@ -0,0 +1,78 @@
1
+ """Pure builders for the ``uv`` and ``micromamba`` commands uv-stack runs.
2
+
3
+ Keeping command construction in one place (free of side effects) lets both the
4
+ real execution path and the ``--dry-run`` plan share identical argv lists, and
5
+ makes the command shapes trivially unit-testable.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Sequence
11
+ from pathlib import Path
12
+
13
+ from uv_stack.runner import Command
14
+
15
+ _PYTHON_PATH_SNIPPET = "import sys; print(sys.executable)"
16
+
17
+
18
+ def uv_pip_compile(
19
+ python: str,
20
+ requirements_in: Path,
21
+ output: Path,
22
+ *,
23
+ upgrade: bool = False,
24
+ upgrade_packages: Sequence[str] = (),
25
+ ) -> Command:
26
+ """Build ``uv pip compile`` for a named environment's requirements."""
27
+ args = ["uv", "pip", "compile", "--python", python, str(requirements_in), "-o", str(output)]
28
+ if upgrade:
29
+ args.append("--upgrade")
30
+ for pkg in upgrade_packages:
31
+ args += ["--upgrade-package", pkg]
32
+ return Command(args)
33
+
34
+
35
+ def uv_pip_install(python: str, lock: Path) -> Command:
36
+ """Build ``uv pip install -r <lock>`` against a specific interpreter."""
37
+ return Command(["uv", "pip", "install", "--python", python, "-r", str(lock)])
38
+
39
+
40
+ def uv_pip_check(python: str) -> Command:
41
+ """Build ``uv pip check`` against a specific interpreter."""
42
+ return Command(["uv", "pip", "check", "--python", python])
43
+
44
+
45
+ def micromamba_create(environment_yml: Path) -> Command:
46
+ """Build ``micromamba create -f <env.yml> -y``."""
47
+ return Command(["micromamba", "create", "-f", str(environment_yml), "-y"])
48
+
49
+
50
+ def micromamba_remove(env_name: str) -> Command:
51
+ """Build ``micromamba remove -n <env> --all -y``."""
52
+ return Command(["micromamba", "remove", "-n", env_name, "--all", "-y"])
53
+
54
+
55
+ def micromamba_python_path(env_name: str) -> Command:
56
+ """Build a command that prints the env's Python executable path."""
57
+ return Command(
58
+ ["micromamba", "run", "-n", env_name, "python", "-c", _PYTHON_PATH_SNIPPET]
59
+ )
60
+
61
+
62
+ def uv_init(python: str, name: str | None = None) -> Command:
63
+ """Build ``uv init --bare`` for a new project."""
64
+ args = ["uv", "init", "--bare"]
65
+ if name:
66
+ args += ["--name", name]
67
+ args += ["--python", python]
68
+ return Command(args)
69
+
70
+
71
+ def uv_add(requirements_file: Path) -> Command:
72
+ """Build ``uv add --no-sync -r <file>``."""
73
+ return Command(["uv", "add", "--no-sync", "-r", str(requirements_file)])
74
+
75
+
76
+ def uv_sync() -> Command:
77
+ """Build ``uv sync``."""
78
+ return Command(["uv", "sync"])