Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e5b702cd73 | |||
| 60de1149ac | |||
| 666e41c87d | |||
| bae86db9fe | |||
| 948c8bd416 | |||
| 35679fdb0f |
@@ -0,0 +1,29 @@
|
||||
name: CI
|
||||
# Run the unit tests and the sanity checks on every push and pull request.
|
||||
# SPEC 2.5 (uv.lock is the source of truth), uv plan item 9.1.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
container: python:3.11
|
||||
steps:
|
||||
- name: Install git for the git tool tests
|
||||
run: apt-get update && apt-get install -y --no-install-recommends git
|
||||
- name: Check out the repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Install uv
|
||||
run: python -m pip install "uv==0.11.26" --retries 10 --timeout 120
|
||||
- name: Sync the locked environment
|
||||
# --locked fails the job when uv.lock is stale (SPEC 2.5).
|
||||
run: uv sync --locked
|
||||
- name: Run the unit tests
|
||||
run: uv run python scripts/run_tests.py
|
||||
- name: Run the sanity checks
|
||||
run: uv run python scripts/run_sanity.py --non-interactive
|
||||
@@ -0,0 +1 @@
|
||||
3.13
|
||||
@@ -1,10 +1,10 @@
|
||||
---
|
||||
name: Fiona-Assistant Development Agent Rules
|
||||
version: 1.12.1
|
||||
version: 1.13.0
|
||||
title: Agents
|
||||
type: summary
|
||||
created: 2025-09-23
|
||||
updated: 2026-11-28
|
||||
updated: 2026-11-29
|
||||
tags: [agents, rules, guidelines, llm, ai]
|
||||
sources: []
|
||||
---
|
||||
@@ -143,52 +143,51 @@ bumps versions (step 5). It skips the test and implementation steps.
|
||||
|
||||
> BEFORE any testing or development work, you MUST load the bootstrap script
|
||||
|
||||
Bootstrap uses [uv](https://docs.astral.sh/uv/). If uv is missing, bootstrap
|
||||
prints the install command and stops. Install uv, then run it again.
|
||||
|
||||
Linux / macOS (bash, must be sourced):
|
||||
|
||||
```bash
|
||||
# Bare minimum - always run this first
|
||||
# Bare minimum - always run this first: uv sync creates .venv
|
||||
# shellcheck source=/dev/null
|
||||
source bootstrap
|
||||
|
||||
# For a specific environment name
|
||||
# Recreate .venv from scratch
|
||||
# shellcheck source=/dev/null
|
||||
source bootstrap --env fiona_env
|
||||
source bootstrap -c
|
||||
|
||||
# With Python version
|
||||
# With a Python version (uv installs it if needed)
|
||||
# shellcheck source=/dev/null
|
||||
source bootstrap --env ENV_NAME --python PYTHON_VERSION
|
||||
source bootstrap --python 3.13.8
|
||||
|
||||
# With cleanup flag
|
||||
# shellcheck source=/dev/null
|
||||
source bootstrap --env <env_name> -c
|
||||
|
||||
# This checkout as a normal package (not editable)
|
||||
# This checkout as a normal package (not editable, no dev group)
|
||||
# shellcheck source=/dev/null
|
||||
source bootstrap --local
|
||||
|
||||
# Current user, no virtual environment
|
||||
# Current user, uv tool install, no virtual environment
|
||||
# shellcheck source=/dev/null
|
||||
source bootstrap --local --no-env
|
||||
source bootstrap --no-env
|
||||
```
|
||||
|
||||
Windows (PowerShell). A virtual-environment install must be
|
||||
dot-sourced. This creates a repo-local venv at `.venvs\<name>` with
|
||||
the Python launcher. It does not install pyenv. `--no-env` skips that
|
||||
venv and may be executed with `-File`. `--local` installs this
|
||||
repository with `pip install .` (not editable, no `dev` extra).
|
||||
`--no-env` installs with `pip install --user`, so `fiona-assistant`
|
||||
runs without activating an environment. The two flags combine.
|
||||
dot-sourced. It creates `.venv` in the checkout with `uv sync`.
|
||||
`--no-env` installs a uv tool and may be executed with `-File`.
|
||||
`--local` installs this repository non-editable, without the `dev` group.
|
||||
|
||||
```powershell
|
||||
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
|
||||
. .\bootstrap.ps1
|
||||
. .\bootstrap.ps1 --env fiona_env
|
||||
. .\bootstrap.ps1 --env <env_name> --python <version>
|
||||
. .\bootstrap.ps1 --env <env_name> -c
|
||||
. .\bootstrap.ps1 -c
|
||||
. .\bootstrap.ps1 --python <version>
|
||||
. .\bootstrap.ps1 --local
|
||||
powershell -ExecutionPolicy Bypass -File .\bootstrap.ps1 --local --no-env
|
||||
```
|
||||
|
||||
Plain uv also works in the checkout: `uv sync`, then `uv run <command>`
|
||||
(for example `uv run python scripts/run_tests.py`). `--env` is accepted
|
||||
for one release and ignored; the environment is always `.venv`.
|
||||
|
||||
**Rationale**: The bootstrap script sets up the Python virtual environment,
|
||||
installs dependencies, and ensures a consistent development environment.
|
||||
All testing and development MUST happen within this environment.
|
||||
@@ -265,8 +264,9 @@ fiona-assistant/
|
||||
│ ├── run_sanity.py # Launcher for fiona.run_sanity
|
||||
│ ├── settings_dev.json # Development settings
|
||||
│ ├── utils.sh # Shell utilities
|
||||
│ └── install_packages.sh # Dependency installer
|
||||
├── pyproject.toml # Project configuration
|
||||
├── uv.lock # Locked dependencies (uv sync --locked)
|
||||
├── .python-version # Default interpreter for uv (3.13)
|
||||
├── bootstrap # Environment setup (bash; source it)
|
||||
├── bootstrap.ps1 # Environment setup (PowerShell; dot-source it)
|
||||
└── README.md # Project documentation
|
||||
@@ -546,7 +546,7 @@ These rules **CAN** be overridden by:
|
||||
| Development | project agent rule 2.1, in order |
|
||||
| Any Python work | Load the python-tdd skill (`phronesis show python-tdd`) |
|
||||
| Before testing | `source bootstrap` (Windows: `. .\bootstrap.ps1`) |
|
||||
| Local install, no venv | `bootstrap --local --no-env` |
|
||||
| Local install, no venv | `bootstrap --no-env` |
|
||||
| Step 1 | Write or check [SPEC](./SPEC.md) |
|
||||
| Step 2 and 3 | Failing tests, then the smallest change |
|
||||
| Step 4 | Re-read the spec; tests and sanity pass |
|
||||
|
||||
+51
-2
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: changelog
|
||||
version: 1.5.0
|
||||
version: 1.8.0
|
||||
title: Changelog
|
||||
created: 2026-10-08
|
||||
updated: 2026-11-28
|
||||
updated: 2026-12-01
|
||||
type: summary
|
||||
---
|
||||
|
||||
@@ -13,6 +13,55 @@ Revisions of [SPEC](./SPEC.md), newest first. Each entry names the
|
||||
requirements it adds or changes. "Unbuilt" means the requirement is
|
||||
specified and marked `NOT_IMPLEMENTED`.
|
||||
|
||||
## 1.28.0 - 2026-12-01
|
||||
|
||||
- `fiona-assistant --update [--dry-run]` upgrades fiona-assistant with the
|
||||
tool that installed it (*7.24.1.* to *7.24.6.*), the same design as
|
||||
daedalus SPEC item 3.15: a checkout prints the `git pull` hint, uv and
|
||||
pipx installs run their upgrade command, and other installs print the pip
|
||||
command. On Windows the run stays in the foreground, a TLS `invalid peer
|
||||
certificate` failure is retried with `--system-certs`, and uv's
|
||||
locked-launcher error after a successful package upgrade counts as a
|
||||
success. `--dry-run` without `--init` or `--update` names both. Package
|
||||
version 1.23.0.
|
||||
|
||||
## 1.27.0 - 2026-11-30
|
||||
|
||||
- `fiona-assistant --init` registers tab completion for the command
|
||||
(*7.23.1.* to *7.23.14.*). It uses argcomplete (`argcomplete>=3.3`, a
|
||||
runtime dependency) and follows the phronesis pattern:
|
||||
- On bash, one managed `eval` block in `~/.bashrc` (`--bashrc PATH`
|
||||
overrides). On Windows, one `Invoke-Expression` block in `$PROFILE`
|
||||
(`--profile PATH` overrides); a `Restricted` execution policy prints
|
||||
a hint and is never changed (*7.23.7.* to *7.23.10.*).
|
||||
- `--dry-run` and idempotence (`already enabled`) as in phronesis;
|
||||
exit 3 when the register script or the PowerShell profile cannot be
|
||||
found (*7.23.4.*, *7.23.9.*).
|
||||
- Only `fiona-assistant` gets completion; `librarian`, `mdoctor`, and
|
||||
`html-js-lint` do not (*7.23.13.*).
|
||||
- `bootstrap` and `bootstrap.ps1` print `fiona-assistant --init` as the
|
||||
tab-completion step (*7.23.14.*).
|
||||
|
||||
## 1.26.0 - 2026-11-29
|
||||
|
||||
- uv replaces pyenv and pip for development and for publishing
|
||||
(uv plan for fiona-assistant, phases 1 to 5):
|
||||
- The development environment is `.venv`, made by `uv sync` from the
|
||||
committed `uv.lock` (*2.4.*, *2.5.*). The `dev` group replaces the
|
||||
`dev` extra, which stays for one release (*2.6.*).
|
||||
- `.python-version` pins 3.13. `requires-python` is `>=3.11.4`, the
|
||||
floor set by daedalus-tools (*2.7.*).
|
||||
- Bootstrap (bash and PowerShell) runs uv and no longer builds Python,
|
||||
uses pyenv, or passes `--break-system-packages`. `--env` is accepted
|
||||
for one release with a warning; `--pyenv` is refused (*7.21.1.* to
|
||||
*7.21.10.*).
|
||||
- `--no-env` installs a uv tool that also exposes `phronesis`.
|
||||
- `scripts/publish.py` builds with `uv build` and refuses, rather than
|
||||
installs, when uv or twine is missing (*4.9.1.*, *4.9.7.*).
|
||||
- `scripts/install_packages.sh` is removed; nothing called it.
|
||||
- `.gitea/workflows/ci.yml` runs `uv sync --locked`, the unit tests,
|
||||
and the sanity checks.
|
||||
|
||||
## 1.25.0 - 2026-11-28
|
||||
|
||||
- The publish runner moves to section 4.9 and gains release guards
|
||||
|
||||
@@ -14,7 +14,7 @@ The result: the agent spends its tokens on reading and writing, not on
|
||||
listing files, chasing broken links, or reformatting tables.
|
||||
|
||||
```bash
|
||||
python -m pip install fiona-assistant
|
||||
uv tool install fiona-assistant --with-executables-from phronesis
|
||||
fiona-assistant wiki init my-wiki
|
||||
cd my-wiki || exit
|
||||
fiona-assistant wiki ingest https://example.com/article.html
|
||||
@@ -165,12 +165,43 @@ date, with optional section numbering (`--sectionized`).
|
||||
|
||||
### 1. Install
|
||||
|
||||
Requires Python 3.11 or newer.
|
||||
Requires Python 3.11.4 or newer. [uv](https://docs.astral.sh/uv/)
|
||||
installs Fiona in its own environment and fetches Python when needed.
|
||||
|
||||
```bash
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh # or: winget install astral-sh.uv
|
||||
uv tool install fiona-assistant --with-executables-from phronesis
|
||||
uv tool update-shell # once: puts uv's bin directory on PATH
|
||||
```
|
||||
|
||||
`--with-executables-from phronesis` also puts `phronesis` on `PATH`, so
|
||||
`phronesis show fiona` works. Upgrade with `fiona-assistant --update`: it
|
||||
runs `uv tool upgrade fiona-assistant` (or the pipx command), prints the old
|
||||
and new version, and on Windows retries with `--system-certs` when a proxy's
|
||||
TLS certificate is not trusted (SPEC 7.24). `--update --dry-run` only prints
|
||||
the command. Wikis are not touched; `wiki check-update` and `wiki update`
|
||||
handle those.
|
||||
|
||||
With pip instead (no isolation, `phronesis` is installed with it):
|
||||
|
||||
```bash
|
||||
python -m pip install fiona-assistant
|
||||
```
|
||||
|
||||
Tab completion for `fiona-assistant` is one command, run once. It adds a
|
||||
managed block to your shell profile, and a re-run reports `already enabled`:
|
||||
|
||||
```bash
|
||||
fiona-assistant --init # bash: ~/.bashrc (--bashrc PATH overrides)
|
||||
```
|
||||
|
||||
```powershell
|
||||
fiona-assistant --init # PowerShell: $PROFILE (--profile PATH overrides)
|
||||
```
|
||||
|
||||
`--dry-run` prints the block without writing it. Open a new shell (or
|
||||
run `. $PROFILE` in PowerShell) to use it.
|
||||
|
||||
### 2. Create a wiki
|
||||
|
||||
```bash
|
||||
@@ -208,8 +239,8 @@ fiona-assistant git save --description "ingest meeting notes"
|
||||
- Run the loop: `housekeeping`, fix the style violations it lists, then
|
||||
refine the page and set `status: refined`.
|
||||
- `LOG_LEVEL=ERROR` hides diagnostics until the logging settings ship.
|
||||
- `fiona-assistant --version` or `pip show fiona-assistant` prints the
|
||||
installed version.
|
||||
- `fiona-assistant --version` or `uv tool list` (or `pip show
|
||||
fiona-assistant` after a pip install) prints the installed version.
|
||||
|
||||
### On Windows
|
||||
|
||||
@@ -372,6 +403,8 @@ Planned work, tracked with requirements and acceptance criteria in
|
||||
### Set up
|
||||
|
||||
Clone the repository and load the environment with the bootstrap script.
|
||||
Bootstrap needs [uv](https://docs.astral.sh/uv/) on `PATH`. It stops with
|
||||
the install command when uv is missing, and it never installs uv itself.
|
||||
|
||||
Linux and macOS:
|
||||
|
||||
@@ -379,29 +412,33 @@ Linux and macOS:
|
||||
git clone REPOSITORY_URL
|
||||
cd fiona-assistant || exit
|
||||
# shellcheck source=/dev/null
|
||||
source bootstrap --env fiona_env -c
|
||||
source bootstrap -c
|
||||
```
|
||||
|
||||
Windows (PowerShell):
|
||||
|
||||
```powershell
|
||||
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
|
||||
. .\bootstrap.ps1 --env fiona_env -c
|
||||
. .\bootstrap.ps1 -c
|
||||
```
|
||||
|
||||
The default install is editable (`pip install -e ".[dev]"`). On Windows
|
||||
the environment lives in `.venvs\fiona_env`.
|
||||
`uv sync` creates `.venv` in the checkout with the package editable and
|
||||
the `dev` group, from the committed `uv.lock`. The Python version comes
|
||||
from `.python-version` (3.13); `--python 3.13.8` overrides it. `--env` is
|
||||
accepted for one release and ignored, because the environment is always
|
||||
`.venv`.
|
||||
|
||||
### Other install modes
|
||||
|
||||
| Goal | Bash | PowerShell |
|
||||
| --- | --- | --- |
|
||||
| Install this checkout as a normal package | `source bootstrap --local` | `. .\bootstrap.ps1 --local` |
|
||||
| Same as `pip install fiona-assistant`, no venv | `source bootstrap --local --no-env` | `powershell -ExecutionPolicy Bypass -File .\bootstrap.ps1 --local --no-env` |
|
||||
| Install this checkout as a normal package, no dev group | `source bootstrap --local` | `. .\bootstrap.ps1 --local` |
|
||||
| Install as a uv tool, no venv to activate | `source bootstrap --no-env` | `powershell -ExecutionPolicy Bypass -File .\bootstrap.ps1 --no-env` |
|
||||
|
||||
`--local --no-env` runs `python -m pip install --user .`. If
|
||||
`fiona-assistant` is not found afterwards, add the user scripts
|
||||
directory printed by bootstrap to `PATH`.
|
||||
`--no-env` runs `uv tool install --editable .`. If `fiona-assistant` is
|
||||
not found afterwards, run `uv tool update-shell` and open a new shell.
|
||||
|
||||
Plain uv works too: `uv sync` to set up, then `uv run python scripts/run_tests.py`.
|
||||
|
||||
### Test and check
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: Fiona-Assistant Specification
|
||||
version: 1.25.0
|
||||
version: 1.28.0
|
||||
title: Project Spec Sheet
|
||||
created: 2026-09-23
|
||||
updated: 2026-11-28
|
||||
updated: 2026-12-01
|
||||
type: summary
|
||||
---
|
||||
|
||||
@@ -79,6 +79,8 @@ type: summary
|
||||
- [7.20. Wiki Root Discovery](#720-wiki-root-discovery)
|
||||
- [7.21. Bootstrap install modes](#721-bootstrap-install-modes)
|
||||
- [7.22. Markdown Spell Check](#722-markdown-spell-check)
|
||||
- [7.23. Tab Completion Init](#723-tab-completion-init)
|
||||
- [7.24. Self-Update](#724-self-update)
|
||||
- [Appendix A. Non-Goals](#appendix-a-non-goals)
|
||||
- [Appendix B. Priority Order](#appendix-b-priority-order)
|
||||
- [Appendix C. Open Questions](#appendix-c-open-questions)
|
||||
@@ -281,11 +283,12 @@ These apply to every feature.
|
||||
|
||||
> Status: Partially Implemented
|
||||
|
||||
Python `>= 3.11` (also 3.12 and 3.13). The default development
|
||||
install from the repository root is `pip install -e ".[dev]"`.
|
||||
`bootstrap --local` installs the same tree as a normal package
|
||||
(`pip install .`). Section 7.21 defines those modes. The build
|
||||
requires setuptools 61 or newer.
|
||||
Python `>= 3.11.4` (also 3.12 and 3.13). The floor is set by
|
||||
daedalus-tools (*3.5.1.*), which needs 3.11.4. The default development
|
||||
install from the repository root is `uv sync`, which creates `.venv`
|
||||
from `uv.lock` (*2.5.*). `bootstrap --local` installs the same tree as a
|
||||
normal package (`uv sync --no-editable --no-dev`). Section 7.21 defines
|
||||
those modes. The build requires setuptools 61 or newer.
|
||||
|
||||
Runtime dependencies:
|
||||
|
||||
@@ -295,9 +298,11 @@ Runtime dependencies:
|
||||
| pyyaml | 6.0.3 |
|
||||
| GitPython | 3.1.0 |
|
||||
| phronesis | 0.16.0 (*3.4.1.*) |
|
||||
| argcomplete | 3.3 (*7.23.2.*) |
|
||||
|
||||
Development extras: `pytest>=7.0`, `pytest-cov>=4.0`, `pytest-mock`,
|
||||
`pylint`. `html5lib`, `esprima`, `pymarkdownlnt`, and `ruff` come with
|
||||
Development group `dev` (*2.5.*): `pytest>=7.0`, `pytest-cov>=4.0`,
|
||||
`pytest-mock`, `pylint`, `build`, `twine`, `ruff`. The `dev` extra mirrors
|
||||
it for one release (*2.6.*). `html5lib`, `esprima`, `pymarkdownlnt`, and `ruff` come with
|
||||
`daedalus-tools` (*3.5.4.*). `beautifulsoup4`, `markdownify`, and `pypdf` become
|
||||
runtime dependencies when section 7.1.5 is implemented.
|
||||
`shellcheck-py` becomes one with section 7.9 (*7.9.4.*), and
|
||||
@@ -338,7 +343,7 @@ stdout. Package loggers set their level explicitly because
|
||||
pymarkdown resets the root logger mid-run.
|
||||
|
||||
- *2.1.* The three console scripts above are installed by
|
||||
`pip install -e .`.
|
||||
`uv sync` (editable) or `uv tool install fiona-assistant`.
|
||||
- *acceptance*: `fiona-assistant` with no arguments prints help and
|
||||
exits 0.
|
||||
- *2.2.* `html-js-lint` is an installed script with section 7.15.
|
||||
@@ -365,6 +370,21 @@ pymarkdown resets the root logger mid-run.
|
||||
- *acceptance*: `librarian move --dry-run a.md b.md` and
|
||||
`fiona-assistant librarian move --dry-run a.md b.md` print the
|
||||
same stdout.
|
||||
- *2.5.* Development dependencies live in the `[dependency-groups]`
|
||||
table `dev` of `pyproject.toml`. `uv.lock` is committed and
|
||||
`uv sync --locked` fails when it is stale.
|
||||
- *acceptance*: `uv sync --locked` succeeds from a clean clone and
|
||||
`tests/test_packaging.py` passes. `.gitea/workflows/ci.yml` runs
|
||||
`uv sync --locked`, then the unit tests and the sanity checks
|
||||
under `uv run` (`tests/test_packaging.py::TestCi`).
|
||||
- *2.6.* The `[project.optional-dependencies] dev` extra lists the same
|
||||
packages as the `dev` group for one release, so
|
||||
`pip install -e ".[dev]"` keeps working. The next minor release
|
||||
removes the extra.
|
||||
- *acceptance*: `tests/test_packaging.py` fails when the extra and
|
||||
the group differ.
|
||||
- *2.7.* `.python-version` pins `3.13`. `requires-python` is `>=3.11.4`.
|
||||
- *acceptance*: `tests/test_packaging.py` reads both values.
|
||||
|
||||
---
|
||||
|
||||
@@ -1203,7 +1223,7 @@ prints one `Error: <reason>` line on stderr and exits 1, before any
|
||||
build or upload command runs.
|
||||
|
||||
- *4.9.1.* Without `--upload`, publish removes `dist/`, `build/`, and
|
||||
`src/*.egg-info`, runs `python -m build`, then `twine check` on the
|
||||
`src/*.egg-info`, runs `uv build` (sdist, then wheel), then `twine check` on the
|
||||
new artifacts. It uploads nothing and exits 0.
|
||||
- *acceptance*: `tests/test_publish.py::TestDefaultRun` passes.
|
||||
- *4.9.2.* Publish refuses when `[project] dependencies` in
|
||||
@@ -1228,6 +1248,13 @@ build or upload command runs.
|
||||
`twine upload --repository <repository>` on the new artifacts.
|
||||
Credentials come from `~/.pypirc` or the twine prompt.
|
||||
- *acceptance*: `tests/test_publish.py::TestUpload` passes.
|
||||
- *4.9.7.* Publish installs nothing. A missing `uv` or `twine` is a
|
||||
refusal that names `uv sync` in the checkout as the fix, and exits 1
|
||||
before any build or upload command runs. The build tool is `uv build`,
|
||||
not `python -m build`.
|
||||
- *acceptance*: `tests/test_publish.py::TestMissingTools` passes, and no
|
||||
test command in `tests/test_publish.py` contains `pip` or
|
||||
`--break-system-packages`.
|
||||
|
||||
## 5. Settings Schema
|
||||
|
||||
@@ -4235,39 +4262,41 @@ not.
|
||||
|
||||
### 7.21. Bootstrap install modes
|
||||
|
||||
> Status: Implemented
|
||||
> Status: Partially Implemented
|
||||
|
||||
`bootstrap` (bash, sourced) and `bootstrap.ps1` (PowerShell) prepare
|
||||
a Python environment and install this repository. With no install
|
||||
flag, both create or reuse a virtual environment and run
|
||||
`python -m pip install -e ".[dev]"`. `scripts/bootstrap_install.py`
|
||||
is the pip-argument source both scripts call.
|
||||
a Python environment with [uv](https://docs.astral.sh/uv/) and install
|
||||
this repository. Neither script uses pip, pyenv, or
|
||||
`--break-system-packages`. With no install flag, both run `uv sync`,
|
||||
which creates `.venv` in the checkout and installs the package
|
||||
editable with the `dev` group from `uv.lock`. `scripts/bootstrap_install.py`
|
||||
prints the uv arguments both scripts call, one per line.
|
||||
|
||||
- *7.21.1.* `--local` installs this repository as a normal package.
|
||||
The pip arguments are `install` and `.`. They do not include `-e`
|
||||
and they do not include the `dev` extra.
|
||||
- *acceptance*: `pip_install_args(local=True, no_env=False)` is
|
||||
`["install", "."]`.
|
||||
- *7.21.2.* `--no-env` does not create or activate a virtual
|
||||
environment. The install adds `--user`, so the console scripts
|
||||
land in the user scripts directory and run without activating an
|
||||
environment.
|
||||
- *acceptance*: `pip_install_args(local=False, no_env=True)`
|
||||
contains `--user`. PowerShell skips virtual environment creation
|
||||
when `$NoEnv` is set. Bash skips it when `NO_ENV` is `true`.
|
||||
- *7.21.3.* `--local` and `--no-env` combine. The install is
|
||||
`install`, `--user`, and `.`, with no `-e`.
|
||||
- *acceptance*: `pip_install_args(local=True, no_env=True)` is
|
||||
`["install", "--user", "."]`.
|
||||
- *7.21.4.* Neither flag keeps the default: `-e` and `.[dev]`, and
|
||||
no `--user`.
|
||||
- *acceptance*: `pip_install_args(local=False, no_env=False)` is
|
||||
`["install", "-e", ".[dev]"]`.
|
||||
- *7.21.5.* Bash adds `--break-system-packages` on every install.
|
||||
PowerShell does not.
|
||||
- *acceptance*: `break_system_packages=True` inserts that flag
|
||||
after `--user` when both are set, and after `install` when
|
||||
`--user` is absent.
|
||||
- *7.21.1.* `--local` installs this repository as a normal package
|
||||
in `.venv`: `uv sync --no-editable --no-dev`. The `dev` group is not
|
||||
installed.
|
||||
- *acceptance*: `uv_install_args(local=True, no_env=False)` is
|
||||
`["sync", "--no-editable", "--no-dev"]`.
|
||||
- *7.21.2.* `--no-env` does not create or activate `.venv`. The
|
||||
install is a uv tool, so `fiona-assistant`, `librarian`, `mdoctor`,
|
||||
`html-js-lint`, and `phronesis` run from `PATH` with no activation:
|
||||
`uv tool install --force --editable . --with-executables-from phronesis`.
|
||||
- *acceptance*: `uv_install_args(local=False, no_env=True)` is
|
||||
`["tool", "install", "--force", "--editable", ".",
|
||||
"--with-executables-from", "phronesis"]`.
|
||||
- *7.21.3.* `--local` and `--no-env` combine. The tool install is not
|
||||
editable: `["tool", "install", "--force", ".",
|
||||
"--with-executables-from", "phronesis"]`.
|
||||
- *acceptance*: `uv_install_args(local=True, no_env=True)` omits
|
||||
`--editable`.
|
||||
- *7.21.4.* Neither flag keeps the default: `["sync"]`, editable with
|
||||
the `dev` group.
|
||||
- *acceptance*: `uv_install_args(local=False, no_env=False)` is
|
||||
`["sync"]`.
|
||||
- *7.21.5.* No bootstrap path passes `--break-system-packages`, runs
|
||||
`pip`, or installs pyenv. uv never writes into the system Python.
|
||||
- *acceptance*: neither script text contains `break-system-packages`
|
||||
or `pyenv`.
|
||||
- *7.21.6.* A virtual-environment install on PowerShell must be
|
||||
dot-sourced so the environment stays active. `--no-env` may be
|
||||
executed with `-File`, because there is no environment to keep
|
||||
@@ -4276,6 +4305,25 @@ is the pip-argument source both scripts call.
|
||||
`--local` is used without `--no-env` and the script is not
|
||||
dot-sourced. The message does not call `--local` an unknown
|
||||
option.
|
||||
- *7.21.7.* `--python X.Y[.Z]` runs `uv python install X.Y[.Z]` and
|
||||
passes `--python X.Y[.Z]` to the uv install. Without it, uv reads
|
||||
`.python-version` (`3.13`).
|
||||
- *acceptance*: `uv_install_args(local=False, no_env=False,
|
||||
python="3.13.8")` is `["sync", "--python", "3.13.8"]`.
|
||||
- *7.21.8.* `-c` / `--clean` deletes `.venv` before `uv sync`. With
|
||||
`--no-env`, `--force` replaces any earlier tool install, so the flag
|
||||
has no effect there.
|
||||
- *acceptance*: `bootstrap --clean` removes `.venv` before syncing.
|
||||
- *7.21.9.* When `uv` is not on `PATH`, bootstrap prints the official
|
||||
install command and stops with a nonzero exit. It does not download
|
||||
or run an installer.
|
||||
- *acceptance*: with `uv` absent from `PATH`, bootstrap prints
|
||||
`astral.sh/uv` and returns 1.
|
||||
- *7.21.10.* `--env NAME` is accepted for one release. It prints a
|
||||
warning that the environment is always `.venv` and ignores the name.
|
||||
`--pyenv` is refused with an error.
|
||||
- *acceptance*: `source bootstrap --env x` warns and still creates
|
||||
`.venv`; `source bootstrap --pyenv` exits 1.
|
||||
|
||||
### 7.22. Markdown Spell Check
|
||||
|
||||
@@ -4329,6 +4377,183 @@ built.
|
||||
- *acceptance*: The `Results:` tables of `wiki sanity` and
|
||||
`run_sanity.py` have no spelling row.
|
||||
|
||||
### 7.23. Tab Completion Init
|
||||
|
||||
> Status: Implemented
|
||||
|
||||
`fiona-assistant --init` registers argcomplete tab completion for the
|
||||
`fiona-assistant` command, so that `fiona-assistant <Tab>` completes
|
||||
subcommands and `fiona-assistant wiki <Tab>` completes their flags. It
|
||||
follows the phronesis pattern (phronesis SPEC section 13), with the
|
||||
Windows PowerShell form supported from the start. Installing the
|
||||
package never touches a shell; the one-time registration is this
|
||||
command.
|
||||
|
||||
- *7.23.1.* `fiona-assistant --init [--bashrc PATH |
|
||||
--profile PATH] [--dry-run]` performs the registration. `--init` runs
|
||||
and exits before any other dispatch, after `--version`. `--bashrc`,
|
||||
`--profile`, or `--dry-run` without `--init` exits 2 with a usage
|
||||
error on stderr that names `--init`.
|
||||
- *acceptance*: `fiona-assistant --dry-run` exits 2 and its stderr
|
||||
contains `--init`.
|
||||
- *7.23.2.* Completion runs through argcomplete.
|
||||
`src/fiona/__main__.py` calls `argcomplete.autocomplete(parser)` on
|
||||
the root parser before `parse_args`, and carries the
|
||||
`# PYTHON_ARGCOMPLETE_OK` marker within its first 1024 bytes.
|
||||
`argcomplete>=3.3` is a runtime dependency (the runtime table in
|
||||
section 2).
|
||||
- *acceptance*: With `_ARGCOMPLETE=1` set and the completion line
|
||||
`fiona-assistant wiki` with the cursor after a trailing space, the
|
||||
candidates include `init` and `update`.
|
||||
- *7.23.3.* On posix (`os.name == "posix"`) the
|
||||
managed block is one bash line between the markers
|
||||
`# BEGIN fiona-assistant init: argcomplete` and
|
||||
`# END fiona-assistant init: argcomplete`:
|
||||
`eval "$('<path to register-python-argcomplete>' fiona-assistant)"`.
|
||||
- *acceptance*: The block text contains the two markers and the
|
||||
eval line, and no other command name.
|
||||
- *7.23.4.* On posix, `register-python-argcomplete`
|
||||
is located beside `sys.executable` first, then on `PATH` via
|
||||
`shutil.which`. When neither finds it, an error names the interpreter
|
||||
path on stderr and the run exits 3.
|
||||
- *acceptance*: With the script absent from both places, `--init`
|
||||
exits 3 and writes no file.
|
||||
- *7.23.5.* On posix the target is `--bashrc PATH`,
|
||||
default `~/.bashrc`. Existing content is kept verbatim; the block is
|
||||
appended, with one blank line before it when the file is non-empty.
|
||||
A target that already holds the begin marker prints
|
||||
`already enabled`, writes nothing, and exits 0. The registration
|
||||
prints the target and `exec bash` (or a new shell) as the way to
|
||||
activate it.
|
||||
- *acceptance*: Running `--init` twice leaves the file unchanged the
|
||||
second time and prints `already enabled`.
|
||||
- *7.23.6.* `--dry-run` prints the block and the
|
||||
target, and creates or appends nothing. An already-enabled dry run
|
||||
prints the `already enabled` line instead.
|
||||
- *acceptance*: A dry run leaves a missing target file missing.
|
||||
- *7.23.7.* On Windows (`os.name == "nt"`) the managed
|
||||
block is:
|
||||
|
||||
```text
|
||||
# BEGIN fiona-assistant init: argcomplete
|
||||
& '<path to register-python-argcomplete.exe>' --shell powershell fiona-assistant | Out-String | Invoke-Expression
|
||||
# END fiona-assistant init: argcomplete
|
||||
```
|
||||
|
||||
- *acceptance*: The block text contains the `Invoke-Expression` line
|
||||
with the `--shell powershell fiona-assistant` arguments.
|
||||
- *7.23.8.* On Windows `register-python-argcomplete.exe`
|
||||
is located the way item 7.23.4 locates it, with the `.exe` name. The
|
||||
interpreter's `Scripts` folder is the first place looked at.
|
||||
- *acceptance*: With the `.exe` beside the faked `sys.executable`, the
|
||||
lookup returns that path.
|
||||
- *7.23.9.* On Windows the target is `--profile PATH`
|
||||
when given. Otherwise it is `$PROFILE` (CurrentUserCurrentHost),
|
||||
asked of `pwsh -NoProfile -Command $PROFILE`, falling back to
|
||||
`powershell`, so OneDrive-redirected Documents are honored. When
|
||||
neither answers, an error on stderr names `--profile` and the run
|
||||
exits 3. A missing profile file and its folder are created on
|
||||
registering, never on a dry run.
|
||||
- *acceptance*: With the lookup faked to a path under a missing
|
||||
folder, `--init` creates the folder and the file.
|
||||
- *7.23.10.* On Windows, when registering, the command
|
||||
reads the execution policy with
|
||||
`powershell -NoProfile -Command Get-ExecutionPolicy`. When it is
|
||||
`Restricted`, the command prints
|
||||
`Set-ExecutionPolicy -Scope CurrentUser RemoteSigned` as a hint and
|
||||
changes no policy. A probe that fails is ignored.
|
||||
- *acceptance*: A faked `Restricted` answer prints the hint and leaves
|
||||
the profile written; a faked failed probe exits 0.
|
||||
- *7.23.11.* `--bashrc` on Windows and `--profile` on
|
||||
posix exit 2 with a usage error on stderr that names the flag for the
|
||||
platform.
|
||||
- *acceptance*: `--init --profile x` on posix exits 2 and names
|
||||
`--bashrc` on stderr.
|
||||
- *7.23.12.* Only the target file is written. The
|
||||
PowerShell probes of items 7.23.9 and 7.23.10 only read. No package
|
||||
is installed and no system file is touched.
|
||||
- *acceptance*: A run with `--init` changes no file other than the
|
||||
target.
|
||||
- *7.23.13.* `fiona-assistant` is the only command
|
||||
that gets completion from `--init`. The `librarian`, `mdoctor`, and
|
||||
`html-js-lint` console scripts get none in this section, so their
|
||||
completion, if wanted, is a later section.
|
||||
- *acceptance*: The managed block names `fiona-assistant` and no
|
||||
other command.
|
||||
- *7.23.14.* `bootstrap` and `bootstrap.ps1` print
|
||||
`fiona-assistant --init` as the tab-completion step after the
|
||||
verification lines they already print.
|
||||
- *acceptance*: Both scripts contain the text `fiona-assistant --init`.
|
||||
|
||||
### 7.24. Self-Update
|
||||
|
||||
> Status: Implemented
|
||||
|
||||
`fiona-assistant --update` upgrades fiona-assistant itself with the
|
||||
tool that installed it. It is the same design as daedalus SPEC item
|
||||
3.15 and phronesis SPEC item 3.12, which were verified on Windows
|
||||
behind a TLS-inspecting proxy with daedalus 0.39.11. One upgrade covers
|
||||
every console script of the package (`fiona-assistant`, `librarian`,
|
||||
`mdoctor`, `html-js-lint`) and the pinned `phronesis` and
|
||||
`daedalus-tools` inside the tool's own environment. `wiki update` is
|
||||
unrelated: it updates a wiki's files.
|
||||
|
||||
- *7.24.1.* `fiona-assistant --update [--dry-run]` takes no subcommand
|
||||
and no other root option. `--update` with a subcommand, `--init`,
|
||||
`--bashrc`, or `--profile` exits 2 with a usage error that names
|
||||
`--update`. `--dry-run` without `--init` or `--update` exits 2 and
|
||||
names both.
|
||||
- *acceptance*: `fiona-assistant --update wiki` and
|
||||
`fiona-assistant --dry-run` exit 2.
|
||||
- *7.24.2.* Detection, first match wins, from `sys.prefix` and the
|
||||
`direct_url.json` of the `fiona-assistant` distribution. A checkout
|
||||
(`dir_info.editable`, or a `file://` URL) prints `fiona-assistant
|
||||
runs from a checkout at <path>; update it with git pull`, runs
|
||||
nothing, and exits 0. Under `uv tool dir` the command is `uv tool
|
||||
upgrade fiona-assistant`. Under pipx's `PIPX_LOCAL_VENVS` it is
|
||||
`pipx upgrade fiona-assistant`, or `pipx install --force <url>` for
|
||||
a Git install. Anything else prints the `pip install --upgrade
|
||||
fiona-assistant` command and exits 3.
|
||||
- *acceptance*: tests with faked `sys.prefix` and `direct_url.json`
|
||||
pick each method.
|
||||
- *7.24.3.* The upgrade tool missing from `PATH` prints which tool is
|
||||
needed and exits 3. `--dry-run` prints `method: <method>` and
|
||||
`would run: <command>` and runs nothing.
|
||||
- *acceptance*: `--update --dry-run` runs no command.
|
||||
- *7.24.4.* Output: `fiona-assistant <old version>`, `running:
|
||||
<command>`, then the command's own output. After success a fresh
|
||||
`python -m fiona --version` reads the new version, and one of
|
||||
`fiona-assistant updated <old> -> <new>` or `fiona-assistant
|
||||
<version> is already up to date` is printed, followed by `wikis are
|
||||
not updated; run 'fiona-assistant wiki check-update' in each wiki`.
|
||||
Exit 0. A failed command prints `upgrade failed with exit <code>;
|
||||
run it by hand: <command>` and exits 4.
|
||||
- *acceptance*: a faked runner shows both version lines and the
|
||||
hint.
|
||||
- *7.24.5.* Windows: the command runs in the foreground in the same
|
||||
terminal; its output is shown as it runs and also kept. uv's
|
||||
`fiona-assistant.exe` keeps its own file open, so uv upgrades the
|
||||
package, then fails with `Failed to install entrypoint` and `os
|
||||
error 32`. When the last command fails with both marks and a fresh
|
||||
`--version` differs from the old one, the run counts as a success:
|
||||
`note: uv could not replace the running fiona-assistant.exe; the
|
||||
package is updated and the current launcher keeps working`, then
|
||||
the item 7.24.4 lines, exit 0. A release that changes the
|
||||
`fiona.__main__:main` entry point or the tool's Python says in its
|
||||
CHANGELOG to run `uv tool upgrade fiona-assistant` with
|
||||
fiona-assistant closed.
|
||||
- *acceptance*: a faked run with that output and a new version
|
||||
exits 0 and prints the note.
|
||||
- *7.24.6.* Windows, TLS retry: when a `uv` command fails with
|
||||
`invalid peer certificate` in its output, print `warning: uv could
|
||||
not verify a TLS certificate; retrying with --system-certs (the
|
||||
Windows certificate store)` and run it once more with
|
||||
`--system-certs` appended. A command that already has the flag, and
|
||||
pipx commands, are not retried. A failed retry prints the retried
|
||||
command.
|
||||
- *acceptance*: a faked certificate failure runs the command twice,
|
||||
the second time with `--system-certs`.
|
||||
|
||||
## Appendix A. Non-Goals
|
||||
|
||||
- *A.1.* No LLM or network API inside Fiona-Assistant. The tools are
|
||||
|
||||
@@ -1,47 +1,40 @@
|
||||
#!/bin/bash
|
||||
# version: 1.0.0
|
||||
# Modified by AI/LLM: 2026-09-30 - --local and --no-env install options.
|
||||
# version: 2.1.0
|
||||
# Updated by AI/LLM: 2026-11-29 - uv replaces the old interpreter tooling (SPEC 7.21).
|
||||
# Updated by AI/LLM: 2026-11-30 - prints the tab-completion step (SPEC 7.23.14).
|
||||
#
|
||||
# Project bootstrap script - Sets up Python development environment
|
||||
# Project bootstrap script - Sets up the Python environment with uv
|
||||
#
|
||||
# This script MUST be sourced to properly set up the environment:
|
||||
# source bootstrap
|
||||
#
|
||||
# Windows (PowerShell): dot-source bootstrap.ps1 instead
|
||||
# . .\bootstrap.ps1 [--env name] [--python 3.x.x] [-c|--clean] [--local] [--no-env]
|
||||
# . .\bootstrap.ps1 [--python 3.x.x] [-c|--clean] [--local] [--no-env]
|
||||
#
|
||||
# What it does:
|
||||
# 1. Installs pyenv and required system dependencies if needed
|
||||
# 2. Initializes pyenv and pyenv-virtualenv in the current shell
|
||||
# 3. Creates a Python virtual environment named 'test_env' (or custom name)
|
||||
# 4. Activates the virtual environment
|
||||
# 5. Installs this repository (editable with the dev extra, unless --local)
|
||||
# 1. Checks that uv is installed (SPEC 7.21.9). It never installs uv.
|
||||
# 2. Installs the Python version from --python, if given (uv python install)
|
||||
# 3. Runs uv sync: creates .venv in this checkout and installs the package
|
||||
# editable with the dev group, from uv.lock
|
||||
# 4. Activates .venv
|
||||
#
|
||||
# With --clean/-c option:
|
||||
# - Deletes existing environment before creating a new one
|
||||
#
|
||||
# With --local:
|
||||
# - Installs this repository as a normal package (pip install .), not editable
|
||||
#
|
||||
# With --no-env:
|
||||
# - Skips pyenv and the virtual environment
|
||||
# - Installs with pip --user so the commands run without activating an environment
|
||||
# With --clean/-c: deletes .venv before the sync.
|
||||
# With --local: installs this repository non-editable, without the dev group.
|
||||
# With --no-env: installs a uv tool (no .venv, no activation). Commands
|
||||
# land in uv's bin directory, which must be on PATH.
|
||||
#
|
||||
# Usage:
|
||||
# source bootstrap [--pyenv] [-c|--clean] [--env custom_name] [--python 3.x.x] [--local] [--no-env]
|
||||
# ex. source bootstrap --pyenv -c --env my_env --python 3.10.6
|
||||
# source bootstrap [-c|--clean] [--python 3.x.x] [--local] [--no-env]
|
||||
# ex. source bootstrap -c --python 3.13.8
|
||||
# ex. source bootstrap --local --no-env
|
||||
|
||||
# =============================================
|
||||
# VARIABLES
|
||||
# =============================================
|
||||
PYTHON_VERSION="3.13.8" # Default Python version
|
||||
export PYENV_NAME="test_env" # Default environment name
|
||||
FORCE_PYENV_INSTALL=false # Flag to force pyenv reinstallation
|
||||
CLEAN_ENVIRONMENT=false # Flag to delete and recreate environment
|
||||
PYTHON_VERSION="" # Empty: uv reads .python-version (3.13)
|
||||
CLEAN_ENVIRONMENT=false # Flag to delete .venv before the sync
|
||||
LOCAL_INSTALL=false # Install this repo as a normal package, not editable
|
||||
NO_ENV=false # Skip the virtual environment and pip install --user
|
||||
PYTHON_BIN="python"
|
||||
NO_ENV=false # Install a uv tool instead of syncing .venv
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # scripts root directory
|
||||
|
||||
# Source utilities (needed for echo_error, echo_status, etc.)
|
||||
@@ -51,8 +44,8 @@ source "$SCRIPT_DIR/scripts/utils.sh"
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--pyenv)
|
||||
FORCE_PYENV_INSTALL=true
|
||||
shift
|
||||
echo_error "--pyenv was removed: bootstrap uses uv (https://docs.astral.sh/uv/)"
|
||||
return 1
|
||||
;;
|
||||
-c|--clean)
|
||||
CLEAN_ENVIRONMENT=true
|
||||
@@ -68,7 +61,7 @@ while [[ $# -gt 0 ]]; do
|
||||
;;
|
||||
--env)
|
||||
if [ -n "$2" ]; then
|
||||
PYENV_NAME="$2"
|
||||
echo_warning "--env is ignored: the environment is always .venv (SPEC 7.21.10)"
|
||||
shift 2
|
||||
else
|
||||
echo_error "--env requires an environment name argument"
|
||||
@@ -86,374 +79,88 @@ while [[ $# -gt 0 ]]; do
|
||||
;;
|
||||
*)
|
||||
echo_error "Unknown option: $1"
|
||||
echo "Usage: source bootstrap [--pyenv] [-c|--clean] [--env custom_name] [--python 3.x.x] [--local] [--no-env]"
|
||||
echo "Usage: source bootstrap [-c|--clean] [--python 3.x.x] [--local] [--no-env]"
|
||||
return 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Export the environment name for use throughout the script
|
||||
export PYENV_NAME
|
||||
|
||||
# =============================================
|
||||
# FUNCTION DEFINITIONS
|
||||
# =============================================
|
||||
|
||||
check_python_installed() {
|
||||
# First check if Python is installed at all
|
||||
if ! command -v python &> /dev/null && ! command -v python3 &> /dev/null; then
|
||||
echo_error "Python is not installed. Please install Python $PYTHON_VERSION before running this script."
|
||||
echo_error "On Ubuntu/Debian: sudo apt-get install python3"
|
||||
echo_error "On macOS: brew install python@$PYTHON_VERSION"
|
||||
echo_error "Or download from: https://www.python.org/downloads/"
|
||||
check_uv() {
|
||||
if ! command -v uv >/dev/null 2>&1; then
|
||||
echo_error "uv is not installed. bootstrap does not install it."
|
||||
echo_error "Install uv, then run bootstrap again:"
|
||||
echo_error " curl -LsSf https://astral.sh/uv/install.sh | sh"
|
||||
echo_error " winget install astral-sh.uv (Windows)"
|
||||
echo_error "Docs: https://docs.astral.sh/uv/getting-started/installation/"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# If pyenv is available, check if the specific version is installed
|
||||
if command -v pyenv &> /dev/null; then
|
||||
if ! pyenv versions | grep -q "$PYTHON_VERSION"; then
|
||||
echo_status "Python $PYTHON_VERSION is not available in pyenv. Installing it now..."
|
||||
if ! pyenv install "$PYTHON_VERSION"; then
|
||||
echo_error "Failed to install Python $PYTHON_VERSION via pyenv"
|
||||
echo_error "You may need to install build dependencies first or install it manually"
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
echo_status "Using $(uv --version)"
|
||||
return 0
|
||||
}
|
||||
|
||||
initialize_pyenv() {
|
||||
# Set up pyenv environment variables
|
||||
export PYENV_ROOT="$HOME/.pyenv"
|
||||
export PATH="$PYENV_ROOT/bin:$PATH"
|
||||
|
||||
# Check if pyenv is already properly initialized
|
||||
if command -v pyenv &> /dev/null && pyenv virtualenvs &> /dev/null; then
|
||||
echo_status "pyenv is already properly initialized"
|
||||
install_python() {
|
||||
if [ -z "$PYTHON_VERSION" ]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Check if pyenv exists
|
||||
if [ ! -f "$PYENV_ROOT/bin/pyenv" ]; then
|
||||
echo_error "pyenv not found at $PYENV_ROOT/bin/pyenv"
|
||||
echo_error "Please install pyenv first or use --pyenv flag"
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo_status "Initializing pyenv..."
|
||||
|
||||
# Clear any existing pyenv functions to avoid conflicts
|
||||
if declare -F | grep -q 'pyenv$'; then
|
||||
unset -f pyenv
|
||||
fi
|
||||
|
||||
# Initialize pyenv and pyenv-virtualenv
|
||||
eval "$("$PYENV_ROOT/bin/pyenv" init -)" || {
|
||||
echo_error "Failed to initialize pyenv"
|
||||
echo_status "Installing Python $PYTHON_VERSION with uv..."
|
||||
uv python install "$PYTHON_VERSION" || {
|
||||
echo_error "Failed to install Python $PYTHON_VERSION with uv"
|
||||
return 1
|
||||
}
|
||||
|
||||
# Only init virtualenv plugin if available
|
||||
if [ -f "$PYENV_ROOT/plugins/pyenv-virtualenv/bin/pyenv-virtualenv-init" ]; then
|
||||
eval "$("$PYENV_ROOT/bin/pyenv" virtualenv-init -)" || {
|
||||
echo_warning "Failed to initialize pyenv-virtualenv plugin"
|
||||
}
|
||||
fi
|
||||
|
||||
# Verify initialization
|
||||
if ! pyenv virtualenvs &> /dev/null; then
|
||||
echo_error "Failed to initialize pyenv"
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo_status "pyenv initialized successfully"
|
||||
return 0
|
||||
}
|
||||
|
||||
install_pyenv_dependencies() {
|
||||
# Install pyenv dependencies on Debian-based systems
|
||||
if [ -f /etc/debian_version ] || [ -f /etc/os-release ] && grep -q "ID=debian\|ID=ubuntu" /etc/os-release 2>/dev/null; then
|
||||
echo_status "Installing pyenv dependencies..."
|
||||
if ! command -v sudo &> /dev/null; then
|
||||
echo_error "sudo is required to install dependencies"
|
||||
return 1
|
||||
fi
|
||||
sudo apt-get update && sudo apt-get install -y \
|
||||
make build-essential libssl-dev zlib1g-dev \
|
||||
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \
|
||||
libncurses-dev xz-utils tk-dev libffi-dev liblzma-dev \
|
||||
python3-openssl git || {
|
||||
echo_error "Failed to install pyenv dependencies"
|
||||
echo_warning "You may need to install them manually"
|
||||
return 1
|
||||
}
|
||||
elif [ "$(uname)" = "Darwin" ]; then
|
||||
echo_status "Detected macOS - ensuring required tools are available"
|
||||
if ! command -v brew &> /dev/null; then
|
||||
echo_warning "Homebrew (brew) not found. You may need to install pyenv dependencies manually."
|
||||
echo_warning "Recommended: brew install pyenv"
|
||||
return 0
|
||||
fi
|
||||
if ! brew list pyenv &> /dev/null; then
|
||||
echo_status "Installing pyenv via homebrew..."
|
||||
brew install pyenv || {
|
||||
echo_error "Failed to install pyenv via homebrew"
|
||||
return 1
|
||||
}
|
||||
fi
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
install_pyenv() {
|
||||
echo_status "Installing pyenv..."
|
||||
curl -fsSL https://pyenv.run | bash || {
|
||||
echo_error "Failed to install pyenv"
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
check_and_install_pyenv() {
|
||||
# Check if pyenv is already available
|
||||
if command -v pyenv &> /dev/null && [ "$FORCE_PYENV_INSTALL" = false ]; then
|
||||
echo_status "pyenv is already available"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Handle existing pyenv directory
|
||||
if [ -d "$HOME/.pyenv" ]; then
|
||||
if [ "$FORCE_PYENV_INSTALL" = true ]; then
|
||||
echo_status "Removing existing pyenv installation..."
|
||||
rm -rf "$HOME/.pyenv" || {
|
||||
echo_error "Failed to remove existing pyenv installation"
|
||||
return 1
|
||||
}
|
||||
else
|
||||
echo_status "Found existing pyenv directory"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Install dependencies first
|
||||
install_pyenv_dependencies || return 1
|
||||
|
||||
# Install pyenv
|
||||
install_pyenv || return 1
|
||||
|
||||
# Source the pyenv setup in current shell
|
||||
export PYENV_ROOT="$HOME/.pyenv"
|
||||
export PATH="$PYENV_ROOT/bin:$PATH"
|
||||
eval "$("$PYENV_ROOT/bin/pyenv" init -)"
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
clean_environment() {
|
||||
if pyenv virtualenvs | grep -q "$PYENV_NAME"; then
|
||||
echo_status "Deleting existing virtual environment $PYENV_NAME..."
|
||||
pyenv uninstall -f "$PYENV_NAME" >/dev/null 2>&1 || {
|
||||
echo_error "Failed to delete virtual environment $PYENV_NAME"
|
||||
if [ "$CLEAN_ENVIRONMENT" = true ] && [ "$NO_ENV" = false ] && [ -d "$SCRIPT_DIR/.venv" ]; then
|
||||
echo_status "Removing existing .venv..."
|
||||
rm -rf "$SCRIPT_DIR/.venv" || {
|
||||
echo_error "Failed to remove $SCRIPT_DIR/.venv"
|
||||
return 1
|
||||
}
|
||||
else
|
||||
echo_status "Virtual environment $PYENV_NAME does not exist, skipping deletion"
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
install_python_version() {
|
||||
local version="$1"
|
||||
echo_status "Installing Python $version using pyenv..."
|
||||
pyenv install "$version" || {
|
||||
echo_error "Failed to install Python $version"
|
||||
install_repository() {
|
||||
local flags=()
|
||||
if [ "$LOCAL_INSTALL" = true ]; then
|
||||
flags+=(--local)
|
||||
fi
|
||||
if [ "$NO_ENV" = true ]; then
|
||||
flags+=(--no-env)
|
||||
fi
|
||||
if [ -n "$PYTHON_VERSION" ]; then
|
||||
flags+=(--python "$PYTHON_VERSION")
|
||||
fi
|
||||
local uv_words=()
|
||||
local word
|
||||
while IFS= read -r word; do
|
||||
if [ -n "$word" ]; then
|
||||
uv_words+=("$word")
|
||||
fi
|
||||
done < <(python3 "$SCRIPT_DIR/scripts/bootstrap_install.py" "${flags[@]}")
|
||||
if [ "${#uv_words[@]}" -eq 0 ]; then
|
||||
echo_error "Failed to resolve uv arguments"
|
||||
return 1
|
||||
fi
|
||||
echo_status "Running: uv ${uv_words[*]}"
|
||||
(cd "$SCRIPT_DIR" && uv "${uv_words[@]}") || {
|
||||
echo_error "uv ${uv_words[*]} failed"
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
check_environment_exists() {
|
||||
# Clean if requested
|
||||
if [ "$CLEAN_ENVIRONMENT" = true ]; then
|
||||
clean_environment || return 1
|
||||
fi
|
||||
|
||||
# Check if Python version is available
|
||||
if ! pyenv versions | grep -q "$PYTHON_VERSION"; then
|
||||
install_python_version "$PYTHON_VERSION" || return 1
|
||||
fi
|
||||
|
||||
# Create environment if it doesn't exist (exact name match:
|
||||
# a plain grep would also match "test_env2" when asked for "test_env")
|
||||
if ! pyenv virtualenvs --bare 2>/dev/null | grep -qx "$PYENV_NAME"; then
|
||||
echo_status "Creating virtual environment $PYENV_NAME..."
|
||||
pyenv virtualenv "$PYTHON_VERSION" "$PYENV_NAME" || {
|
||||
echo_error "Failed to create virtual environment $PYENV_NAME"
|
||||
return 1
|
||||
}
|
||||
else
|
||||
echo_status "Virtual environment $PYENV_NAME already exists"
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
activate_environment() {
|
||||
echo_status "Activating $PYENV_NAME..."
|
||||
|
||||
# Try pyenv activate first
|
||||
if command -v pyenv &> /dev/null; then
|
||||
# Get the virtualenv path
|
||||
local venv_path
|
||||
venv_path=$(pyenv prefix "$PYENV_NAME" 2>/dev/null)
|
||||
|
||||
if [ -n "$venv_path" ] && [ -d "$venv_path" ]; then
|
||||
# Manually activate by sourcing the activate script
|
||||
local activate_script="$venv_path/bin/activate"
|
||||
if [ -f "$activate_script" ]; then
|
||||
source "$activate_script" || {
|
||||
echo_error "Failed to source activation script: $activate_script"
|
||||
return 1
|
||||
}
|
||||
echo_status "Successfully activated $PYENV_NAME"
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
|
||||
# Fallback: try pyenv activate
|
||||
if pyenv activate "$PYENV_NAME" 2>/dev/null; then
|
||||
echo_status "Successfully activated $PYENV_NAME with pyenv"
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
|
||||
# Last resort: check common virtualenv locations
|
||||
local possible_paths=(
|
||||
"$HOME/.pyenv/versions/$PYENV_NAME/bin/activate"
|
||||
"$HOME/.virtualenvs/$PYENV_NAME/bin/activate"
|
||||
"$SCRIPT_DIR/venv/bin/activate"
|
||||
"$SCRIPT_DIR/src/venv/bin/activate"
|
||||
)
|
||||
|
||||
for path in "${possible_paths[@]}"; do
|
||||
if [ -f "$path" ]; then
|
||||
source "$path" || {
|
||||
echo_error "Failed to source activation script: $path"
|
||||
return 1
|
||||
}
|
||||
echo_status "Successfully activated $PYENV_NAME"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
|
||||
echo_error "Failed to activate $PYENV_NAME - could not find activation script"
|
||||
return 1
|
||||
}
|
||||
|
||||
install_requirements() {
|
||||
echo_status "Installing requirements..."
|
||||
|
||||
# Check if pyproject.toml exists (could be in root or src/)
|
||||
local project_dir=""
|
||||
if [ -f "$SCRIPT_DIR/pyproject.toml" ]; then
|
||||
project_dir="$SCRIPT_DIR"
|
||||
elif [ -f "$SCRIPT_DIR/src/pyproject.toml" ]; then
|
||||
project_dir="$SCRIPT_DIR/src"
|
||||
fi
|
||||
|
||||
if [ -n "$project_dir" ]; then
|
||||
local helper="$SCRIPT_DIR/scripts/bootstrap_install.py"
|
||||
if [ ! -f "$helper" ]; then
|
||||
echo_error "Missing $helper"
|
||||
return 1
|
||||
fi
|
||||
local flags=(--break-system-packages)
|
||||
if [ "$LOCAL_INSTALL" = true ]; then
|
||||
echo_status "Installing this repository as a normal package..."
|
||||
flags+=(--local)
|
||||
else
|
||||
echo_status "Installing package and dependencies from pyproject.toml..."
|
||||
fi
|
||||
if [ "$NO_ENV" = true ]; then
|
||||
flags+=(--no-env)
|
||||
fi
|
||||
local pip_words=()
|
||||
local word
|
||||
while IFS= read -r word; do
|
||||
if [ -n "$word" ]; then
|
||||
pip_words+=("$word")
|
||||
fi
|
||||
done < <("$PYTHON_BIN" "$helper" "${flags[@]}")
|
||||
if [ "${#pip_words[@]}" -eq 0 ]; then
|
||||
echo_error "Failed to resolve pip install arguments"
|
||||
return 1
|
||||
fi
|
||||
(cd "$project_dir" && "$PYTHON_BIN" -m pip "${pip_words[@]}") || {
|
||||
echo_error "Failed to install package and dependencies from pyproject.toml"
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo_warning "No pyproject.toml found"
|
||||
|
||||
# Fallback: look for any requirements.txt files
|
||||
local req_files=()
|
||||
while IFS= read -r -d '' req_file; do
|
||||
req_files+=("$req_file")
|
||||
done < <(find "$SCRIPT_DIR" -name "requirements.txt" -print0)
|
||||
|
||||
if [ ${#req_files[@]} -eq 0 ]; then
|
||||
echo_status "No requirements files found"
|
||||
return 0
|
||||
fi
|
||||
|
||||
local user_args=()
|
||||
if [ "$NO_ENV" = true ]; then
|
||||
user_args+=(--user)
|
||||
fi
|
||||
for req_file in "${req_files[@]}"; do
|
||||
echo_status "Installing requirements from: $req_file"
|
||||
"$PYTHON_BIN" -m pip install "${user_args[@]}" -r "$req_file" --break-system-packages || {
|
||||
echo_error "Failed to install requirements from $req_file"
|
||||
return 1
|
||||
}
|
||||
done
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
upgrade_pip() {
|
||||
echo_status "Upgrading pip..."
|
||||
local upgrade_args=(install --upgrade pip --break-system-packages)
|
||||
if [ "$NO_ENV" = true ]; then
|
||||
upgrade_args=(install --user --upgrade pip --break-system-packages)
|
||||
fi
|
||||
"$PYTHON_BIN" -m pip "${upgrade_args[@]}" || {
|
||||
echo_warning "Failed to upgrade pip"
|
||||
echo_warning "Continuing with requirements installation..."
|
||||
# shellcheck source=/dev/null
|
||||
source "$SCRIPT_DIR/.venv/bin/activate" || {
|
||||
echo_error "Failed to activate $SCRIPT_DIR/.venv"
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
install_dev_packages() {
|
||||
echo_status "Installing local Python packages in development mode..."
|
||||
local install_script="$SCRIPT_DIR/scripts/install_packages.sh"
|
||||
|
||||
if [ -f "$install_script" ]; then
|
||||
# Use source to run in current shell context, preserving environment variables
|
||||
(cd "$SCRIPT_DIR" && . "$install_script") || {
|
||||
echo_error "Dev packages not installed!"
|
||||
return 1
|
||||
}
|
||||
else
|
||||
echo_status "Install script not found at $install_script, attempting direct install..."
|
||||
# Fallback: install in editable mode from the repository root
|
||||
(cd "$SCRIPT_DIR" && pip install -e . --break-system-packages) || {
|
||||
echo_error "Failed to install package in development mode"
|
||||
return 1
|
||||
}
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -465,16 +172,13 @@ sanitize_pytest_env() {
|
||||
# Also remove -S or --no-summary (older versions)
|
||||
local sanitized
|
||||
sanitized=$(echo "$PYTEST_ADDOPTS" | sed -e 's/--no-summary[[:space:]]*//g' -e 's/--no-summary//g' -e 's/-S[[:space:]]*//g' -e 's/-S//g')
|
||||
|
||||
# Remove leading/trailing whitespace and any double spaces
|
||||
sanitized=$(echo "$sanitized" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/[[:space:]]\+/ /g')
|
||||
|
||||
if [ "$sanitized" != "$PYTEST_ADDOPTS" ]; then
|
||||
echo_warning "Removing --no-summary from PYTEST_ADDOPTS to ensure test output is parsed correctly"
|
||||
export PYTEST_ADDOPTS="$sanitized"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Also unset FORCE_COLOR and PY_COLORS as they can interfere with output parsing
|
||||
if [ -n "$FORCE_COLOR" ]; then
|
||||
echo_warning "Unsetting FORCE_COLOR to ensure pytest output is parsed correctly"
|
||||
@@ -484,7 +188,6 @@ sanitize_pytest_env() {
|
||||
echo_warning "Unsetting PY_COLORS to ensure pytest output is parsed correctly"
|
||||
unset PY_COLORS
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -492,90 +195,60 @@ sanitize_pytest_env() {
|
||||
# MAIN EXECUTION
|
||||
# =============================================
|
||||
if [ "$NO_ENV" = true ]; then
|
||||
echo_status "Starting project bootstrap (no virtual environment)"
|
||||
echo_status "Starting project bootstrap (uv tool, no virtual environment)"
|
||||
else
|
||||
echo_status "Starting project bootstrap with environment: $PYENV_NAME"
|
||||
echo_status "Starting project bootstrap with uv (.venv)"
|
||||
fi
|
||||
|
||||
if [ "$LOCAL_INSTALL" = true ]; then
|
||||
echo_status "Local install: this repository, not editable"
|
||||
fi
|
||||
if [ "$NO_ENV" = true ]; then
|
||||
echo_status "No virtual environment: installing with --user"
|
||||
echo_status "Local install: this repository, not editable, no dev group"
|
||||
fi
|
||||
|
||||
if [ "$NO_ENV" = true ]; then
|
||||
if ! command -v python >/dev/null 2>&1 && ! command -v python3 >/dev/null 2>&1; then
|
||||
echo_error "Python is not installed. Please install Python $PYTHON_VERSION before running this script."
|
||||
echo_error "Or download from: https://www.python.org/downloads/"
|
||||
return 1
|
||||
fi
|
||||
if command -v python >/dev/null 2>&1; then
|
||||
PYTHON_BIN="python"
|
||||
else
|
||||
PYTHON_BIN="python3"
|
||||
fi
|
||||
else
|
||||
if [ "$FORCE_PYENV_INSTALL" = true ]; then
|
||||
echo_status "Forcing pyenv reinstallation"
|
||||
fi
|
||||
# 1. Check uv
|
||||
if ! check_uv; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
# 1. Check if Python is installed
|
||||
if ! check_python_installed; then
|
||||
return 1
|
||||
fi
|
||||
# 2. Python version
|
||||
if ! install_python; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
# 2. Check/install pyenv
|
||||
if ! check_and_install_pyenv; then
|
||||
return 1
|
||||
fi
|
||||
# 3. Clean, then install this repository
|
||||
if ! clean_environment; then
|
||||
return 1
|
||||
fi
|
||||
if ! install_repository; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
# 3. Initialize pyenv
|
||||
if ! initialize_pyenv; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
# 4. Check/create virtual environment
|
||||
if ! check_environment_exists; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
# 5. Activate the environment
|
||||
# 4. Activate .venv unless the install is a uv tool
|
||||
if [ "$NO_ENV" = false ]; then
|
||||
if ! activate_environment; then
|
||||
return 1
|
||||
fi
|
||||
PYTHON_BIN="python"
|
||||
fi
|
||||
|
||||
# 5.5. Sanitize pytest environment to ensure proper output parsing
|
||||
# 5. Sanitize pytest environment to ensure proper output parsing
|
||||
sanitize_pytest_env
|
||||
|
||||
# 6. Upgrade pip
|
||||
upgrade_pip
|
||||
|
||||
# 7. Install this repository
|
||||
if ! install_requirements; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Final verification
|
||||
echo_status "Bootstrap completed successfully!"
|
||||
if [ "$NO_ENV" = true ]; then
|
||||
scripts_dir=$("$PYTHON_BIN" -c "import sys, sysconfig; scheme = 'nt_user' if sys.platform == 'win32' else 'posix_user'; print(sysconfig.get_path('scripts', scheme))")
|
||||
echo_status "Installed for the current user (no virtual environment)"
|
||||
echo_status "Command directory: $scripts_dir"
|
||||
echo_status "If fiona-assistant is not found, add that directory to PATH."
|
||||
echo_status "Python: $("$PYTHON_BIN" --version) ($PYTHON_BIN)"
|
||||
echo_status "Pip: $("$PYTHON_BIN" -m pip --version)"
|
||||
echo_status "Installed as a uv tool (no virtual environment)"
|
||||
echo_status "Command directory: $(uv tool dir --bin)"
|
||||
echo_status "If fiona-assistant is not found, run: uv tool update-shell"
|
||||
else
|
||||
echo_status "Virtual environment '$PYENV_NAME' is active"
|
||||
echo_status "Python: $(python --version) ($(which python))"
|
||||
echo_status "Pip: $(pip --version)"
|
||||
echo_status "Virtual environment .venv is active"
|
||||
echo_status "Python: $(python --version) ($(command -v python))"
|
||||
echo_status "uv: $(uv --version)"
|
||||
fi
|
||||
echo_status ""
|
||||
echo_status "To verify installation, try:"
|
||||
echo_status " fiona-assistant test"
|
||||
echo_status " fiona-assistant --version"
|
||||
echo_status " librarian --help"
|
||||
echo_status " mdoctor --help"
|
||||
echo_status ""
|
||||
echo_status "To enable tab completion for fiona-assistant, run once:"
|
||||
echo_status " fiona-assistant --init"
|
||||
echo_status ""
|
||||
echo_status "Happy coding!"
|
||||
|
||||
+124
-180
@@ -1,5 +1,7 @@
|
||||
# Generated by AI/LLM: 2026-09-29 - Windows PowerShell bootstrap for Fiona development
|
||||
# Modified by AI/LLM: 2026-09-30 - --local and --no-env install options.
|
||||
# Updated by AI/LLM: 2026-11-29 - uv replaces the venv and pip steps (SPEC 7.21).
|
||||
# Modified by AI/LLM: 2026-11-30 - prints the tab-completion step (SPEC 7.23.14).
|
||||
#
|
||||
# Project bootstrap for Windows. Dot-source a virtual-environment install so
|
||||
# the environment stays active in the current session (same idea as
|
||||
@@ -7,18 +9,15 @@
|
||||
#
|
||||
# Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
|
||||
# . .\bootstrap.ps1
|
||||
# . .\bootstrap.ps1 --env fiona_env
|
||||
# . .\bootstrap.ps1 --env fiona_env --python 3.13.8 -c
|
||||
# . .\bootstrap.ps1 --python 3.13.8 -c
|
||||
# . .\bootstrap.ps1 --local
|
||||
# powershell -ExecutionPolicy Bypass -File .\bootstrap.ps1 --local --no-env
|
||||
#
|
||||
# Creates a repo-local venv at .venvs\<name> with the Python launcher (py)
|
||||
# or python on PATH. Does not install pyenv. --pyenv is accepted so the
|
||||
# Linux flag still parses; on Windows it is a no-op notice.
|
||||
# Requires uv (https://docs.astral.sh/uv/). This script never installs uv.
|
||||
# It runs `uv sync`, which creates .venv in the checkout from uv.lock.
|
||||
#
|
||||
# --local installs this repository as a normal package (not editable).
|
||||
# --no-env skips the virtual environment and installs with pip --user,
|
||||
# so fiona-assistant can run without activating an environment.
|
||||
# --local installs this repository non-editable, without the dev group.
|
||||
# --no-env installs a uv tool, so fiona-assistant runs with no activation.
|
||||
# --no-env may be executed with -File. A venv install must be dot-sourced.
|
||||
|
||||
#Requires -Version 5.1
|
||||
@@ -58,67 +57,43 @@ function Remove-FionaBootstrapFunctions {
|
||||
}
|
||||
|
||||
function Resolve-FionaPython {
|
||||
# AI/LLM: pick a real interpreter. Prefer the py launcher so a requested
|
||||
# version (3.13.8, then 3.13) wins over whatever `python` happens to be.
|
||||
param([string]$Version)
|
||||
|
||||
$tags = @()
|
||||
if ($Version) {
|
||||
$tags += $Version
|
||||
if ($Version -match '^(\d+\.\d+)') {
|
||||
$minor = $Matches[1]
|
||||
if ($minor -ne $Version) {
|
||||
$tags += $minor
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# AI/LLM: find any real interpreter for the stdlib-only uv argument helper.
|
||||
# uv itself chooses the project interpreter from .python-version.
|
||||
$py = Get-Command py -ErrorAction SilentlyContinue
|
||||
if ($py) {
|
||||
foreach ($tag in $tags) {
|
||||
$exe = & py "-$tag" -c "import sys; print(sys.executable)" 2>$null
|
||||
if ($LASTEXITCODE -eq 0 -and $exe) {
|
||||
return @($exe)[-1].ToString().Trim()
|
||||
}
|
||||
}
|
||||
if (-not $Version) {
|
||||
$exe = & py -3 -c "import sys; print(sys.executable)" 2>$null
|
||||
if ($LASTEXITCODE -eq 0 -and $exe) {
|
||||
return @($exe)[-1].ToString().Trim()
|
||||
}
|
||||
$exe = & py -3 -c "import sys; print(sys.executable)" 2>$null
|
||||
if ($LASTEXITCODE -eq 0 -and $exe) {
|
||||
return @($exe)[-1].ToString().Trim()
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $Version) {
|
||||
foreach ($name in @("python", "python3")) {
|
||||
$cmd = Get-Command $name -ErrorAction SilentlyContinue
|
||||
if ($cmd -and $cmd.Source -notmatch "WindowsApps") {
|
||||
return $cmd.Source
|
||||
}
|
||||
foreach ($name in @("python", "python3")) {
|
||||
$cmd = Get-Command $name -ErrorAction SilentlyContinue
|
||||
if ($cmd -and $cmd.Source -notmatch "WindowsApps") {
|
||||
return $cmd.Source
|
||||
}
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
$FionaPrevErrorAction = $ErrorActionPreference
|
||||
$ErrorActionPreference = "Stop"
|
||||
# AI/LLM: a failed pip/py call must be checked via $LASTEXITCODE, not thrown.
|
||||
# AI/LLM: a failed uv call must be checked via $LASTEXITCODE, not thrown.
|
||||
if (Get-Variable -Name PSNativeCommandUseErrorActionPreference -ErrorAction SilentlyContinue) {
|
||||
$PSNativeCommandUseErrorActionPreference = $false
|
||||
}
|
||||
|
||||
$Clean = $false
|
||||
$EnvName = "test_env"
|
||||
$EnvName = ".venv"
|
||||
$PythonVersion = ""
|
||||
$Pyenv = $false
|
||||
$Local = $false
|
||||
$NoEnv = $false
|
||||
$bootstrapArgs = @($args)
|
||||
for ($i = 0; $i -lt $bootstrapArgs.Count; $i++) {
|
||||
$token = [string]$bootstrapArgs[$i]
|
||||
if ($token -eq "--pyenv") {
|
||||
$Pyenv = $true
|
||||
Write-FionaError "--pyenv was removed: bootstrap uses uv (https://docs.astral.sh/uv/)"
|
||||
Remove-FionaBootstrapFunctions
|
||||
return
|
||||
}
|
||||
elseif ($token -eq "-c" -or $token -eq "--clean") {
|
||||
$Clean = $true
|
||||
@@ -136,7 +111,7 @@ for ($i = 0; $i -lt $bootstrapArgs.Count; $i++) {
|
||||
return
|
||||
}
|
||||
$i++
|
||||
$EnvName = [string]$bootstrapArgs[$i]
|
||||
Write-FionaWarning "--env is ignored: the environment is always .venv (SPEC 7.21.10)"
|
||||
}
|
||||
elseif ($token -eq "--python") {
|
||||
if (($i + 1) -ge $bootstrapArgs.Count) {
|
||||
@@ -149,7 +124,7 @@ for ($i = 0; $i -lt $bootstrapArgs.Count; $i++) {
|
||||
}
|
||||
else {
|
||||
Write-FionaError "Unknown option: $token"
|
||||
Write-FionaError "Usage: . .\bootstrap.ps1 [--pyenv] [-c|--clean] [--env custom_name] [--python 3.x.x] [--local] [--no-env]"
|
||||
Write-FionaError "Usage: . .\bootstrap.ps1 [-c|--clean] [--python 3.x.x] [--local] [--no-env]"
|
||||
Remove-FionaBootstrapFunctions
|
||||
return
|
||||
}
|
||||
@@ -164,31 +139,11 @@ if (-not $NoEnv -and $MyInvocation.InvocationName -ne ".") {
|
||||
return
|
||||
}
|
||||
|
||||
if ($Pyenv) {
|
||||
Write-FionaWarning "Windows bootstrap uses a local venv under .venvs\. It does not install pyenv."
|
||||
}
|
||||
|
||||
$repoRoot = $PSScriptRoot
|
||||
if (-not $repoRoot) {
|
||||
$repoRoot = (Get-Location).Path
|
||||
}
|
||||
|
||||
if ($NoEnv) {
|
||||
Write-FionaStatus "Starting project bootstrap (no virtual environment)"
|
||||
}
|
||||
else {
|
||||
Write-FionaStatus "Starting project bootstrap with environment: $EnvName"
|
||||
}
|
||||
if ($Local) {
|
||||
Write-FionaStatus "Local install: this repository, not editable"
|
||||
}
|
||||
if ($NoEnv) {
|
||||
Write-FionaStatus "No virtual environment: installing with --user"
|
||||
}
|
||||
if ($NoEnv -and $Clean) {
|
||||
Write-FionaWarning "--clean has no effect with --no-env"
|
||||
}
|
||||
|
||||
try {
|
||||
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force -ErrorAction Stop | Out-Null
|
||||
}
|
||||
@@ -196,60 +151,109 @@ catch {
|
||||
# AI/LLM: a GPO can refuse the process override. RemoteSigned still runs local scripts.
|
||||
}
|
||||
|
||||
$pythonExe = Resolve-FionaPython -Version $PythonVersion
|
||||
if (-not $pythonExe) {
|
||||
Write-FionaError "Python is not installed, or version '$PythonVersion' is not available to the py launcher."
|
||||
Write-FionaError "Install Python from https://www.python.org/downloads/ and enable the py launcher."
|
||||
if ($PythonVersion) {
|
||||
Write-FionaError "Then re-run: . .\bootstrap.ps1 --python $PythonVersion"
|
||||
if ($NoEnv) {
|
||||
Write-FionaStatus "Starting project bootstrap (uv tool, no virtual environment)"
|
||||
}
|
||||
else {
|
||||
Write-FionaStatus "Starting project bootstrap with uv (.venv)"
|
||||
}
|
||||
if ($Local) {
|
||||
Write-FionaStatus "Local install: this repository, not editable, no dev group"
|
||||
}
|
||||
|
||||
# 1. Check uv (SPEC 7.21.9)
|
||||
$uvCmd = Get-Command uv -ErrorAction SilentlyContinue
|
||||
if (-not $uvCmd) {
|
||||
Write-FionaError "uv is not installed. bootstrap does not install it."
|
||||
Write-FionaError "Install uv, then run bootstrap again:"
|
||||
Write-FionaError " winget install astral-sh.uv"
|
||||
Write-FionaError " (or: powershell -ExecutionPolicy ByPass -c `"irm https://astral.sh/uv/install.ps1 | iex`")"
|
||||
Write-FionaError "Docs: https://docs.astral.sh/uv/getting-started/installation/"
|
||||
Remove-FionaBootstrapFunctions
|
||||
return
|
||||
}
|
||||
Write-FionaStatus "Using $(& uv --version)"
|
||||
|
||||
# 2. Python version
|
||||
if ($PythonVersion) {
|
||||
Write-FionaStatus "Installing Python $PythonVersion with uv..."
|
||||
& uv python install $PythonVersion
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-FionaError "Failed to install Python $PythonVersion with uv"
|
||||
Remove-FionaBootstrapFunctions
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
# 3. Clean
|
||||
$venvPath = Join-Path $repoRoot $EnvName
|
||||
if ($Clean -and -not $NoEnv -and (Test-Path -LiteralPath $venvPath)) {
|
||||
Write-FionaStatus "Deleting existing $EnvName..."
|
||||
try {
|
||||
Remove-Item -LiteralPath $venvPath -Recurse -Force
|
||||
}
|
||||
catch {
|
||||
Write-FionaError "Failed to delete $EnvName"
|
||||
Write-FionaError $_.Exception.Message
|
||||
Remove-FionaBootstrapFunctions
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
# 4. Install this repository through uv
|
||||
$helperPython = Resolve-FionaPython
|
||||
if (-not $helperPython) {
|
||||
Write-FionaError "Python is needed to print the uv arguments, and none was found."
|
||||
Write-FionaError "Install Python from https://www.python.org/downloads/ and enable the py launcher."
|
||||
Remove-FionaBootstrapFunctions
|
||||
return
|
||||
}
|
||||
$helper = Join-Path $repoRoot "scripts\bootstrap_install.py"
|
||||
if (-not (Test-Path -LiteralPath $helper)) {
|
||||
Write-FionaError "Missing $helper"
|
||||
Remove-FionaBootstrapFunctions
|
||||
return
|
||||
}
|
||||
$helperArgs = @($helper)
|
||||
if ($Local) {
|
||||
$helperArgs += "--local"
|
||||
}
|
||||
if ($NoEnv) {
|
||||
$helperArgs += "--no-env"
|
||||
}
|
||||
if ($PythonVersion) {
|
||||
$helperArgs += @("--python", $PythonVersion)
|
||||
}
|
||||
$uvWords = @(& $helperPython @helperArgs | Where-Object { $_ -and "$_".Trim() -ne "" })
|
||||
if ($LASTEXITCODE -ne 0 -or $uvWords.Count -eq 0) {
|
||||
Write-FionaError "Failed to resolve uv arguments"
|
||||
Remove-FionaBootstrapFunctions
|
||||
return
|
||||
}
|
||||
|
||||
$pipPython = $pythonExe
|
||||
Write-FionaStatus "Running: uv $($uvWords -join ' ')"
|
||||
Push-Location $repoRoot
|
||||
try {
|
||||
& uv @uvWords
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-FionaError "uv $($uvWords -join ' ') failed"
|
||||
Remove-FionaBootstrapFunctions
|
||||
return
|
||||
}
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
# 5. Activate .venv unless the install is a uv tool
|
||||
if (-not $NoEnv) {
|
||||
$venvRoot = Join-Path $repoRoot ".venvs"
|
||||
$venvPath = Join-Path $venvRoot $EnvName
|
||||
|
||||
if ($Clean -and (Test-Path -LiteralPath $venvPath)) {
|
||||
Write-FionaStatus "Deleting existing virtual environment $EnvName..."
|
||||
try {
|
||||
Remove-Item -LiteralPath $venvPath -Recurse -Force
|
||||
}
|
||||
catch {
|
||||
Write-FionaError "Failed to delete virtual environment $EnvName"
|
||||
Write-FionaError $_.Exception.Message
|
||||
Remove-FionaBootstrapFunctions
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
$activate = Join-Path $venvPath "Scripts\Activate.ps1"
|
||||
if (-not (Test-Path -LiteralPath $activate)) {
|
||||
Write-FionaStatus "Creating virtual environment $EnvName with $pythonExe..."
|
||||
New-Item -ItemType Directory -Path $venvRoot -Force | Out-Null
|
||||
& $pythonExe -m venv $venvPath
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-FionaError "Failed to create virtual environment $EnvName"
|
||||
Remove-FionaBootstrapFunctions
|
||||
return
|
||||
}
|
||||
}
|
||||
else {
|
||||
Write-FionaStatus "Virtual environment $EnvName already exists"
|
||||
}
|
||||
|
||||
Write-FionaStatus "Activating $EnvName..."
|
||||
. $activate
|
||||
|
||||
if (-not $env:VIRTUAL_ENV) {
|
||||
Write-FionaError "Failed to activate $EnvName"
|
||||
Remove-FionaBootstrapFunctions
|
||||
return
|
||||
}
|
||||
|
||||
$pipPython = Join-Path $venvPath "Scripts\python.exe"
|
||||
}
|
||||
|
||||
if ($env:PYTEST_ADDOPTS) {
|
||||
@@ -274,84 +278,24 @@ if ($env:PY_COLORS) {
|
||||
Remove-Item Env:PY_COLORS
|
||||
}
|
||||
|
||||
$pyproject = Join-Path $repoRoot "pyproject.toml"
|
||||
if (-not (Test-Path -LiteralPath $pyproject)) {
|
||||
Write-FionaError "No pyproject.toml found at $pyproject"
|
||||
Remove-FionaBootstrapFunctions
|
||||
return
|
||||
}
|
||||
|
||||
Write-FionaStatus "Upgrading pip..."
|
||||
if ($NoEnv) {
|
||||
& $pipPython -m pip install --upgrade pip --user
|
||||
}
|
||||
else {
|
||||
& $pipPython -m pip install --upgrade pip
|
||||
}
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-FionaWarning "Failed to upgrade pip. Continuing with package installation..."
|
||||
}
|
||||
|
||||
$helper = Join-Path $repoRoot "scripts\bootstrap_install.py"
|
||||
if (-not (Test-Path -LiteralPath $helper)) {
|
||||
Write-FionaError "Missing $helper"
|
||||
Remove-FionaBootstrapFunctions
|
||||
return
|
||||
}
|
||||
$helperArgs = @($helper)
|
||||
if ($Local) {
|
||||
$helperArgs += "--local"
|
||||
}
|
||||
if ($NoEnv) {
|
||||
$helperArgs += "--no-env"
|
||||
}
|
||||
$pipWords = @(& $pipPython @helperArgs | Where-Object { $_ -and "$_".Trim() -ne "" })
|
||||
if ($LASTEXITCODE -ne 0 -or $pipWords.Count -eq 0) {
|
||||
Write-FionaError "Failed to resolve pip install arguments"
|
||||
Remove-FionaBootstrapFunctions
|
||||
return
|
||||
}
|
||||
|
||||
if ($Local) {
|
||||
Write-FionaStatus "Installing this repository as a normal package..."
|
||||
}
|
||||
else {
|
||||
Write-FionaStatus "Installing package and dependencies from pyproject.toml..."
|
||||
}
|
||||
Push-Location $repoRoot
|
||||
try {
|
||||
& $pipPython -m pip @pipWords
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-FionaError "Failed to install package and dependencies from pyproject.toml"
|
||||
Remove-FionaBootstrapFunctions
|
||||
return
|
||||
}
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
$pythonVersionText = (& $pipPython --version 2>&1 | Out-String).Trim()
|
||||
$pipVersionText = (& $pipPython -m pip --version 2>&1 | Out-String).Trim()
|
||||
|
||||
Write-FionaStatus "Bootstrap completed successfully!"
|
||||
if ($NoEnv) {
|
||||
$scriptsDir = (& $pipPython -c "import sysconfig; print(sysconfig.get_path('scripts', 'nt_user'))" | Out-String).Trim()
|
||||
Write-FionaStatus "Installed for the current user (no virtual environment)"
|
||||
Write-FionaStatus "Command directory: $scriptsDir"
|
||||
Write-FionaStatus "If fiona-assistant is not found, add that directory to PATH."
|
||||
$toolBin = (& uv tool dir --bin | Out-String).Trim()
|
||||
Write-FionaStatus "Installed as a uv tool (no virtual environment)"
|
||||
Write-FionaStatus "Command directory: $toolBin"
|
||||
Write-FionaStatus "If fiona-assistant is not found, run: uv tool update-shell"
|
||||
}
|
||||
else {
|
||||
Write-FionaStatus "Virtual environment '$EnvName' is active"
|
||||
Write-FionaStatus "Virtual environment .venv is active"
|
||||
Write-FionaStatus "Python: $((& python --version 2>&1 | Out-String).Trim())"
|
||||
Write-FionaStatus "uv: $((& uv --version 2>&1 | Out-String).Trim())"
|
||||
}
|
||||
Write-FionaStatus "Python: $pythonVersionText ($pipPython)"
|
||||
Write-FionaStatus "Pip: $pipVersionText"
|
||||
Write-FionaStatus ""
|
||||
Write-FionaStatus "To verify installation, try:"
|
||||
if (-not $NoEnv) {
|
||||
Write-FionaStatus " python scripts/run_tests.py"
|
||||
}
|
||||
Write-FionaStatus " fiona-assistant --help"
|
||||
Write-FionaStatus " fiona-assistant --version"
|
||||
Write-FionaStatus ""
|
||||
Write-FionaStatus "To enable tab completion for fiona-assistant, run once:"
|
||||
Write-FionaStatus " fiona-assistant --init"
|
||||
Write-FionaStatus ""
|
||||
Write-FionaStatus "Happy coding!"
|
||||
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
---
|
||||
name: plan
|
||||
version: 1.0.0
|
||||
description: Review findings for fiona-assistant and the proposed fixes.
|
||||
---
|
||||
|
||||
# fiona-assistant plan: review 2026-12-02
|
||||
|
||||
A review of fiona-assistant 1.23.0 (`60de114`). The test suite was
|
||||
green when it ran (1195 passed, 3 skipped, in 116 s). Each item says
|
||||
what is wrong, how it was seen, and the proposed fix. Items marked
|
||||
*confirmed* were reproduced. Cite an item as `plan item N.M`; new items
|
||||
take the next free number. Items are not behavior yet: SPEC changes
|
||||
first. [todo.md](./todo.md) stays the backlog; this file holds the
|
||||
review.
|
||||
|
||||
<!-- toc-start: headings 2..6 -->
|
||||
|
||||
- [1. What to keep](#1-what-to-keep)
|
||||
- [2. Flaws](#2-flaws)
|
||||
- [3. Performance](#3-performance)
|
||||
- [4. User experience](#4-user-experience)
|
||||
- [5. Third-party libraries](#5-third-party-libraries)
|
||||
- [6. Consistency with daedalus and phronesis](#6-consistency-with-daedalus-and-phronesis)
|
||||
- [7. Suggested order](#7-suggested-order)
|
||||
|
||||
<!-- toc-end -->
|
||||
|
||||
## 1. What to keep
|
||||
|
||||
- **1.1** The split of work is right: the agent writes, and fiona does
|
||||
the deterministic chores. `housekeeping`, which ends in a concrete
|
||||
"next steps" list, is the best part of the user experience. Keep it
|
||||
as the single entry point the agent learns first.
|
||||
- **1.2** These guardrails should stay: `raw/` and `personal/` are
|
||||
read-only, sources are deduplicated by sha256, provenance goes into
|
||||
the frontmatter, a login wall exits 4 and never asks for credentials,
|
||||
and the graph server binds to loopback by default with a warning for
|
||||
any other host.
|
||||
- **1.3** Delegating linting to daedalus (SPEC 3.5.1) is the right
|
||||
direction. Finish it (daedalus plan item 23.12), so that
|
||||
`sanity_runner`, `run_sanity.py`, and `linting/` shrink to thin
|
||||
adapters.
|
||||
|
||||
## 2. Flaws
|
||||
|
||||
- **2.1** *Confirmed.* `git restore` does not remove files that were
|
||||
added after the snapshot.
|
||||
- **2.1.1** Reproduction: snapshot `base`, add `b.md`, `git save`,
|
||||
then `git restore base`. `b.md` is still there.
|
||||
- **2.1.2** The cause is that
|
||||
`self.repo.git.checkout(tag_ref.commit, "--", ".")`
|
||||
(`src/fiona/gittool/git_tool.py:198`) only writes the paths that
|
||||
exist in the tag.
|
||||
- **2.1.3** Fix:
|
||||
`git restore --source=<tag> --staged --worktree -- :/`. It deletes
|
||||
tracked files that are absent from the source. Then commit.
|
||||
- **2.1.4** Add a test for the case where a file was added after the
|
||||
snapshot.
|
||||
- **2.2** *Confirmed.* `git clean` and `git undo` destroy work without
|
||||
asking.
|
||||
- **2.2.1** `clean` runs `reset --hard HEAD` and then `clean -fd`
|
||||
(`git_tool.py:219-222`). `undo` runs `reset --hard HEAD~1`
|
||||
(`git_tool.py:246`). Neither command has a prompt or a `--yes`.
|
||||
- **2.2.2** The wiki `.gitignore` ignores only `personal/`, so
|
||||
`clean` also deletes a new file dropped into `ingest/` and a fresh
|
||||
`raw/` archive that has not been committed yet. That breaks the
|
||||
"raw/ is never lost" guarantee.
|
||||
- **2.2.3** The README says "Commands that need a decision prompt on
|
||||
a terminal."
|
||||
- **2.2.4** Fix for `clean`: list what will be lost and ask `[y/N]`
|
||||
(`--yes` for agents). Use
|
||||
`git stash push --include-untracked -m "fiona clean <timestamp>"`
|
||||
instead of deleting, so the work can be recovered.
|
||||
- **2.2.5** Fix for `undo`: use `git revert --no-edit HEAD`, which
|
||||
keeps the history and matches the "restore without losing history"
|
||||
promise.
|
||||
- **2.3** *Confirmed.* The link graph misses real links and counts fake
|
||||
ones. `MarkdownLinkParser` (`src/fiona/wiki/graph_generator.py:593`)
|
||||
uses two regular expressions on the raw text.
|
||||
- **2.3.1** `_is_external_or_fragment` drops every link containing
|
||||
`#`, so `[b](b.md#intro)` and `[[c#x]]` produce no edge.
|
||||
- **2.3.2** Links inside code fences count as links.
|
||||
- **2.3.3** `[^)]+` cuts a URL that contains `)`.
|
||||
- **2.3.4** Seen in this run: for
|
||||
`[b](b.md#intro)`, `[[c#x]]`, a fenced `[fake](nope.md)`, and
|
||||
`[u](https://x.org/a_(b))`, the parser returned only
|
||||
`['nope.md']`.
|
||||
- **2.3.5** The result is false orphans in `housekeeping`, missing
|
||||
edges, and false broken links.
|
||||
- **2.3.6** Fix: strip the fragment instead of dropping the link, and
|
||||
parse with markdown-it-py (item 5.1), which skips code by
|
||||
construction.
|
||||
- **2.4** *Confirmed.* `housekeeping` miscounts the sanity checks. It
|
||||
printed `[PASS] sanity: 0 violation(s) in 0 check(s)` when
|
||||
`wiki sanity` ran 7 checks. `housekeeping.py:264` counts only the
|
||||
failing checks. Print the number of checks that ran.
|
||||
- **2.5** *Confirmed.* `fiona.log` appears wherever fiona runs.
|
||||
- **2.5.1** The packaged default `file_log_location` is a relative
|
||||
`fiona.log`, resolved against the current working directory.
|
||||
- **2.5.2** Seen in this run: a `fiona.log` appeared in a plain git
|
||||
repository that is not a wiki, and in a wiki's `wiki/` subfolder.
|
||||
- **2.5.3** Nothing rotates the log. This repository's own
|
||||
`fiona.log` is 11.8 MB, all of it from test runs.
|
||||
- **2.5.4** Fix: resolve the location against the wiki root. Write no
|
||||
file log outside a wiki. Use `logging.handlers.RotatingFileHandler`
|
||||
(for example 1 MB times 3). Turn file logging off in the test
|
||||
fixtures.
|
||||
- **2.6** *Confirmed.* Some commands find the wiki root and some do not.
|
||||
`wiki check-update` run from the `wiki/` subfolder fails with
|
||||
`Directory '.' is not an llm-wiki directory`, although
|
||||
`resolve_directory` (SPEC 7.20) exists and other commands use it. The
|
||||
README still says discovery is not built. Route every command's
|
||||
default directory through `_root_or_exit`, then fix the README.
|
||||
- **2.7** The graph HTML needs the network. The template loads
|
||||
`https://d3js.org/d3.v7.min.js`
|
||||
(`src/fiona/wiki/templates/graph_template.fragment.html:7`), which
|
||||
floats on major version 7 and carries no integrity hash. The README
|
||||
calls the result "a single self-contained HTML file". Fix: vendor a
|
||||
pinned `d3.min.js` (ISC license, compatible with GPL-3.0) as package
|
||||
data and inline it, the same way `graph_live.js` and
|
||||
`graph_physics.js` are already inlined.
|
||||
- **2.8** `GitPython` commits skip the user's git setup.
|
||||
`repo.index.commit(...)` writes the commit in Python, so it skips git
|
||||
hooks and `commit.gpgsign`, and a YubiKey-signing setup (daedalus
|
||||
gpgtools) gets unsigned wiki commits without warning. Item 5.4
|
||||
proposes the fix.
|
||||
- **2.9** *Confirmed.* Versions are stale in two places.
|
||||
- **2.9.1** `.venv/bin/fiona-assistant --version` prints `1.21.1`,
|
||||
while `pyproject.toml` says `1.23.0` (the editable install is
|
||||
stale; run through `uv run`).
|
||||
- **2.9.2** 30 modules carry their own `__version__` constant (for
|
||||
example `__main__.py` has `1.2.0` and `logging_config.py` has
|
||||
`1.0.0`) that nothing reads or maintains. Delete them and use
|
||||
`importlib.metadata` as the only source.
|
||||
|
||||
## 3. Performance
|
||||
|
||||
- **3.1** Every command takes about 1 s to start, `--version`
|
||||
included (1.3 s on the Pi). `__main__.py` imports every subcommand
|
||||
module at the top. In the import profile:
|
||||
- **3.1.1** `fiona.linting.commands` pulls in `daedalus.linter.api`,
|
||||
0.68 s.
|
||||
- **3.1.2** `esprima.character` alone takes 0.42 s.
|
||||
- **3.1.3** The ingest pipeline takes 0.15 s.
|
||||
- **3.1.4** argcomplete runs the program up to `autocomplete()` for
|
||||
each Tab press, so tab completion pays the same second on every
|
||||
keystroke.
|
||||
- **3.1.5** Fix: import inside each `_run_*` handler, and keep only
|
||||
argparse and argcomplete at module level. Target under 150 ms for
|
||||
`--help`, `--version`, and completion.
|
||||
- **3.1.6** Add a test that fails if `import fiona.__main__` pulls in
|
||||
`daedalus.linter`.
|
||||
- **3.2** `wiki sanity` takes 13 s on a 22-page wiki (100 KB) on the
|
||||
Pi, and `housekeeping` takes the same time because it runs sanity.
|
||||
- **3.2.1** `markdownlint` took 12 s and `mdlinter` took 12 s.
|
||||
- **3.2.2** A profile shows pymarkdown's block parser at about 1.2 s
|
||||
per file.
|
||||
- **3.2.3** Fix: a per-file result cache keyed by content sha256,
|
||||
settings, and tool version (daedalus plan item 33.5.2).
|
||||
- **3.2.4** Also check whether `mdlinter` parses every file a second
|
||||
time; one parse should serve both checks.
|
||||
|
||||
## 4. User experience
|
||||
|
||||
- **4.1** The command tree is flat and mixed. Five linters (`mdoctor`,
|
||||
`fmlint`, `python-ruff`, `json-lint`, `html-js-lint`) sit at the top
|
||||
level next to `wiki`, `git`, `housekeeping`, and `setup`, while
|
||||
`wiki sanity`, which runs those same linters, sits under `wiki`.
|
||||
Users cannot guess where a command lives. Proposal, with the old
|
||||
forms kept as hidden aliases for one minor release:
|
||||
- **4.1.1** Top level, for the daily verbs: `init`, `ingest`,
|
||||
`housekeeping`, `sanity`, `graph`, `update`, and `check-update`.
|
||||
- **4.1.2** `lint <check> [paths]` for the single linters:
|
||||
`markdown`, `frontmatter`, `python`, `json`, and `htmljs`.
|
||||
- **4.1.3** `git ...` and `librarian ...` stay as they are.
|
||||
- **4.1.4** `self update` and `self completion` replace the top-level
|
||||
`--update`, `--init`, `--bashrc`, `--profile`, and `--dry-run`,
|
||||
which today crowd the main `--help`.
|
||||
- **4.1.5** With no subcommand, print a short usage block like
|
||||
phronesis does (phronesis plan item 15.1.2): the five most-used
|
||||
commands and one line each.
|
||||
- **4.2** The program name is long, and the extra entry points crowd
|
||||
`PATH`.
|
||||
- **4.2.1** Add a `fiona` console script next to `fiona-assistant`.
|
||||
- **4.2.2** Remove the global `librarian`, `mdoctor`, and
|
||||
`html-js-lint` entry points. They are generic names that can
|
||||
collide with other tools, and the same commands already exist
|
||||
under `fiona-assistant`.
|
||||
- **4.3** `--help` cites SPEC sections (`(SPEC 7.23)`, `(SPEC 7.24)`),
|
||||
which users do not have. Keep the citations in comments.
|
||||
- **4.4** Some names and help lines say nothing. `mdoctor` is described
|
||||
as "Diagnose wiki content", and the name tells nothing about
|
||||
markdown links or tables. With item 4.1.2 it becomes
|
||||
`lint markdown`.
|
||||
- **4.5** The README has drifted from the CLI.
|
||||
- **4.5.1** It says `wiki sanity` runs "five checks"; the run here
|
||||
showed seven (`fenced-code` and `html-js-lint` are missing from the
|
||||
table).
|
||||
- **4.5.2** It says root discovery is not built (item 2.6).
|
||||
- **4.5.3** It promises a self-contained graph (item 2.7).
|
||||
- **4.5.4** Fix: add a test that checks every subcommand in the
|
||||
parser appears in the README's command reference, so the next
|
||||
drift fails `autotest`.
|
||||
- **4.6** In the help text, `git clean` and `git undo` read like
|
||||
harmless chores. After item 2.2, the help line should say what is
|
||||
discarded and that it can be recovered.
|
||||
|
||||
## 5. Third-party libraries
|
||||
|
||||
Each library here is widely used and actively maintained.
|
||||
|
||||
- **5.1** **markdown-it-py** (Executable Books, MIT) with
|
||||
**mdit-py-plugins** (`front_matter`, `anchors`) replaces the regular
|
||||
expressions in `graph_generator.py`, `link_rewriter.py`, and
|
||||
`toc_generator.py`. `HEADER_RE` misses setext headings, the fence
|
||||
detection misses indented and nested fences, and the graph regexes
|
||||
have the flaws of item 2.3. A token stream gives links, headings,
|
||||
and code spans correctly in one pass. Wikilinks need a short custom
|
||||
inline rule, about 30 lines.
|
||||
- **5.2** **trafilatura** (Apache-2.0) for HTML ingest. It extracts the
|
||||
main article text and metadata (title, author, date) and drops
|
||||
navigation, footers, and cookie banners. That means fewer tokens
|
||||
spent by the agent refining raw pages, which is the product's core
|
||||
promise. Keep the BeautifulSoup and markdownify path as the
|
||||
fallback when trafilatura finds no main content.
|
||||
- **5.3** **markitdown** (Microsoft, MIT) as an optional extra,
|
||||
`fiona-assistant[office]`, for `.docx`, `.pptx`, `.xlsx`, and
|
||||
`.epub`. Keep `pypdf` for PDF, since it has no heavy native
|
||||
dependencies.
|
||||
- **5.4** Drop **GitPython**. Its maintainers describe it as being in
|
||||
maintenance mode. fiona mostly calls `repo.git.<cmd>`, which already
|
||||
just runs git. Call git with `subprocess` as daedalus and phronesis
|
||||
do, and use real `git commit`, which fixes item 2.8.
|
||||
- **5.5** **packaging** (already installed through daedalus-tools):
|
||||
`packaging.version.Version` replaces the hand-written
|
||||
`is_version_newer` (`src/fiona/wiki/update_manager.py:268`), which
|
||||
returns wrong answers for pre-release versions.
|
||||
- **5.6** For template updates, use a three-way merge with
|
||||
`git merge-file`, which needs no new dependency since git is already
|
||||
required.
|
||||
- **5.6.1** Today `corefiles.json` stores only hashes, so a change on
|
||||
both sides always produces a `*-update.md` for the agent to merge
|
||||
by hand.
|
||||
- **5.6.2** Store the template copy that was applied (under
|
||||
`.fiona/base/`), merge base, wiki, and new template with
|
||||
`git merge-file`, and write `*-update.md` (with conflict markers)
|
||||
only for real conflicts.
|
||||
- **5.6.3** In the wiki reviewed here, 3 of 3 conflicts were waiting
|
||||
for a manual merge.
|
||||
- **5.6.4** Copier was considered and does not fit: it needs the
|
||||
template in a git repository, while fiona's template ships inside
|
||||
the wheel.
|
||||
- **5.7** Use the standard library's
|
||||
`logging.handlers.RotatingFileHandler` (item 2.5).
|
||||
|
||||
## 6. Consistency with daedalus and phronesis
|
||||
|
||||
- **6.1** The copies have drifted apart. fiona carries its own copy of
|
||||
`self_update.py` (267 lines), `publish.py` (297 lines), and
|
||||
`completion_init.py` (184 lines). daedalus and phronesis carry the
|
||||
same modules, and every fix (the Windows `--system-certs` retry,
|
||||
PowerShell completion) has landed three times.
|
||||
- **6.2** daedalus plan item 33.4.1 proposes one small shared package.
|
||||
fiona should take it as soon as it exists.
|
||||
- **6.3** Confirmation flags differ across the three tools: daedalus
|
||||
uses `-y`, phronesis uses `-f`, and fiona uses `--yes`, `--force`,
|
||||
and `--non-interactive`. Agree on `-y`/`--yes` everywhere and keep
|
||||
`--non-interactive` for "never prompt, fail instead"
|
||||
(daedalus plan item 33.6).
|
||||
|
||||
## 7. Suggested order
|
||||
|
||||
- **7.1** Bugs that can lose data: items 2.2 and 2.1.
|
||||
- **7.2** Correctness of what the agent is told: items 2.3, 2.4, and
|
||||
2.6.
|
||||
- **7.3** Startup time: item 3.1. It is small and touches every
|
||||
command.
|
||||
- **7.4** Hygiene: items 2.5, 2.7, 2.9, and 4.3.
|
||||
- **7.5** The CLI restructure: item 4.1, with aliases.
|
||||
- **7.6** Library swaps: items 5.1, 5.4, and 5.6, then 5.2 and 5.3.
|
||||
+19
-3
@@ -4,12 +4,12 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "fiona-assistant"
|
||||
version = "1.21.1"
|
||||
version = "1.23.0"
|
||||
description = "Tools for managing the LLM wiki."
|
||||
authors = [{name = "nvaldeziii"}]
|
||||
readme = "README.md"
|
||||
license = "GPL-3.0-only"
|
||||
requires-python = ">=3.11"
|
||||
requires-python = ">=3.11.4" # daedalus-tools needs 3.11.4 (SPEC 2.7)
|
||||
classifiers = [
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
@@ -29,9 +29,24 @@ dependencies = [
|
||||
"pypdf>=5.0.0",
|
||||
# AI/LLM: 2026-11-27 - skills come from phronesis (SPEC 3.4.1).
|
||||
"phronesis>=0.16.0",
|
||||
# AI/LLM: 2026-11-30 - tab completion for fiona-assistant (SPEC 7.23.2).
|
||||
"argcomplete>=3.3",
|
||||
]
|
||||
|
||||
# Optional dependencies groups
|
||||
# Development dependencies: uv sync installs this group (SPEC 2.5).
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"pytest>=7.0.0",
|
||||
"pytest-cov>=4.0.0",
|
||||
"pytest-mock",
|
||||
"pylint",
|
||||
"build",
|
||||
"twine",
|
||||
"ruff",
|
||||
]
|
||||
|
||||
# Optional dependencies groups. The dev extra mirrors the dev group for one
|
||||
# release so pip install -e ".[dev]" keeps working (SPEC 2.6).
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"pytest>=7.0.0",
|
||||
@@ -40,6 +55,7 @@ dev = [
|
||||
"pylint",
|
||||
"build",
|
||||
"twine",
|
||||
"ruff",
|
||||
]
|
||||
|
||||
[tool.setuptools]
|
||||
|
||||
@@ -1,51 +1,56 @@
|
||||
"""Pip arguments for bootstrap install modes.
|
||||
"""uv arguments for bootstrap install modes.
|
||||
|
||||
Generated by AI/LLM: 2026-09-30 - local and no-env install options.
|
||||
Updated by AI/LLM: 2026-11-29 - uv replaces pip (SPEC 7.21).
|
||||
|
||||
SPEC 7.21. Both ``bootstrap`` and ``bootstrap.ps1`` call this script
|
||||
and read one pip argument per stdout line.
|
||||
and read one uv argument per stdout line.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
__version__ = "1.0.0"
|
||||
__version__ = "2.0.0"
|
||||
|
||||
TOOL_EXECUTABLES_FROM = "phronesis"
|
||||
|
||||
|
||||
def pip_install_args(
|
||||
def uv_install_args(
|
||||
*,
|
||||
local: bool,
|
||||
no_env: bool,
|
||||
break_system_packages: bool = False,
|
||||
python: str | None = None,
|
||||
) -> list[str]:
|
||||
"""Return the arguments passed to ``python -m pip``.
|
||||
"""Return the arguments passed to ``uv``.
|
||||
|
||||
Args:
|
||||
local: Install this repository as a normal package. When
|
||||
false, the install is editable and includes the ``dev``
|
||||
extra.
|
||||
no_env: Add ``--user`` so the install does not need a virtual
|
||||
environment.
|
||||
break_system_packages: Add ``--break-system-packages``. Bash
|
||||
sets this. PowerShell does not.
|
||||
local: Install this repository as a normal, non-editable package.
|
||||
When false, the install is editable and includes the ``dev``
|
||||
group.
|
||||
no_env: Install a uv tool instead of syncing ``.venv``. The tool
|
||||
puts the commands on ``PATH`` with no activation.
|
||||
python: Interpreter version to pass as ``--python``, or None to
|
||||
let uv read ``.python-version``.
|
||||
|
||||
Returns:
|
||||
The pip argument list, starting with ``install``.
|
||||
The uv argument list, without the leading ``uv``.
|
||||
"""
|
||||
args = ["install"]
|
||||
if no_env:
|
||||
args.append("--user")
|
||||
if break_system_packages:
|
||||
args.append("--break-system-packages")
|
||||
if local:
|
||||
args.append(".")
|
||||
args = ["tool", "install", "--force"]
|
||||
if not local:
|
||||
args.append("--editable")
|
||||
args.extend([".", "--with-executables-from", TOOL_EXECUTABLES_FROM])
|
||||
elif local:
|
||||
args = ["sync", "--no-editable", "--no-dev"]
|
||||
else:
|
||||
args.extend(["-e", ".[dev]"])
|
||||
args = ["sync"]
|
||||
if python:
|
||||
args.extend(["--python", python])
|
||||
return args
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
"""Print pip arguments, one per line.
|
||||
"""Print uv arguments, one per line.
|
||||
|
||||
Args:
|
||||
argv: Flags to parse. ``None`` reads ``sys.argv``.
|
||||
@@ -54,28 +59,28 @@ def main(argv: list[str] | None = None) -> int:
|
||||
Process exit code. ``0`` after the arguments are written.
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Print pip install arguments for bootstrap.",
|
||||
description="Print uv arguments for bootstrap.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--local",
|
||||
action="store_true",
|
||||
help="install this repository as a normal package",
|
||||
help="install this repository as a normal, non-editable package",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-env",
|
||||
action="store_true",
|
||||
help="add --user so no virtual environment is required",
|
||||
help="install a uv tool so no virtual environment is activated",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--break-system-packages",
|
||||
action="store_true",
|
||||
help="pass --break-system-packages to pip",
|
||||
"--python",
|
||||
default=None,
|
||||
help="interpreter version to pass to uv as --python",
|
||||
)
|
||||
parsed = parser.parse_args(argv)
|
||||
words = pip_install_args(
|
||||
words = uv_install_args(
|
||||
local=parsed.local,
|
||||
no_env=parsed.no_env,
|
||||
break_system_packages=parsed.break_system_packages,
|
||||
python=parsed.python,
|
||||
)
|
||||
sys.stdout.write("\n".join(words) + "\n")
|
||||
return 0
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
#!/bin/bash
|
||||
# version: 1.0.1
|
||||
|
||||
SILENT_INSTALL=false
|
||||
PIP_INSTALL_FLAGS="--force-reinstall -q"
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # scripts root directory
|
||||
|
||||
# Default virtual environment name (can be overridden by bootstrap)
|
||||
export PYENV_NAME="${PYENV_NAME:-test_env}"
|
||||
|
||||
# shellcheck source=utils.sh
|
||||
source "${SCRIPT_DIR}/utils.sh"
|
||||
|
||||
# Function to check if a package is already installed
|
||||
is_installed() {
|
||||
local package_name="$1"
|
||||
pip show "$package_name" > /dev/null 2>&1
|
||||
}
|
||||
|
||||
# Function to uninstall a package
|
||||
uninstall_package() {
|
||||
local package_name="$1"
|
||||
if is_installed "$package_name"; then
|
||||
echo_warning "Uninstalling $package_name..."
|
||||
pip uninstall -y "$package_name"
|
||||
fi
|
||||
}
|
||||
|
||||
# Function to check if a virtual environment is active
|
||||
check_pyenv() {
|
||||
# Check if a virtual environment is active
|
||||
if [ -z "$VIRTUAL_ENV" ] && [ -z "$PYENV_VIRTUAL_ENV" ]; then
|
||||
echo "No virtual environment is loaded."
|
||||
echo "Please activate a pyenv virtual environment first."
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Get the current environment name for logging
|
||||
local current_env_name=""
|
||||
if [ -n "$PYENV_VIRTUAL_ENV" ]; then
|
||||
current_env_name="$(basename "$PYENV_VIRTUAL_ENV")"
|
||||
elif [ -n "$VIRTUAL_ENV" ]; then
|
||||
current_env_name="$(basename "$VIRTUAL_ENV")"
|
||||
fi
|
||||
|
||||
echo "Pyenv environment $current_env_name is active"
|
||||
return 0
|
||||
}
|
||||
|
||||
# Function to install a package in development mode
|
||||
install_package() {
|
||||
local package_dir="."
|
||||
echo_status "Installing $package_name in development mode..."
|
||||
# PIP_INSTALL_FLAGS holds several flags that must split into words
|
||||
# shellcheck disable=SC2086
|
||||
pip install ${PIP_INSTALL_FLAGS} -e "$package_dir"
|
||||
}
|
||||
|
||||
# Main function
|
||||
main() {
|
||||
local skip_installed=false
|
||||
local package_name=""
|
||||
|
||||
# Parse arguments
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
-s|--skip-installed)
|
||||
skip_installed=true
|
||||
shift
|
||||
;;
|
||||
--silent)
|
||||
export SILENT_INSTALL=true
|
||||
shift
|
||||
;;
|
||||
*)
|
||||
echo "Unknown argument: $1"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
check_pyenv || {
|
||||
echo_error "py env required!"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Check for root pyproject.toml
|
||||
if [ -f "pyproject.toml" ]; then
|
||||
# Extract package name from pyproject.toml
|
||||
package_name=$(grep -oP '^name\s*=\s*"\K[^"]+' "pyproject.toml")
|
||||
|
||||
if [ -z "$package_name" ]; then
|
||||
echo_error "Could not extract package name from pyproject.toml."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Found package: $package_name"
|
||||
|
||||
if [ "$skip_installed" = true ] && is_installed "$package_name"; then
|
||||
echo_warning "$package_name is already installed. Skipping..."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Uninstall existing package (unless skipping)
|
||||
if [ "$skip_installed" = false ]; then
|
||||
uninstall_package "$package_name"
|
||||
fi
|
||||
|
||||
# Install the package
|
||||
install_package
|
||||
else
|
||||
echo_warning "No pyproject.toml found in the current directory."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo_status "Packages installed successfully."
|
||||
}
|
||||
|
||||
# Run the main function
|
||||
pushd "${SCRIPT_DIR}" >/dev/null || exit
|
||||
main "$@"
|
||||
popd >/dev/null || exit
|
||||
+64
-1
@@ -3,12 +3,17 @@
|
||||
This module provides a command-line interface for the Fiona-Assistant package.
|
||||
It delegates commands to the appropriate sub-tools (e.g., librarian, mdoctor).
|
||||
"""
|
||||
# PYTHON_ARGCOMPLETE_OK
|
||||
|
||||
import argparse
|
||||
import dataclasses
|
||||
import logging
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
import argcomplete
|
||||
|
||||
from fiona import completion_init, self_update
|
||||
from fiona.gittool import diff_report
|
||||
from fiona.gittool import git_tool as git_tool_module
|
||||
from fiona.librarian import librarian as librarian_tool
|
||||
@@ -28,7 +33,7 @@ from fiona.wiki.skills import SkillsError
|
||||
from fiona.wiki.update_manager import check_update_main, update_main
|
||||
from fiona.wiki.wiki import wiki_init
|
||||
|
||||
__version__ = "1.1.0"
|
||||
__version__ = "1.2.0"
|
||||
|
||||
|
||||
def _root_or_exit(directory: str | None) -> str:
|
||||
@@ -77,6 +82,44 @@ def _build_parser() -> _Parsers:
|
||||
action="version",
|
||||
version=f"fiona-assistant {package_version()}",
|
||||
)
|
||||
# Tab completion init (SPEC section 7.23).
|
||||
# Distinct dest names: a subcommand's own --dry-run shares this namespace.
|
||||
parser.add_argument(
|
||||
"--init",
|
||||
dest="init_shell",
|
||||
action="store_true",
|
||||
help="register tab completion for fiona-assistant in the shell (SPEC 7.23)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--bashrc",
|
||||
dest="init_bashrc",
|
||||
metavar="PATH",
|
||||
type=pathlib.Path,
|
||||
default=None,
|
||||
help="with --init on bash: the target file (default ~/.bashrc)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--profile",
|
||||
dest="init_profile",
|
||||
metavar="PATH",
|
||||
type=pathlib.Path,
|
||||
default=None,
|
||||
help="with --init on Windows: the PowerShell profile (default $PROFILE)",
|
||||
)
|
||||
# Self-update (SPEC 7.24).
|
||||
parser.add_argument(
|
||||
"--update",
|
||||
dest="self_update",
|
||||
action="store_true",
|
||||
help="upgrade fiona-assistant itself with the tool that installed it (SPEC 7.24)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dry-run",
|
||||
dest="init_dry_run",
|
||||
action="store_true",
|
||||
help="with --init: print the block and the target; with --update: "
|
||||
"print what would run; change nothing",
|
||||
)
|
||||
subparsers = parser.add_subparsers(dest="command", help="Available commands")
|
||||
|
||||
# fiona-assistant librarian
|
||||
@@ -614,7 +657,27 @@ def _run_housekeeping(args: argparse.Namespace, _parsers: _Parsers) -> None:
|
||||
def _dispatch() -> None:
|
||||
"""Entry point for the Fiona-Assistant CLI."""
|
||||
parsers = _build_parser()
|
||||
argcomplete.autocomplete(parsers.root)
|
||||
args = parsers.root.parse_args()
|
||||
if args.self_update: # SPEC 7.24.1: runs before any other dispatch
|
||||
if (
|
||||
args.command is not None
|
||||
or args.init_shell
|
||||
or args.init_bashrc is not None
|
||||
or args.init_profile is not None
|
||||
):
|
||||
parsers.root.error("--update takes no subcommand: fiona-assistant --update [--dry-run]")
|
||||
sys.exit(self_update.run(args.init_dry_run))
|
||||
if args.init_dry_run and not args.init_shell:
|
||||
parsers.root.error("--dry-run needs --init or --update")
|
||||
if (args.init_bashrc is not None or args.init_profile is not None) and not args.init_shell:
|
||||
parsers.root.error("--bashrc and --profile need --init")
|
||||
if args.init_shell: # SPEC 7.23.1: runs before any other dispatch
|
||||
sys.exit(
|
||||
completion_init.init_shell_completion(
|
||||
args.init_bashrc, args.init_dry_run, args.init_profile
|
||||
)
|
||||
)
|
||||
setup_logging()
|
||||
logging.getLogger(__name__).debug("fiona-assistant command: %s", args.command)
|
||||
if args.command is None:
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
"""Tab-completion registration for ``fiona-assistant --init`` (SPEC section 7.23).
|
||||
|
||||
Installing the package never touches a shell. This module writes one managed
|
||||
block to the user's shell profile: a bash ``eval`` line on posix, and a
|
||||
PowerShell ``Invoke-Expression`` line on Windows.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
__version__ = "1.0.0"
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
INIT_MARKER_BEGIN = "# BEGIN fiona-assistant init: argcomplete"
|
||||
INIT_MARKER_END = "# END fiona-assistant init: argcomplete"
|
||||
EXIT_NO_REGISTER = 3
|
||||
PROGRAM = "fiona-assistant"
|
||||
POLICY_HINT = "Set-ExecutionPolicy -Scope CurrentUser RemoteSigned"
|
||||
|
||||
|
||||
def is_windows() -> bool:
|
||||
"""Return True on Windows, where the hook is a PowerShell block (SPEC 7.23.7)."""
|
||||
return os.name == "nt"
|
||||
|
||||
|
||||
def register_script_path() -> pathlib.Path | None:
|
||||
"""Locate this interpreter's register-python-argcomplete (SPEC 7.23.4, 7.23.8).
|
||||
|
||||
Returns:
|
||||
The script beside ``sys.executable`` if present, else the first match
|
||||
on ``PATH``, else None.
|
||||
"""
|
||||
name = "register-python-argcomplete" + (".exe" if is_windows() else "")
|
||||
beside = pathlib.Path(sys.executable).parent / name
|
||||
# No resolve(): a venv python is a symlink into the system install.
|
||||
if beside.is_file():
|
||||
return beside
|
||||
found = shutil.which(name)
|
||||
return pathlib.Path(found) if found else None
|
||||
|
||||
|
||||
def build_hook_block(register_path: pathlib.Path) -> str:
|
||||
"""Build the managed bash block (SPEC 7.23.3)."""
|
||||
line = f"eval \"$('{register_path}' {PROGRAM})\""
|
||||
return f"{INIT_MARKER_BEGIN}\n{line}\n{INIT_MARKER_END}\n"
|
||||
|
||||
|
||||
def build_powershell_hook_block(register_path: pathlib.Path) -> str:
|
||||
"""Build the managed PowerShell block (SPEC 7.23.7)."""
|
||||
line = (f"& '{register_path}' --shell powershell {PROGRAM}"
|
||||
" | Out-String | Invoke-Expression")
|
||||
return f"{INIT_MARKER_BEGIN}\n{line}\n{INIT_MARKER_END}\n"
|
||||
|
||||
|
||||
def _powershell_output(command: str) -> str | None:
|
||||
"""Run one command in PowerShell with no profile (SPEC 7.23.9, 7.23.10).
|
||||
|
||||
Returns:
|
||||
The last non-empty output line, or None when no shell answers.
|
||||
"""
|
||||
for shell in ("pwsh", "powershell"):
|
||||
try:
|
||||
done = subprocess.run(
|
||||
[shell, "-NoProfile", "-Command", command],
|
||||
check=False, capture_output=True, text=True, timeout=60,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
logger.debug("%s did not run for %r", shell, command)
|
||||
continue
|
||||
if done.returncode == 0 and done.stdout.strip():
|
||||
return done.stdout.strip().splitlines()[-1].strip()
|
||||
return None
|
||||
|
||||
|
||||
def powershell_profile() -> pathlib.Path | None:
|
||||
"""Return the CurrentUserCurrentHost profile path PowerShell reports."""
|
||||
answer = _powershell_output("$PROFILE")
|
||||
return pathlib.Path(answer) if answer else None
|
||||
|
||||
|
||||
def execution_policy() -> str | None:
|
||||
"""Return the CurrentUser execution policy, or None when it cannot be read."""
|
||||
return _powershell_output("Get-ExecutionPolicy")
|
||||
|
||||
|
||||
def _append_block(target: pathlib.Path, block: str) -> None:
|
||||
"""Append ``block`` to ``target``, keeping existing content (SPEC 7.23.5)."""
|
||||
existing = target.read_text(encoding="utf-8") if target.exists() else ""
|
||||
content = existing
|
||||
if content and not content.endswith("\n"):
|
||||
content += "\n" # never glue the marker onto a line
|
||||
if content.strip():
|
||||
content += "\n" # one blank line before the block
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(content + block, encoding="utf-8")
|
||||
|
||||
|
||||
def _init_posix(bashrc: pathlib.Path | None, dry_run: bool) -> int:
|
||||
"""Register the bash hook (SPEC 7.23.3 to 7.23.6)."""
|
||||
register = register_script_path()
|
||||
if register is None:
|
||||
print(f"fiona-assistant: register-python-argcomplete not found next to "
|
||||
f"python ({sys.executable}) nor on PATH; reinstall fiona-assistant "
|
||||
f"(argcomplete is a declared dependency)", file=sys.stderr)
|
||||
return EXIT_NO_REGISTER
|
||||
target = bashrc if bashrc is not None else pathlib.Path.home() / ".bashrc"
|
||||
existing = target.read_text(encoding="utf-8") if target.exists() else ""
|
||||
if INIT_MARKER_BEGIN in existing:
|
||||
print(f"already enabled: {INIT_MARKER_BEGIN} found in {target}")
|
||||
return 0
|
||||
block = build_hook_block(register)
|
||||
if dry_run:
|
||||
print(block, end="")
|
||||
print(f"dry run: would append the block to {target}")
|
||||
return 0
|
||||
_append_block(target, block)
|
||||
print(f"registered tab completion for fiona-assistant in {target}")
|
||||
print("activate it now with: exec bash (or open a new shell)")
|
||||
return 0
|
||||
|
||||
|
||||
def _init_windows(profile: pathlib.Path | None, dry_run: bool) -> int:
|
||||
"""Register the PowerShell hook (SPEC 7.23.7 to 7.23.10)."""
|
||||
register = register_script_path()
|
||||
if register is None:
|
||||
print(f"fiona-assistant: register-python-argcomplete.exe not found next to "
|
||||
f"python ({sys.executable}) nor on PATH; reinstall fiona-assistant "
|
||||
f"(argcomplete is a declared dependency)", file=sys.stderr)
|
||||
return EXIT_NO_REGISTER
|
||||
if profile is None:
|
||||
profile = powershell_profile()
|
||||
if profile is None:
|
||||
print("fiona-assistant: could not ask PowerShell for $PROFILE (neither "
|
||||
"pwsh nor powershell answered); pass --profile <path>", file=sys.stderr)
|
||||
return EXIT_NO_REGISTER
|
||||
existing = profile.read_text(encoding="utf-8") if profile.exists() else ""
|
||||
if INIT_MARKER_BEGIN in existing:
|
||||
print(f"already enabled: {INIT_MARKER_BEGIN} found in {profile}")
|
||||
return 0
|
||||
block = build_powershell_hook_block(register)
|
||||
if dry_run:
|
||||
print(block, end="")
|
||||
print(f"dry run: would append the block to {profile}")
|
||||
return 0
|
||||
_append_block(profile, block)
|
||||
print(f"registered tab completion for fiona-assistant in {profile}")
|
||||
print("activate it now with: . $PROFILE (or open a new PowerShell window)")
|
||||
if execution_policy() == "Restricted":
|
||||
print("fiona-assistant: the execution policy is Restricted, so the profile "
|
||||
f"will not load; to allow it run: {POLICY_HINT}")
|
||||
return 0
|
||||
|
||||
|
||||
def init_shell_completion(bashrc: pathlib.Path | None, dry_run: bool,
|
||||
profile: pathlib.Path | None = None) -> int:
|
||||
"""Register tab completion in the shell (SPEC section 7.23).
|
||||
|
||||
Args:
|
||||
bashrc: The posix target from ``--bashrc``, or None for ``~/.bashrc``.
|
||||
dry_run: Print the block and the target without writing.
|
||||
profile: The Windows target from ``--profile``, or None for ``$PROFILE``.
|
||||
|
||||
Returns:
|
||||
The exit code: 0 on success, 2 for a flag on the wrong platform, and 3
|
||||
when a register script or the PowerShell profile cannot be found.
|
||||
"""
|
||||
if is_windows():
|
||||
if bashrc is not None:
|
||||
print("fiona-assistant: --bashrc is for bash; on Windows use --profile",
|
||||
file=sys.stderr)
|
||||
return 2
|
||||
return _init_windows(profile, dry_run)
|
||||
if profile is not None:
|
||||
print("fiona-assistant: --profile is for Windows; on this system use --bashrc",
|
||||
file=sys.stderr)
|
||||
return 2
|
||||
return _init_posix(bashrc, dry_run)
|
||||
+30
-25
@@ -1,9 +1,11 @@
|
||||
"""Publish runner for Fiona-Assistant.
|
||||
|
||||
Builds the distribution artifacts and optionally uploads them to
|
||||
PyPI or TestPyPI (SPEC 4.9). Guards refuse a direct-reference
|
||||
dependency on every run and, for an upload, a dirty tree, a missing
|
||||
``v<version>`` tag, and a version the index already holds.
|
||||
Builds the distribution artifacts with ``uv build`` and optionally
|
||||
uploads them to PyPI or TestPyPI with twine (SPEC 4.9). Guards refuse a
|
||||
direct-reference dependency on every run and, for an upload, a dirty
|
||||
tree, a missing ``v<version>`` tag, and a version the index already
|
||||
holds. Publish never installs a package: a missing uv or twine is a
|
||||
refusal (SPEC 4.9.7).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,7 +28,7 @@ HTTP_OK = 200
|
||||
HTTP_NOT_FOUND = 404
|
||||
|
||||
|
||||
__version__ = "1.1.0"
|
||||
__version__ = "2.0.0"
|
||||
|
||||
|
||||
class PublishError(Exception):
|
||||
@@ -135,23 +137,23 @@ class PublishRunner:
|
||||
msg = f"could not check {repository} (status {status}); never publish blind."
|
||||
raise PublishError(msg)
|
||||
|
||||
def ensure_module(self, module: str) -> None:
|
||||
"""Install a Python module with pip when it is missing.
|
||||
def require_tools(self) -> None:
|
||||
"""Refuse to run when uv or twine is missing (SPEC 4.9.7).
|
||||
|
||||
Args:
|
||||
module: The module name to check and install.
|
||||
Publish never installs a package. The fix is named in the error.
|
||||
|
||||
Raises:
|
||||
PublishError: The pre-check or the install failed.
|
||||
PublishError: uv is not on PATH, or twine is not importable
|
||||
by this interpreter.
|
||||
"""
|
||||
if self.run([sys.executable, "-m", module, "--version"]) == 0:
|
||||
return
|
||||
installed = self.run(
|
||||
[sys.executable, "-m", "pip", "install",
|
||||
module, "--break-system-packages"]
|
||||
)
|
||||
if installed != 0:
|
||||
msg = f"pip install {module} failed."
|
||||
if shutil.which("uv") is None:
|
||||
msg = ("uv is not on PATH. Install uv (https://docs.astral.sh/uv/), "
|
||||
"then run `uv sync` in the checkout.")
|
||||
raise PublishError(msg)
|
||||
code, _ = self.capture([sys.executable, "-m", "twine", "--version"])
|
||||
if code != 0:
|
||||
msg = ("twine is not installed for this Python. "
|
||||
"Run `uv sync` in the checkout.")
|
||||
raise PublishError(msg)
|
||||
|
||||
def clean(self) -> None:
|
||||
@@ -165,20 +167,24 @@ class PublishRunner:
|
||||
def artifacts(self) -> list[str]:
|
||||
"""List the distribution file names in dist/.
|
||||
|
||||
uv build also writes a dist/.gitignore; only the wheel and the
|
||||
sdist are distributions, so only those are listed.
|
||||
|
||||
Returns:
|
||||
Sorted names of every regular file under dist/.
|
||||
Sorted names of every wheel and sdist under dist/.
|
||||
"""
|
||||
return sorted(
|
||||
entry.name for entry in self.dist_dir.iterdir() if entry.is_file()
|
||||
entry.name for entry in self.dist_dir.iterdir()
|
||||
if entry.is_file() and entry.name.endswith((".whl", ".tar.gz"))
|
||||
)
|
||||
|
||||
def build(self) -> int:
|
||||
"""Build the distributions with python -m build.
|
||||
"""Build the sdist and wheel with uv build.
|
||||
|
||||
Returns:
|
||||
The build command's exit code.
|
||||
"""
|
||||
return self.run([sys.executable, "-m", "build"])
|
||||
return self.run(["uv", "build"])
|
||||
|
||||
def check(self) -> int:
|
||||
"""Run twine check on every artifact in dist/.
|
||||
@@ -269,12 +275,11 @@ def _publish(runner: PublishRunner, args: argparse.Namespace) -> int:
|
||||
Exit code: 0 when built (and uploaded), otherwise the upload result.
|
||||
"""
|
||||
runner.guard(args.upload, args.repository)
|
||||
runner.ensure_module("build")
|
||||
runner.require_tools()
|
||||
runner.clean()
|
||||
if runner.build() != 0:
|
||||
msg = "python -m build failed."
|
||||
msg = "uv build failed."
|
||||
raise PublishError(msg)
|
||||
runner.ensure_module("twine")
|
||||
if runner.check() != 0:
|
||||
msg = "twine check failed."
|
||||
raise PublishError(msg)
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
"""fiona-assistant --update: upgrade fiona-assistant with the tool that installed it.
|
||||
|
||||
Spec: SPEC 7.24, the same design as daedalus SPEC item 3.15. Detection is
|
||||
pure: it takes the install facts as arguments, so tests fake them.
|
||||
``current_plan`` is the one place that reads the real facts.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import codecs
|
||||
import dataclasses
|
||||
import importlib.metadata
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from fiona.wiki.ingest.settings import package_version as cli_version
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
__version__ = "1.0.0"
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
|
||||
DISTRIBUTION = "fiona-assistant"
|
||||
HINT = "wikis are not updated; run 'fiona-assistant wiki check-update' in each wiki"
|
||||
EXIT_OK = 0
|
||||
EXIT_USAGE = 2
|
||||
EXIT_NO_TOOL = 3
|
||||
EXIT_FAILED = 4
|
||||
CERT_ERROR_MARK = "invalid peer certificate"
|
||||
LOCKED_MARKS = ("Failed to install entrypoint", "os error 32")
|
||||
LOCKED_NOTE = ("note: uv could not replace the running fiona-assistant.exe; the package "
|
||||
"is updated and the current launcher keeps working")
|
||||
SYSTEM_CERTS = "--system-certs"
|
||||
CERT_WARNING = ("warning: uv could not verify a TLS certificate; retrying "
|
||||
"with --system-certs (the Windows certificate store)")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Plan:
|
||||
"""What --update does for this install.
|
||||
|
||||
Attributes:
|
||||
method: checkout, uv, pipx, or other.
|
||||
command: argv to run, or None when nothing runs.
|
||||
message: the line printed for checkout and other installs.
|
||||
exit_code: exit status when command is None.
|
||||
"""
|
||||
|
||||
method: str
|
||||
command: list[str] | None
|
||||
message: str = ""
|
||||
exit_code: int = EXIT_OK
|
||||
|
||||
|
||||
def _under(prefix: str | os.PathLike[str], base: str | os.PathLike[str]) -> bool:
|
||||
"""Return True when prefix is inside base (both resolved)."""
|
||||
return pathlib.Path(prefix).resolve().is_relative_to(pathlib.Path(base).resolve())
|
||||
|
||||
|
||||
def _checkout_path(direct_url: dict) -> str:
|
||||
"""Return the checkout path named by a file:// URL, else the running checkout."""
|
||||
url = direct_url.get("url", "")
|
||||
if url.startswith("file:"):
|
||||
return urllib.request.url2pathname(urllib.parse.urlsplit(url).path)
|
||||
return str(REPO_ROOT)
|
||||
|
||||
|
||||
def detect(
|
||||
prefix: str | os.PathLike[str],
|
||||
direct_url: dict | None,
|
||||
uv_tool_dir: pathlib.Path | None,
|
||||
pipx_venvs: pathlib.Path | None,
|
||||
) -> Plan:
|
||||
"""Choose the update method (SPEC item 7.24.2).
|
||||
|
||||
Args:
|
||||
prefix: sys.prefix of the running fiona-assistant.
|
||||
direct_url: parsed direct_url.json of fiona-assistant, or None.
|
||||
uv_tool_dir: output of ``uv tool dir``, or None.
|
||||
pipx_venvs: PIPX_LOCAL_VENVS, or None.
|
||||
|
||||
Returns:
|
||||
The Plan to run or report.
|
||||
"""
|
||||
direct_url = direct_url or {}
|
||||
url = direct_url.get("url", "")
|
||||
if direct_url.get("dir_info", {}).get("editable") or url.startswith("file:"):
|
||||
return Plan("checkout", None,
|
||||
f"fiona-assistant runs from a checkout at {_checkout_path(direct_url)}; "
|
||||
"update it with git pull")
|
||||
if uv_tool_dir is not None and _under(prefix, uv_tool_dir):
|
||||
return Plan("uv", ["uv", "tool", "upgrade", DISTRIBUTION])
|
||||
if pipx_venvs is not None and _under(prefix, pipx_venvs):
|
||||
if "vcs_info" in direct_url:
|
||||
return Plan("pipx", ["pipx", "install", "--force", url])
|
||||
return Plan("pipx", ["pipx", "upgrade", DISTRIBUTION])
|
||||
return Plan("other", None,
|
||||
"fiona-assistant was not installed by uv or pipx; upgrade it with "
|
||||
f"pip install --upgrade {DISTRIBUTION}", EXIT_NO_TOOL)
|
||||
|
||||
|
||||
def read_direct_url() -> dict | None:
|
||||
"""Return the parsed direct_url.json of fiona-assistant, or None."""
|
||||
try:
|
||||
text = importlib.metadata.distribution(DISTRIBUTION).read_text("direct_url.json")
|
||||
except importlib.metadata.PackageNotFoundError:
|
||||
return None
|
||||
return json.loads(text) if text else None
|
||||
|
||||
|
||||
def _ask_path(argv: list[str]) -> pathlib.Path | None:
|
||||
"""Run a tool that prints one path; None when it is missing or fails."""
|
||||
try:
|
||||
done = subprocess.run(argv, capture_output=True, text=True, check=False)
|
||||
except OSError:
|
||||
return None
|
||||
text = done.stdout.strip()
|
||||
return pathlib.Path(text) if done.returncode == 0 and text else None
|
||||
|
||||
|
||||
def current_plan() -> Plan:
|
||||
"""Detect from the real install: sys.prefix, direct_url.json, uv, pipx."""
|
||||
return detect(sys.prefix, read_direct_url(),
|
||||
_ask_path(["uv", "tool", "dir"]),
|
||||
_ask_path(["pipx", "environment", "--value", "PIPX_LOCAL_VENVS"]))
|
||||
|
||||
|
||||
def parse_version_line(text: str) -> str:
|
||||
"""Return the version from a 'fiona-assistant X' line."""
|
||||
return text.strip().split()[-1]
|
||||
|
||||
|
||||
def fresh_version() -> str:
|
||||
"""Return the version a new process reads, after the upgrade replaced the code."""
|
||||
done = subprocess.run([sys.executable, "-m", "fiona", "--version"],
|
||||
capture_output=True, text=True, check=False)
|
||||
return parse_version_line(done.stdout)
|
||||
|
||||
|
||||
def stream_output(command: list[str]) -> tuple[int, str]:
|
||||
"""Run command, echo its output as it comes, and return (code, output)."""
|
||||
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
|
||||
kept = []
|
||||
with subprocess.Popen(command, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT) as proc:
|
||||
for chunk in iter(lambda: proc.stdout.read1(4096), b""):
|
||||
text = decoder.decode(chunk)
|
||||
sys.stdout.write(text)
|
||||
sys.stdout.flush()
|
||||
kept.append(text)
|
||||
tail = decoder.decode(b"", final=True)
|
||||
sys.stdout.write(tail)
|
||||
kept.append(tail)
|
||||
return proc.wait(), "".join(kept)
|
||||
|
||||
|
||||
def should_retry_with_system_certs(command: list[str], returncode: int,
|
||||
output: str) -> bool:
|
||||
"""Return True when a uv command failed on an unverified TLS certificate (7.24.6)."""
|
||||
return (returncode != 0 and command[:1] == ["uv"]
|
||||
and SYSTEM_CERTS not in command and CERT_ERROR_MARK in output)
|
||||
|
||||
|
||||
def run_windows_command(
|
||||
command: list[str], stream: Callable[[list[str]], tuple[int, str]]
|
||||
) -> tuple[int, list[str], str]:
|
||||
"""Run command, retrying once with --system-certs on a TLS error (7.24.6).
|
||||
|
||||
Returns:
|
||||
(exit code, command, and output of the last run).
|
||||
"""
|
||||
returncode, output = stream(command)
|
||||
if should_retry_with_system_certs(command, returncode, output):
|
||||
print(CERT_WARNING)
|
||||
command = [*command, SYSTEM_CERTS]
|
||||
print(f"running: {shlex.join(command)}")
|
||||
returncode, output = stream(command)
|
||||
return returncode, command, output
|
||||
|
||||
|
||||
def launcher_was_locked(output: str) -> bool:
|
||||
"""Return True when uv upgraded the package but not fiona-assistant.exe (7.24.5)."""
|
||||
return all(mark in output for mark in LOCKED_MARKS)
|
||||
|
||||
|
||||
def report(returncode: int, shown: str, old: str,
|
||||
fresh_version_of: Callable[[], str], locked: bool = False) -> int:
|
||||
"""Print the outcome of the upgrade command (items 7.24.4, 7.24.5)."""
|
||||
new = None
|
||||
if returncode != 0 and locked:
|
||||
new = fresh_version_of()
|
||||
if new != old:
|
||||
print(LOCKED_NOTE)
|
||||
returncode = 0
|
||||
if returncode != 0:
|
||||
print(f"upgrade failed with exit {returncode}; run it by hand: {shown}")
|
||||
return EXIT_FAILED
|
||||
new = fresh_version_of() if new is None else new
|
||||
if new == old:
|
||||
print(f"fiona-assistant {new} is already up to date")
|
||||
else:
|
||||
print(f"fiona-assistant updated {old} -> {new}")
|
||||
print(HINT)
|
||||
return EXIT_OK
|
||||
|
||||
|
||||
def run( # noqa: PLR0913 - keyword-only stand-ins so tests fake every external fact
|
||||
dry_run: bool,
|
||||
*,
|
||||
plan: Plan | None = None,
|
||||
which: Callable[[str], str | None] = shutil.which,
|
||||
call: Callable[..., subprocess.CompletedProcess] = subprocess.run,
|
||||
version_of: Callable[[], str] | None = None,
|
||||
fresh_version_of: Callable[[], str] = fresh_version,
|
||||
windows: bool | None = None,
|
||||
stream: Callable[[list[str]], tuple[int, str]] = stream_output,
|
||||
) -> int:
|
||||
"""Run fiona-assistant --update (SPEC 7.24).
|
||||
|
||||
Args:
|
||||
dry_run: print the method and command, run nothing.
|
||||
plan: the detected plan; detected from the install when None.
|
||||
which: shutil.which stand-in.
|
||||
call: subprocess.run stand-in.
|
||||
version_of: the running version; cli_version when None.
|
||||
fresh_version_of: the version a new process reads.
|
||||
windows: stream the output for items 7.24.5 and 7.24.6;
|
||||
os.name == "nt" when None.
|
||||
stream: stream_output stand-in (Windows: echo and keep output).
|
||||
|
||||
Returns:
|
||||
The exit code (0, 3, or 4).
|
||||
"""
|
||||
plan = plan or current_plan()
|
||||
if plan.command is None:
|
||||
print(plan.message)
|
||||
return plan.exit_code
|
||||
tool = plan.command[0]
|
||||
if which(tool) is None:
|
||||
print(f"{tool} is needed to update fiona-assistant but is not on PATH")
|
||||
return EXIT_NO_TOOL
|
||||
shown = shlex.join(plan.command)
|
||||
if dry_run:
|
||||
print(f"method: {plan.method}")
|
||||
print(f"would run: {shown}")
|
||||
return EXIT_OK
|
||||
old = (version_of or cli_version)()
|
||||
print(f"fiona-assistant {old}")
|
||||
on_windows = os.name == "nt" if windows is None else windows
|
||||
print(f"running: {shown}")
|
||||
locked = False
|
||||
if on_windows:
|
||||
returncode, ran, output = run_windows_command(plan.command, stream)
|
||||
shown = shlex.join(ran)
|
||||
locked = launcher_was_locked(output)
|
||||
else:
|
||||
returncode = call(plan.command, check=False).returncode
|
||||
return report(returncode, shown, old, fresh_version_of, locked)
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Tests for bootstrap install modes (SPEC 7.21).
|
||||
|
||||
Generated by AI/LLM: 2026-09-30 - local and no-env install options.
|
||||
Updated by AI/LLM: 2026-11-29 - uv replaces pip (SPEC 7.21).
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
@@ -12,7 +13,7 @@ import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
|
||||
__version__ = "1.0.1"
|
||||
__version__ = "1.1.0"
|
||||
|
||||
|
||||
def _load_bootstrap_install():
|
||||
@@ -29,7 +30,7 @@ def _load_bootstrap_install():
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def bootstrap_install():
|
||||
"""The pip-argument helper both bootstrap scripts call."""
|
||||
"""The uv-argument helper both bootstrap scripts call."""
|
||||
return _load_bootstrap_install()
|
||||
|
||||
|
||||
@@ -57,69 +58,72 @@ def _powershell(*args: str) -> subprocess.CompletedProcess[str]:
|
||||
)
|
||||
|
||||
|
||||
class TestPipInstallArgs:
|
||||
"""SPEC 7.21.1 through 7.21.5: pip argument matrix."""
|
||||
class TestUvInstallArgs:
|
||||
"""SPEC 7.21.1 through 7.21.4 and 7.21.7: uv argument matrix."""
|
||||
|
||||
def test_local_installs_without_editable_mode(self, bootstrap_install):
|
||||
"""--local installs '.' and does not pass -e or the dev extra."""
|
||||
assert bootstrap_install.pip_install_args(local=True, no_env=False) == [
|
||||
def test_local_syncs_without_editable_or_dev(self, bootstrap_install):
|
||||
"""--local installs the project non-editable and skips the dev group."""
|
||||
assert bootstrap_install.uv_install_args(local=True, no_env=False) == [
|
||||
"sync",
|
||||
"--no-editable",
|
||||
"--no-dev",
|
||||
]
|
||||
|
||||
def test_no_env_is_an_editable_tool_install(self, bootstrap_install):
|
||||
"""--no-env installs a uv tool with phronesis executables on PATH."""
|
||||
assert bootstrap_install.uv_install_args(local=False, no_env=True) == [
|
||||
"tool",
|
||||
"install",
|
||||
"--force",
|
||||
"--editable",
|
||||
".",
|
||||
"--with-executables-from",
|
||||
"phronesis",
|
||||
]
|
||||
|
||||
def test_no_env_adds_user_and_keeps_editable_dev(self, bootstrap_install):
|
||||
"""--no-env adds --user. Without --local the install stays editable."""
|
||||
assert bootstrap_install.pip_install_args(local=False, no_env=True) == [
|
||||
def test_local_and_no_env_combine_without_editable(self, bootstrap_install):
|
||||
"""--local --no-env is a non-editable tool install."""
|
||||
assert bootstrap_install.uv_install_args(local=True, no_env=True) == [
|
||||
"tool",
|
||||
"install",
|
||||
"--user",
|
||||
"-e",
|
||||
".[dev]",
|
||||
]
|
||||
|
||||
def test_local_and_no_env_combine(self, bootstrap_install):
|
||||
"""--local --no-env installs '.' with --user and without -e."""
|
||||
assert bootstrap_install.pip_install_args(local=True, no_env=True) == [
|
||||
"install",
|
||||
"--user",
|
||||
"--force",
|
||||
".",
|
||||
"--with-executables-from",
|
||||
"phronesis",
|
||||
]
|
||||
|
||||
def test_default_is_editable_dev_extra(self, bootstrap_install):
|
||||
"""Neither flag keeps pip install -e '.[dev]'."""
|
||||
assert bootstrap_install.pip_install_args(local=False, no_env=False) == [
|
||||
"install",
|
||||
"-e",
|
||||
".[dev]",
|
||||
def test_default_is_sync(self, bootstrap_install):
|
||||
"""Neither flag keeps uv sync: editable with the dev group."""
|
||||
assert bootstrap_install.uv_install_args(local=False, no_env=False) == [
|
||||
"sync",
|
||||
]
|
||||
|
||||
def test_break_system_packages_after_user(self, bootstrap_install):
|
||||
"""Bash inserts --break-system-packages after --user."""
|
||||
args = bootstrap_install.pip_install_args(
|
||||
local=True,
|
||||
no_env=True,
|
||||
break_system_packages=True,
|
||||
)
|
||||
assert args == ["install", "--user", "--break-system-packages", "."]
|
||||
def test_python_version_is_passed_through(self, bootstrap_install):
|
||||
"""--python adds --python to the sync command (SPEC 7.21.7)."""
|
||||
assert bootstrap_install.uv_install_args(
|
||||
local=False, no_env=False, python="3.13.8",
|
||||
) == ["sync", "--python", "3.13.8"]
|
||||
|
||||
def test_break_system_packages_without_user(self, bootstrap_install):
|
||||
"""Bash inserts --break-system-packages after install when no --user."""
|
||||
args = bootstrap_install.pip_install_args(
|
||||
local=False,
|
||||
no_env=False,
|
||||
break_system_packages=True,
|
||||
)
|
||||
assert args == [
|
||||
"install",
|
||||
"--break-system-packages",
|
||||
"-e",
|
||||
".[dev]",
|
||||
]
|
||||
def test_no_pip_or_break_system_packages_words(self, bootstrap_install):
|
||||
"""No argument list uses pip or --break-system-packages."""
|
||||
for local in (True, False):
|
||||
for no_env in (True, False):
|
||||
words = bootstrap_install.uv_install_args(local=local, no_env=no_env)
|
||||
assert "pip" not in words
|
||||
assert "--break-system-packages" not in words
|
||||
|
||||
def test_main_prints_one_argument_per_line(self, bootstrap_install, capsys):
|
||||
"""The shell reads one pip argument per stdout line."""
|
||||
"""The shell reads one uv argument per stdout line."""
|
||||
assert bootstrap_install.main(["--local", "--no-env"]) == 0
|
||||
captured = capsys.readouterr()
|
||||
assert captured.out.splitlines() == ["install", "--user", "."]
|
||||
assert captured.out.splitlines() == [
|
||||
"tool",
|
||||
"install",
|
||||
"--force",
|
||||
".",
|
||||
"--with-executables-from",
|
||||
"phronesis",
|
||||
]
|
||||
assert captured.err == ""
|
||||
|
||||
|
||||
@@ -134,6 +138,40 @@ class TestBootstrapScripts:
|
||||
assert "--no-env" in text
|
||||
assert "bootstrap_install.py" in text
|
||||
|
||||
def test_no_script_uses_pip_pyenv_or_system_break(self):
|
||||
"""SPEC 7.21.5: uv never writes into the system Python."""
|
||||
for name in ("bootstrap", "bootstrap.ps1"):
|
||||
text = _script(name)
|
||||
assert "break-system-packages" not in text
|
||||
assert "pyenv install" not in text
|
||||
assert "pyenv virtualenv" not in text
|
||||
assert "-m pip" not in text
|
||||
|
||||
def test_bash_stops_with_hint_when_uv_is_missing(self):
|
||||
"""SPEC 7.21.9: without uv, bash prints the install hint and stops."""
|
||||
result = subprocess.run(
|
||||
["bash", "-c", f"source '{ROOT / 'bootstrap'}' --local; echo rc=$?"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
env={"PATH": "/usr/bin:/bin", "HOME": "/nonexistent"},
|
||||
timeout=60,
|
||||
check=False,
|
||||
)
|
||||
combined = result.stdout + result.stderr
|
||||
assert "astral.sh/uv" in combined
|
||||
assert "rc=1" in combined
|
||||
|
||||
def test_bash_refuses_pyenv_flag(self):
|
||||
"""SPEC 7.21.10: --pyenv is refused."""
|
||||
result = subprocess.run(
|
||||
["bash", "-c", f"source '{ROOT / 'bootstrap'}' --pyenv; echo rc=$?"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=60,
|
||||
check=False,
|
||||
)
|
||||
assert "rc=1" in result.stdout + result.stderr
|
||||
|
||||
def test_powershell_skips_venv_when_no_env(self):
|
||||
"""PowerShell does not create a virtual environment when $NoEnv is set."""
|
||||
assert "if (-not $NoEnv)" in _script("bootstrap.ps1")
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Tests for uv packaging metadata (SPEC 2.5 to 2.7).
|
||||
|
||||
Generated by AI/LLM: 2026-11-29 - uv integration, phase 2.
|
||||
"""
|
||||
|
||||
import pathlib
|
||||
import re
|
||||
import tomllib
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
|
||||
__version__ = "1.0.0"
|
||||
|
||||
|
||||
def _pyproject() -> dict:
|
||||
"""Parse the repository pyproject.toml."""
|
||||
return tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def _names(requirements: list[str]) -> set[str]:
|
||||
"""Return the normalized project names of PEP 508 requirement strings."""
|
||||
names = set()
|
||||
for requirement in requirements:
|
||||
name = re.split(r"[\s<>=!~;\[]", requirement, maxsplit=1)[0]
|
||||
names.add(name.lower().replace("_", "-"))
|
||||
return names
|
||||
|
||||
|
||||
class TestDevGroupMatchesExtra:
|
||||
"""SPEC 2.5 and 2.6: the dev group and the dev extra list the same packages."""
|
||||
|
||||
def test_dev_group_exists(self):
|
||||
"""The dev group is a PEP 735 dependency group."""
|
||||
data = _pyproject()
|
||||
assert "dev" in data["dependency-groups"]
|
||||
|
||||
def test_dev_group_and_extra_list_the_same_packages(self):
|
||||
"""The extra mirrors the group for one release."""
|
||||
data = _pyproject()
|
||||
group = _names(data["dependency-groups"]["dev"])
|
||||
extra = _names(data["project"]["optional-dependencies"]["dev"])
|
||||
assert group == extra
|
||||
|
||||
def test_dev_group_includes_ruff(self):
|
||||
"""Ruff is installed in the dev environment (SPEC 2.5)."""
|
||||
data = _pyproject()
|
||||
assert "ruff" in _names(data["dependency-groups"]["dev"])
|
||||
|
||||
|
||||
class TestPythonVersion:
|
||||
"""SPEC 2.7: requires-python and .python-version."""
|
||||
|
||||
def test_requires_python_is_3_11_4(self):
|
||||
"""The floor is 3.11.4, the lowest daedalus-tools supports."""
|
||||
assert _pyproject()["project"]["requires-python"] == ">=3.11.4"
|
||||
|
||||
def test_python_version_file_pins_3_13(self):
|
||||
"""uv reads .python-version to pick the default interpreter."""
|
||||
text = (ROOT / ".python-version").read_text(encoding="utf-8").strip()
|
||||
assert text == "3.13"
|
||||
|
||||
|
||||
class TestLockfile:
|
||||
"""SPEC 2.5: uv.lock is committed."""
|
||||
|
||||
def test_lock_file_exists(self):
|
||||
"""uv.lock sits beside pyproject.toml."""
|
||||
assert (ROOT / "uv.lock").is_file()
|
||||
|
||||
def test_lock_file_is_not_ignored(self):
|
||||
""".gitignore does not hide uv.lock."""
|
||||
ignored = (ROOT / ".gitignore").read_text(encoding="utf-8").splitlines()
|
||||
assert "uv.lock" not in ignored
|
||||
|
||||
|
||||
class TestCi:
|
||||
"""SPEC 2.5: CI installs from the lock and runs the checks through uv."""
|
||||
|
||||
def test_workflow_syncs_with_locked(self):
|
||||
"""The workflow fails when uv.lock is stale."""
|
||||
text = (ROOT / ".gitea" / "workflows" / "ci.yml").read_text(encoding="utf-8")
|
||||
assert "uv sync --locked" in text
|
||||
|
||||
def test_workflow_runs_tests_and_sanity_through_uv(self):
|
||||
"""Tests and sanity run inside the locked environment."""
|
||||
text = (ROOT / ".gitea" / "workflows" / "ci.yml").read_text(encoding="utf-8")
|
||||
assert "uv run python scripts/run_tests.py" in text
|
||||
assert "uv run python scripts/run_sanity.py --non-interactive" in text
|
||||
+49
-27
@@ -9,7 +9,7 @@ import pytest
|
||||
|
||||
from fiona import publish
|
||||
|
||||
__version__ = "1.1.0"
|
||||
__version__ = "1.2.0"
|
||||
|
||||
PYPROJECT = """\
|
||||
[project]
|
||||
@@ -39,7 +39,7 @@ class FakeSubprocess:
|
||||
return MagicMock(returncode=1, stdout="")
|
||||
if name in self.outputs:
|
||||
return MagicMock(returncode=0, stdout=self.outputs[name])
|
||||
if len(cmd) == 3 and cmd[1:3] == ["-m", "build"]:
|
||||
if cmd[:2] == ["uv", "build"]:
|
||||
dist = pathlib.Path(cwd) / "dist"
|
||||
dist.mkdir(parents=True, exist_ok=True)
|
||||
(dist / "fiona_assistant-1.19.0.tar.gz").write_text("sdist")
|
||||
@@ -108,12 +108,21 @@ class TestPublishRunner:
|
||||
"""Test that artifacts lists every file under dist/."""
|
||||
runner = publish.PublishRunner()
|
||||
runner.clean()
|
||||
runner.ensure_module = lambda module: None
|
||||
fake = FakeSubprocess()
|
||||
with patch("fiona.publish.subprocess.run", side_effect=fake):
|
||||
runner.build()
|
||||
assert [f"dist/{n}" for n in runner.artifacts()] == artifact_names(repo)
|
||||
|
||||
def test_artifacts_ignores_uv_gitignore(self, repo):
|
||||
"""uv build writes dist/.gitignore; it is not a distribution (SPEC 4.9.1)."""
|
||||
runner = publish.PublishRunner()
|
||||
runner.clean()
|
||||
fake = FakeSubprocess()
|
||||
with patch("fiona.publish.subprocess.run", side_effect=fake):
|
||||
runner.build()
|
||||
(repo / "dist" / ".gitignore").write_text("*\n")
|
||||
assert [f"dist/{n}" for n in runner.artifacts()] == artifact_names(repo)
|
||||
|
||||
|
||||
class TestDefaultRun:
|
||||
"""Default behavior: clean, build, check, no upload (4.9.1)."""
|
||||
@@ -230,36 +239,49 @@ class TestFailures:
|
||||
for cmd in fake.commands)
|
||||
|
||||
def test_build_failure_aborts_before_twine(self, repo):
|
||||
"""Test a failing build exits 1 before any twine command."""
|
||||
fake = FakeSubprocess(failing=["-m build"])
|
||||
"""Test a failing build exits 1 before twine check or upload."""
|
||||
fake = FakeSubprocess(failing=["uv build"])
|
||||
with patch("fiona.publish.subprocess.run", side_effect=fake):
|
||||
rc = publish.main([])
|
||||
assert rc == 1
|
||||
assert not any("twine" in cmd for cmd in fake.flat())
|
||||
assert not any("twine check" in cmd or "twine upload" in cmd
|
||||
for cmd in fake.flat())
|
||||
|
||||
def test_missing_module_triggers_pip_install(self, repo):
|
||||
"""Test that a missing build/twine module is pip-installed first."""
|
||||
fake = FakeSubprocess(failing=["--version"])
|
||||
with patch("fiona.publish.subprocess.run", side_effect=fake):
|
||||
rc = publish.main([])
|
||||
flat = fake.flat()
|
||||
assert rc == 0
|
||||
assert f"{sys.executable} -m pip install build --break-system-packages" in [
|
||||
" ".join(c) for c in fake.commands]
|
||||
assert f"{sys.executable} -m pip install twine --break-system-packages" in [
|
||||
" ".join(c) for c in fake.commands]
|
||||
assert "build" in flat
|
||||
class TestMissingTools:
|
||||
"""Missing uv or twine refuses before any change (SPEC 4.9.7)."""
|
||||
|
||||
def test_failed_pip_install_aborts(self, repo, capsys):
|
||||
"""Test a failed module install exits 1 before the build."""
|
||||
fake = FakeSubprocess(failing=["build --version", "pip install build"])
|
||||
with patch("fiona.publish.subprocess.run", side_effect=fake):
|
||||
def test_missing_uv_refuses_before_any_change(self, repo, capsys):
|
||||
"""Test a missing uv exits 1 with a uv sync hint and builds nothing (4.9.7)."""
|
||||
fake = FakeSubprocess()
|
||||
with patch("fiona.publish.shutil.which", return_value=None), \
|
||||
patch("fiona.publish.subprocess.run", side_effect=fake):
|
||||
rc = publish.main([])
|
||||
flat = fake.flat()
|
||||
assert rc == 1
|
||||
assert not any(cmd.endswith("-m build") for cmd in flat)
|
||||
captured = capsys.readouterr()
|
||||
assert captured.err.startswith("Error: ")
|
||||
assert not any(cmd[:2] == ["uv", "build"] for cmd in fake.commands)
|
||||
assert (repo / "build").exists()
|
||||
assert "uv sync" in capsys.readouterr().err
|
||||
|
||||
def test_missing_twine_refuses_before_build(self, repo, capsys):
|
||||
"""Test a missing twine exits 1 with a uv sync hint and never runs pip (4.9.7)."""
|
||||
fake = FakeSubprocess(failing=["-m twine --version"])
|
||||
with patch("fiona.publish.subprocess.run", side_effect=fake):
|
||||
rc = publish.main([])
|
||||
assert rc == 1
|
||||
flat = fake.flat()
|
||||
assert not any("pip" in cmd for cmd in flat)
|
||||
assert not any(cmd.endswith("uv build") for cmd in flat)
|
||||
assert "uv sync" in capsys.readouterr().err
|
||||
|
||||
def test_failed_build_reports_uv_build(self, repo, capsys):
|
||||
"""Test a failed uv build names the command in the error."""
|
||||
fake = FakeSubprocess(failing=["uv build"])
|
||||
with patch("fiona.publish.subprocess.run", side_effect=fake):
|
||||
rc = publish.main([])
|
||||
assert rc == 1
|
||||
assert "uv build failed." in capsys.readouterr().err
|
||||
|
||||
class TestUploadFailures:
|
||||
"""Child-command failures during upload (4.9.6)."""
|
||||
|
||||
def test_upload_failure_returns_child_code(self, repo):
|
||||
"""Test a failed upload exits 1."""
|
||||
@@ -274,7 +296,7 @@ class TestGuards:
|
||||
|
||||
@staticmethod
|
||||
def no_build(fake):
|
||||
assert not any(cmd.endswith("-m build") or "twine" in cmd for cmd in fake.flat())
|
||||
assert not any(cmd.endswith("uv build") or "twine" in cmd for cmd in fake.flat())
|
||||
|
||||
def test_direct_reference_refused(self, repo, capsys):
|
||||
"""Test a name @ url dependency stops even a build-only run."""
|
||||
|
||||
@@ -0,0 +1,440 @@
|
||||
"""fiona-assistant --update: detection, the upgrade run, the Windows run and retry, usage.
|
||||
|
||||
Spec: SPEC 7.24. Nothing here runs uv or
|
||||
pipx; every external fact is passed in or faked.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from fiona import __main__ as fiona_main
|
||||
from fiona import self_update
|
||||
|
||||
__version__ = "1.0.0"
|
||||
|
||||
UV_DIR = pathlib.Path("/home/u/.local/share/uv/tools")
|
||||
PIPX_DIR = pathlib.Path("/home/u/.local/pipx/venvs")
|
||||
UV_PREFIX = UV_DIR / "fiona-assistant"
|
||||
PIPX_PREFIX = PIPX_DIR / "fiona-assistant"
|
||||
OTHER_PREFIX = pathlib.Path("/usr")
|
||||
GIT_URL = "git+https://gitea.example.com/nvaldez/fiona-assistant.git"
|
||||
UV_CMD = ["uv", "tool", "upgrade", "fiona-assistant"]
|
||||
ENTRYPOINT_LOCKED = (
|
||||
"Updated fiona-assistant v0.38.0 -> v0.39.0\n"
|
||||
"error: Failed to upgrade fiona-assistant\n"
|
||||
" cause: Failed to install entrypoint\n"
|
||||
" cause: failed to copy file from C:\\uv\\Scripts\\fiona-assistant.exe to "
|
||||
"C:\\Users\\u\\.local\\bin\\fiona-assistant.exe: The process cannot access the "
|
||||
"file because it is being used by another process. (os error 32)\n")
|
||||
CERT_ERROR = ("error: Failed to upgrade fiona-assistant\n"
|
||||
" cause: invalid peer certificate: UnknownIssuer\n"
|
||||
"hint: Consider enabling use of system TLS certificates with "
|
||||
"the `--system-certs` command-line flag\n")
|
||||
|
||||
|
||||
def plan_for(prefix, direct_url=None, uv_dir=UV_DIR, pipx_dir=PIPX_DIR):
|
||||
"""Detect with the given facts."""
|
||||
return self_update.detect(prefix=prefix, direct_url=direct_url,
|
||||
uv_tool_dir=uv_dir, pipx_venvs=pipx_dir)
|
||||
|
||||
|
||||
def test_editable_checkout_runs_nothing():
|
||||
"""dir_info.editable is a checkout: a git pull message, no command, exit 0."""
|
||||
plan = plan_for(OTHER_PREFIX, {"url": "file:///src/fiona-assistant",
|
||||
"dir_info": {"editable": True}})
|
||||
assert plan.command is None
|
||||
assert plan.exit_code == 0
|
||||
assert "runs from a checkout at" in plan.message
|
||||
assert "update it with git pull" in plan.message
|
||||
|
||||
|
||||
def test_file_url_is_a_checkout():
|
||||
"""A file:// direct URL is a checkout even without dir_info."""
|
||||
plan = plan_for(UV_PREFIX, {"url": "file:///src/fiona-assistant"})
|
||||
assert plan.method == "checkout"
|
||||
assert plan.command is None
|
||||
|
||||
|
||||
def test_uv_tool_install_upgrades_with_uv():
|
||||
"""sys.prefix under the uv tool dir runs uv tool upgrade."""
|
||||
plan = plan_for(UV_PREFIX, None)
|
||||
assert plan.method == "uv"
|
||||
assert plan.command == UV_CMD
|
||||
|
||||
|
||||
def test_pipx_pypi_install_upgrades_with_pipx():
|
||||
"""A PyPI install under pipx runs pipx upgrade."""
|
||||
plan = plan_for(PIPX_PREFIX, None)
|
||||
assert plan.method == "pipx"
|
||||
assert plan.command == ["pipx", "upgrade", "fiona-assistant"]
|
||||
|
||||
|
||||
def test_pipx_git_install_reinstalls_from_url():
|
||||
"""A Git install under pipx re-runs pipx install --force on the URL."""
|
||||
plan = plan_for(PIPX_PREFIX, {"url": GIT_URL, "vcs_info": {"vcs": "git"}})
|
||||
assert plan.method == "pipx"
|
||||
assert plan.command == ["pipx", "install", "--force", GIT_URL]
|
||||
|
||||
|
||||
def test_other_install_prints_the_command_and_exits_3():
|
||||
"""pip or a system package: nothing runs, the user gets the command, exit 3."""
|
||||
plan = plan_for(OTHER_PREFIX, None)
|
||||
assert plan.method == "other"
|
||||
assert plan.command is None
|
||||
assert plan.exit_code == 3
|
||||
assert "pip install --upgrade fiona-assistant" in plan.message
|
||||
|
||||
|
||||
def test_prefix_must_be_under_the_tool_dir():
|
||||
"""A uv tool dir that does not hold sys.prefix is not a uv install."""
|
||||
plan = plan_for(OTHER_PREFIX, None, uv_dir=UV_DIR)
|
||||
assert plan.method == "other"
|
||||
|
||||
|
||||
def test_unknown_tool_dirs_fall_through():
|
||||
"""No uv or pipx answer (None) means the other branch."""
|
||||
plan = plan_for(UV_PREFIX, None, uv_dir=None, pipx_dir=None)
|
||||
assert plan.method == "other"
|
||||
|
||||
|
||||
def fake_version(values):
|
||||
"""A version_of that returns the given values in order."""
|
||||
queue = list(values)
|
||||
return lambda *_args, **_kwargs: queue.pop(0)
|
||||
|
||||
|
||||
def recording_call(returncode=0):
|
||||
"""A subprocess.run stand-in that records argv and returns returncode."""
|
||||
calls = []
|
||||
|
||||
def call(argv, **kwargs):
|
||||
calls.append((list(argv), kwargs))
|
||||
|
||||
class Done:
|
||||
pass
|
||||
|
||||
done = Done()
|
||||
done.returncode = returncode
|
||||
return done
|
||||
|
||||
return call, calls
|
||||
|
||||
|
||||
def always_on_path(_name):
|
||||
"""shutil.which stand-in: every tool is found."""
|
||||
return f"/usr/bin/{_name}"
|
||||
|
||||
|
||||
def test_dry_run_prints_method_and_command_and_runs_nothing(capsys):
|
||||
"""--dry-run prints what would run and never calls the runner."""
|
||||
call, calls = recording_call()
|
||||
code = self_update.run(True, plan=plan_for(UV_PREFIX, None),
|
||||
which=always_on_path, call=call)
|
||||
assert code == 0
|
||||
assert calls == []
|
||||
out = capsys.readouterr().out
|
||||
assert "method: uv" in out
|
||||
assert "would run: uv tool upgrade fiona-assistant" in out
|
||||
|
||||
|
||||
def test_missing_upgrade_tool_exits_3(capsys):
|
||||
"""uv not on PATH: say which tool is needed, run nothing, exit 3."""
|
||||
call, calls = recording_call()
|
||||
code = self_update.run(False, plan=plan_for(UV_PREFIX, None),
|
||||
which=lambda _name: None, call=call)
|
||||
assert code == 3
|
||||
assert calls == []
|
||||
assert "uv is needed" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_update_prints_old_and_new_versions(capsys):
|
||||
"""Old version, the command, then the new version from a fresh process."""
|
||||
call, calls = recording_call(0)
|
||||
code = self_update.run(False, plan=plan_for(UV_PREFIX, None),
|
||||
which=always_on_path, call=call,
|
||||
version_of=fake_version(["0.37.1"]),
|
||||
fresh_version_of=lambda: "0.38.0", windows=False)
|
||||
assert code == 0
|
||||
assert calls[0][0] == UV_CMD
|
||||
out = capsys.readouterr().out
|
||||
assert "fiona-assistant 0.37.1" in out
|
||||
assert "fiona-assistant updated 0.37.1 -> 0.38.0" in out
|
||||
assert "wikis are not updated; run 'fiona-assistant wiki check-update' in each wiki" in out
|
||||
|
||||
|
||||
def test_update_already_current(capsys):
|
||||
"""Same version before and after: the up-to-date line."""
|
||||
call, _calls = recording_call(0)
|
||||
code = self_update.run(False, plan=plan_for(UV_PREFIX, None),
|
||||
which=always_on_path, call=call,
|
||||
version_of=fake_version(["0.38.0"]),
|
||||
fresh_version_of=lambda: "0.38.0", windows=False)
|
||||
assert code == 0
|
||||
assert "fiona-assistant 0.38.0 is already up to date" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_failed_upgrade_exits_4_with_manual_command(capsys):
|
||||
"""The upgrade command fails: its exit code and the manual command, exit 4."""
|
||||
call, _calls = recording_call(7)
|
||||
code = self_update.run(False, plan=plan_for(UV_PREFIX, None),
|
||||
which=always_on_path, call=call,
|
||||
version_of=fake_version(["0.37.1"]),
|
||||
fresh_version_of=lambda: "0.38.0", windows=False)
|
||||
assert code == 4
|
||||
out = capsys.readouterr().out
|
||||
assert "exit 7" in out
|
||||
assert "uv tool upgrade fiona-assistant" in out
|
||||
|
||||
|
||||
def test_checkout_run_prints_message_and_exits_0(capsys):
|
||||
"""A checkout never runs a command from --update."""
|
||||
call, calls = recording_call()
|
||||
plan = plan_for(OTHER_PREFIX, {"url": "file:///src/fiona-assistant",
|
||||
"dir_info": {"editable": True}})
|
||||
assert self_update.run(False, plan=plan, which=always_on_path, call=call) == 0
|
||||
assert calls == []
|
||||
assert "git pull" in capsys.readouterr().out
|
||||
|
||||
|
||||
def win_stream(results):
|
||||
"""A stream(argv) stand-in returning (code, output) pairs in order."""
|
||||
seen = []
|
||||
queue = list(results)
|
||||
|
||||
def stream(argv):
|
||||
seen.append(list(argv))
|
||||
return queue.pop(0)
|
||||
|
||||
return stream, seen
|
||||
|
||||
|
||||
def win_run(results, versions=("0.38.0", "0.39.0"), plan=None):
|
||||
"""run() on Windows with streamed results; returns (code, argvs run)."""
|
||||
stream, seen = win_stream(results)
|
||||
call, calls = recording_call()
|
||||
code = self_update.run(False, plan=plan or plan_for(UV_PREFIX, None),
|
||||
which=always_on_path, call=call,
|
||||
version_of=fake_version([versions[0]]),
|
||||
fresh_version_of=lambda: versions[1],
|
||||
windows=True, stream=stream)
|
||||
assert calls == [] # Windows always streams
|
||||
return code, seen
|
||||
|
||||
|
||||
def test_windows_runs_in_the_foreground(capsys):
|
||||
"""Item 7.24.5: the command runs here and the versions are printed."""
|
||||
code, seen = win_run([(0, "")])
|
||||
assert code == 0
|
||||
assert seen == [UV_CMD]
|
||||
out = capsys.readouterr().out
|
||||
assert "running: uv tool upgrade fiona-assistant" in out
|
||||
assert "fiona-assistant updated 0.38.0 -> 0.39.0" in out
|
||||
assert "in use" not in out
|
||||
assert "press Enter" not in out
|
||||
|
||||
|
||||
def test_windows_locked_launcher_after_upgrade_is_success(capsys):
|
||||
"""Item 7.24.5: only the launcher copy failed and the version moved."""
|
||||
code, _seen = win_run([(2, ENTRYPOINT_LOCKED)])
|
||||
assert code == 0
|
||||
out = capsys.readouterr().out
|
||||
assert ("note: uv could not replace the running fiona-assistant.exe; the package "
|
||||
"is updated and the current launcher keeps working") in out
|
||||
assert "fiona-assistant updated 0.38.0 -> 0.39.0" in out
|
||||
assert "upgrade failed" not in out
|
||||
|
||||
|
||||
def test_windows_locked_launcher_without_new_version_fails(capsys):
|
||||
"""Item 7.24.5: the same error but no version change is a failure."""
|
||||
code, _seen = win_run([(2, ENTRYPOINT_LOCKED)], versions=("0.38.0", "0.38.0"))
|
||||
assert code == 4
|
||||
out = capsys.readouterr().out
|
||||
assert "upgrade failed with exit 2" in out
|
||||
assert "note:" not in out
|
||||
|
||||
|
||||
def test_windows_cert_retry_then_locked_launcher_is_success(capsys):
|
||||
"""Items 7.24.5 and 7.24.6: retry, then the tolerated launcher error."""
|
||||
code, seen = win_run([(1, CERT_ERROR), (2, ENTRYPOINT_LOCKED)])
|
||||
assert code == 0
|
||||
assert seen == [UV_CMD, [*UV_CMD, "--system-certs"]]
|
||||
out = capsys.readouterr().out
|
||||
assert "retrying with --system-certs" in out
|
||||
assert "fiona-assistant updated 0.38.0 -> 0.39.0" in out
|
||||
|
||||
|
||||
def test_windows_cert_retry_failure_names_the_retried_command(capsys):
|
||||
"""Item 7.24.6: a failed retry prints the retried command."""
|
||||
code, seen = win_run([(1, CERT_ERROR), (1, CERT_ERROR)])
|
||||
assert code == 4
|
||||
assert len(seen) == 2
|
||||
assert ("run it by hand: uv tool upgrade fiona-assistant --system-certs"
|
||||
in capsys.readouterr().out)
|
||||
|
||||
|
||||
def test_windows_other_failure_is_not_retried(capsys):
|
||||
"""Item 7.24.6: only the certificate error is retried."""
|
||||
code, seen = win_run([(1, "error: no such tool\n")])
|
||||
assert code == 4
|
||||
assert seen == [UV_CMD]
|
||||
|
||||
|
||||
def test_windows_pipx_cert_error_is_not_retried():
|
||||
"""Item 7.24.6: pipx has no --system-certs; no retry."""
|
||||
_code, seen = win_run([(1, CERT_ERROR)], plan=plan_for(PIPX_PREFIX, None))
|
||||
assert seen == [["pipx", "upgrade", "fiona-assistant"]]
|
||||
|
||||
|
||||
def test_stream_output_echoes_and_keeps_the_output(capsys):
|
||||
"""Item 7.24.6: output is shown as it runs and returned."""
|
||||
code, text = self_update.stream_output(
|
||||
[sys.executable, "-c", "import sys; print('out'); print('err', file=sys.stderr); sys.exit(3)"])
|
||||
assert code == 3
|
||||
assert "out" in text
|
||||
assert "err" in text
|
||||
shown = capsys.readouterr().out
|
||||
assert "out" in shown
|
||||
assert "err" in shown
|
||||
|
||||
|
||||
def test_parse_version_line():
|
||||
"""The fresh process prints 'fiona-assistant X'; X is the version."""
|
||||
assert self_update.parse_version_line("fiona-assistant 1.22.0\n") == "1.22.0"
|
||||
|
||||
|
||||
def run_main(monkeypatch: pytest.MonkeyPatch, *argv: str) -> int:
|
||||
"""Run ``fiona.__main__.main`` with ``argv`` and return its exit code."""
|
||||
monkeypatch.setattr(sys, "argv", ["fiona-assistant", *argv])
|
||||
try:
|
||||
fiona_main.main()
|
||||
except SystemExit as error:
|
||||
return int(error.code or 0)
|
||||
return 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("extra", [["wiki"], ["--init"], ["--bashrc", "x"], ["--profile", "x"]])
|
||||
def test_update_with_a_subcommand_or_root_option_is_a_usage_error(monkeypatch, capsys, extra):
|
||||
"""SPEC 7.24.1: --update takes no subcommand and no other root option."""
|
||||
assert run_main(monkeypatch, "--update", *extra) == 2
|
||||
assert "--update" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_dry_run_alone_names_init_and_update(monkeypatch, capsys):
|
||||
"""SPEC 7.24.1: --dry-run without --init or --update names both."""
|
||||
assert run_main(monkeypatch, "--dry-run") == 2
|
||||
err = capsys.readouterr().err
|
||||
assert "--init" in err
|
||||
assert "--update" in err
|
||||
|
||||
|
||||
def test_update_dry_run_through_the_cli(monkeypatch, capsys):
|
||||
"""SPEC 7.24.3: --update --dry-run reaches the runner and runs nothing."""
|
||||
monkeypatch.setattr(self_update, "current_plan", lambda: plan_for(UV_PREFIX, None))
|
||||
monkeypatch.setattr(self_update.shutil, "which", always_on_path)
|
||||
assert run_main(monkeypatch, "--update", "--dry-run") == 0
|
||||
assert "would run: uv tool upgrade fiona-assistant" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_update_is_in_the_help(monkeypatch, capsys):
|
||||
"""The root parser offers --update, so help and completion list it."""
|
||||
assert run_main(monkeypatch, "--help") == 0
|
||||
assert "--update" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_repo_root_is_the_checkout():
|
||||
"""Sanity: REPO_ROOT is the fiona-assistant checkout."""
|
||||
assert (self_update.REPO_ROOT / "pyproject.toml").is_file()
|
||||
|
||||
|
||||
# --- the functions that read the real install (SPEC 7.24.2, 7.24.4)
|
||||
|
||||
|
||||
class _Done:
|
||||
"""A subprocess.run result."""
|
||||
|
||||
def __init__(self, returncode: int, stdout: str) -> None:
|
||||
self.returncode = returncode
|
||||
self.stdout = stdout
|
||||
|
||||
|
||||
def test_checkout_path_from_a_file_url():
|
||||
"""SPEC 7.24.2: a file:// URL names the checkout in the message."""
|
||||
plan = plan_for(OTHER_PREFIX, {"url": "file:///src/fiona", "dir_info": {"editable": True}})
|
||||
assert "/src/fiona" in plan.message
|
||||
|
||||
|
||||
def test_read_direct_url_parses_the_distribution_file(monkeypatch):
|
||||
"""direct_url.json of the distribution is parsed; empty or missing is None."""
|
||||
|
||||
class Dist:
|
||||
def __init__(self, text: str | None) -> None:
|
||||
self.text = text
|
||||
|
||||
def read_text(self, _name: str) -> str | None:
|
||||
return self.text
|
||||
|
||||
monkeypatch.setattr(self_update.importlib.metadata, "distribution",
|
||||
lambda _name: Dist('{"url": "file:///src"}'))
|
||||
assert self_update.read_direct_url() == {"url": "file:///src"}
|
||||
monkeypatch.setattr(self_update.importlib.metadata, "distribution",
|
||||
lambda _name: Dist(None))
|
||||
assert self_update.read_direct_url() is None
|
||||
|
||||
def missing(name: str) -> None:
|
||||
raise self_update.importlib.metadata.PackageNotFoundError(name)
|
||||
|
||||
monkeypatch.setattr(self_update.importlib.metadata, "distribution", missing)
|
||||
assert self_update.read_direct_url() is None
|
||||
|
||||
|
||||
def test_ask_path_reads_one_path_or_none(monkeypatch):
|
||||
"""A tool that prints a path gives it; failure, no output, or no tool is None."""
|
||||
monkeypatch.setattr(self_update.subprocess, "run",
|
||||
lambda *_a, **_k: _Done(0, "/home/u/tools\n"))
|
||||
assert self_update._ask_path(["uv", "tool", "dir"]) == pathlib.Path("/home/u/tools")
|
||||
monkeypatch.setattr(self_update.subprocess, "run", lambda *_a, **_k: _Done(1, "x"))
|
||||
assert self_update._ask_path(["uv", "tool", "dir"]) is None
|
||||
|
||||
def no_tool(*_args: object, **_kwargs: object) -> None:
|
||||
raise FileNotFoundError
|
||||
|
||||
monkeypatch.setattr(self_update.subprocess, "run", no_tool)
|
||||
assert self_update._ask_path(["uv", "tool", "dir"]) is None
|
||||
|
||||
|
||||
def test_current_plan_asks_uv_and_pipx(monkeypatch):
|
||||
"""current_plan combines sys.prefix, direct_url.json, and both tool dirs."""
|
||||
asked = []
|
||||
|
||||
def ask(argv: list[str]) -> pathlib.Path | None:
|
||||
asked.append(argv)
|
||||
return UV_DIR if argv[0] == "uv" else None
|
||||
|
||||
monkeypatch.setattr(self_update, "_ask_path", ask)
|
||||
monkeypatch.setattr(self_update, "read_direct_url", lambda: None)
|
||||
monkeypatch.setattr(self_update.sys, "prefix", str(UV_PREFIX))
|
||||
assert self_update.current_plan().command == UV_CMD
|
||||
assert asked == [["uv", "tool", "dir"],
|
||||
["pipx", "environment", "--value", "PIPX_LOCAL_VENVS"]]
|
||||
|
||||
|
||||
def test_fresh_version_runs_a_new_python(monkeypatch):
|
||||
"""SPEC 7.24.4: the new version comes from python -m fiona --version."""
|
||||
seen = []
|
||||
|
||||
def run(argv: list[str], **_kwargs: object) -> _Done:
|
||||
seen.append(argv)
|
||||
return _Done(0, "fiona-assistant 1.23.0\n")
|
||||
|
||||
monkeypatch.setattr(self_update.subprocess, "run", run)
|
||||
assert self_update.fresh_version() == "1.23.0"
|
||||
assert seen == [[sys.executable, "-m", "fiona", "--version"]]
|
||||
|
||||
|
||||
def test_checkout_path_falls_back_to_the_running_checkout():
|
||||
"""SPEC 7.24.2: an editable install with no file:// URL names REPO_ROOT."""
|
||||
plan = plan_for(OTHER_PREFIX, {"url": "https://example.com/fiona", "dir_info": {"editable": True}})
|
||||
assert str(self_update.REPO_ROOT) in plan.message
|
||||
@@ -0,0 +1,282 @@
|
||||
"""Tests for ``fiona-assistant --init`` tab completion (SPEC section 7.23).
|
||||
|
||||
Generated by AI/LLM: 2026-11-30 - written before the implementation (TDD red phase).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tomllib
|
||||
|
||||
import pytest
|
||||
|
||||
from fiona import __main__ as fiona_main
|
||||
from fiona import completion_init as ci
|
||||
|
||||
__version__ = "1.0.0"
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
SRC = ROOT / "src"
|
||||
BEGIN = "# BEGIN fiona-assistant init: argcomplete"
|
||||
END = "# END fiona-assistant init: argcomplete"
|
||||
POSIX_REGISTER = pathlib.Path("/opt/fiona/bin/register-python-argcomplete")
|
||||
WIN_REGISTER = pathlib.Path("C:/tools/fiona/Scripts/register-python-argcomplete.exe")
|
||||
|
||||
|
||||
def run_main(monkeypatch: pytest.MonkeyPatch, *argv: str) -> int:
|
||||
"""Run ``fiona.__main__.main`` with ``argv`` and return its exit code."""
|
||||
monkeypatch.setattr(sys, "argv", ["fiona-assistant", *argv])
|
||||
try:
|
||||
fiona_main.main()
|
||||
except SystemExit as error:
|
||||
return int(error.code or 0)
|
||||
return 0
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def posix(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Pretend to be on posix with a fixed register script."""
|
||||
monkeypatch.setattr(ci, "is_windows", lambda: False)
|
||||
monkeypatch.setattr(ci, "register_script_path", lambda: POSIX_REGISTER)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def windows(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Pretend to be on Windows with a fixed register script and a policy."""
|
||||
monkeypatch.setattr(ci, "is_windows", lambda: True)
|
||||
monkeypatch.setattr(ci, "register_script_path", lambda: WIN_REGISTER)
|
||||
monkeypatch.setattr(ci, "execution_policy", lambda: "RemoteSigned")
|
||||
|
||||
|
||||
# --- usage (7.23.1, 7.23.11)
|
||||
|
||||
|
||||
def test_dry_run_without_init_is_a_usage_error(monkeypatch, capsys):
|
||||
assert run_main(monkeypatch, "--dry-run") == 2
|
||||
assert "--init" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_bashrc_without_init_is_a_usage_error(monkeypatch, capsys, tmp_path):
|
||||
assert run_main(monkeypatch, "--bashrc", str(tmp_path / "rc")) == 2
|
||||
assert "--init" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_profile_without_init_is_a_usage_error(monkeypatch, capsys, tmp_path):
|
||||
assert run_main(monkeypatch, "--profile", str(tmp_path / "p.ps1")) == 2
|
||||
assert "--init" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_profile_on_posix_is_a_usage_error(posix, monkeypatch, capsys, tmp_path):
|
||||
assert run_main(monkeypatch, "--init", "--profile", str(tmp_path / "p")) == 2
|
||||
assert "--bashrc" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_bashrc_on_windows_is_a_usage_error(windows, monkeypatch, capsys, tmp_path):
|
||||
assert run_main(monkeypatch, "--init", "--bashrc", str(tmp_path / "rc")) == 2
|
||||
assert "--profile" in capsys.readouterr().err
|
||||
|
||||
|
||||
# --- register script lookup (7.23.4, 7.23.8)
|
||||
|
||||
|
||||
def test_register_script_is_found_beside_the_interpreter(monkeypatch, tmp_path):
|
||||
scripts = tmp_path / "bin"
|
||||
scripts.mkdir()
|
||||
(scripts / "register-python-argcomplete").write_text("", encoding="utf-8")
|
||||
monkeypatch.setattr(ci, "is_windows", lambda: False)
|
||||
monkeypatch.setattr(sys, "executable", str(scripts / "python"))
|
||||
assert ci.register_script_path() == scripts / "register-python-argcomplete"
|
||||
|
||||
|
||||
def test_register_script_on_windows_has_the_exe_name(monkeypatch, tmp_path):
|
||||
scripts = tmp_path / "Scripts"
|
||||
scripts.mkdir()
|
||||
(scripts / "register-python-argcomplete.exe").write_text("", encoding="utf-8")
|
||||
monkeypatch.setattr(ci, "is_windows", lambda: True)
|
||||
monkeypatch.setattr(sys, "executable", str(scripts / "python.exe"))
|
||||
assert ci.register_script_path() == scripts / "register-python-argcomplete.exe"
|
||||
|
||||
|
||||
def test_missing_register_script_exits_three(posix, monkeypatch, capsys, tmp_path):
|
||||
monkeypatch.setattr(ci, "register_script_path", lambda: None)
|
||||
rc = tmp_path / "rc"
|
||||
assert run_main(monkeypatch, "--init", "--bashrc", str(rc)) == 3
|
||||
assert "register-python-argcomplete" in capsys.readouterr().err
|
||||
assert not rc.exists()
|
||||
|
||||
|
||||
# --- posix bash target (7.23.3, 7.23.5, 7.23.6)
|
||||
|
||||
|
||||
def test_init_appends_the_bash_block(posix, monkeypatch, capsys, tmp_path):
|
||||
rc = tmp_path / "bashrc"
|
||||
rc.write_text("export A=1\n", encoding="utf-8")
|
||||
assert run_main(monkeypatch, "--init", "--bashrc", str(rc)) == 0
|
||||
text = rc.read_text(encoding="utf-8")
|
||||
assert text.startswith("export A=1\n\n" + BEGIN + "\n")
|
||||
assert f"eval \"$('{POSIX_REGISTER}' fiona-assistant)\"" in text
|
||||
assert text.endswith(END + "\n")
|
||||
assert "exec bash" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_init_defaults_to_the_home_bashrc(posix, monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("HOME", str(tmp_path))
|
||||
assert run_main(monkeypatch, "--init") == 0
|
||||
assert BEGIN in (tmp_path / ".bashrc").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_init_is_idempotent(posix, monkeypatch, capsys, tmp_path):
|
||||
rc = tmp_path / "bashrc"
|
||||
run_main(monkeypatch, "--init", "--bashrc", str(rc))
|
||||
before = rc.read_text(encoding="utf-8")
|
||||
assert run_main(monkeypatch, "--init", "--bashrc", str(rc)) == 0
|
||||
assert "already enabled" in capsys.readouterr().out
|
||||
assert rc.read_text(encoding="utf-8") == before
|
||||
|
||||
|
||||
def test_dry_run_prints_and_writes_nothing(posix, monkeypatch, capsys, tmp_path):
|
||||
rc = tmp_path / "bashrc"
|
||||
assert run_main(monkeypatch, "--init", "--dry-run", "--bashrc", str(rc)) == 0
|
||||
out = capsys.readouterr().out
|
||||
assert BEGIN in out
|
||||
assert "dry run" in out
|
||||
assert not rc.exists()
|
||||
|
||||
|
||||
def test_dry_run_on_an_enabled_file_says_already_enabled(
|
||||
posix, monkeypatch, capsys, tmp_path):
|
||||
rc = tmp_path / "bashrc"
|
||||
run_main(monkeypatch, "--init", "--bashrc", str(rc))
|
||||
assert run_main(monkeypatch, "--init", "--dry-run", "--bashrc", str(rc)) == 0
|
||||
assert "already enabled" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_only_the_target_file_is_written(posix, monkeypatch, tmp_path):
|
||||
rc = tmp_path / "bashrc"
|
||||
run_main(monkeypatch, "--init", "--bashrc", str(rc))
|
||||
assert sorted(p.name for p in tmp_path.iterdir()) == ["bashrc"]
|
||||
|
||||
|
||||
# --- Windows PowerShell (7.23.7, 7.23.9, 7.23.10)
|
||||
|
||||
|
||||
def test_windows_block_runs_the_register_script_through_invoke_expression(windows):
|
||||
block = ci.build_powershell_hook_block(WIN_REGISTER)
|
||||
assert block.startswith(BEGIN + "\n")
|
||||
assert block.endswith(END + "\n")
|
||||
assert (f"& '{WIN_REGISTER}' --shell powershell fiona-assistant"
|
||||
" | Out-String | Invoke-Expression") in block
|
||||
|
||||
|
||||
def test_windows_init_writes_the_profile(windows, monkeypatch, capsys, tmp_path):
|
||||
profile = tmp_path / "Documents" / "PowerShell" / "profile.ps1"
|
||||
assert run_main(monkeypatch, "--init", "--profile", str(profile)) == 0
|
||||
text = profile.read_text(encoding="utf-8")
|
||||
assert BEGIN in text
|
||||
assert "Invoke-Expression" in text
|
||||
assert ". $PROFILE" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_windows_init_asks_powershell_for_the_profile(
|
||||
windows, monkeypatch, tmp_path):
|
||||
profile = tmp_path / "onedrive" / "profile.ps1"
|
||||
monkeypatch.setattr(ci, "powershell_profile", lambda: profile)
|
||||
assert run_main(monkeypatch, "--init") == 0
|
||||
assert BEGIN in profile.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_windows_profile_lookup_failure_exits_three(
|
||||
windows, monkeypatch, capsys):
|
||||
monkeypatch.setattr(ci, "powershell_profile", lambda: None)
|
||||
assert run_main(monkeypatch, "--init") == 3
|
||||
assert "--profile" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_windows_init_is_idempotent(windows, monkeypatch, capsys, tmp_path):
|
||||
profile = tmp_path / "profile.ps1"
|
||||
run_main(monkeypatch, "--init", "--profile", str(profile))
|
||||
before = profile.read_text(encoding="utf-8")
|
||||
assert run_main(monkeypatch, "--init", "--profile", str(profile)) == 0
|
||||
assert "already enabled" in capsys.readouterr().out
|
||||
assert profile.read_text(encoding="utf-8") == before
|
||||
|
||||
|
||||
def test_windows_dry_run_writes_nothing(windows, monkeypatch, capsys, tmp_path):
|
||||
profile = tmp_path / "profile.ps1"
|
||||
assert run_main(monkeypatch, "--init", "--dry-run", "--profile", str(profile)) == 0
|
||||
assert BEGIN in capsys.readouterr().out
|
||||
assert not profile.exists()
|
||||
|
||||
|
||||
def test_restricted_policy_prints_a_hint_and_changes_nothing(
|
||||
windows, monkeypatch, capsys, tmp_path):
|
||||
monkeypatch.setattr(ci, "execution_policy", lambda: "Restricted")
|
||||
profile = tmp_path / "profile.ps1"
|
||||
assert run_main(monkeypatch, "--init", "--profile", str(profile)) == 0
|
||||
assert "Set-ExecutionPolicy -Scope CurrentUser RemoteSigned" in capsys.readouterr().out
|
||||
assert BEGIN in profile.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_failed_policy_probe_is_ignored(windows, monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(ci, "execution_policy", lambda: None)
|
||||
profile = tmp_path / "profile.ps1"
|
||||
assert run_main(monkeypatch, "--init", "--profile", str(profile)) == 0
|
||||
assert BEGIN in profile.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_profile_lookup_returns_none_when_no_shell_answers(monkeypatch):
|
||||
def no_shell(*_args, **_kwargs):
|
||||
raise FileNotFoundError("no shell")
|
||||
|
||||
monkeypatch.setattr(ci.subprocess, "run", no_shell)
|
||||
assert ci.powershell_profile() is None
|
||||
assert ci.execution_policy() is None
|
||||
|
||||
|
||||
# --- completion itself (7.23.2) and packaging
|
||||
|
||||
|
||||
def test_completion_offers_subcommands_and_wiki_subcommands(tmp_path):
|
||||
env = dict(os.environ)
|
||||
env.update({
|
||||
"PYTHONPATH": str(SRC),
|
||||
"_ARGCOMPLETE": "1",
|
||||
"_ARGCOMPLETE_SHELL": "bash",
|
||||
"_ARGCOMPLETE_IFS": "\n",
|
||||
"COMP_WORDBREAKS": " \t\n\"'><=;|&(:",
|
||||
})
|
||||
cases = {
|
||||
"fiona-assistant wiki ": {"init", "update"},
|
||||
"fiona-assistant wi": {"wiki"},
|
||||
}
|
||||
for line, expected in cases.items():
|
||||
out = tmp_path / "candidates.txt"
|
||||
env.update({
|
||||
"COMP_LINE": line,
|
||||
"COMP_POINT": str(len(line)),
|
||||
"_ARGCOMPLETE_STDOUT_FILENAME": str(out),
|
||||
})
|
||||
subprocess.run(
|
||||
[sys.executable, "-m", "fiona"],
|
||||
env=env, check=False, capture_output=True, timeout=120,
|
||||
)
|
||||
candidates = set(out.read_text(encoding="utf-8").split())
|
||||
assert expected <= candidates, (line, candidates)
|
||||
|
||||
|
||||
def test_main_module_carries_the_argcomplete_marker():
|
||||
head = (SRC / "fiona" / "__main__.py").read_bytes()[:1024]
|
||||
assert b"# PYTHON_ARGCOMPLETE_OK" in head
|
||||
|
||||
|
||||
def test_argcomplete_is_a_runtime_dependency_at_3_3():
|
||||
data = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8"))
|
||||
assert "argcomplete>=3.3" in data["project"]["dependencies"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["bootstrap", "bootstrap.ps1"])
|
||||
def test_bootstrap_prints_the_init_step(name):
|
||||
assert "fiona-assistant --init" in (ROOT / name).read_text(encoding="utf-8")
|
||||
@@ -8,6 +8,8 @@
|
||||
- [P1 — Wiki Lifecycle and Version Control](#p1--wiki-lifecycle-and-version-control)
|
||||
- [P2 — Quality Tooling](#p2--quality-tooling)
|
||||
- [P3 — Metadata, Backup, and Documentation](#p3--metadata-backup-and-documentation)
|
||||
- [Tab completion (bash and Windows PowerShell)](#tab-completion-bash-and-windows-powershell)
|
||||
- [Self-update with fiona-assistant --update](#self-update-with-fiona-assistant---update)
|
||||
- [P4 — Design Decisions Needed](#p4--design-decisions-needed)
|
||||
- [Open Questions (SPEC)](#open-questions-spec)
|
||||
|
||||
@@ -1332,6 +1334,78 @@ WARNING run_tests: pytest short summary missing from output; failure details com
|
||||
- [x] Test runner summary: `run_tests.py` prints a minimal "Some tests
|
||||
failed" line. Print the failing test names and the counts.
|
||||
|
||||
## Tab completion (bash and Windows PowerShell)
|
||||
|
||||
Requested by the owner on 2026-11-30. fiona-assistant has no tab
|
||||
completion today: there is no `--init` and no argcomplete hook. Add
|
||||
it the way daedalus and phronesis do (`daedalus --init`, phronesis
|
||||
SPEC section 13), with Windows PowerShell supported from the start
|
||||
(daedalus plan item 29, phronesis plan section 13).
|
||||
|
||||
- [x] SPEC: a new section for `fiona-assistant --init [--bashrc PATH]
|
||||
[--profile PATH] [--dry-run]`. Same managed block markers
|
||||
(`# BEGIN fiona-assistant init: argcomplete` / `# END ...`), the
|
||||
same idempotence, `--dry-run`, and exit 3 rules as phronesis
|
||||
SPEC items 13.2 to 13.10.
|
||||
- [x] Dependency: `argcomplete` as a runtime dependency, and
|
||||
`argcomplete.autocomplete(parser)` in `src/fiona/__main__.py`
|
||||
before `parse_args`, with a `# PYTHON_ARGCOMPLETE_OK` marker.
|
||||
Completion covers the subcommands (`wiki init`, `wiki update`,
|
||||
and the rest) and their flags.
|
||||
- [x] Linux: append
|
||||
`eval "$('<path to register-python-argcomplete>' fiona-assistant)"`
|
||||
to `~/.bashrc` (or `--bashrc PATH`).
|
||||
- [x] Windows PowerShell: append
|
||||
`& '<path to register-python-argcomplete>' --shell powershell fiona-assistant | Out-String | Invoke-Expression`
|
||||
to `$PROFILE` (or `--profile PATH`), found by asking `pwsh`, then
|
||||
`powershell`, for `$PROFILE` because OneDrive can redirect
|
||||
Documents. Create the file and its folder when missing. Find
|
||||
`register-python-argcomplete.exe` in the interpreter's `Scripts`
|
||||
folder, then on `PATH`. If the execution policy is `Restricted`,
|
||||
print a hint and do not change it.
|
||||
- [x] Decide whether `librarian`, `mdoctor`, and `html-js-lint` get
|
||||
completion too, from the same `--init` run. Decided: no, only
|
||||
`fiona-assistant` (SPEC 7.23.13).
|
||||
- [x] Tests, failing first: `os.name`, the `$PROFILE` lookup, and the
|
||||
register-python-argcomplete path are faked, so no Windows host is
|
||||
needed.
|
||||
- [x] Docs: README shows `fiona-assistant --init` for bash and
|
||||
PowerShell; `bootstrap` and `bootstrap.ps1` print it as the next
|
||||
step. Minor version bump and a CHANGELOG entry.
|
||||
- [ ] Done when: the tests pass, and on Windows after
|
||||
`uv tool install fiona-assistant`, `--init` in PowerShell writes
|
||||
the block, a new window completes `fiona-assistant <Tab>`, and a
|
||||
second `--init` reports `already enabled`. The same on Linux in
|
||||
bash.
|
||||
|
||||
## Self-update with fiona-assistant --update
|
||||
|
||||
Requested by the owner on 2026-12-01. Built as SPEC 7.24 in 1.23.0, with
|
||||
the final daedalus 0.39.11 design (daedalus plan item 31, phronesis plan
|
||||
section 14): the run stays in the foreground, Windows TLS failures are
|
||||
retried with `--system-certs`, and uv's locked-launcher error (os error 32)
|
||||
after an upgrade counts as a success.
|
||||
|
||||
- [x] SPEC 7.24 for `fiona-assistant --update [--dry-run]`: detection of a
|
||||
checkout, `uv tool`, pipx, or another install; old and new version
|
||||
from a fresh `python -m fiona --version`.
|
||||
- [x] One upgrade covers every console script and the pinned `phronesis`
|
||||
and `daedalus-tools` in the tool environment (SPEC 7.24 intro).
|
||||
- [x] Name clash: the success hint is `wikis are not updated; run
|
||||
'fiona-assistant wiki check-update' in each wiki`.
|
||||
- [x] Windows: foreground run; the locked-launcher error is a success with
|
||||
a note when the version changed (SPEC 7.24.5); TLS retry with
|
||||
`--system-certs` (SPEC 7.24.6).
|
||||
- [x] Tests, failing first: `tests/test_self_update.py`.
|
||||
- [x] Code: `src/fiona/self_update.py` and the flag in `src/fiona/__main__.py`.
|
||||
- [x] Docs: README shows `fiona-assistant --update`. `bootstrap` and
|
||||
`bootstrap.ps1` do not mention it: they set up a checkout, where
|
||||
`--update` only prints the `git pull` hint.
|
||||
- [ ] Done when: with `uv tool install fiona-assistant` one release behind,
|
||||
`--update` installs the newest release and prints both versions, and
|
||||
a second run reports `already up to date`, on Linux and on Windows in
|
||||
PowerShell.
|
||||
|
||||
## P4 — Design Decisions Needed
|
||||
|
||||
- [ ] Should `git undo` and `git clean` prompt on a TTY, with `--yes`
|
||||
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
---
|
||||
name: uv-plan
|
||||
version: 0.1.0
|
||||
title: Fiona-Assistant plan, uv integration
|
||||
created: 2026-11-29
|
||||
updated: 2026-11-29
|
||||
type: summary
|
||||
tags: [plan, uv, packaging, bootstrap]
|
||||
---
|
||||
|
||||
# Fiona-Assistant plan: uv integration
|
||||
|
||||
How Fiona-Assistant can adopt [uv](https://docs.astral.sh/uv/) for
|
||||
installing, bootstrapping a dev environment, and releasing. Written
|
||||
2026-11-29 against fiona-assistant 1.21.1 and uv 0.11.26, after the
|
||||
same change landed in daedalus 0.31.0 (its `plan-uv-integration.md`).
|
||||
Cite an item as `uv plan item N.M`. Nothing here is behavior yet: each
|
||||
phase changes [SPEC](./SPEC.md) first (project agent rule 2.1).
|
||||
|
||||
<!-- toc-start: headings 2..6 -->
|
||||
|
||||
- [1. Verdict](#1-verdict)
|
||||
- [2. Where pip, pyenv, and venv are used today](#2-where-pip-pyenv-and-venv-are-used-today)
|
||||
- [3. Changes that alter usage](#3-changes-that-alter-usage)
|
||||
- [4. Decisions for the owner](#4-decisions-for-the-owner)
|
||||
- [5. Phase 1: install Fiona with uv](#5-phase-1-install-fiona-with-uv)
|
||||
- [6. Phase 2: dependency group and uv.lock](#6-phase-2-dependency-group-and-uvlock)
|
||||
- [7. Phase 3: bootstrap on uv](#7-phase-3-bootstrap-on-uv)
|
||||
- [8. Phase 4: publish with uv build](#8-phase-4-publish-with-uv-build)
|
||||
- [9. Phase 5: CI](#9-phase-5-ci)
|
||||
- [10. Not adopted](#10-not-adopted)
|
||||
- [11. Risks](#11-risks)
|
||||
- [12. Verification checklist](#12-verification-checklist)
|
||||
|
||||
<!-- toc-end -->
|
||||
|
||||
## 1. Verdict
|
||||
|
||||
- **1.1** Feasible and lower risk than daedalus. Fiona never builds
|
||||
environments at run time, so uv is an install, development, and
|
||||
release tool only. **Fiona does not need uv as a runtime
|
||||
dependency** and should not import it.
|
||||
- **1.2** The best gains, in order:
|
||||
- **1.2.1** `bootstrap` stops building Python from source. Today it
|
||||
installs pyenv, needs `sudo apt-get install` of about 15 build
|
||||
packages, and compiles CPython 3.13.8. `uv python install` fetches
|
||||
a prebuilt Python in seconds, with no sudo (uv plan item 7.2).
|
||||
- **1.2.2** One reproducible dev environment from a committed
|
||||
`uv.lock`, the same on Linux and Windows (uv plan item 6.2).
|
||||
- **1.2.3** One install command for users, `uv tool install
|
||||
fiona-assistant`, that isolates Fiona from the system Python
|
||||
(no `--break-system-packages`, uv plan item 5.1).
|
||||
- **1.2.4** `publish` stops `pip install`ing `build` and `twine` into
|
||||
whatever interpreter runs it (`ensure_module`, uv plan item 8.1).
|
||||
- **1.3** Already true without any change here: daedalus-tools 0.31.0
|
||||
declares `uv>=0.11,<0.12`, so every Fiona install that resolves
|
||||
daedalus-tools 0.31 or newer already carries the uv wheel (about
|
||||
15 to 20 MB). Fiona's own pin, `daedalus-tools>=0.29.0,<1`, allows
|
||||
it. Nothing in Fiona uses it (uv plan item 11.1).
|
||||
|
||||
## 2. Where pip, pyenv, and venv are used today
|
||||
|
||||
| Place | What it does | SPEC |
|
||||
| --- | --- | --- |
|
||||
| README quick start and section 1 | `python -m pip install fiona-assistant` | 2 |
|
||||
| `bootstrap` (bash, sourced) | Installs pyenv and its apt build deps, `pyenv install 3.13.8`, `pyenv virtualenv`, upgrades pip, then `pip <words>` from `scripts/bootstrap_install.py`; always `--break-system-packages` | 7.21 |
|
||||
| `bootstrap.ps1` | `py -<version> -m venv .venvs\<name>`, upgrades pip, then the same pip words | 7.21 |
|
||||
| `scripts/bootstrap_install.py` | Prints the pip words: `install -e .[dev]`, `--local` gives `install .`, `--no-env` adds `--user` | 7.21.1 to 7.21.5 |
|
||||
| `scripts/install_packages.sh` | `pip show`, `pip uninstall`, `pip install --force-reinstall`; needs `VIRTUAL_ENV` | - |
|
||||
| `pyproject.toml` | `[project.optional-dependencies] dev` (pytest, pytest-cov, pytest-mock, pylint, build, twine) | 2 |
|
||||
| `src/fiona/publish.py` | `ensure_module` runs `pip install <module> --break-system-packages` when `build` or `twine` is missing; `python -m build`; `twine check`; `twine upload` | 4.9 |
|
||||
| AGENTS.md section 3 | Mandatory `source bootstrap` before any work | - |
|
||||
| CI | None in this repository | - |
|
||||
|
||||
- **2.1** `install_dev_packages` in `bootstrap` is defined but never
|
||||
called, so `scripts/install_packages.sh` is unused by bootstrap.
|
||||
Phase 3 removes both (uv plan item 7.6).
|
||||
|
||||
## 3. Changes that alter usage
|
||||
|
||||
- **3.1** **Recommended user install changes from pip to uv.**
|
||||
`uv tool install fiona-assistant` and `uv tool upgrade
|
||||
fiona-assistant`. `pip install fiona-assistant` keeps working,
|
||||
because the wheel is unchanged. README shows uv first and pip
|
||||
second.
|
||||
- **3.2** **The `phronesis` and `daedalus` commands are not on `PATH`
|
||||
after a uv tool install.** `pip install` puts every dependency's
|
||||
console script on `PATH`; `uv tool install` exposes only Fiona's own
|
||||
four (`fiona-assistant`, `librarian`, `mdoctor`, `html-js-lint`).
|
||||
README and the deployed wiki tell agents to run `phronesis show
|
||||
fiona`. Fix: document `uv tool install fiona-assistant
|
||||
--with-executables-from phronesis` (and `daedalus-tools` if the owner
|
||||
wants `daedalus` too). Fiona's own code reads phronesis through
|
||||
`importlib.resources` (`src/fiona/wiki/skills.py`), so it is not
|
||||
affected.
|
||||
- **3.3** **The dev environment moves from a pyenv virtualenv named
|
||||
`test_env` to `.venv` in the checkout.** `source bootstrap` still
|
||||
activates it, so `python`, `pytest`, and `fiona-assistant` still
|
||||
work in that shell. Anyone who runs `pyenv activate test_env` by
|
||||
hand must switch to `source .venv/bin/activate` or `uv run`.
|
||||
- **3.4** **The `dev` extra becomes a dependency group.** `pip install
|
||||
-e ".[dev]"` keeps working for one release, then the extra is
|
||||
removed (uv plan item 6.3). pip 25.1 and newer can install the group
|
||||
with `pip install --group dev -e .`.
|
||||
|
||||
## 4. Decisions for the owner
|
||||
|
||||
- **4.1** Whether bootstrap keeps pyenv at all. Recommended: **no**.
|
||||
uv installs the pinned Python (`.python-version`, `3.13`), creates
|
||||
`.venv`, and syncs. A `--pyenv` path doubles the code to test.
|
||||
Alternative: keep `--pyenv` as an opt-in fallback for one release.
|
||||
- **4.2** How bootstrap gets uv when it is missing. Recommended: print
|
||||
the official install command and stop (`curl -LsSf
|
||||
https://astral.sh/uv/install.sh | sh`, or `winget install
|
||||
astral-sh.uv`), the same way it reports a missing Python today.
|
||||
Alternative: run the installer itself. Not recommended: a sourced
|
||||
script that pipes a download into `sh` is surprising.
|
||||
- **4.3** `--no-env`. Today it is `pip install --user`. Recommended:
|
||||
`--no-env` becomes `uv tool install --editable .` (or `uv tool
|
||||
install .` with `--local`), which gives commands on `PATH` with no
|
||||
activation and no `--break-system-packages`. This is a behavior
|
||||
change of SPEC item 7.21.2.
|
||||
- **4.4** Release upload. Recommended: keep `twine upload` (SPEC item
|
||||
4.9.6 reads `~/.pypirc`, which `uv publish` does not). Switch only
|
||||
together with PyPI trusted publishing from CI, as its own change.
|
||||
- **4.5** Whether to add CI (section 9). Recommended: yes, a Gitea job
|
||||
like daedalus and phronesis, since `uv sync --locked` is the gate
|
||||
that keeps `uv.lock` honest.
|
||||
|
||||
## 5. Phase 1: install Fiona with uv
|
||||
|
||||
Docs only; no code change.
|
||||
|
||||
- **5.1** README quick start and section 1:
|
||||
|
||||
```bash
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh # or: winget install astral-sh.uv
|
||||
uv tool install fiona-assistant --with-executables-from phronesis
|
||||
uv tool update-shell # once: puts ~/.local/bin on PATH
|
||||
uv tool upgrade fiona-assistant
|
||||
```
|
||||
|
||||
The pip line stays as the second option.
|
||||
- **5.2** SPEC section 2 names both install commands.
|
||||
- **5.3** README "After ingest": `fiona-assistant --version` stays; `pip
|
||||
show fiona-assistant` gains `uv tool list` as the uv equivalent.
|
||||
- **5.4** Done when: a fresh `uv tool install` on Linux and Windows
|
||||
gives working `fiona-assistant wiki init`, `housekeeping`, and
|
||||
`phronesis show fiona`.
|
||||
|
||||
## 6. Phase 2: dependency group and uv.lock
|
||||
|
||||
- **6.1** `pyproject.toml`: add `[dependency-groups] dev = [...]` with
|
||||
the current extra's packages plus `ruff` (SPEC 1.2.5.1 selects every
|
||||
Ruff rule, but nothing installs ruff in the dev environment today
|
||||
except through daedalus-tools).
|
||||
- **6.2** Commit `uv.lock`. Contributors run `uv sync` (creates `.venv`
|
||||
with Fiona editable and the `dev` group), then `uv run python
|
||||
scripts/run_tests.py` and `uv run python scripts/run_sanity.py`.
|
||||
- **6.3** Keep `[project.optional-dependencies] dev` for one release
|
||||
with the same list, so `pip install -e ".[dev]"` and the current
|
||||
bootstrap work while Phase 3 lands. A test fails when the extra and
|
||||
the group differ. The next minor release removes the extra.
|
||||
- **6.4** Add `.python-version` with `3.13` (the bootstrap default
|
||||
today is 3.13.8). `requires-python` stays `>=3.11`.
|
||||
- **6.5** Done when: `uv sync --locked` succeeds from a clean clone and
|
||||
every test and sanity check passes under `uv run`.
|
||||
|
||||
## 7. Phase 3: bootstrap on uv
|
||||
|
||||
The largest change. SPEC section 7.21 is rewritten first.
|
||||
|
||||
- **7.1** Mapping:
|
||||
|
||||
| Today | With uv |
|
||||
| --- | --- |
|
||||
| pyenv install, apt build deps, `pyenv install 3.13.8` | `uv python install` (reads `.python-version`) |
|
||||
| `pyenv virtualenv 3.13.8 test_env` / `py -m venv .venvs\<name>` | `uv venv` (`.venv`) |
|
||||
| `pip install -e .[dev]` | `uv sync` (editable plus `dev`, from `uv.lock`) |
|
||||
| `--local`: `pip install .` | `uv sync --no-editable --no-dev` |
|
||||
| `--no-env`: `pip install --user` | `uv tool install [--editable] .` (uv plan item 4.3) |
|
||||
| `--python 3.x.y` | `uv python install 3.x.y` and `uv sync --python 3.x.y` |
|
||||
| `-c`/`--clean` | delete `.venv`, then sync |
|
||||
| `upgrade_pip` | removed: uv venvs have no pip |
|
||||
| `--break-system-packages` | removed: uv never writes into the system Python |
|
||||
|
||||
- **7.2** `bootstrap` and `bootstrap.ps1` shrink to: find uv (or stop
|
||||
with the install hint, uv plan item 4.2), run the uv steps, source
|
||||
`.venv/bin/activate` (or `.venv\Scripts\Activate.ps1`), print the
|
||||
Python and uv versions. The same flags keep their names.
|
||||
- **7.3** `scripts/bootstrap_install.py` changes from "pip words" to
|
||||
"uv words" and keeps its role as the one argument source both
|
||||
scripts call, so SPEC items 7.21.1 to 7.21.4 keep their acceptance
|
||||
tests with new expected lists. Item 7.21.5
|
||||
(`--break-system-packages`) is removed.
|
||||
- **7.4** `--env <name>` has no uv meaning (the venv is always
|
||||
`.venv`). Recommended: accept it for one release with a warning,
|
||||
then remove it.
|
||||
- **7.5** AGENTS.md section 3 shows `source bootstrap` unchanged as the
|
||||
mandatory step, plus the bare uv commands (`uv sync`, `uv run`) for
|
||||
agents that cannot source a script.
|
||||
- **7.6** Remove the dead `install_dev_packages` function and
|
||||
`scripts/install_packages.sh` (uv plan item 2.1).
|
||||
- **7.7** Done when: on a fresh Debian 12 machine without pyenv,
|
||||
`source bootstrap` takes under a minute, needs no sudo, and
|
||||
`python scripts/run_tests.py` passes in that shell; the same on
|
||||
Windows with `. .\bootstrap.ps1`.
|
||||
|
||||
## 8. Phase 4: publish with uv build
|
||||
|
||||
- **8.1** `src/fiona/publish.py`: remove `ensure_module` and its `pip
|
||||
install --break-system-packages`. Build with `uv build` (same
|
||||
setuptools backend, same sdist then wheel) instead of `python -m
|
||||
build`. Keep `twine check` and `twine upload` (uv plan item 4.4).
|
||||
- **8.2** A missing `twine` or `uv` becomes a refusal with a hint
|
||||
(`uv sync` in a checkout), never an install, so publish cannot
|
||||
change the environment it runs in.
|
||||
- **8.3** SPEC items 4.9.1 and 4.9.6 change first; the acceptance tests
|
||||
in `tests/test_publish.py` stub `uv build` instead of `python -m
|
||||
build`.
|
||||
- **8.4** Done when: `python scripts/publish.py` (no `--upload`) builds
|
||||
the same file list in `dist/` as today and `twine check` passes.
|
||||
|
||||
## 9. Phase 5: CI
|
||||
|
||||
- **9.1** Add `.gitea/workflows/ci.yml`: a `python:3.11` container,
|
||||
`pip install uv==<pinned>`, `uv sync --locked`, then `uv run python
|
||||
scripts/run_tests.py` and `uv run python scripts/run_sanity.py`.
|
||||
- **9.2** `--locked` fails the job when `uv.lock` is stale, which is the
|
||||
only automatic check that keeps the lock in step with
|
||||
`pyproject.toml`.
|
||||
- **9.3** Done when: the job is green on a pull request.
|
||||
|
||||
## 10. Not adopted
|
||||
|
||||
- **10.1** uv as a runtime dependency of Fiona. Nothing at run time
|
||||
installs packages or builds environments.
|
||||
- **10.2** PEP 723 blocks for the wiki template scripts
|
||||
(`src/fiona/data/llm_wiki/utils/scripts/backup.py`, `example.py`).
|
||||
They use the standard library only, so a block would add nothing
|
||||
but a `requires-python` line. Revisit if a template script gains a
|
||||
dependency.
|
||||
- **10.3** The `uv_build` backend. setuptools package-data globs
|
||||
(`data/llm_wiki/**/*`) work today; no gain from switching.
|
||||
- **10.4** `uv publish`, until trusted publishing (uv plan item 4.4).
|
||||
|
||||
## 11. Risks
|
||||
|
||||
- **11.1** The transitive uv wheel from daedalus-tools 0.31 (uv plan
|
||||
item 1.3) grows every Fiona install whether or not this plan runs.
|
||||
If size matters, the fix belongs in daedalus (a lighter `linter`
|
||||
extra), not here.
|
||||
- **11.2** uv is 0.x. Pin the CI uv version and bump it deliberately.
|
||||
- **11.3** Agents and scripts that hard-code `test_env` or
|
||||
`$HOME/.pyenv/versions/test_env` break after Phase 3 (uv plan item
|
||||
3.3). Search the workspace before shipping.
|
||||
- **11.4** `uv tool install` without `--with-executables-from
|
||||
phronesis` leaves `phronesis show fiona` broken for users (uv plan
|
||||
item 3.2). The README line must carry the flag.
|
||||
|
||||
## 12. Verification checklist
|
||||
|
||||
Run before each phase ships; record results here.
|
||||
|
||||
- **12.1** `uv tool install fiona-assistant --with-executables-from
|
||||
phronesis` puts `phronesis` on `PATH` (Linux, Windows).
|
||||
- **12.2** `uv tool upgrade fiona-assistant` picks up a new release.
|
||||
- **12.3** `uv sync --locked` from a clean clone; all tests and sanity
|
||||
checks pass under `uv run`.
|
||||
- **12.4** `source bootstrap` on a machine without pyenv: no sudo, no
|
||||
compile, under a minute.
|
||||
- **12.5** `. .\bootstrap.ps1` on Windows creates `.venv` and activates
|
||||
it.
|
||||
- **12.6** `python scripts/publish.py` builds the same `dist/` file
|
||||
list with `uv build` as with `python -m build`.
|
||||
Reference in New Issue
Block a user