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/config.py ADDED
@@ -0,0 +1,151 @@
1
+ """Filesystem layout and loaders for a uv-stack config root.
2
+
3
+ A config root contains ``profiles/``, ``bundles/``, and ``envs/`` directories.
4
+ ``ConfigRoot`` centralizes path construction, existence checks, enumeration, and
5
+ loading of :mod:`uv_stack.models` objects. It performs the only config-file I/O
6
+ in the pure layer.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ from pathlib import Path
13
+
14
+ from uv_stack.errors import ConfigError
15
+ from uv_stack.models import Bundle, EnvConfig, Profile
16
+ from uv_stack.parse import first_clean_line, read_clean_lines
17
+
18
+ DEFAULT_ROOT = Path.home() / ".config" / "python-envs"
19
+
20
+
21
+ class ConfigRoot:
22
+ """Resolves and reads a uv-stack configuration tree.
23
+
24
+ :param root: The base directory containing ``profiles/``, ``bundles/``,
25
+ and ``envs/``.
26
+ """
27
+
28
+ def __init__(self, root: str | Path) -> None:
29
+ self.root = Path(root).expanduser()
30
+
31
+ @classmethod
32
+ def discover(cls, root: str | Path | None = None) -> ConfigRoot:
33
+ """Resolve the config root using flag, then env var, then default.
34
+
35
+ :param root: Explicit root from ``--root`` (highest precedence).
36
+ :returns: A configured :class:`ConfigRoot`.
37
+ """
38
+ if root is not None:
39
+ return cls(root)
40
+ env = os.environ.get("UV_ENV_ROOT")
41
+ if env:
42
+ return cls(env)
43
+ return cls(DEFAULT_ROOT)
44
+
45
+ # -- directories -----------------------------------------------------
46
+ @property
47
+ def profiles_dir(self) -> Path:
48
+ return self.root / "profiles"
49
+
50
+ @property
51
+ def bundles_dir(self) -> Path:
52
+ return self.root / "bundles"
53
+
54
+ @property
55
+ def envs_dir(self) -> Path:
56
+ return self.root / "envs"
57
+
58
+ # -- path helpers ----------------------------------------------------
59
+ def profile_path(self, name: str) -> Path:
60
+ return self.profiles_dir / f"{name}.in"
61
+
62
+ def bundle_path(self, name: str) -> Path:
63
+ return self.bundles_dir / f"{name}.bundle"
64
+
65
+ def env_dir(self, name: str) -> Path:
66
+ return self.envs_dir / name
67
+
68
+ def env_python_path(self, name: str) -> Path:
69
+ return self.env_dir(name) / "python.txt"
70
+
71
+ def env_stack_path(self, name: str) -> Path:
72
+ return self.env_dir(name) / "stack.txt"
73
+
74
+ def env_micromamba_path(self, name: str) -> Path:
75
+ return self.env_dir(name) / "micromamba.txt"
76
+
77
+ def env_channels_path(self, name: str) -> Path:
78
+ return self.env_dir(name) / "channels.txt"
79
+
80
+ def env_local_path(self, name: str) -> Path:
81
+ return self.env_dir(name) / "requirements.local.in"
82
+
83
+ def env_requirements_in(self, name: str) -> Path:
84
+ return self.env_dir(name) / "requirements.in"
85
+
86
+ def env_lock(self, name: str) -> Path:
87
+ return self.env_dir(name) / "requirements.lock.txt"
88
+
89
+ def env_environment_yml(self, name: str) -> Path:
90
+ return self.env_dir(name) / "environment.yml"
91
+
92
+ # -- existence -------------------------------------------------------
93
+ def profile_exists(self, name: str) -> bool:
94
+ return self.profile_path(name).is_file()
95
+
96
+ def bundle_exists(self, name: str) -> bool:
97
+ return self.bundle_path(name).is_file()
98
+
99
+ def env_exists(self, name: str) -> bool:
100
+ return self.env_stack_path(name).is_file()
101
+
102
+ # -- listing ---------------------------------------------------------
103
+ def list_profiles(self) -> list[str]:
104
+ if not self.profiles_dir.is_dir():
105
+ return []
106
+ return sorted(p.stem for p in self.profiles_dir.glob("*.in"))
107
+
108
+ def list_bundles(self) -> list[str]:
109
+ if not self.bundles_dir.is_dir():
110
+ return []
111
+ return sorted(p.stem for p in self.bundles_dir.glob("*.bundle"))
112
+
113
+ def list_envs(self) -> list[str]:
114
+ if not self.envs_dir.is_dir():
115
+ return []
116
+ return sorted(
117
+ d.name for d in self.envs_dir.iterdir() if (d / "stack.txt").is_file()
118
+ )
119
+
120
+ # -- loaders ---------------------------------------------------------
121
+ def load_profile(self, name: str) -> Profile:
122
+ path = self.profile_path(name)
123
+ if not path.is_file():
124
+ raise ConfigError(
125
+ f"Missing profile: {path}",
126
+ hint=f"Create {path} or check the profile name.",
127
+ )
128
+ return Profile.from_lines(name, path.read_text().splitlines())
129
+
130
+ def load_bundle(self, name: str) -> Bundle:
131
+ path = self.bundle_path(name)
132
+ if not path.is_file():
133
+ raise ConfigError(
134
+ f"Missing bundle: {path}",
135
+ hint=f"Create {path} or check the bundle name.",
136
+ )
137
+ return Bundle.from_lines(name, path.read_text().splitlines())
138
+
139
+ def load_env(self, name: str) -> EnvConfig:
140
+ if not self.env_exists(name):
141
+ raise ConfigError(
142
+ f"Missing stack file for env '{name}': expected {self.env_stack_path(name)}",
143
+ hint="Create stack.txt in the env config directory.",
144
+ )
145
+ return EnvConfig(
146
+ name=name,
147
+ python=first_clean_line(self.env_python_path(name), default="3.12"),
148
+ stack=read_clean_lines(self.env_stack_path(name)),
149
+ micromamba=read_clean_lines(self.env_micromamba_path(name)),
150
+ channels=read_clean_lines(self.env_channels_path(name)),
151
+ )
uv_stack/errors.py ADDED
@@ -0,0 +1,52 @@
1
+ """Exception hierarchy for uv-stack.
2
+
3
+ All recoverable, user-facing failures are :class:`UvStackError` subclasses so
4
+ the CLI edge can render them as panels with a remediation hint. Anything else
5
+ propagates as an ordinary exception (a real bug) with a full traceback.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+
11
+ class UvStackError(Exception):
12
+ """Base class for user-facing uv-stack errors.
13
+
14
+ :param message: Human-readable description of what went wrong.
15
+ :param hint: Optional remediation hint shown alongside the message.
16
+ """
17
+
18
+ def __init__(self, message: str, hint: str | None = None) -> None:
19
+ super().__init__(message)
20
+ self.message = message
21
+ self.hint = hint
22
+
23
+
24
+ class ConfigError(UvStackError):
25
+ """A config file or directory is missing or invalid."""
26
+
27
+
28
+ class ResolutionError(UvStackError):
29
+ """A stack token could not be resolved (bad token, missing profile/bundle, cycle)."""
30
+
31
+
32
+ class EnvError(UvStackError):
33
+ """A micromamba environment is missing and creation was not requested."""
34
+
35
+
36
+ class ToolError(UvStackError):
37
+ """An external ``uv`` or ``micromamba`` command exited non-zero.
38
+
39
+ :param command: The argv list of the command that failed.
40
+ :param returncode: The process exit code.
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ message: str,
46
+ command: list[str],
47
+ returncode: int,
48
+ hint: str | None = None,
49
+ ) -> None:
50
+ super().__init__(message, hint)
51
+ self.command = command
52
+ self.returncode = returncode
uv_stack/fsutil.py ADDED
@@ -0,0 +1,35 @@
1
+ """Filesystem helpers shared by operations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import tempfile
7
+ from pathlib import Path
8
+
9
+
10
+ def atomic_write(path: Path, text: str) -> None:
11
+ """Write ``text`` to ``path`` atomically.
12
+
13
+ The content is written to a temporary file in the same directory and then
14
+ moved into place with :func:`os.replace`, so a crash mid-write never leaves
15
+ a partially-written target.
16
+
17
+ :param path: Destination file.
18
+ :param text: Content to write.
19
+ """
20
+ path.parent.mkdir(parents=True, exist_ok=True)
21
+ fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=path.name + ".", suffix=".tmp")
22
+ try:
23
+ with os.fdopen(fd, "w") as handle:
24
+ handle.write(text)
25
+ # mkstemp creates the file 0600; relax it to the conventional file mode
26
+ # (honoring the process umask) so generated config files are readable
27
+ # like the hand-authored sources alongside them.
28
+ umask = os.umask(0)
29
+ os.umask(umask)
30
+ os.chmod(tmp_name, 0o666 & ~umask)
31
+ os.replace(tmp_name, path)
32
+ except BaseException:
33
+ if os.path.exists(tmp_name):
34
+ os.unlink(tmp_name)
35
+ raise
uv_stack/models.py ADDED
@@ -0,0 +1,72 @@
1
+ """Pydantic data models for uv-stack config objects.
2
+
3
+ Models are pure data: they hold no filesystem or subprocess knowledge. The
4
+ ``from_lines`` constructors accept raw file lines and clean them, so callers may
5
+ pass either raw or pre-cleaned input.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Iterable
11
+
12
+ from pydantic import BaseModel, Field
13
+
14
+ from uv_stack.parse import clean_line
15
+
16
+
17
+ def _clean(lines: Iterable[str]) -> list[str]:
18
+ cleaned = (clean_line(line) for line in lines)
19
+ return [line for line in cleaned if line]
20
+
21
+
22
+ class Profile(BaseModel):
23
+ """A reusable package group (``profiles/<name>.in``)."""
24
+
25
+ name: str
26
+ requirements: list[str] = Field(default_factory=list)
27
+
28
+ @classmethod
29
+ def from_lines(cls, name: str, lines: Iterable[str]) -> Profile:
30
+ """Build a profile from raw file lines.
31
+
32
+ :param name: Profile name (file stem).
33
+ :param lines: Raw lines from the ``.in`` file.
34
+ """
35
+ return cls(name=name, requirements=_clean(lines))
36
+
37
+
38
+ class Bundle(BaseModel):
39
+ """A composable recipe (``bundles/<name>.bundle``) of stack tokens."""
40
+
41
+ name: str
42
+ tokens: list[str] = Field(default_factory=list)
43
+
44
+ @classmethod
45
+ def from_lines(cls, name: str, lines: Iterable[str]) -> Bundle:
46
+ """Build a bundle from raw file lines.
47
+
48
+ :param name: Bundle name (file stem).
49
+ :param lines: Raw lines from the ``.bundle`` file.
50
+ """
51
+ return cls(name=name, tokens=_clean(lines))
52
+
53
+
54
+ class EnvConfig(BaseModel):
55
+ """Resolved view of a named environment's source files."""
56
+
57
+ name: str
58
+ python: str = "3.12"
59
+ stack: list[str] = Field(default_factory=list)
60
+ micromamba: list[str] = Field(default_factory=list)
61
+ channels: list[str] = Field(default_factory=list)
62
+
63
+
64
+ class ResolvedStack(BaseModel):
65
+ """The result of resolving a list of stack tokens.
66
+
67
+ ``profiles`` are emitted as ``-r profiles/<name>.in`` references; ``inline``
68
+ holds literal packages, editable installs, and local archive paths.
69
+ """
70
+
71
+ profiles: list[str] = Field(default_factory=list)
72
+ inline: list[str] = Field(default_factory=list)
File without changes
@@ -0,0 +1,61 @@
1
+ """Micromamba environment existence checks and creation/recreation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from uv_stack.commands import micromamba_create, micromamba_python_path, micromamba_remove
6
+ from uv_stack.config import ConfigRoot
7
+ from uv_stack.errors import EnvError
8
+ from uv_stack.runner import Runner
9
+
10
+
11
+ def env_micromamba_exists(config: ConfigRoot, runner: Runner, env_name: str) -> bool:
12
+ """Return whether a micromamba environment named ``env_name`` exists.
13
+
14
+ Probes by running ``python`` inside the env and checking for a usable
15
+ interpreter path.
16
+
17
+ :param config: Configuration root (unused beyond signature symmetry).
18
+ :param runner: Command runner.
19
+ :param env_name: Environment name.
20
+ """
21
+ result = runner.run(micromamba_python_path(env_name), capture=True, check=False)
22
+ return result.returncode == 0 and bool(result.stdout.strip())
23
+
24
+
25
+ def ensure_env(
26
+ config: ConfigRoot,
27
+ runner: Runner,
28
+ env_name: str,
29
+ *,
30
+ create: bool,
31
+ recreate: bool,
32
+ ) -> None:
33
+ """Ensure the micromamba environment is in the desired state.
34
+
35
+ Assumes ``environment.yml`` has already been rendered by the caller.
36
+
37
+ :param config: Configuration root.
38
+ :param runner: Command runner.
39
+ :param env_name: Environment name.
40
+ :param create: Create the env if it is missing.
41
+ :param recreate: Remove (if present) and recreate the env.
42
+ :raises EnvError: If the env is missing and neither ``create`` nor
43
+ ``recreate`` was requested.
44
+ """
45
+ environment_yml = config.env_environment_yml(env_name)
46
+ exists = env_micromamba_exists(config, runner, env_name)
47
+
48
+ if recreate:
49
+ if exists:
50
+ runner.run(micromamba_remove(env_name))
51
+ runner.run(micromamba_create(environment_yml))
52
+ return
53
+
54
+ if not exists:
55
+ if create:
56
+ runner.run(micromamba_create(environment_yml))
57
+ return
58
+ raise EnvError(
59
+ f"Micromamba environment '{env_name}' does not exist.",
60
+ hint=f"Run 'stack create env {env_name}' to create it.",
61
+ )
@@ -0,0 +1,112 @@
1
+ """Detect-only diagnostics for a uv-stack config tree.
2
+
3
+ ``diagnose`` never mutates the filesystem; it returns a list of findings the CLI
4
+ prints with suggested fixes. It flags missing directories, legacy names
5
+ (``*.profiles``, ``profiles.txt``), env-like directories left at the root, and
6
+ envs missing their source files.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+
13
+ from uv_stack.config import ConfigRoot
14
+
15
+ _KNOWN_TOP_LEVEL = {"profiles", "bundles", "envs", "lib"}
16
+
17
+
18
+ @dataclass
19
+ class Finding:
20
+ """A single diagnostic result.
21
+
22
+ :param level: ``"error"`` or ``"warn"``.
23
+ :param message: What was detected.
24
+ :param fix: Optional suggested remediation.
25
+ """
26
+
27
+ level: str
28
+ message: str
29
+ fix: str | None = None
30
+
31
+
32
+ def diagnose(config: ConfigRoot) -> list[Finding]:
33
+ """Inspect the config tree and return findings.
34
+
35
+ :param config: The configuration root to inspect.
36
+ :returns: A list of :class:`Finding` (empty if everything looks correct).
37
+ """
38
+ findings: list[Finding] = []
39
+
40
+ if not config.root.is_dir():
41
+ findings.append(
42
+ Finding(
43
+ "error",
44
+ f"Config root does not exist: {config.root}",
45
+ fix=f"Run 'stack config init' or create {config.root}.",
46
+ )
47
+ )
48
+ return findings
49
+
50
+ for name, directory in (
51
+ ("profiles", config.profiles_dir),
52
+ ("bundles", config.bundles_dir),
53
+ ("envs", config.envs_dir),
54
+ ):
55
+ if not directory.is_dir():
56
+ findings.append(
57
+ Finding(
58
+ "error",
59
+ f"Missing {name} directory: {directory}",
60
+ fix=f"Create {directory} (or run 'stack config init').",
61
+ )
62
+ )
63
+
64
+ # Legacy bundle extension.
65
+ if config.bundles_dir.is_dir():
66
+ for legacy in config.bundles_dir.glob("*.profiles"):
67
+ findings.append(
68
+ Finding(
69
+ "warn",
70
+ f"Legacy bundle file: {legacy}",
71
+ fix=f"Rename to {legacy.with_suffix('.bundle')}.",
72
+ )
73
+ )
74
+
75
+ # Env-like directories left directly under root.
76
+ for child in config.root.iterdir():
77
+ if not child.is_dir() or child.name in _KNOWN_TOP_LEVEL:
78
+ continue
79
+ if (child / "requirements.in").exists() or (child / "environment.yml").exists():
80
+ findings.append(
81
+ Finding(
82
+ "warn",
83
+ f"Env-like directory not under envs/: {child.name}",
84
+ fix=f"Move it: mv {child} {config.envs_dir / child.name}",
85
+ )
86
+ )
87
+
88
+ # Per-env source-file checks.
89
+ if config.envs_dir.is_dir():
90
+ for env_dir in config.envs_dir.iterdir():
91
+ if not env_dir.is_dir():
92
+ continue
93
+ if (env_dir / "profiles.txt").exists():
94
+ findings.append(
95
+ Finding(
96
+ "warn",
97
+ f"Legacy profiles.txt in env '{env_dir.name}'",
98
+ fix=f"Rename {env_dir / 'profiles.txt'} to stack.txt.",
99
+ )
100
+ )
101
+ if (env_dir / "stack.txt").is_file() and not (
102
+ env_dir / "python.txt"
103
+ ).is_file():
104
+ findings.append(
105
+ Finding(
106
+ "warn",
107
+ f"Env '{env_dir.name}' missing python.txt (will default to 3.12)",
108
+ fix=f"Create {env_dir / 'python.txt'}.",
109
+ )
110
+ )
111
+
112
+ return findings
@@ -0,0 +1,26 @@
1
+ """The ``config init`` operation: create the config directory tree.
2
+
3
+ Creates ``profiles/``, ``bundles/``, and ``envs/`` under the config root if they
4
+ are absent. It seeds no profiles or bundles; those are authored by the user.
5
+ Existing directories are left untouched.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+
12
+ from uv_stack.config import ConfigRoot
13
+
14
+
15
+ def init_config_root(config: ConfigRoot) -> list[Path]:
16
+ """Create any missing config directories under the root.
17
+
18
+ :param config: The configuration root to initialize.
19
+ :returns: The directories actually created (absent ones only).
20
+ """
21
+ created: list[Path] = []
22
+ for directory in (config.profiles_dir, config.bundles_dir, config.envs_dir):
23
+ if not directory.is_dir():
24
+ directory.mkdir(parents=True, exist_ok=True)
25
+ created.append(directory)
26
+ return created
@@ -0,0 +1,82 @@
1
+ """The ``project init`` operation: scaffold a uv project from a stack.
2
+
3
+ The resolved stack is flattened (profiles expanded inline) so the project's
4
+ dependencies do not reference files under the config root. Dependencies are
5
+ written to a temp requirements file and added via ``uv add``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import tempfile
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+
14
+ from uv_stack.commands import uv_add, uv_init, uv_sync
15
+ from uv_stack.config import ConfigRoot
16
+ from uv_stack.errors import ConfigError
17
+ from uv_stack.render import render_requirements_flat
18
+ from uv_stack.resolver import Resolver
19
+ from uv_stack.runner import Command, Runner
20
+
21
+
22
+ @dataclass
23
+ class ProjectOptions:
24
+ """Options for ``project init``.
25
+
26
+ :param python: Python version to pin.
27
+ :param name: Optional project name passed to ``uv init``.
28
+ :param no_sync: Add dependencies but skip ``uv sync``.
29
+ :param force: Allow adding to an existing ``pyproject.toml``.
30
+ """
31
+
32
+ python: str = "3.12"
33
+ name: str | None = None
34
+ no_sync: bool = False
35
+ force: bool = False
36
+
37
+
38
+ def init_project(
39
+ config: ConfigRoot,
40
+ runner: Runner,
41
+ tokens: list[str],
42
+ options: ProjectOptions,
43
+ *,
44
+ cwd: Path,
45
+ ) -> None:
46
+ """Initialize a uv project in ``cwd`` from resolved stack ``tokens``.
47
+
48
+ :param config: Configuration root.
49
+ :param runner: Command runner.
50
+ :param tokens: Stack tokens (profiles, bundles, packages).
51
+ :param options: Project options.
52
+ :param cwd: Directory in which to create the project.
53
+ :raises ConfigError: If a ``pyproject.toml`` exists and ``force`` is False.
54
+ """
55
+ pyproject = cwd / "pyproject.toml"
56
+ if pyproject.is_file() and not options.force:
57
+ raise ConfigError(
58
+ "pyproject.toml already exists.",
59
+ hint="Use --force to add to the existing project.",
60
+ )
61
+
62
+ stack = Resolver(config).resolve(tokens)
63
+ flat = render_requirements_flat(stack, config)
64
+
65
+ fd, tmp_name = tempfile.mkstemp(prefix="uv-stack-stack.", suffix=".txt")
66
+ tmp_req = Path(tmp_name)
67
+ try:
68
+ with open(fd, "w") as handle:
69
+ handle.write(flat)
70
+
71
+ if not pyproject.is_file():
72
+ runner.run(_with_cwd(uv_init(options.python, options.name), cwd))
73
+ runner.run(_with_cwd(uv_add(tmp_req), cwd))
74
+ if not options.no_sync:
75
+ runner.run(_with_cwd(uv_sync(), cwd))
76
+ finally:
77
+ if tmp_req.exists():
78
+ tmp_req.unlink()
79
+
80
+
81
+ def _with_cwd(command: Command, cwd: Path) -> Command:
82
+ return Command(command.args, cwd=cwd)