.cargo/config.toml+22−0
| @@ -0,0 +1,22 @@ | |||
| 1 | + | # Release binary hygiene: | |
| 2 | + | # - Strip symbols & dead code directly in the native linker (avoids broken rust-objcopy rpath | |
| 3 | + | # on some macOS toolchains and guarantees zero build warnings across macOS & Linux). | |
| 4 | + | # - Note: `--remap-path-prefix` is passed in release builds to avoid leaking local home paths. | |
| 5 | + | ||
| 6 | + | [target.aarch64-apple-darwin] | |
| 7 | + | rustflags = ["-C", "link-arg=-Wl,-S,-x,-dead_strip"] | |
| 8 | + | ||
| 9 | + | [target.x86_64-apple-darwin] | |
| 10 | + | rustflags = ["-C", "link-arg=-Wl,-S,-x,-dead_strip"] | |
| 11 | + | ||
| 12 | + | [target.aarch64-unknown-linux-musl] | |
| 13 | + | rustflags = ["-C", "link-arg=-s", "-C", "link-arg=-Wl,-z,relro,-z,now,-z,noexecstack", "-C", "target-feature=+crt-static"] | |
| 14 | + | ||
| 15 | + | [target.x86_64-unknown-linux-musl] | |
| 16 | + | rustflags = ["-C", "link-arg=-s", "-C", "link-arg=-Wl,-z,relro,-z,now,-z,noexecstack", "-C", "target-feature=+crt-static"] | |
| 17 | + | ||
| 18 | + | [target.aarch64-unknown-linux-gnu] | |
| 19 | + | rustflags = ["-C", "link-arg=-s"] | |
| 20 | + | ||
| 21 | + | [target.x86_64-unknown-linux-gnu] | |
| 22 | + | rustflags = ["-C", "link-arg=-s"] |
.gitignore+6−0
| @@ -0,0 +1,6 @@ | |||
| 1 | + | /target | |
| 2 | + | **/*.rs.bk | |
| 3 | + | *.pdb | |
| 4 | + | .DS_Store | |
| 5 | + | .idea/ | |
| 6 | + | .vscode/ |
ARCHITECTURE.md+49−0
| @@ -0,0 +1,49 @@ | |||
| 1 | + | # Architecture de Ronéo | |
| 2 | + | ||
| 3 | + | Ronéo est conçu autour d'un cœur générique sans aucune dépendance métier, avec un graphe de dépendances minimal (**156 crates transitives** au total, **120** pour `roneo-core`, **15** pour `roneo-plugin-sdk`) et extensible par des plugins WebAssembly sandboxés : | |
| 4 | + | ||
| 5 | + | ```text | |
| 6 | + | roneo/ | |
| 7 | + | ├── .cargo/config.toml # Strip natif côté linker + durcissement ELF/Mach-O (zéro warning) | |
| 8 | + | ├── forge.toml # Profil dépôt Forge (default_branch, description, release_tag) | |
| 9 | + | ├── ci/jobs.toml # CI native Forge (format, clippy, tests par crate + gitleaks) | |
| 10 | + | ├── deny.toml # Politique cargo-deny (advisories RustSec, licences, sources) | |
| 11 | + | ├── crates/ | |
| 12 | + | │ ├── roneo-core/ # Moteur pur (0 bloc `unsafe`) : gix + MiniJinja + rayon + wasmi | |
| 13 | + | │ │ └── src/ | |
| 14 | + | │ │ ├── answers.rs # .copier-answers.yml (clés triées, secrets filtrés, defaults when:false séparés) | |
| 15 | + | │ │ ├── config.rs # Parseur copier.yml / roneo.yml (multi-doc + !include confinés + globs + _roneo_plugins) | |
| 16 | + | │ │ ├── error.rs # RoneoError (#[non_exhaustive]) en Rust std pur (zéro `thiserror`) | |
| 17 | + | │ │ ├── filter.rs # Matcher gitignore & glob_match zéro-dépendance et zéro-allocation | |
| 18 | + | │ │ ├── fs_util.rs # TempDir RAII (mode 0700 Unix), walk_dir_sorted, permissions, symlinks | |
| 19 | + | │ │ ├── plugin.rs # Trait Extension + pool parallèle `wasmi` (fuel 100M, RAM 64 Mio, IPC 16 Mio) | |
| 20 | + | │ │ ├── prompt.rs # Évaluation des questions (`ask`, `--ask` glob, `when`, `validator`) + Prompter trait | |
| 21 | + | │ │ ├── renderer.rs # MiniJinja (AutoEscape::None) + pycompat + {% yield %} + validation path traversal | |
| 22 | + | │ │ ├── settings.rs # Réglages utilisateur `settings.yml` (`defaults` + `trust` RFC 3986 strict) | |
| 23 | + | │ │ ├── tasks.rs # Exécution sécurisée de _tasks et _migrations (`_stage`, `extra_env`, `--trust`) | |
| 24 | + | │ │ ├── template.rs # TemplateBacking::Disk vs TemplateBacking::GitTree + confinement chemins/symlinks | |
| 25 | + | │ │ ├── vcs.rs # InMemoryGitTree (`gix`) + cache miroir nu + `git status -z` + 3-way merge / merge-file | |
| 26 | + | │ │ ├── version.rs # Parseur/comparateur PEP 440 zéro-dépendance (tags + `_min_copier_version` 9.19.1) | |
| 27 | + | │ │ └── worker.rs # Orchestration copy/recopy/update/diff/check-update + rendu/écriture parallèle `rayon` | |
| 28 | + | │ ├── roneo-plugin-sdk/ # SDK minimal (3 deps) pour écrire des plugins `.wasm` externes | |
| 29 | + | │ └── roneo-cli/ # Binaire `roneo` 100 % générique + style ANSI zéro-dep + `roneo plugin` | |
| 30 | + | └── examples/ | |
| 31 | + | └── starter-template/ # Template Copier complet pour tester immédiatement | |
| 32 | + | ``` | |
| 33 | + | ||
| 34 | + | ## Choix techniques & optimisations | |
| 35 | + | ||
| 36 | + | 1. **Lecture Git 100 % en mémoire via `gix` minimal (`revision`, `sha1`, `max-performance` — sans `status`)** : | |
| 37 | + | - Pour les dépôts Git locaux, `InMemoryGitTree` encapsule `gix::ThreadSafeRepository`. `copier.yml`, `!include`, `{% include %}` et les fichiers demandés par les plugins sont lus directement dans les blobs Git sans extraction temporaire. | |
| 38 | + | - La résolution de tags lit les OIDs déjà *peeled* dans `packed-refs` sans décompresser les objets tags. Les répertoires exclus sont élagués avant lecture des blobs. | |
| 39 | + | - Les dépôts distants utilisent un **cache miroir nu persistant** (`~/.cache/roneo/repos/<fnv1a64>.git`, URL nettoyée des credentials) suivi de `git clone --shared` et de `resolve_sibling` en mémoire. | |
| 40 | + | 2. **Rendu et mise à jour rapides (`MiniJinja` + `rayon` + `filter.rs` zéro-alloc)** : | |
| 41 | + | - Le contexte de rendu est converti **une seule fois** en `minijinja::Value` réutilisable sur tous les cœurs CPU. | |
| 42 | + | - Chemins et chaînes sans délimiteurs Jinja court-circuitent le parseur, chaque dossier parent n'est rendu qu'**une seule fois**, et le mode Unix des fichiers sur disque est conservé dès le scan (`PlanCtx` / `FileRenderCtx`, sans second `stat()`). | |
| 43 | + | - `PathFilter` pré-compile les règles en `Literal` / `Prefix` / `Suffix` / `GlobStar` / `Wildcard` ASCII sans regex ni crate externe. | |
| 44 | + | - `rayon::map_init` réutilise un handle `gix::Repository` (cache LRU de deltas) par thread worker, et `WasmExtension` maintient un pool d'instances `wasmi` pré-initialisées. | |
| 45 | + | - `update` et `diff` réutilisent le même `gix::ThreadSafeRepository`, rendent les snapshots `old` et `new` **en parallèle via `rayon::join`**, puis génèrent le patch en **un seul `git diff --no-index --no-prefix --no-renames`** (fallback automatique `git apply --reject` + `git merge-file` en cas de squash merge). | |
| 46 | + | 3. **Sécurité & isolation par conception** : | |
| 47 | + | - **0 bloc `unsafe`** dans `roneo-core` et `roneo-cli` ; binaires release compilés avec `panic = "abort"`, strippés dans le linker, remapping de chemins (`--remap-path-prefix`), `GNU_RELRO` + `GNU_STACK RW` (NX) sur Linux statique `musl` et `PIE` sur macOS. | |
| 48 | + | - Confinement strict des chemins (`!include`, `{% include %}`, segments rendus, `_answers_file`, `_subdirectory`, `_roneo_plugins`, `_external_data` non-trusted, refus d'écriture à travers un dossier symlink, alias `roneo plugin`), validation RFC 3986 sur `trust:`, `-c core.hooksPath=/dev/null` et séparateurs `--` sur tous les sous-processus Git, `TempDir` en mode `0700`. | |
| 49 | + | - Plugins WebAssembly (`roneo-plugin-sdk`) strictement isolés dans `wasmi` sans accès système (ni WASI, ni FS, ni réseau), bornés en CPU (**100M fuel**), RAM (**64 Mio**) et IPC (**16 Mio**), et soumis à `--trust` lorsqu'ils sont déclarés par `_roneo_plugins`. |
CONTRIBUTING.md+26−0
| @@ -0,0 +1,26 @@ | |||
| 1 | + | # Contributing to Ronéo | |
| 2 | + | ||
| 3 | + | Thank you for your interest in **Ronéo**! | |
| 4 | + | ||
| 5 | + | Ronéo is developed internally on Cleyrop's forge and published as a read-only open-source mirror at `https://code.cleyrop.tech/roneo`. | |
| 6 | + | ||
| 7 | + | ## Local Development | |
| 8 | + | ||
| 9 | + | ```bash | |
| 10 | + | # Format, lint, and run all tests | |
| 11 | + | cargo fmt --all -- --check | |
| 12 | + | cargo clippy --workspace --all-targets -- -D warnings | |
| 13 | + | cargo test --workspace | |
| 14 | + | cargo deny check | |
| 15 | + | ``` | |
| 16 | + | ||
| 17 | + | ## Submitting Patches or Issues | |
| 18 | + | ||
| 19 | + | External patches (`git format-patch`) and bug reports can be sent to `opensource@cleyrop.com`. | |
| 20 | + | ||
| 21 | + | Please ensure your changes: | |
| 22 | + | ||
| 23 | + | - Pass `cargo fmt --all -- --check` and `cargo clippy --workspace --all-targets -- -D warnings` | |
| 24 | + | - Include unit or integration tests in `crates/roneo-core/tests/integration.rs` | |
| 25 | + | - Avoid unnecessary external dependencies | |
| 26 | + | - Keep `roneo-core` and `roneo-cli` free of `unsafe` code |
Cargo.lock+1987−0
| @@ -0,0 +1,1987 @@ | |||
| 1 | + | # This file is automatically @generated by Cargo. | |
| 2 | + | # It is not intended for manual editing. | |
| 3 | + | version = 4 | |
| 4 | + | ||
| 5 | + | [[package]] | |
| 6 | + | name = "allocator-api2" | |
| 7 | + | version = "0.2.22" | |
| 8 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 9 | + | checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014" | |
| 10 | + | ||
| 11 | + | [[package]] | |
| 12 | + | name = "anstream" | |
| 13 | + | version = "1.0.1" | |
| 14 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 15 | + | checksum = "85c097ce94629611e0a15ef1078a2fe2ce3b4a0f4b44708e85eeb09dd5f188eb" | |
| 16 | + | dependencies = [ | |
| 17 | + | "anstyle", | |
| 18 | + | "anstyle-parse", | |
| 19 | + | "anstyle-query", | |
| 20 | + | "anstyle-wincon", | |
| 21 | + | "colorchoice", | |
| 22 | + | "is_terminal_polyfill", | |
| 23 | + | "utf8parse", | |
| 24 | + | ] | |
| 25 | + | ||
| 26 | + | [[package]] | |
| 27 | + | name = "anstyle" | |
| 28 | + | version = "1.0.15" | |
| 29 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 30 | + | checksum = "6c7a9e344b352bef7873e51ff425c2f90d5aa2a252db2b84289c93ff30beb3d7" | |
| 31 | + | ||
| 32 | + | [[package]] | |
| 33 | + | name = "anstyle-parse" | |
| 34 | + | version = "1.0.1" | |
| 35 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 36 | + | checksum = "a0571a23d2188b4aae7adc1df454cc81d6232cf37674fa717ac119f6c74d0dc1" | |
| 37 | + | dependencies = [ | |
| 38 | + | "utf8parse", | |
| 39 | + | ] | |
| 40 | + | ||
| 41 | + | [[package]] | |
| 42 | + | name = "anstyle-query" | |
| 43 | + | version = "1.1.6" | |
| 44 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 45 | + | checksum = "76a5cf9d05ffa9c878c447b33b069605e890ebcd36d2761f86367873c2ecaa7f" | |
| 46 | + | dependencies = [ | |
| 47 | + | "windows-sys 0.101.0", | |
| 48 | + | ] | |
| 49 | + | ||
| 50 | + | [[package]] | |
| 51 | + | name = "anstyle-wincon" | |
| 52 | + | version = "3.0.12" | |
| 53 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 54 | + | checksum = "2c2d00c1b2d84cef823d89d4da02ad8ff1e76c969e029da990b40f16dc834221" | |
| 55 | + | dependencies = [ | |
| 56 | + | "anstyle", | |
| 57 | + | "once_cell_polyfill", | |
| 58 | + | "windows-sys 0.101.0", | |
| 59 | + | ] | |
| 60 | + | ||
| 61 | + | [[package]] | |
| 62 | + | name = "arc-swap" | |
| 63 | + | version = "1.9.5" | |
| 64 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 65 | + | checksum = "84a22b5d51209f6de83d37a0b33d320acb8da88823e42a94c075140708f032a5" | |
| 66 | + | dependencies = [ | |
| 67 | + | "rustversion", | |
| 68 | + | ] | |
| 69 | + | ||
| 70 | + | [[package]] | |
| 71 | + | name = "arrayvec" | |
| 72 | + | version = "0.7.9" | |
| 73 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 74 | + | checksum = "47a64a0fd06e123e9e3cf3ad01432af17dcab8185e8023edcf184fe696f9675d" | |
| 75 | + | ||
| 76 | + | [[package]] | |
| 77 | + | name = "bitflags" | |
| 78 | + | version = "1.3.2" | |
| 79 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 80 | + | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" | |
| 81 | + | ||
| 82 | + | [[package]] | |
| 83 | + | name = "bitflags" | |
| 84 | + | version = "2.13.2" | |
| 85 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 86 | + | checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" | |
| 87 | + | ||
| 88 | + | [[package]] | |
| 89 | + | name = "bstr" | |
| 90 | + | version = "1.14.0" | |
| 91 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 92 | + | checksum = "a680398c10c7bc0488067c4612226ea905a85f607134b69f3068d505d58c4214" | |
| 93 | + | dependencies = [ | |
| 94 | + | "memchr", | |
| 95 | + | "regex-automata", | |
| 96 | + | "serde_core", | |
| 97 | + | ] | |
| 98 | + | ||
| 99 | + | [[package]] | |
| 100 | + | name = "bytes" | |
| 101 | + | version = "1.12.2" | |
| 102 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 103 | + | checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" | |
| 104 | + | ||
| 105 | + | [[package]] | |
| 106 | + | name = "cfg-if" | |
| 107 | + | version = "1.0.5" | |
| 108 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 109 | + | checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" | |
| 110 | + | ||
| 111 | + | [[package]] | |
| 112 | + | name = "clap" | |
| 113 | + | version = "4.6.10" | |
| 114 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 115 | + | checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3" | |
| 116 | + | dependencies = [ | |
| 117 | + | "clap_builder", | |
| 118 | + | "clap_derive", | |
| 119 | + | ] | |
| 120 | + | ||
| 121 | + | [[package]] | |
| 122 | + | name = "clap_builder" | |
| 123 | + | version = "4.6.10" | |
| 124 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 125 | + | checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590" | |
| 126 | + | dependencies = [ | |
| 127 | + | "anstream", | |
| 128 | + | "anstyle", | |
| 129 | + | "clap_lex", | |
| 130 | + | "strsim", | |
| 131 | + | ] | |
| 132 | + | ||
| 133 | + | [[package]] | |
| 134 | + | name = "clap_derive" | |
| 135 | + | version = "4.6.9" | |
| 136 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 137 | + | checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" | |
| 138 | + | dependencies = [ | |
| 139 | + | "heck", | |
| 140 | + | "proc-macro2", | |
| 141 | + | "quote", | |
| 142 | + | "syn 3.0.10", | |
| 143 | + | ] | |
| 144 | + | ||
| 145 | + | [[package]] | |
| 146 | + | name = "clap_lex" | |
| 147 | + | version = "1.1.2" | |
| 148 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 149 | + | checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" | |
| 150 | + | ||
| 151 | + | [[package]] | |
| 152 | + | name = "clru" | |
| 153 | + | version = "0.6.3" | |
| 154 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 155 | + | checksum = "197fd99cb113a8d5d9b6376f3aa817f32c1078f2343b714fff7d2ca44fdf67d5" | |
| 156 | + | dependencies = [ | |
| 157 | + | "hashbrown 0.16.1", | |
| 158 | + | ] | |
| 159 | + | ||
| 160 | + | [[package]] | |
| 161 | + | name = "colorchoice" | |
| 162 | + | version = "1.0.6" | |
| 163 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 164 | + | checksum = "8f7f11958434c85b6efac08f8299dc08bd263184ce080232e2168940cda4368e" | |
| 165 | + | ||
| 166 | + | [[package]] | |
| 167 | + | name = "convert_case" | |
| 168 | + | version = "0.10.0" | |
| 169 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 170 | + | checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" | |
| 171 | + | dependencies = [ | |
| 172 | + | "unicode-segmentation", | |
| 173 | + | ] | |
| 174 | + | ||
| 175 | + | [[package]] | |
| 176 | + | name = "crc32fast" | |
| 177 | + | version = "1.5.6" | |
| 178 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 179 | + | checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" | |
| 180 | + | dependencies = [ | |
| 181 | + | "cfg-if", | |
| 182 | + | ] | |
| 183 | + | ||
| 184 | + | [[package]] | |
| 185 | + | name = "crossbeam-channel" | |
| 186 | + | version = "0.5.17" | |
| 187 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 188 | + | checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" | |
| 189 | + | dependencies = [ | |
| 190 | + | "crossbeam-utils", | |
| 191 | + | ] | |
| 192 | + | ||
| 193 | + | [[package]] | |
| 194 | + | name = "crossbeam-deque" | |
| 195 | + | version = "0.8.8" | |
| 196 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 197 | + | checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" | |
| 198 | + | dependencies = [ | |
| 199 | + | "crossbeam-epoch", | |
| 200 | + | "crossbeam-utils", | |
| 201 | + | ] | |
| 202 | + | ||
| 203 | + | [[package]] | |
| 204 | + | name = "crossbeam-epoch" | |
| 205 | + | version = "0.9.21" | |
| 206 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 207 | + | checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" | |
| 208 | + | dependencies = [ | |
| 209 | + | "crossbeam-utils", | |
| 210 | + | ] | |
| 211 | + | ||
| 212 | + | [[package]] | |
| 213 | + | name = "crossbeam-utils" | |
| 214 | + | version = "0.8.23" | |
| 215 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 216 | + | checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" | |
| 217 | + | ||
| 218 | + | [[package]] | |
| 219 | + | name = "crossterm" | |
| 220 | + | version = "0.29.0" | |
| 221 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 222 | + | checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" | |
| 223 | + | dependencies = [ | |
| 224 | + | "bitflags 2.13.2", | |
| 225 | + | "crossterm_winapi", | |
| 226 | + | "derive_more", | |
| 227 | + | "document-features", | |
| 228 | + | "mio", | |
| 229 | + | "parking_lot 0.12.5", | |
| 230 | + | "rustix", | |
| 231 | + | "signal-hook", | |
| 232 | + | "signal-hook-mio", | |
| 233 | + | "winapi", | |
| 234 | + | ] | |
| 235 | + | ||
| 236 | + | [[package]] | |
| 237 | + | name = "crossterm_winapi" | |
| 238 | + | version = "0.9.1" | |
| 239 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 240 | + | checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" | |
| 241 | + | dependencies = [ | |
| 242 | + | "winapi", | |
| 243 | + | ] | |
| 244 | + | ||
| 245 | + | [[package]] | |
| 246 | + | name = "defmt" | |
| 247 | + | version = "0.3.101" | |
| 248 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 249 | + | checksum = "4deef977660e373c458df605a913d4ab121db0ccd18d1ad6976dff7d37cddb53" | |
| 250 | + | dependencies = [ | |
| 251 | + | "defmt 1.2.0", | |
| 252 | + | ] | |
| 253 | + | ||
| 254 | + | [[package]] | |
| 255 | + | name = "defmt" | |
| 256 | + | version = "1.2.0" | |
| 257 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 258 | + | checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" | |
| 259 | + | dependencies = [ | |
| 260 | + | "bitflags 1.3.2", | |
| 261 | + | "defmt-macros", | |
| 262 | + | ] | |
| 263 | + | ||
| 264 | + | [[package]] | |
| 265 | + | name = "defmt-macros" | |
| 266 | + | version = "1.2.0" | |
| 267 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 268 | + | checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" | |
| 269 | + | dependencies = [ | |
| 270 | + | "defmt-parser", | |
| 271 | + | "proc-macro2", | |
| 272 | + | "quote", | |
| 273 | + | "syn 3.0.10", | |
| 274 | + | ] | |
| 275 | + | ||
| 276 | + | [[package]] | |
| 277 | + | name = "defmt-parser" | |
| 278 | + | version = "1.1.0" | |
| 279 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 280 | + | checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" | |
| 281 | + | dependencies = [ | |
| 282 | + | "thiserror", | |
| 283 | + | ] | |
| 284 | + | ||
| 285 | + | [[package]] | |
| 286 | + | name = "derive_more" | |
| 287 | + | version = "2.1.1" | |
| 288 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 289 | + | checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" | |
| 290 | + | dependencies = [ | |
| 291 | + | "derive_more-impl", | |
| 292 | + | ] | |
| 293 | + | ||
| 294 | + | [[package]] | |
| 295 | + | name = "derive_more-impl" | |
| 296 | + | version = "2.1.1" | |
| 297 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 298 | + | checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" | |
| 299 | + | dependencies = [ | |
| 300 | + | "convert_case", | |
| 301 | + | "proc-macro2", | |
| 302 | + | "quote", | |
| 303 | + | "rustc_version", | |
| 304 | + | "syn 2.0.119", | |
| 305 | + | ] | |
| 306 | + | ||
| 307 | + | [[package]] | |
| 308 | + | name = "document-features" | |
| 309 | + | version = "0.2.12" | |
| 310 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 311 | + | checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" | |
| 312 | + | dependencies = [ | |
| 313 | + | "litrs", | |
| 314 | + | ] | |
| 315 | + | ||
| 316 | + | [[package]] | |
| 317 | + | name = "dunce" | |
| 318 | + | version = "1.0.5" | |
| 319 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 320 | + | checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" | |
| 321 | + | ||
| 322 | + | [[package]] | |
| 323 | + | name = "dyn-clone" | |
| 324 | + | version = "1.0.20" | |
| 325 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 326 | + | checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" | |
| 327 | + | ||
| 328 | + | [[package]] | |
| 329 | + | name = "either" | |
| 330 | + | version = "1.19.0" | |
| 331 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 332 | + | checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" | |
| 333 | + | ||
| 334 | + | [[package]] | |
| 335 | + | name = "equivalent" | |
| 336 | + | version = "1.0.3" | |
| 337 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 338 | + | checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" | |
| 339 | + | ||
| 340 | + | [[package]] | |
| 341 | + | name = "errno" | |
| 342 | + | version = "0.3.15" | |
| 343 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 344 | + | checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" | |
| 345 | + | dependencies = [ | |
| 346 | + | "libc", | |
| 347 | + | "windows-sys 0.61.2", | |
| 348 | + | ] | |
| 349 | + | ||
| 350 | + | [[package]] | |
| 351 | + | name = "faster-hex" | |
| 352 | + | version = "2.1.0" | |
| 353 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 354 | + | checksum = "52094542d09210d54b87d1a7a13996182c8170cd84e7baa56b332b7ca0d7a7de" | |
| 355 | + | dependencies = [ | |
| 356 | + | "defmt 0.3.101", | |
| 357 | + | "serde", | |
| 358 | + | ] | |
| 359 | + | ||
| 360 | + | [[package]] | |
| 361 | + | name = "fastrand" | |
| 362 | + | version = "2.5.0" | |
| 363 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 364 | + | checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" | |
| 365 | + | ||
| 366 | + | [[package]] | |
| 367 | + | name = "filetime" | |
| 368 | + | version = "0.2.30" | |
| 369 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 370 | + | checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7" | |
| 371 | + | dependencies = [ | |
| 372 | + | "cfg-if", | |
| 373 | + | "libc", | |
| 374 | + | ] | |
| 375 | + | ||
| 376 | + | [[package]] | |
| 377 | + | name = "fnv" | |
| 378 | + | version = "1.0.7" | |
| 379 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 380 | + | checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" | |
| 381 | + | ||
| 382 | + | [[package]] | |
| 383 | + | name = "foldhash" | |
| 384 | + | version = "0.1.5" | |
| 385 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 386 | + | checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" | |
| 387 | + | ||
| 388 | + | [[package]] | |
| 389 | + | name = "foldhash" | |
| 390 | + | version = "0.2.0" | |
| 391 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 392 | + | checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" | |
| 393 | + | ||
| 394 | + | [[package]] | |
| 395 | + | name = "fuzzy-matcher" | |
| 396 | + | version = "0.3.7" | |
| 397 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 398 | + | checksum = "54614a3312934d066701a80f20f15fa3b56d67ac7722b39eea5b4c9dd1d66c94" | |
| 399 | + | dependencies = [ | |
| 400 | + | "thread_local", | |
| 401 | + | ] | |
| 402 | + | ||
| 403 | + | [[package]] | |
| 404 | + | name = "getrandom" | |
| 405 | + | version = "0.4.3" | |
| 406 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 407 | + | checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" | |
| 408 | + | dependencies = [ | |
| 409 | + | "cfg-if", | |
| 410 | + | "libc", | |
| 411 | + | "r-efi", | |
| 412 | + | ] | |
| 413 | + | ||
| 414 | + | [[package]] | |
| 415 | + | name = "gix" | |
| 416 | + | version = "0.91.0" | |
| 417 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 418 | + | checksum = "c55489aa5c697624ae3841c75c5817bc08e87c3f44743d2b9621920e21a9a4c5" | |
| 419 | + | dependencies = [ | |
| 420 | + | "gix-actor", | |
| 421 | + | "gix-commitgraph", | |
| 422 | + | "gix-config", | |
| 423 | + | "gix-date", | |
| 424 | + | "gix-diff", | |
| 425 | + | "gix-discover", | |
| 426 | + | "gix-error", | |
| 427 | + | "gix-fs", | |
| 428 | + | "gix-glob", | |
| 429 | + | "gix-hash", | |
| 430 | + | "gix-hashtable", | |
| 431 | + | "gix-index", | |
| 432 | + | "gix-lock", | |
| 433 | + | "gix-macros", | |
| 434 | + | "gix-note", | |
| 435 | + | "gix-object", | |
| 436 | + | "gix-odb", | |
| 437 | + | "gix-pack", | |
| 438 | + | "gix-parallel", | |
| 439 | + | "gix-path", | |
| 440 | + | "gix-protocol", | |
| 441 | + | "gix-quote", | |
| 442 | + | "gix-ref", | |
| 443 | + | "gix-refspec", | |
| 444 | + | "gix-revision", | |
| 445 | + | "gix-revwalk", | |
| 446 | + | "gix-sec", | |
| 447 | + | "gix-shallow", | |
| 448 | + | "gix-tempfile", | |
| 449 | + | "gix-trace", | |
| 450 | + | "gix-traverse", | |
| 451 | + | "gix-url", | |
| 452 | + | "gix-utils", | |
| 453 | + | "gix-validate", | |
| 454 | + | "gix-worktree-stream", | |
| 455 | + | "gix-zlib", | |
| 456 | + | "nonempty", | |
| 457 | + | "smallvec", | |
| 458 | + | ] | |
| 459 | + | ||
| 460 | + | [[package]] | |
| 461 | + | name = "gix-actor" | |
| 462 | + | version = "0.45.0" | |
| 463 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 464 | + | checksum = "bb0ca2b29b2b0c1f13d83434f9e4344a4b7fe0c59eeb104fa68e3bb6e62415e7" | |
| 465 | + | dependencies = [ | |
| 466 | + | "bstr", | |
| 467 | + | "gix-date", | |
| 468 | + | "gix-error", | |
| 469 | + | "gix-macros", | |
| 470 | + | ] | |
| 471 | + | ||
| 472 | + | [[package]] | |
| 473 | + | name = "gix-attributes" | |
| 474 | + | version = "0.38.0" | |
| 475 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 476 | + | checksum = "d036e63be361bc5ec653cbf41c8cef56313a518082b0730cc41bfefccafca66d" | |
| 477 | + | dependencies = [ | |
| 478 | + | "bstr", | |
| 479 | + | "gix-error", | |
| 480 | + | "gix-glob", | |
| 481 | + | "gix-parallel", | |
| 482 | + | "gix-path", | |
| 483 | + | "gix-quote", | |
| 484 | + | "gix-trace", | |
| 485 | + | "smallvec", | |
| 486 | + | "unicode-bom", | |
| 487 | + | ] | |
| 488 | + | ||
| 489 | + | [[package]] | |
| 490 | + | name = "gix-bitmap" | |
| 491 | + | version = "0.6.2" | |
| 492 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 493 | + | checksum = "9543567ee22142c81fdf75b2811160bec749a5b9f48665e4763f88b1789b8612" | |
| 494 | + | dependencies = [ | |
| 495 | + | "gix-error", | |
| 496 | + | ] | |
| 497 | + | ||
| 498 | + | [[package]] | |
| 499 | + | name = "gix-chunk" | |
| 500 | + | version = "0.10.2" | |
| 501 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 502 | + | checksum = "60cd5f0e47ffae98bad241ccbc031693765004fb4c2a419f7fda2963232af1e3" | |
| 503 | + | dependencies = [ | |
| 504 | + | "gix-error", | |
| 505 | + | ] | |
| 506 | + | ||
| 507 | + | [[package]] | |
| 508 | + | name = "gix-command" | |
| 509 | + | version = "0.12.2" | |
| 510 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 511 | + | checksum = "2986e78ebad43510ccd7dd18bd9f22e9afd52f2de791e2979b9c715bacb6f0a8" | |
| 512 | + | dependencies = [ | |
| 513 | + | "bstr", | |
| 514 | + | "gix-error", | |
| 515 | + | "gix-path", | |
| 516 | + | "gix-quote", | |
| 517 | + | "gix-trace", | |
| 518 | + | ] | |
| 519 | + | ||
| 520 | + | [[package]] | |
| 521 | + | name = "gix-commitgraph" | |
| 522 | + | version = "0.43.0" | |
| 523 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 524 | + | checksum = "cf9c1d5c9411f84b5e61edff9190542bec56e56d7643dd282c6c8befc9d7e80c" | |
| 525 | + | dependencies = [ | |
| 526 | + | "bstr", | |
| 527 | + | "gix-chunk", | |
| 528 | + | "gix-error", | |
| 529 | + | "gix-hash", | |
| 530 | + | "memmap2", | |
| 531 | + | "nonempty", | |
| 532 | + | ] | |
| 533 | + | ||
| 534 | + | [[package]] | |
| 535 | + | name = "gix-config" | |
| 536 | + | version = "0.63.0" | |
| 537 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 538 | + | checksum = "f06d363f95262db002209d4603a53fd5464101d37b4387698d6045e4d06745ea" | |
| 539 | + | dependencies = [ | |
| 540 | + | "bstr", | |
| 541 | + | "gix-config-value", | |
| 542 | + | "gix-error", | |
| 543 | + | "gix-glob", | |
| 544 | + | "gix-parallel", | |
| 545 | + | "gix-path", | |
| 546 | + | "gix-ref", | |
| 547 | + | "gix-sec", | |
| 548 | + | "gix-trace", | |
| 549 | + | "gix-utils", | |
| 550 | + | "smallvec", | |
| 551 | + | "unicode-bom", | |
| 552 | + | ] | |
| 553 | + | ||
| 554 | + | [[package]] | |
| 555 | + | name = "gix-config-value" | |
| 556 | + | version = "0.21.2" | |
| 557 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 558 | + | checksum = "d7666081ef0ecc5e1dc54bc6ce16dac9d7b9490780f6c130393ef9e50c909d4a" | |
| 559 | + | dependencies = [ | |
| 560 | + | "bitflags 2.13.2", | |
| 561 | + | "bstr", | |
| 562 | + | "gix-error", | |
| 563 | + | "gix-path", | |
| 564 | + | "gix-utils", | |
| 565 | + | "libc", | |
| 566 | + | ] | |
| 567 | + | ||
| 568 | + | [[package]] | |
| 569 | + | name = "gix-date" | |
| 570 | + | version = "0.19.0" | |
| 571 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 572 | + | checksum = "b44e409b7d777f1c9288adb02462a6c713e4837a182a8126f70d68cf280042f0" | |
| 573 | + | dependencies = [ | |
| 574 | + | "bstr", | |
| 575 | + | "gix-error", | |
| 576 | + | "gix-macros", | |
| 577 | + | "itoa", | |
| 578 | + | "jiff", | |
| 579 | + | ] | |
| 580 | + | ||
| 581 | + | [[package]] | |
| 582 | + | name = "gix-diff" | |
| 583 | + | version = "0.71.0" | |
| 584 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 585 | + | checksum = "23c3d75df24ec51259717e7fe7dc6ec39137fdd26c663683447084c27b67e0fd" | |
| 586 | + | dependencies = [ | |
| 587 | + | "bstr", | |
| 588 | + | "gix-error", | |
| 589 | + | "gix-hash", | |
| 590 | + | "gix-object", | |
| 591 | + | ] | |
| 592 | + | ||
| 593 | + | [[package]] | |
| 594 | + | name = "gix-discover" | |
| 595 | + | version = "0.58.0" | |
| 596 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 597 | + | checksum = "cbcdeda976044272db7c6f57b8b987e2609825ea3a0ebbf1bde2053d88738ac0" | |
| 598 | + | dependencies = [ | |
| 599 | + | "bstr", | |
| 600 | + | "dunce", | |
| 601 | + | "gix-error", | |
| 602 | + | "gix-fs", | |
| 603 | + | "gix-path", | |
| 604 | + | "gix-ref", | |
| 605 | + | "gix-sec", | |
| 606 | + | ] | |
| 607 | + | ||
| 608 | + | [[package]] | |
| 609 | + | name = "gix-encoding" | |
| 610 | + | version = "0.1.0" | |
| 611 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 612 | + | checksum = "9d1c46c06ae282ef913b650ed3d0003453bca0fffdbf0cc4d858c4682577f99f" | |
| 613 | + | dependencies = [ | |
| 614 | + | "gix-error", | |
| 615 | + | "gix-zlib", | |
| 616 | + | ] | |
| 617 | + | ||
| 618 | + | [[package]] | |
| 619 | + | name = "gix-error" | |
| 620 | + | version = "0.5.3" | |
| 621 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 622 | + | checksum = "50ad6c42fa50280f382026ff838a8afa7ab2ad83e92349cab4392972baae69cd" | |
| 623 | + | dependencies = [ | |
| 624 | + | "bstr", | |
| 625 | + | ] | |
| 626 | + | ||
| 627 | + | [[package]] | |
| 628 | + | name = "gix-filter" | |
| 629 | + | version = "0.37.0" | |
| 630 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 631 | + | checksum = "3e0be902515f7d8039eda97acc917c9080065ba57b385291a949df68d66b6c71" | |
| 632 | + | dependencies = [ | |
| 633 | + | "bstr", | |
| 634 | + | "gix-attributes", | |
| 635 | + | "gix-command", | |
| 636 | + | "gix-encoding", | |
| 637 | + | "gix-error", | |
| 638 | + | "gix-hash", | |
| 639 | + | "gix-object", | |
| 640 | + | "gix-packetline", | |
| 641 | + | "gix-path", | |
| 642 | + | "gix-quote", | |
| 643 | + | "gix-trace", | |
| 644 | + | "gix-utils", | |
| 645 | + | "smallvec", | |
| 646 | + | ] | |
| 647 | + | ||
| 648 | + | [[package]] | |
| 649 | + | name = "gix-fs" | |
| 650 | + | version = "1.0.0" | |
| 651 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 652 | + | checksum = "516aec0f136bdfb26420ced8e43e1d5b36b967cd94aa1c763036208f25b8e888" | |
| 653 | + | dependencies = [ | |
| 654 | + | "bstr", | |
| 655 | + | "gix-error", | |
| 656 | + | "gix-macros", | |
| 657 | + | "gix-parallel", | |
| 658 | + | "gix-path", | |
| 659 | + | "gix-utils", | |
| 660 | + | "libc", | |
| 661 | + | "walkdir", | |
| 662 | + | ] | |
| 663 | + | ||
| 664 | + | [[package]] | |
| 665 | + | name = "gix-glob" | |
| 666 | + | version = "0.30.0" | |
| 667 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 668 | + | checksum = "48b4b3c2353cc9f9709a49d8c3b9c7a7a0188d43eeb756ac9a5a36bc397b013c" | |
| 669 | + | dependencies = [ | |
| 670 | + | "bitflags 2.13.2", | |
| 671 | + | "bstr", | |
| 672 | + | "gix-fs", | |
| 673 | + | "gix-path", | |
| 674 | + | "gix-trace", | |
| 675 | + | "gix-utils", | |
| 676 | + | ] | |
| 677 | + | ||
| 678 | + | [[package]] | |
| 679 | + | name = "gix-hash" | |
| 680 | + | version = "0.29.0" | |
| 681 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 682 | + | checksum = "2b6253d384423a2240f1098c2fefe11d44191c1668e94546f6f727f4afc6b8b3" | |
| 683 | + | dependencies = [ | |
| 684 | + | "faster-hex", | |
| 685 | + | "gix-error", | |
| 686 | + | "gix-macros", | |
| 687 | + | "gix-utils", | |
| 688 | + | "sha1dc", | |
| 689 | + | ] | |
| 690 | + | ||
| 691 | + | [[package]] | |
| 692 | + | name = "gix-hashtable" | |
| 693 | + | version = "0.19.0" | |
| 694 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 695 | + | checksum = "647aa884e63e533c8f5dc32ee7f47a3ed3bc268abdb6ba0312168c238899cde0" | |
| 696 | + | dependencies = [ | |
| 697 | + | "gix-hash", | |
| 698 | + | "hashbrown 0.17.2", | |
| 699 | + | "parking_lot 0.13.0", | |
| 700 | + | ] | |
| 701 | + | ||
| 702 | + | [[package]] | |
| 703 | + | name = "gix-index" | |
| 704 | + | version = "0.59.0" | |
| 705 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 706 | + | checksum = "0dd26a69f9f1dc3d41140472d1494cde938a34a5ace620c2945df99a4317b628" | |
| 707 | + | dependencies = [ | |
| 708 | + | "bitflags 2.13.2", | |
| 709 | + | "bstr", | |
| 710 | + | "filetime", | |
| 711 | + | "fnv", | |
| 712 | + | "gix-bitmap", | |
| 713 | + | "gix-error", | |
| 714 | + | "gix-fs", | |
| 715 | + | "gix-hash", | |
| 716 | + | "gix-lock", | |
| 717 | + | "gix-object", | |
| 718 | + | "gix-parallel", | |
| 719 | + | "gix-trace", | |
| 720 | + | "gix-traverse", | |
| 721 | + | "gix-utils", | |
| 722 | + | "gix-validate", | |
| 723 | + | "hashbrown 0.17.2", | |
| 724 | + | "itoa", | |
| 725 | + | "libc", | |
| 726 | + | "memmap2", | |
| 727 | + | "rustix", | |
| 728 | + | "smallvec", | |
| 729 | + | ] | |
| 730 | + | ||
| 731 | + | [[package]] | |
| 732 | + | name = "gix-lock" | |
| 733 | + | version = "27.0.0" | |
| 734 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 735 | + | checksum = "9699276e6ce4321f42a648e6964615ac3e0c4efabf6644e8d7c044971817894d" | |
| 736 | + | dependencies = [ | |
| 737 | + | "gix-error", | |
| 738 | + | "gix-fs", | |
| 739 | + | "gix-macros", | |
| 740 | + | "gix-tempfile", | |
| 741 | + | "gix-utils", | |
| 742 | + | ] | |
| 743 | + | ||
| 744 | + | [[package]] | |
| 745 | + | name = "gix-macros" | |
| 746 | + | version = "0.2.2" | |
| 747 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 748 | + | checksum = "79ca2ec664aea06d549444f9cd35546dd1732b2ea188b48159cea4fbf2a05848" | |
| 749 | + | dependencies = [ | |
| 750 | + | "proc-macro2", | |
| 751 | + | "quote", | |
| 752 | + | "syn 3.0.10", | |
| 753 | + | ] | |
| 754 | + | ||
| 755 | + | [[package]] | |
| 756 | + | name = "gix-note" | |
| 757 | + | version = "0.4.0" | |
| 758 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 759 | + | checksum = "e6960a93c036a132802cc72824a8973327777ff291fdb16455db44cb18dcd1c5" | |
| 760 | + | dependencies = [ | |
| 761 | + | "gix-error", | |
| 762 | + | "gix-hash", | |
| 763 | + | "gix-object", | |
| 764 | + | ] | |
| 765 | + | ||
| 766 | + | [[package]] | |
| 767 | + | name = "gix-object" | |
| 768 | + | version = "0.67.0" | |
| 769 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 770 | + | checksum = "902209f89e8f90fb347bb34eaf79b5bd0f4f1d998e7996bfa87cf7efb9b00cb8" | |
| 771 | + | dependencies = [ | |
| 772 | + | "bstr", | |
| 773 | + | "gix-actor", | |
| 774 | + | "gix-date", | |
| 775 | + | "gix-error", | |
| 776 | + | "gix-hash", | |
| 777 | + | "gix-hashtable", | |
| 778 | + | "gix-utils", | |
| 779 | + | "gix-validate", | |
| 780 | + | "itoa", | |
| 781 | + | "smallvec", | |
| 782 | + | ] | |
| 783 | + | ||
| 784 | + | [[package]] | |
| 785 | + | name = "gix-odb" | |
| 786 | + | version = "0.88.0" | |
| 787 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 788 | + | checksum = "aa609d917320d748466e5be7f65243cdbb42f94eedc3d041d5ee3549d42c6c8e" | |
| 789 | + | dependencies = [ | |
| 790 | + | "arc-swap", | |
| 791 | + | "crc32fast", | |
| 792 | + | "gix-error", | |
| 793 | + | "gix-fs", | |
| 794 | + | "gix-hash", | |
| 795 | + | "gix-hashtable", | |
| 796 | + | "gix-object", | |
| 797 | + | "gix-pack", | |
| 798 | + | "gix-parallel", | |
| 799 | + | "gix-path", | |
| 800 | + | "gix-quote", | |
| 801 | + | "gix-trace", | |
| 802 | + | "gix-utils", | |
| 803 | + | "gix-zlib", | |
| 804 | + | "memmap2", | |
| 805 | + | "parking_lot 0.13.0", | |
| 806 | + | "tempfile", | |
| 807 | + | ] | |
| 808 | + | ||
| 809 | + | [[package]] | |
| 810 | + | name = "gix-pack" | |
| 811 | + | version = "0.78.0" | |
| 812 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 813 | + | checksum = "d73ec40dd101c3fd10f83037e354ee4ac200f81cd45c39e63d517d3fc03a186a" | |
| 814 | + | dependencies = [ | |
| 815 | + | "clru", | |
| 816 | + | "crc32fast", | |
| 817 | + | "crossbeam-deque", | |
| 818 | + | "gix-chunk", | |
| 819 | + | "gix-error", | |
| 820 | + | "gix-hash", | |
| 821 | + | "gix-hashtable", | |
| 822 | + | "gix-object", | |
| 823 | + | "gix-parallel", | |
| 824 | + | "gix-path", | |
| 825 | + | "gix-trace", | |
| 826 | + | "gix-utils", | |
| 827 | + | "gix-zlib", | |
| 828 | + | "memmap2", | |
| 829 | + | "smallvec", | |
| 830 | + | "uluru", | |
| 831 | + | ] | |
| 832 | + | ||
| 833 | + | [[package]] | |
| 834 | + | name = "gix-packetline" | |
| 835 | + | version = "0.24.2" | |
| 836 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 837 | + | checksum = "6e198121152a397ad1007e3334931b04b393fa17f6af34f17b33e376b15bf5ea" | |
| 838 | + | dependencies = [ | |
| 839 | + | "bstr", | |
| 840 | + | "faster-hex", | |
| 841 | + | "gix-error", | |
| 842 | + | "gix-trace", | |
| 843 | + | ] | |
| 844 | + | ||
| 845 | + | [[package]] | |
| 846 | + | name = "gix-parallel" | |
| 847 | + | version = "0.50.2" | |
| 848 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 849 | + | checksum = "d3a5c86eeec0194a3444611b4762ba05cc5029408a617348b4f6a74a34c222cd" | |
| 850 | + | dependencies = [ | |
| 851 | + | "crossbeam-channel", | |
| 852 | + | "gix-trace", | |
| 853 | + | "once_cell", | |
| 854 | + | "parking_lot 0.13.0", | |
| 855 | + | ] | |
| 856 | + | ||
| 857 | + | [[package]] | |
| 858 | + | name = "gix-path" | |
| 859 | + | version = "0.14.2" | |
| 860 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 861 | + | checksum = "615e3ff75800c67022ec8065b67e0846420a88c5f484e6c4fd81c78472e4c77a" | |
| 862 | + | dependencies = [ | |
| 863 | + | "bstr", | |
| 864 | + | "gix-error", | |
| 865 | + | "gix-trace", | |
| 866 | + | "gix-validate", | |
| 867 | + | "winreg", | |
| 868 | + | ] | |
| 869 | + | ||
| 870 | + | [[package]] | |
| 871 | + | name = "gix-protocol" | |
| 872 | + | version = "0.69.0" | |
| 873 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 874 | + | checksum = "6faba99a4e1b831c6fe8500601cac3e8e167be548977adb800ab1cf709255253" | |
| 875 | + | dependencies = [ | |
| 876 | + | "bstr", | |
| 877 | + | "gix-date", | |
| 878 | + | "gix-error", | |
| 879 | + | "gix-fs", | |
| 880 | + | "gix-hash", | |
| 881 | + | "gix-macros", | |
| 882 | + | "gix-ref", | |
| 883 | + | "gix-shallow", | |
| 884 | + | "gix-transport", | |
| 885 | + | "gix-utils", | |
| 886 | + | "nonempty", | |
| 887 | + | ] | |
| 888 | + | ||
| 889 | + | [[package]] | |
| 890 | + | name = "gix-quote" | |
| 891 | + | version = "0.10.2" | |
| 892 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 893 | + | checksum = "5069a7ec021bb47abe9f12dcc075d292e8cf4a9dff5fffd38595b39c6b419aaa" | |
| 894 | + | dependencies = [ | |
| 895 | + | "bstr", | |
| 896 | + | "gix-error", | |
| 897 | + | "gix-utils", | |
| 898 | + | ] | |
| 899 | + | ||
| 900 | + | [[package]] | |
| 901 | + | name = "gix-ref" | |
| 902 | + | version = "0.70.0" | |
| 903 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 904 | + | checksum = "f83eab15f4e13abd04d85b9e1e90f42d6590bdac03e1c2fa244423549b93bee7" | |
| 905 | + | dependencies = [ | |
| 906 | + | "gix-actor", | |
| 907 | + | "gix-error", | |
| 908 | + | "gix-fs", | |
| 909 | + | "gix-hash", | |
| 910 | + | "gix-lock", | |
| 911 | + | "gix-object", | |
| 912 | + | "gix-parallel", | |
| 913 | + | "gix-path", | |
| 914 | + | "gix-utils", | |
| 915 | + | "gix-validate", | |
| 916 | + | "memmap2", | |
| 917 | + | ] | |
| 918 | + | ||
| 919 | + | [[package]] | |
| 920 | + | name = "gix-refspec" | |
| 921 | + | version = "0.48.0" | |
| 922 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 923 | + | checksum = "08952887f08278177edb42d7a6ee0d8f6dbdcca70bf8a2cf4403d4fdfa3d6a25" | |
| 924 | + | dependencies = [ | |
| 925 | + | "bstr", | |
| 926 | + | "gix-error", | |
| 927 | + | "gix-hash", | |
| 928 | + | "gix-validate", | |
| 929 | + | "smallvec", | |
| 930 | + | ] | |
| 931 | + | ||
| 932 | + | [[package]] | |
| 933 | + | name = "gix-revision" | |
| 934 | + | version = "0.53.0" | |
| 935 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 936 | + | checksum = "95fc3aab116a365eda6ceca976933f6883bed16ea6c578c367b7699dbb8a63b3" | |
| 937 | + | dependencies = [ | |
| 938 | + | "bitflags 2.13.2", | |
| 939 | + | "bstr", | |
| 940 | + | "gix-commitgraph", | |
| 941 | + | "gix-date", | |
| 942 | + | "gix-error", | |
| 943 | + | "gix-hash", | |
| 944 | + | "gix-hashtable", | |
| 945 | + | "gix-object", | |
| 946 | + | "gix-revwalk", | |
| 947 | + | "gix-trace", | |
| 948 | + | "nonempty", | |
| 949 | + | ] | |
| 950 | + | ||
| 951 | + | [[package]] | |
| 952 | + | name = "gix-revwalk" | |
| 953 | + | version = "0.39.0" | |
| 954 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 955 | + | checksum = "a076d96d648ef96da59488ecd73b00c9ced978df4b5d579d3c2876e4a249ee96" | |
| 956 | + | dependencies = [ | |
| 957 | + | "gix-commitgraph", | |
| 958 | + | "gix-date", | |
| 959 | + | "gix-error", | |
| 960 | + | "gix-hash", | |
| 961 | + | "gix-hashtable", | |
| 962 | + | "gix-object", | |
| 963 | + | "smallvec", | |
| 964 | + | ] | |
| 965 | + | ||
| 966 | + | [[package]] | |
| 967 | + | name = "gix-sec" | |
| 968 | + | version = "0.17.0" | |
| 969 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 970 | + | checksum = "7a5b38f169ca1d20c255d7e25d2d043bcf68765f30ba5ff7f6672af98284f528" | |
| 971 | + | dependencies = [ | |
| 972 | + | "bitflags 2.13.2", | |
| 973 | + | "gix-path", | |
| 974 | + | "libc", | |
| 975 | + | "windows-sys 0.61.2", | |
| 976 | + | ] | |
| 977 | + | ||
| 978 | + | [[package]] | |
| 979 | + | name = "gix-shallow" | |
| 980 | + | version = "0.16.0" | |
| 981 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 982 | + | checksum = "cc2e70667c3ef18153751b45636c34f6927358974bf0d6b909789ab53c724e1a" | |
| 983 | + | dependencies = [ | |
| 984 | + | "bstr", | |
| 985 | + | "gix-error", | |
| 986 | + | "gix-hash", | |
| 987 | + | "gix-lock", | |
| 988 | + | "nonempty", | |
| 989 | + | ] | |
| 990 | + | ||
| 991 | + | [[package]] | |
| 992 | + | name = "gix-tempfile" | |
| 993 | + | version = "27.0.0" | |
| 994 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 995 | + | checksum = "2f8d5e0ff49e478166c5dfb46389f30ad143aea8735da32e554079e03b4de142" | |
| 996 | + | dependencies = [ | |
| 997 | + | "gix-fs", | |
| 998 | + | "libc", | |
| 999 | + | "parking_lot 0.13.0", | |
| 1000 | + | "tempfile", | |
| 1001 | + | "windows-sys 0.61.2", | |
| 1002 | + | ] | |
| 1003 | + | ||
| 1004 | + | [[package]] | |
| 1005 | + | name = "gix-trace" | |
| 1006 | + | version = "0.3.2" | |
| 1007 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1008 | + | checksum = "1c96f84d731a96780e6a7ad5ee70b4ecc398499946b62617945fbaeb6ab878f8" | |
| 1009 | + | ||
| 1010 | + | [[package]] | |
| 1011 | + | name = "gix-transport" | |
| 1012 | + | version = "0.63.0" | |
| 1013 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1014 | + | checksum = "ca5b6ec3375166c8693d0768198106cfc241e67433b06de8736b025c5997241c" | |
| 1015 | + | dependencies = [ | |
| 1016 | + | "bstr", | |
| 1017 | + | "gix-command", | |
| 1018 | + | "gix-error", | |
| 1019 | + | "gix-packetline", | |
| 1020 | + | "gix-path", | |
| 1021 | + | "gix-quote", | |
| 1022 | + | "gix-sec", | |
| 1023 | + | "gix-trace", | |
| 1024 | + | "gix-url", | |
| 1025 | + | "gix-utils", | |
| 1026 | + | ] | |
| 1027 | + | ||
| 1028 | + | [[package]] | |
| 1029 | + | name = "gix-traverse" | |
| 1030 | + | version = "0.65.0" | |
| 1031 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1032 | + | checksum = "6add38e8233db45018e85ee540775fe6c26bbae16ca850aa96799364575826e9" | |
| 1033 | + | dependencies = [ | |
| 1034 | + | "bitflags 2.13.2", | |
| 1035 | + | "gix-commitgraph", | |
| 1036 | + | "gix-date", | |
| 1037 | + | "gix-error", | |
| 1038 | + | "gix-hash", | |
| 1039 | + | "gix-hashtable", | |
| 1040 | + | "gix-object", | |
| 1041 | + | "gix-revwalk", | |
| 1042 | + | "smallvec", | |
| 1043 | + | ] | |
| 1044 | + | ||
| 1045 | + | [[package]] | |
| 1046 | + | name = "gix-url" | |
| 1047 | + | version = "0.41.0" | |
| 1048 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1049 | + | checksum = "6c70991bc97388e98cba88fe98adb270fbd9bd1724c68836e58556d593829197" | |
| 1050 | + | dependencies = [ | |
| 1051 | + | "bstr", | |
| 1052 | + | "gix-error", | |
| 1053 | + | "gix-path", | |
| 1054 | + | "gix-utils", | |
| 1055 | + | "percent-encoding", | |
| 1056 | + | ] | |
| 1057 | + | ||
| 1058 | + | [[package]] | |
| 1059 | + | name = "gix-utils" | |
| 1060 | + | version = "0.5.3" | |
| 1061 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1062 | + | checksum = "b5e6d46894c7a4fd9c5e26d233a0fa836002ba0af9a11aef58923d317c486e10" | |
| 1063 | + | dependencies = [ | |
| 1064 | + | "bstr", | |
| 1065 | + | "bytes", | |
| 1066 | + | "fastrand", | |
| 1067 | + | "getrandom", | |
| 1068 | + | "gix-error", | |
| 1069 | + | "prodash", | |
| 1070 | + | "unicode-normalization", | |
| 1071 | + | ] | |
| 1072 | + | ||
| 1073 | + | [[package]] | |
| 1074 | + | name = "gix-validate" | |
| 1075 | + | version = "0.13.2" | |
| 1076 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1077 | + | checksum = "5d6f293fd8abd9bd9bc1e0a23541f73607e932b5a2bde2246320da38edde5726" | |
| 1078 | + | dependencies = [ | |
| 1079 | + | "bstr", | |
| 1080 | + | "gix-error", | |
| 1081 | + | ] | |
| 1082 | + | ||
| 1083 | + | [[package]] | |
| 1084 | + | name = "gix-worktree-stream" | |
| 1085 | + | version = "0.40.0" | |
| 1086 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1087 | + | checksum = "e5a4062dc780f7fad657ecf30c0fd5c4b7e555929b967345a8ba0f4a81e29ec0" | |
| 1088 | + | dependencies = [ | |
| 1089 | + | "gix-attributes", | |
| 1090 | + | "gix-error", | |
| 1091 | + | "gix-filter", | |
| 1092 | + | "gix-fs", | |
| 1093 | + | "gix-hash", | |
| 1094 | + | "gix-object", | |
| 1095 | + | "gix-parallel", | |
| 1096 | + | "gix-path", | |
| 1097 | + | "gix-trace", | |
| 1098 | + | "gix-traverse", | |
| 1099 | + | "gix-utils", | |
| 1100 | + | "parking_lot 0.13.0", | |
| 1101 | + | ] | |
| 1102 | + | ||
| 1103 | + | [[package]] | |
| 1104 | + | name = "gix-zlib" | |
| 1105 | + | version = "0.4.1" | |
| 1106 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1107 | + | checksum = "81a49a8b263d2a140f1c178ff93375b8d4cc7b1d3252cd87ce1ca88bce62b9b9" | |
| 1108 | + | dependencies = [ | |
| 1109 | + | "gix-error", | |
| 1110 | + | "zlib-rs", | |
| 1111 | + | ] | |
| 1112 | + | ||
| 1113 | + | [[package]] | |
| 1114 | + | name = "hashbrown" | |
| 1115 | + | version = "0.15.5" | |
| 1116 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1117 | + | checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" | |
| 1118 | + | dependencies = [ | |
| 1119 | + | "foldhash 0.1.5", | |
| 1120 | + | ] | |
| 1121 | + | ||
| 1122 | + | [[package]] | |
| 1123 | + | name = "hashbrown" | |
| 1124 | + | version = "0.16.1" | |
| 1125 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1126 | + | checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" | |
| 1127 | + | dependencies = [ | |
| 1128 | + | "allocator-api2", | |
| 1129 | + | "equivalent", | |
| 1130 | + | "foldhash 0.2.0", | |
| 1131 | + | ] | |
| 1132 | + | ||
| 1133 | + | [[package]] | |
| 1134 | + | name = "hashbrown" | |
| 1135 | + | version = "0.17.2" | |
| 1136 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1137 | + | checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" | |
| 1138 | + | dependencies = [ | |
| 1139 | + | "allocator-api2", | |
| 1140 | + | "equivalent", | |
| 1141 | + | "foldhash 0.2.0", | |
| 1142 | + | ] | |
| 1143 | + | ||
| 1144 | + | [[package]] | |
| 1145 | + | name = "heck" | |
| 1146 | + | version = "0.5.0" | |
| 1147 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1148 | + | checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" | |
| 1149 | + | ||
| 1150 | + | [[package]] | |
| 1151 | + | name = "indexmap" | |
| 1152 | + | version = "2.14.2" | |
| 1153 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1154 | + | checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" | |
| 1155 | + | dependencies = [ | |
| 1156 | + | "equivalent", | |
| 1157 | + | "hashbrown 0.17.2", | |
| 1158 | + | "serde", | |
| 1159 | + | "serde_core", | |
| 1160 | + | ] | |
| 1161 | + | ||
| 1162 | + | [[package]] | |
| 1163 | + | name = "inquire" | |
| 1164 | + | version = "0.9.5" | |
| 1165 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1166 | + | checksum = "e8740906750ed5eebb24721bc5261928ed39ac9fb3b7ac78d2d2486f8037c8ab" | |
| 1167 | + | dependencies = [ | |
| 1168 | + | "bitflags 2.13.2", | |
| 1169 | + | "crossterm", | |
| 1170 | + | "dyn-clone", | |
| 1171 | + | "fuzzy-matcher", | |
| 1172 | + | "tempfile", | |
| 1173 | + | "unicode-segmentation", | |
| 1174 | + | "unicode-width", | |
| 1175 | + | ] | |
| 1176 | + | ||
| 1177 | + | [[package]] | |
| 1178 | + | name = "is_terminal_polyfill" | |
| 1179 | + | version = "1.70.2" | |
| 1180 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1181 | + | checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" | |
| 1182 | + | ||
| 1183 | + | [[package]] | |
| 1184 | + | name = "itoa" | |
| 1185 | + | version = "1.0.19" | |
| 1186 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1187 | + | checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" | |
| 1188 | + | ||
| 1189 | + | [[package]] | |
| 1190 | + | name = "jiff" | |
| 1191 | + | version = "1.1.0" | |
| 1192 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1193 | + | checksum = "379ed44bd4e16d3926160e2b3a78b79ca0952ef5c037f124f554842ba272ef92" | |
| 1194 | + | dependencies = [ | |
| 1195 | + | "jiff-core", | |
| 1196 | + | "jiff-static", | |
| 1197 | + | "jiff-tzdb-platform", | |
| 1198 | + | "log", | |
| 1199 | + | "portable-atomic", | |
| 1200 | + | "portable-atomic-util", | |
| 1201 | + | "serde_core", | |
| 1202 | + | "windows-link 0.2.1", | |
| 1203 | + | ] | |
| 1204 | + | ||
| 1205 | + | [[package]] | |
| 1206 | + | name = "jiff-core" | |
| 1207 | + | version = "1.1.0" | |
| 1208 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1209 | + | checksum = "0df46fc314b4f458aee614afcd8676ed6cb3637413aa359d47d2646cbc038b79" | |
| 1210 | + | dependencies = [ | |
| 1211 | + | "log", | |
| 1212 | + | ] | |
| 1213 | + | ||
| 1214 | + | [[package]] | |
| 1215 | + | name = "jiff-static" | |
| 1216 | + | version = "1.1.0" | |
| 1217 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1218 | + | checksum = "27b729c549d3efb5855b3c80b0ee8ee1850d56330a127382fe2760965741c1f3" | |
| 1219 | + | dependencies = [ | |
| 1220 | + | "jiff-core", | |
| 1221 | + | "proc-macro2", | |
| 1222 | + | "quote", | |
| 1223 | + | "syn 3.0.10", | |
| 1224 | + | ] | |
| 1225 | + | ||
| 1226 | + | [[package]] | |
| 1227 | + | name = "jiff-tzdb" | |
| 1228 | + | version = "1.0.0" | |
| 1229 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1230 | + | checksum = "12e71a1b68a875a44a33bb7a1dd84392cb77145a3367a552a3cfe6a4f5cf3afc" | |
| 1231 | + | ||
| 1232 | + | [[package]] | |
| 1233 | + | name = "jiff-tzdb-platform" | |
| 1234 | + | version = "1.0.0" | |
| 1235 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1236 | + | checksum = "dc65b284afcfa8f6cf189c7274c805505314a7ab975c60e1f548bff56525420e" | |
| 1237 | + | dependencies = [ | |
| 1238 | + | "jiff-tzdb", | |
| 1239 | + | ] | |
| 1240 | + | ||
| 1241 | + | [[package]] | |
| 1242 | + | name = "libc" | |
| 1243 | + | version = "0.2.191" | |
| 1244 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1245 | + | checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" | |
| 1246 | + | ||
| 1247 | + | [[package]] | |
| 1248 | + | name = "libm" | |
| 1249 | + | version = "0.2.16" | |
| 1250 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1251 | + | checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" | |
| 1252 | + | ||
| 1253 | + | [[package]] | |
| 1254 | + | name = "linux-raw-sys" | |
| 1255 | + | version = "0.12.1" | |
| 1256 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1257 | + | checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" | |
| 1258 | + | ||
| 1259 | + | [[package]] | |
| 1260 | + | name = "litrs" | |
| 1261 | + | version = "1.1.0" | |
| 1262 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1263 | + | checksum = "02b614978e47ce529faee66579f2b2fe19c94aa96d910a6a9a8043b2b02d8175" | |
| 1264 | + | ||
| 1265 | + | [[package]] | |
| 1266 | + | name = "lock_api" | |
| 1267 | + | version = "0.4.14" | |
| 1268 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1269 | + | checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" | |
| 1270 | + | dependencies = [ | |
| 1271 | + | "scopeguard", | |
| 1272 | + | ] | |
| 1273 | + | ||
| 1274 | + | [[package]] | |
| 1275 | + | name = "lock_api" | |
| 1276 | + | version = "0.5.0" | |
| 1277 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1278 | + | checksum = "65d91b22da179613dcf4d6ec8349563f52a363f6849e03b00dd0a185ec4a59af" | |
| 1279 | + | dependencies = [ | |
| 1280 | + | "scopeguard", | |
| 1281 | + | ] | |
| 1282 | + | ||
| 1283 | + | [[package]] | |
| 1284 | + | name = "log" | |
| 1285 | + | version = "0.4.35" | |
| 1286 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1287 | + | checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" | |
| 1288 | + | ||
| 1289 | + | [[package]] | |
| 1290 | + | name = "memchr" | |
| 1291 | + | version = "2.8.3" | |
| 1292 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1293 | + | checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" | |
| 1294 | + | ||
| 1295 | + | [[package]] | |
| 1296 | + | name = "memmap2" | |
| 1297 | + | version = "0.9.12" | |
| 1298 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1299 | + | checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" | |
| 1300 | + | dependencies = [ | |
| 1301 | + | "libc", | |
| 1302 | + | ] | |
| 1303 | + | ||
| 1304 | + | [[package]] | |
| 1305 | + | name = "minijinja" | |
| 1306 | + | version = "3.1.0" | |
| 1307 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1308 | + | checksum = "509eeb2603a84eccabb4d75f6ec8ba23b46bbf441aaeb863d6b83a5887fd51e4" | |
| 1309 | + | dependencies = [ | |
| 1310 | + | "indexmap", | |
| 1311 | + | "percent-encoding", | |
| 1312 | + | "serde", | |
| 1313 | + | "unicase", | |
| 1314 | + | "unicode-ident", | |
| 1315 | + | ] | |
| 1316 | + | ||
| 1317 | + | [[package]] | |
| 1318 | + | name = "minijinja-contrib" | |
| 1319 | + | version = "3.1.0" | |
| 1320 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1321 | + | checksum = "64b62a39daf92d02b89f7888ab57f08d15d22dab862e5c95353253f91e9344f0" | |
| 1322 | + | dependencies = [ | |
| 1323 | + | "minijinja", | |
| 1324 | + | ] | |
| 1325 | + | ||
| 1326 | + | [[package]] | |
| 1327 | + | name = "mio" | |
| 1328 | + | version = "1.2.5" | |
| 1329 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1330 | + | checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" | |
| 1331 | + | dependencies = [ | |
| 1332 | + | "libc", | |
| 1333 | + | "log", | |
| 1334 | + | "wasi", | |
| 1335 | + | "windows-sys 0.61.2", | |
| 1336 | + | ] | |
| 1337 | + | ||
| 1338 | + | [[package]] | |
| 1339 | + | name = "nonempty" | |
| 1340 | + | version = "0.12.0" | |
| 1341 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1342 | + | checksum = "9737e026353e5cd0736f98eddae28665118eb6f6600902a7f50db585621fecb6" | |
| 1343 | + | ||
| 1344 | + | [[package]] | |
| 1345 | + | name = "once_cell" | |
| 1346 | + | version = "1.21.4" | |
| 1347 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1348 | + | checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" | |
| 1349 | + | ||
| 1350 | + | [[package]] | |
| 1351 | + | name = "once_cell_polyfill" | |
| 1352 | + | version = "1.70.2" | |
| 1353 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1354 | + | checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" | |
| 1355 | + | ||
| 1356 | + | [[package]] | |
| 1357 | + | name = "parking_lot" | |
| 1358 | + | version = "0.12.5" | |
| 1359 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1360 | + | checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" | |
| 1361 | + | dependencies = [ | |
| 1362 | + | "lock_api 0.4.14", | |
| 1363 | + | "parking_lot_core 0.9.12", | |
| 1364 | + | ] | |
| 1365 | + | ||
| 1366 | + | [[package]] | |
| 1367 | + | name = "parking_lot" | |
| 1368 | + | version = "0.13.0" | |
| 1369 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1370 | + | checksum = "a9cf937ca4e1d0b7578784559063422fc39ae7c5a00f02471f2614d5486fd226" | |
| 1371 | + | dependencies = [ | |
| 1372 | + | "lock_api 0.5.0", | |
| 1373 | + | "parking_lot_core 0.10.0", | |
| 1374 | + | ] | |
| 1375 | + | ||
| 1376 | + | [[package]] | |
| 1377 | + | name = "parking_lot_core" | |
| 1378 | + | version = "0.9.12" | |
| 1379 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1380 | + | checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" | |
| 1381 | + | dependencies = [ | |
| 1382 | + | "cfg-if", | |
| 1383 | + | "libc", | |
| 1384 | + | "redox_syscall 0.5.18", | |
| 1385 | + | "smallvec", | |
| 1386 | + | "windows-link 0.2.1", | |
| 1387 | + | ] | |
| 1388 | + | ||
| 1389 | + | [[package]] | |
| 1390 | + | name = "parking_lot_core" | |
| 1391 | + | version = "0.10.0" | |
| 1392 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1393 | + | checksum = "9cfff060068cc18aa7815010fcaf80c68c7fb9e85fc7f5c0f9bf142c21d19826" | |
| 1394 | + | dependencies = [ | |
| 1395 | + | "libc", | |
| 1396 | + | "redox_syscall 0.9.5", | |
| 1397 | + | "smallvec", | |
| 1398 | + | "windows-link 0.2.1", | |
| 1399 | + | ] | |
| 1400 | + | ||
| 1401 | + | [[package]] | |
| 1402 | + | name = "percent-encoding" | |
| 1403 | + | version = "2.3.2" | |
| 1404 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1405 | + | checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" | |
| 1406 | + | ||
| 1407 | + | [[package]] | |
| 1408 | + | name = "portable-atomic" | |
| 1409 | + | version = "1.15.0" | |
| 1410 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1411 | + | checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" | |
| 1412 | + | ||
| 1413 | + | [[package]] | |
| 1414 | + | name = "portable-atomic-util" | |
| 1415 | + | version = "0.2.8" | |
| 1416 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1417 | + | checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" | |
| 1418 | + | dependencies = [ | |
| 1419 | + | "portable-atomic", | |
| 1420 | + | ] | |
| 1421 | + | ||
| 1422 | + | [[package]] | |
| 1423 | + | name = "proc-macro2" | |
| 1424 | + | version = "1.0.107" | |
| 1425 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1426 | + | checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" | |
| 1427 | + | dependencies = [ | |
| 1428 | + | "unicode-ident", | |
| 1429 | + | ] | |
| 1430 | + | ||
| 1431 | + | [[package]] | |
| 1432 | + | name = "prodash" | |
| 1433 | + | version = "31.0.1" | |
| 1434 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1435 | + | checksum = "cf52d87428247c5aa3760ac8e7d8b13ec7b3579b955a8c3f311668b6860acba5" | |
| 1436 | + | dependencies = [ | |
| 1437 | + | "parking_lot 0.12.5", | |
| 1438 | + | ] | |
| 1439 | + | ||
| 1440 | + | [[package]] | |
| 1441 | + | name = "quote" | |
| 1442 | + | version = "1.0.47" | |
| 1443 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1444 | + | checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" | |
| 1445 | + | dependencies = [ | |
| 1446 | + | "proc-macro2", | |
| 1447 | + | ] | |
| 1448 | + | ||
| 1449 | + | [[package]] | |
| 1450 | + | name = "r-efi" | |
| 1451 | + | version = "6.0.0" | |
| 1452 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1453 | + | checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" | |
| 1454 | + | ||
| 1455 | + | [[package]] | |
| 1456 | + | name = "rayon" | |
| 1457 | + | version = "1.12.0" | |
| 1458 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1459 | + | checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" | |
| 1460 | + | dependencies = [ | |
| 1461 | + | "either", | |
| 1462 | + | "rayon-core", | |
| 1463 | + | ] | |
| 1464 | + | ||
| 1465 | + | [[package]] | |
| 1466 | + | name = "rayon-core" | |
| 1467 | + | version = "1.13.0" | |
| 1468 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1469 | + | checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" | |
| 1470 | + | dependencies = [ | |
| 1471 | + | "crossbeam-deque", | |
| 1472 | + | "crossbeam-utils", | |
| 1473 | + | ] | |
| 1474 | + | ||
| 1475 | + | [[package]] | |
| 1476 | + | name = "redox_syscall" | |
| 1477 | + | version = "0.5.18" | |
| 1478 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1479 | + | checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" | |
| 1480 | + | dependencies = [ | |
| 1481 | + | "bitflags 2.13.2", | |
| 1482 | + | ] | |
| 1483 | + | ||
| 1484 | + | [[package]] | |
| 1485 | + | name = "redox_syscall" | |
| 1486 | + | version = "0.9.5" | |
| 1487 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1488 | + | checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" | |
| 1489 | + | dependencies = [ | |
| 1490 | + | "bitflags 2.13.2", | |
| 1491 | + | ] | |
| 1492 | + | ||
| 1493 | + | [[package]] | |
| 1494 | + | name = "regex-automata" | |
| 1495 | + | version = "0.4.19" | |
| 1496 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1497 | + | checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" | |
| 1498 | + | ||
| 1499 | + | [[package]] | |
| 1500 | + | name = "roneo-cli" | |
| 1501 | + | version = "0.1.0" | |
| 1502 | + | dependencies = [ | |
| 1503 | + | "clap", | |
| 1504 | + | "indexmap", | |
| 1505 | + | "inquire", | |
| 1506 | + | "roneo-core", | |
| 1507 | + | "serde_json", | |
| 1508 | + | ] | |
| 1509 | + | ||
| 1510 | + | [[package]] | |
| 1511 | + | name = "roneo-core" | |
| 1512 | + | version = "0.1.0" | |
| 1513 | + | dependencies = [ | |
| 1514 | + | "gix", | |
| 1515 | + | "indexmap", | |
| 1516 | + | "minijinja", | |
| 1517 | + | "minijinja-contrib", | |
| 1518 | + | "rayon", | |
| 1519 | + | "serde", | |
| 1520 | + | "serde_json", | |
| 1521 | + | "serde_yaml_ng", | |
| 1522 | + | "wasmi", | |
| 1523 | + | ] | |
| 1524 | + | ||
| 1525 | + | [[package]] | |
| 1526 | + | name = "roneo-plugin-sdk" | |
| 1527 | + | version = "0.1.0" | |
| 1528 | + | dependencies = [ | |
| 1529 | + | "indexmap", | |
| 1530 | + | "serde", | |
| 1531 | + | "serde_json", | |
| 1532 | + | ] | |
| 1533 | + | ||
| 1534 | + | [[package]] | |
| 1535 | + | name = "rustc_version" | |
| 1536 | + | version = "0.4.1" | |
| 1537 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1538 | + | checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" | |
| 1539 | + | dependencies = [ | |
| 1540 | + | "semver", | |
| 1541 | + | ] | |
| 1542 | + | ||
| 1543 | + | [[package]] | |
| 1544 | + | name = "rustix" | |
| 1545 | + | version = "1.1.6" | |
| 1546 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1547 | + | checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" | |
| 1548 | + | dependencies = [ | |
| 1549 | + | "bitflags 2.13.2", | |
| 1550 | + | "errno", | |
| 1551 | + | "libc", | |
| 1552 | + | "linux-raw-sys", | |
| 1553 | + | "windows-sys 0.61.2", | |
| 1554 | + | ] | |
| 1555 | + | ||
| 1556 | + | [[package]] | |
| 1557 | + | name = "rustversion" | |
| 1558 | + | version = "1.0.23" | |
| 1559 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1560 | + | checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" | |
| 1561 | + | ||
| 1562 | + | [[package]] | |
| 1563 | + | name = "ryu" | |
| 1564 | + | version = "1.0.23" | |
| 1565 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1566 | + | checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" | |
| 1567 | + | ||
| 1568 | + | [[package]] | |
| 1569 | + | name = "same-file" | |
| 1570 | + | version = "1.0.6" | |
| 1571 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1572 | + | checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" | |
| 1573 | + | dependencies = [ | |
| 1574 | + | "winapi-util", | |
| 1575 | + | ] | |
| 1576 | + | ||
| 1577 | + | [[package]] | |
| 1578 | + | name = "scopeguard" | |
| 1579 | + | version = "1.2.0" | |
| 1580 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1581 | + | checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" | |
| 1582 | + | ||
| 1583 | + | [[package]] | |
| 1584 | + | name = "semver" | |
| 1585 | + | version = "1.0.28" | |
| 1586 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1587 | + | checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" | |
| 1588 | + | ||
| 1589 | + | [[package]] | |
| 1590 | + | name = "serde" | |
| 1591 | + | version = "1.0.229" | |
| 1592 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1593 | + | checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" | |
| 1594 | + | dependencies = [ | |
| 1595 | + | "serde_core", | |
| 1596 | + | "serde_derive", | |
| 1597 | + | ] | |
| 1598 | + | ||
| 1599 | + | [[package]] | |
| 1600 | + | name = "serde_core" | |
| 1601 | + | version = "1.0.229" | |
| 1602 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1603 | + | checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" | |
| 1604 | + | dependencies = [ | |
| 1605 | + | "serde_derive", | |
| 1606 | + | ] | |
| 1607 | + | ||
| 1608 | + | [[package]] | |
| 1609 | + | name = "serde_derive" | |
| 1610 | + | version = "1.0.229" | |
| 1611 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1612 | + | checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" | |
| 1613 | + | dependencies = [ | |
| 1614 | + | "proc-macro2", | |
| 1615 | + | "quote", | |
| 1616 | + | "syn 3.0.10", | |
| 1617 | + | ] | |
| 1618 | + | ||
| 1619 | + | [[package]] | |
| 1620 | + | name = "serde_json" | |
| 1621 | + | version = "1.0.154" | |
| 1622 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1623 | + | checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" | |
| 1624 | + | dependencies = [ | |
| 1625 | + | "itoa", | |
| 1626 | + | "memchr", | |
| 1627 | + | "serde", | |
| 1628 | + | "serde_core", | |
| 1629 | + | "zmij", | |
| 1630 | + | ] | |
| 1631 | + | ||
| 1632 | + | [[package]] | |
| 1633 | + | name = "serde_yaml_ng" | |
| 1634 | + | version = "0.10.0" | |
| 1635 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1636 | + | checksum = "7b4db627b98b36d4203a7b458cf3573730f2bb591b28871d916dfa9efabfd41f" | |
| 1637 | + | dependencies = [ | |
| 1638 | + | "indexmap", | |
| 1639 | + | "itoa", | |
| 1640 | + | "ryu", | |
| 1641 | + | "serde", | |
| 1642 | + | "unsafe-libyaml", | |
| 1643 | + | ] | |
| 1644 | + | ||
| 1645 | + | [[package]] | |
| 1646 | + | name = "sha1dc" | |
| 1647 | + | version = "0.1.5" | |
| 1648 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1649 | + | checksum = "c5b0ebf6537e3e8db8bb7d21ecb6d7399738c953c757945c6b95e46c4e95df7b" | |
| 1650 | + | ||
| 1651 | + | [[package]] | |
| 1652 | + | name = "signal-hook" | |
| 1653 | + | version = "0.3.18" | |
| 1654 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1655 | + | checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" | |
| 1656 | + | dependencies = [ | |
| 1657 | + | "libc", | |
| 1658 | + | "signal-hook-registry", | |
| 1659 | + | ] | |
| 1660 | + | ||
| 1661 | + | [[package]] | |
| 1662 | + | name = "signal-hook-mio" | |
| 1663 | + | version = "0.2.5" | |
| 1664 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1665 | + | checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" | |
| 1666 | + | dependencies = [ | |
| 1667 | + | "libc", | |
| 1668 | + | "mio", | |
| 1669 | + | "signal-hook", | |
| 1670 | + | ] | |
| 1671 | + | ||
| 1672 | + | [[package]] | |
| 1673 | + | name = "signal-hook-registry" | |
| 1674 | + | version = "1.4.8" | |
| 1675 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1676 | + | checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" | |
| 1677 | + | dependencies = [ | |
| 1678 | + | "errno", | |
| 1679 | + | "libc", | |
| 1680 | + | ] | |
| 1681 | + | ||
| 1682 | + | [[package]] | |
| 1683 | + | name = "smallvec" | |
| 1684 | + | version = "1.16.6" | |
| 1685 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1686 | + | checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" | |
| 1687 | + | ||
| 1688 | + | [[package]] | |
| 1689 | + | name = "spin" | |
| 1690 | + | version = "0.9.9" | |
| 1691 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1692 | + | checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" | |
| 1693 | + | ||
| 1694 | + | [[package]] | |
| 1695 | + | name = "string-interner" | |
| 1696 | + | version = "0.19.0" | |
| 1697 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1698 | + | checksum = "23de088478b31c349c9ba67816fa55d9355232d63c3afea8bf513e31f0f1d2c0" | |
| 1699 | + | dependencies = [ | |
| 1700 | + | "hashbrown 0.15.5", | |
| 1701 | + | "serde", | |
| 1702 | + | ] | |
| 1703 | + | ||
| 1704 | + | [[package]] | |
| 1705 | + | name = "strsim" | |
| 1706 | + | version = "0.11.1" | |
| 1707 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1708 | + | checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" | |
| 1709 | + | ||
| 1710 | + | [[package]] | |
| 1711 | + | name = "syn" | |
| 1712 | + | version = "2.0.119" | |
| 1713 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1714 | + | checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" | |
| 1715 | + | dependencies = [ | |
| 1716 | + | "proc-macro2", | |
| 1717 | + | "quote", | |
| 1718 | + | "unicode-ident", | |
| 1719 | + | ] | |
| 1720 | + | ||
| 1721 | + | [[package]] | |
| 1722 | + | name = "syn" | |
| 1723 | + | version = "3.0.10" | |
| 1724 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1725 | + | checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" | |
| 1726 | + | dependencies = [ | |
| 1727 | + | "proc-macro2", | |
| 1728 | + | "quote", | |
| 1729 | + | "unicode-ident", | |
| 1730 | + | ] | |
| 1731 | + | ||
| 1732 | + | [[package]] | |
| 1733 | + | name = "tempfile" | |
| 1734 | + | version = "3.27.0" | |
| 1735 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1736 | + | checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" | |
| 1737 | + | dependencies = [ | |
| 1738 | + | "fastrand", | |
| 1739 | + | "getrandom", | |
| 1740 | + | "once_cell", | |
| 1741 | + | "rustix", | |
| 1742 | + | "windows-sys 0.61.2", | |
| 1743 | + | ] | |
| 1744 | + | ||
| 1745 | + | [[package]] | |
| 1746 | + | name = "thiserror" | |
| 1747 | + | version = "2.0.21" | |
| 1748 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1749 | + | checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" | |
| 1750 | + | dependencies = [ | |
| 1751 | + | "thiserror-impl", | |
| 1752 | + | ] | |
| 1753 | + | ||
| 1754 | + | [[package]] | |
| 1755 | + | name = "thiserror-impl" | |
| 1756 | + | version = "2.0.21" | |
| 1757 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1758 | + | checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" | |
| 1759 | + | dependencies = [ | |
| 1760 | + | "proc-macro2", | |
| 1761 | + | "quote", | |
| 1762 | + | "syn 3.0.10", | |
| 1763 | + | ] | |
| 1764 | + | ||
| 1765 | + | [[package]] | |
| 1766 | + | name = "thread_local" | |
| 1767 | + | version = "1.1.10" | |
| 1768 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1769 | + | checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" | |
| 1770 | + | dependencies = [ | |
| 1771 | + | "cfg-if", | |
| 1772 | + | ] | |
| 1773 | + | ||
| 1774 | + | [[package]] | |
| 1775 | + | name = "tinyvec" | |
| 1776 | + | version = "1.13.3" | |
| 1777 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1778 | + | checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" | |
| 1779 | + | ||
| 1780 | + | [[package]] | |
| 1781 | + | name = "uluru" | |
| 1782 | + | version = "3.1.0" | |
| 1783 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1784 | + | checksum = "7c8a2469e56e6e5095c82ccd3afb98dad95f7af7929aab6d8ba8d6e0f73657da" | |
| 1785 | + | dependencies = [ | |
| 1786 | + | "arrayvec", | |
| 1787 | + | ] | |
| 1788 | + | ||
| 1789 | + | [[package]] | |
| 1790 | + | name = "unicase" | |
| 1791 | + | version = "2.10.0" | |
| 1792 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1793 | + | checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" | |
| 1794 | + | ||
| 1795 | + | [[package]] | |
| 1796 | + | name = "unicode-bom" | |
| 1797 | + | version = "2.0.3" | |
| 1798 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1799 | + | checksum = "7eec5d1121208364f6793f7d2e222bf75a915c19557537745b195b253dd64217" | |
| 1800 | + | ||
| 1801 | + | [[package]] | |
| 1802 | + | name = "unicode-ident" | |
| 1803 | + | version = "1.0.27" | |
| 1804 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1805 | + | checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" | |
| 1806 | + | ||
| 1807 | + | [[package]] | |
| 1808 | + | name = "unicode-normalization" | |
| 1809 | + | version = "0.1.26" | |
| 1810 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1811 | + | checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" | |
| 1812 | + | dependencies = [ | |
| 1813 | + | "tinyvec", | |
| 1814 | + | ] | |
| 1815 | + | ||
| 1816 | + | [[package]] | |
| 1817 | + | name = "unicode-segmentation" | |
| 1818 | + | version = "1.13.3" | |
| 1819 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1820 | + | checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" | |
| 1821 | + | ||
| 1822 | + | [[package]] | |
| 1823 | + | name = "unicode-width" | |
| 1824 | + | version = "0.2.3" | |
| 1825 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1826 | + | checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" | |
| 1827 | + | ||
| 1828 | + | [[package]] | |
| 1829 | + | name = "unsafe-libyaml" | |
| 1830 | + | version = "0.2.11" | |
| 1831 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1832 | + | checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" | |
| 1833 | + | ||
| 1834 | + | [[package]] | |
| 1835 | + | name = "utf8parse" | |
| 1836 | + | version = "0.2.2" | |
| 1837 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1838 | + | checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" | |
| 1839 | + | ||
| 1840 | + | [[package]] | |
| 1841 | + | name = "walkdir" | |
| 1842 | + | version = "2.5.1" | |
| 1843 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1844 | + | checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" | |
| 1845 | + | dependencies = [ | |
| 1846 | + | "same-file", | |
| 1847 | + | "winapi-util", | |
| 1848 | + | ] | |
| 1849 | + | ||
| 1850 | + | [[package]] | |
| 1851 | + | name = "wasi" | |
| 1852 | + | version = "0.11.1+wasi-snapshot-preview1" | |
| 1853 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1854 | + | checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" | |
| 1855 | + | ||
| 1856 | + | [[package]] | |
| 1857 | + | name = "wasmi" | |
| 1858 | + | version = "2.0.5" | |
| 1859 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1860 | + | checksum = "406e07c65b4c51dfeea29dda06f71ea75e1ae25b94bace2796c49ccfac6e09fe" | |
| 1861 | + | dependencies = [ | |
| 1862 | + | "spin", | |
| 1863 | + | "wasmi_collections", | |
| 1864 | + | "wasmi_core", | |
| 1865 | + | "wasmi_ir", | |
| 1866 | + | "wasmparser", | |
| 1867 | + | ] | |
| 1868 | + | ||
| 1869 | + | [[package]] | |
| 1870 | + | name = "wasmi_collections" | |
| 1871 | + | version = "2.0.5" | |
| 1872 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1873 | + | checksum = "11dbb1e7017984d2592ffd5f9b2f9bf8ed7b7b23ec156d3642600d69bd5e92c2" | |
| 1874 | + | dependencies = [ | |
| 1875 | + | "string-interner", | |
| 1876 | + | ] | |
| 1877 | + | ||
| 1878 | + | [[package]] | |
| 1879 | + | name = "wasmi_core" | |
| 1880 | + | version = "2.0.5" | |
| 1881 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1882 | + | checksum = "dff91fd40890cd8320b85e33c8fcb0568da7c50faef718d193aa4415c68e4e91" | |
| 1883 | + | dependencies = [ | |
| 1884 | + | "libm", | |
| 1885 | + | ] | |
| 1886 | + | ||
| 1887 | + | [[package]] | |
| 1888 | + | name = "wasmi_ir" | |
| 1889 | + | version = "2.0.5" | |
| 1890 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1891 | + | checksum = "98aba37942d3cdf12c2abfa986dd4f7f7c47bec56c6d2e550cff86b5c27e0d5a" | |
| 1892 | + | dependencies = [ | |
| 1893 | + | "wasmi_core", | |
| 1894 | + | ] | |
| 1895 | + | ||
| 1896 | + | [[package]] | |
| 1897 | + | name = "wasmparser" | |
| 1898 | + | version = "0.228.0" | |
| 1899 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1900 | + | checksum = "4abf1132c1fdf747d56bbc1bb52152400c70f336870f968b85e89ea422198ae3" | |
| 1901 | + | dependencies = [ | |
| 1902 | + | "bitflags 2.13.2", | |
| 1903 | + | "indexmap", | |
| 1904 | + | ] | |
| 1905 | + | ||
| 1906 | + | [[package]] | |
| 1907 | + | name = "winapi" | |
| 1908 | + | version = "0.3.9" | |
| 1909 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1910 | + | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" | |
| 1911 | + | dependencies = [ | |
| 1912 | + | "winapi-i686-pc-windows-gnu", | |
| 1913 | + | "winapi-x86_64-pc-windows-gnu", | |
| 1914 | + | ] | |
| 1915 | + | ||
| 1916 | + | [[package]] | |
| 1917 | + | name = "winapi-i686-pc-windows-gnu" | |
| 1918 | + | version = "0.4.0" | |
| 1919 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1920 | + | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" | |
| 1921 | + | ||
| 1922 | + | [[package]] | |
| 1923 | + | name = "winapi-util" | |
| 1924 | + | version = "0.1.11" | |
| 1925 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1926 | + | checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" | |
| 1927 | + | dependencies = [ | |
| 1928 | + | "windows-sys 0.61.2", | |
| 1929 | + | ] | |
| 1930 | + | ||
| 1931 | + | [[package]] | |
| 1932 | + | name = "winapi-x86_64-pc-windows-gnu" | |
| 1933 | + | version = "0.4.0" | |
| 1934 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1935 | + | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" | |
| 1936 | + | ||
| 1937 | + | [[package]] | |
| 1938 | + | name = "windows-link" | |
| 1939 | + | version = "0.2.1" | |
| 1940 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1941 | + | checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" | |
| 1942 | + | ||
| 1943 | + | [[package]] | |
| 1944 | + | name = "windows-link" | |
| 1945 | + | version = "0.101.0" | |
| 1946 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1947 | + | checksum = "f4e57b2aae53a240c62b65069a63eaf8d5fa747f5d0d8e670c5210a98847bce4" | |
| 1948 | + | ||
| 1949 | + | [[package]] | |
| 1950 | + | name = "windows-sys" | |
| 1951 | + | version = "0.61.2" | |
| 1952 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1953 | + | checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" | |
| 1954 | + | dependencies = [ | |
| 1955 | + | "windows-link 0.2.1", | |
| 1956 | + | ] | |
| 1957 | + | ||
| 1958 | + | [[package]] | |
| 1959 | + | name = "windows-sys" | |
| 1960 | + | version = "0.101.0" | |
| 1961 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1962 | + | checksum = "eed2df9f5f458664c87437f6758f0d93085b06433bf66b2b84c23c19f3d2012c" | |
| 1963 | + | dependencies = [ | |
| 1964 | + | "windows-link 0.101.0", | |
| 1965 | + | ] | |
| 1966 | + | ||
| 1967 | + | [[package]] | |
| 1968 | + | name = "winreg" | |
| 1969 | + | version = "0.56.0" | |
| 1970 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1971 | + | checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10" | |
| 1972 | + | dependencies = [ | |
| 1973 | + | "cfg-if", | |
| 1974 | + | "windows-sys 0.61.2", | |
| 1975 | + | ] | |
| 1976 | + | ||
| 1977 | + | [[package]] | |
| 1978 | + | name = "zlib-rs" | |
| 1979 | + | version = "0.6.9" | |
| 1980 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1981 | + | checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" | |
| 1982 | + | ||
| 1983 | + | [[package]] | |
| 1984 | + | name = "zmij" | |
| 1985 | + | version = "1.0.23" | |
| 1986 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1987 | + | checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" |
Cargo.toml+45−0
| @@ -0,0 +1,45 @@ | |||
| 1 | + | [workspace] | |
| 2 | + | resolver = "3" | |
| 3 | + | members = [ | |
| 4 | + | "crates/roneo-core", | |
| 5 | + | "crates/roneo-plugin-sdk", | |
| 6 | + | "crates/roneo-cli", | |
| 7 | + | ] | |
| 8 | + | ||
| 9 | + | [workspace.package] | |
| 10 | + | version = "0.1.0" | |
| 11 | + | edition = "2024" | |
| 12 | + | rust-version = "1.100" | |
| 13 | + | license = "MIT" | |
| 14 | + | repository = "https://code.cleyrop.tech/roneo" | |
| 15 | + | keywords = ["template", "scaffolding", "copier", "jinja", "cli"] | |
| 16 | + | categories = ["command-line-utilities", "development-tools", "template-engine"] | |
| 17 | + | ||
| 18 | + | [workspace.dependencies] | |
| 19 | + | clap = { version = "4.6", features = ["derive"] } | |
| 20 | + | gix = { version = "0.91", default-features = false, features = ["revision", "sha1", "max-performance"] } | |
| 21 | + | indexmap = { version = "2.14", features = ["serde"] } | |
| 22 | + | inquire = { version = "0.9", features = ["editor"] } | |
| 23 | + | minijinja = { version = "3.1", features = ["builtins", "json", "loop_controls", "macros", "preserve_order", "serde", "unicode", "urlencode"] } | |
| 24 | + | minijinja-contrib = { version = "3.1", features = ["pycompat"] } | |
| 25 | + | rayon = "1.12" | |
| 26 | + | serde = { version = "1.0", features = ["derive"] } | |
| 27 | + | serde_json = "1.0" | |
| 28 | + | serde_yaml_ng = "0.10" | |
| 29 | + | wasmi = { version = "2.0", default-features = false, features = ["std", "validate", "auto-dispatch"] } | |
| 30 | + | ||
| 31 | + | [profile.release] | |
| 32 | + | lto = "thin" | |
| 33 | + | codegen-units = 1 | |
| 34 | + | panic = "abort" | |
| 35 | + | strip = "none" | |
| 36 | + | ||
| 37 | + | [workspace.lints.clippy] | |
| 38 | + | all = { level = "warn", priority = -1 } | |
| 39 | + | pedantic = { level = "warn", priority = -1 } | |
| 40 | + | module_name_repetitions = "allow" | |
| 41 | + | missing_errors_doc = "allow" | |
| 42 | + | missing_panics_doc = "allow" | |
| 43 | + | must_use_candidate = "allow" | |
| 44 | + | struct_excessive_bools = "allow" | |
| 45 | + | too_many_lines = "allow" |
LICENSE+21−0
| @@ -0,0 +1,21 @@ | |||
| 1 | + | MIT License | |
| 2 | + | ||
| 3 | + | Copyright (c) 2026 Jean Humann | |
| 4 | + | ||
| 5 | + | Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 6 | + | of this software and associated documentation files (the "Software"), to deal | |
| 7 | + | in the Software without restriction, including without limitation the rights | |
| 8 | + | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 9 | + | copies of the Software, and to permit persons to whom the Software is | |
| 10 | + | furnished to do so, subject to the following conditions: | |
| 11 | + | ||
| 12 | + | The above copyright notice and this permission notice shall be included in all | |
| 13 | + | copies or substantial portions of the Software. | |
| 14 | + | ||
| 15 | + | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 16 | + | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 17 | + | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 18 | + | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 19 | + | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 20 | + | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 21 | + | SOFTWARE. |
README.md+158−0
| @@ -0,0 +1,158 @@ | |||
| 1 | + | <p align="center"> | |
| 2 | + | <img src="assets/logo.svg" alt="Ronéo" width="96" height="96" /> | |
| 3 | + | </p> | |
| 4 | + | ||
| 5 | + | # Ronéo (`roneo`) | |
| 6 | + | ||
| 7 | + | > Un portage Rust rapide, autonome et maniable de [Copier](https://github.com/copier-org/copier) — pour générer et mettre à jour vos projets à partir de templates Jinja2 sans runtime Python. | |
| 8 | + | ||
| 9 | + | Le nom **Ronéo** vient de la célèbre machine à dupliquer au stencil (*« passer à la ronéo »*) : reproduire des modèles proprement, vite et sans friction. | |
| 10 | + | ||
| 11 | + | ## Pourquoi Ronéo ? | |
| 12 | + | ||
| 13 | + | - **Un seul binaire natif** : démarrage instantané (~ms), aucune dépendance Python / virtualenv / `pipx` / `uvx`. | |
| 14 | + | - **Compatible avec l'écosystème Copier** : lit directement `copier.yml` / `copier.yaml` (ou `roneo.yml`), génère des fichiers `.copier-answers.yml` interopérables, supporte `gh:` / `gl:` / Git / dossiers locaux, Jinja2 + méthodes Python (`pycompat`), chemins dynamiques et mises à jour intelligentes par fusion 3-voies (`update`). | |
| 15 | + | - **Plus maniable** : | |
| 16 | + | - Commande bonus `roneo inspect <template>` (texte ou `--json`) pour explorer les questions, réglages et tâches d'un template avant de l'exécuter. | |
| 17 | + | - Architecture en workspace Rust propre : `roneo-core` (bibliothèque réutilisable, traits `Prompter` et `Reporter` découplés du terminal) + `roneo-cli` (binaire `roneo`). | |
| 18 | + | - Auto-génération de `.copier-answers.yml` même si un template n'a pas inclus `{{ _copier_conf.answers_file }}.jinja`. | |
| 19 | + | ||
| 20 | + | ## Démarrage rapide | |
| 21 | + | ||
| 22 | + | ```bash | |
| 23 | + | # Inspecter le template d'exemple inclus | |
| 24 | + | cargo run -- inspect ./examples/starter-template | |
| 25 | + | ||
| 26 | + | # Simuler une génération (dry-run) | |
| 27 | + | cargo run -- copy ./examples/starter-template /tmp/mon-projet --defaults --pretend | |
| 28 | + | ||
| 29 | + | # Générer un projet de façon interactive | |
| 30 | + | cargo run -- copy ./examples/starter-template /tmp/mon-projet | |
| 31 | + | ||
| 32 | + | # Ou sans interaction avec surcharge de variables | |
| 33 | + | cargo run -- copy ./examples/starter-template /tmp/mon-projet \ | |
| 34 | + | --defaults \ | |
| 35 | + | -d project_name=super-api \ | |
| 36 | + | -d license=Apache-2.0 | |
| 37 | + | ``` | |
| 38 | + | ||
| 39 | + | ### Installation | |
| 40 | + | ||
| 41 | + | #### Via `mise` (recommandé — mises à jour automatiques) | |
| 42 | + | ||
| 43 | + | ```bash | |
| 44 | + | mise plugins install forge https://code.cleyrop.tech/mise.git | |
| 45 | + | mise use -g forge:roneo@latest | |
| 46 | + | ``` | |
| 47 | + | ||
| 48 | + | Ou dans un `mise.toml` : | |
| 49 | + | ||
| 50 | + | ```toml | |
| 51 | + | [plugins] | |
| 52 | + | forge = "https://code.cleyrop.tech/mise.git" | |
| 53 | + | ||
| 54 | + | [tools] | |
| 55 | + | "forge:roneo" = "latest" | |
| 56 | + | ``` | |
| 57 | + | ||
| 58 | + | #### Via script d'installation (macOS & Linux, vérification SHA-256) | |
| 59 | + | ||
| 60 | + | ```bash | |
| 61 | + | curl -fsSL https://code.cleyrop.tech/roneo/raw/main/install.sh | sh | |
| 62 | + | ``` | |
| 63 | + | ||
| 64 | + | #### Depuis les sources (`cargo`, Rust `1.100+`) | |
| 65 | + | ||
| 66 | + | ```bash | |
| 67 | + | cargo install --path crates/roneo-cli | |
| 68 | + | ``` | |
| 69 | + | ||
| 70 | + | ## Commandes CLI | |
| 71 | + | ||
| 72 | + | | Commande | Rôle | | |
| 73 | + | | --- | --- | | |
| 74 | + | | `roneo copy <template> [dest]` | Génère un nouveau projet depuis un dossier local, un dépôt Git, `gh:owner/repo` ou `gl:owner/repo`. | | |
| 75 | + | | `roneo update [dest]` | Met à jour un projet suivi par Git vers une version plus récente du template via fusion 3-voies (`--conflict inline\|rej`), en préservant vos modifications locales. | | |
| 76 | + | | `roneo check-update [dest]` | Vérifie si une version plus récente du template existe (`--output-format plain\|json`, `-g/--prereleases`, `-q` retourne le code de sortie `2` si une mise à jour est disponible). | | |
| 77 | + | | `roneo diff [dest]` | Prévisualise en couleur le diff unifié 3-voies qu'appliquerait `roneo update` sans modifier aucun fichier. | | |
| 78 | + | | `roneo recopy [dest]` | Réapplique le template en réutilisant les réponses enregistrées dans `.copier-answers.yml` (sans diff 3-voies). | | |
| 79 | + | | `roneo inspect <template>` | Affiche les métadonnées, réglages, tâches requérant `--trust` et questions d'un template (`--json` supporté). | | |
| 80 | + | | `roneo plugin <install\|list\|inspect\|remove>` | Gère les plugins WebAssembly (`.wasm`) installés localement dans `~/.config/roneo/plugins` (ou `$RONEO_PLUGIN_DIR`). | | |
| 81 | + | | `roneo completions <bash\|zsh\|fish>` | Génère le script d'autocomplétion shell (`bash`, `zsh` ou `fish`). | | |
| 82 | + | ||
| 83 | + | ### Options principales | |
| 84 | + | ||
| 85 | + | - `-r, --vcs-ref REF` : branche, tag, commit cible, ou `:current:` (pour rester sur le commit actuel lors d'un `update`) | |
| 86 | + | - `-d, --data KEY=VALUE` : fournir/surcharger une réponse (répétable) | |
| 87 | + | - `--data-file PATH` : charger un fichier YAML/JSON de réponses | |
| 88 | + | - `-l, --defaults` : utiliser les valeurs par défaut sans prompts interactifs | |
| 89 | + | - `--ask QUESTION` : forcer le prompt interactif d'une question précise même avec `--defaults` ou `ask: false` (répétable) | |
| 90 | + | - `-A, --skip-answered` : ne pas redemander les questions déjà répondues (`update`/`recopy`) | |
| 91 | + | - `-n, --pretend` : mode dry-run (n'écrit rien, n'exécute aucune tâche) | |
| 92 | + | - `-w, --overwrite` : écraser les fichiers existants sans confirmation lors de `copy` | |
| 93 | + | - `-f, --force` : raccourci Copier pour `--defaults --overwrite` | |
| 94 | + | - `-C, --no-cleanup` : ne pas supprimer le dossier créé en cas d'erreur lors de `copy` | |
| 95 | + | - `-c, --context-lines N` : nombre de lignes de contexte pour le diff 3-voies (`update`/`diff`, défaut `3`) | |
| 96 | + | - `-o, --conflict inline|rej` : gestion des conflits lors de `update` (`inline` ou fichiers `.rej`) | |
| 97 | + | - `-s, --skip PATTERN` : ignorer les fichiers existants correspondant au motif (`--skip-if-exists`) | |
| 98 | + | - `-g, --prereleases` : autoriser les tags pré-release PEP 440 (`rc`, `a`, `b`, `dev`) | |
| 99 | + | - `--trust` / `--UNSAFE` : autoriser l'exécution des `_tasks` et `_migrations` shell | |
| 100 | + | - `-T, --skip-tasks` : ignorer les tâches et migrations | |
| 101 | + | - `--plugin PATH_OR_NAME` : charger une extension WebAssembly (`.wasm` par chemin ou alias installé via `roneo plugin install`) | |
| 102 | + | ||
| 103 | + | ### Configuration utilisateur (`settings.yml`) | |
| 104 | + | ||
| 105 | + | Ronéo lit automatiquement vos réglages utilisateur Copier/Ronéo depuis (par ordre de priorité) : | |
| 106 | + | `$RONEO_SETTINGS_PATH`, `$COPIER_SETTINGS_PATH`, `~/.config/roneo/settings.yml`, ou `~/.config/copier/settings.yml`. | |
| 107 | + | ||
| 108 | + | ```yaml | |
| 109 | + | defaults: | |
| 110 | + | author_name: Alice | |
| 111 | + | trust: | |
| 112 | + | - /srv/trusted-templates/ | |
| 113 | + | - https://code.cleyrop.tech/ | |
| 114 | + | ``` | |
| 115 | + | ||
| 116 | + | ## Plugins WebAssembly découplés (`roneo-plugin-sdk`) | |
| 117 | + | ||
| 118 | + | `roneo` reste 100 % générique : aucun plugin métier n'est lié au binaire principal. Les extensions s'écrivent dans un crate indépendant (dans le repo du template ou dans un repo dédié) grâce à `crates/roneo-plugin-sdk`, compilent en `wasm32-unknown-unknown` et tournent dans un bac à sable `wasmi` sans accès disque ni réseau : | |
| 119 | + | ||
| 120 | + | ```bash | |
| 121 | + | # Compiler un plugin WASM externe dépendant de `roneo-plugin-sdk` | |
| 122 | + | cd my-plugin && cargo build --release --target wasm32-unknown-unknown | |
| 123 | + | ||
| 124 | + | # L'installer sous un alias court dans ~/.config/roneo/plugins/my-plugin.wasm | |
| 125 | + | roneo plugin install target/wasm32-unknown-unknown/release/my_plugin.wasm | |
| 126 | + | ||
| 127 | + | # L'utiliser ensuite par simple nom | |
| 128 | + | roneo copy --trust --defaults --plugin my-plugin <template> <dest> | |
| 129 | + | ``` | |
| 130 | + | ||
| 131 | + | Un template peut aussi embarquer directement son `.wasm` et le déclarer dans `copier.yml` / `roneo.yml` via `_roneo_plugins: [template/extensions/mon-plugin.wasm]` (chargement automatique sans aucun flag `--plugin`). | |
| 132 | + | ||
| 133 | + | ## Compatibilité Copier | |
| 134 | + | ||
| 135 | + | | Fonctionnalité Copier | État dans Ronéo | | |
| 136 | + | | --- | --- | | |
| 137 | + | | `copier.yml` / `copier.yaml` (multi-doc, fusion de listes, `!include` + globs, forme courte & longue) | Implémenté | | |
| 138 | + | | Questions typées (`str`, `int`, `float`, `bool`, `yaml`, `json`) + `type:` / `choices:` / `multiline:` Jinja | Implémenté | | |
| 139 | + | | `help`, `default` (Jinja), `choices` (liste & mapping), `multiselect`, `placeholder` | Implémenté | | |
| 140 | + | | `when` conditionnel, `ask` (bool/Jinja) + `--ask`, `validator` Jinja, `secret` / `_secret_questions` | Implémenté | | |
| 141 | + | | Moteur Jinja2 (`minijinja` + `minijinja-contrib::pycompat` + `_envops`) avec confinement des chemins (`!include` / `{% include %}`) | Implémenté | | |
| 142 | + | | Rendu des chemins, dossiers conditionnels et boucles multi-fichiers `{% yield var from list %}...{% endyield %}` | Implémenté | | |
| 143 | + | | `_subdirectory`, `_answers_file`, `_templates_suffix`, `_exclude` / `_skip_if_exists` (motifs multi-lignes supportés), `_preserve_symlinks` (remplacement sûr des symlinks) | Implémenté | | |
| 144 | + | | `_copier_answers`, `_copier_conf` complet, `_folder_name`, `_copier_operation` | Implémenté | | |
| 145 | + | | `_tasks` & `_migrations` (`before` / `after` / `command` + `_stage` + `extra_env` + `COPIER_OPERATION`) avec garde `--trust` | Implémenté | | |
| 146 | + | | `copy`, `recopy`, `update`, `check-update` (3-voies Git `--3way`/`--reject` + fallback `git merge-file` résistant aux squash merges, protection `.gitignore` & `_skip_if_exists`, garde downgrade PEP 440, nettoyage si `_answers_file` renommé, sous-dossiers monorepo, `.bundle`, submodules, cache miroir local `~/.cache/roneo/repos`, `--vcs-ref :current:`, `-c`, `-C`) | Implémenté | | |
| 147 | + | | `_min_copier_version` (compatibilité **Copier 9.19.1** + warning anciens templates) et `settings.yml` utilisateur (`defaults` & `trust` RFC 3986 strict) | Implémenté | | |
| 148 | + | | `_external_data` (chargement YAML/JSON externe), PEP 440 complet + `--prereleases`, `roneo diff`, `multiline`, `qmark`, `--UNSAFE` / `--force` / `-s` | Implémenté | | |
| 149 | + | | Filtres & globaux intégrés (`to_nice_yaml(indent=...)`, `from_yaml`, `from_json`, `to_nice_json`, `slugify`, `to_snake`/`to_camel`/`to_pascal`/`to_kebab`, `b64encode`/`b64decode`, `to_bool`, `pathjoin`, `now()`, `UNSET`) | Implémenté | | |
| 150 | + | | Extensions métier isolées via plugins WebAssembly sandboxés (`roneo-plugin-sdk`, `roneo plugin`, `_roneo_plugins`) | Implémenté | | |
| 151 | + | ||
| 152 | + | ## Développement | |
| 153 | + | ||
| 154 | + | ```bash | |
| 155 | + | cargo test --workspace | |
| 156 | + | cargo clippy --workspace --all-targets -- -D warnings | |
| 157 | + | cargo build --release | |
| 158 | + | ``` |
SECURITY.md+19−0
| @@ -0,0 +1,19 @@ | |||
| 1 | + | # Security Policy | |
| 2 | + | ||
| 3 | + | ## Reporting a Vulnerability | |
| 4 | + | ||
| 5 | + | If you discover a security vulnerability in **Ronéo**, please report it responsibly instead of opening a public issue: | |
| 6 | + | ||
| 7 | + | - Contact: `security@cleyrop.com` | |
| 8 | + | - Include a clear description of the issue, reproduction steps, and affected version/commit. | |
| 9 | + | ||
| 10 | + | We will acknowledge receipt promptly and coordinate a fix and disclosure timeline. | |
| 11 | + | ||
| 12 | + | ## Security Model | |
| 13 | + | ||
| 14 | + | Ronéo follows Copier's trust model: | |
| 15 | + | ||
| 16 | + | - Templates declaring `_tasks`, `_migrations`, or `_roneo_plugins` require explicit `--trust` (or a matching entry in `settings.yml` validated against RFC 3986 §2.3 rules). | |
| 17 | + | - All template paths (`!include`, `{% include %}`, rendered filenames, `_answers_file`, `_subdirectory`, `_roneo_plugins`, `_external_data` when untrusted) are strictly confined to the template or destination root, and writes through symlinked destination directories are rejected. | |
| 18 | + | - WebAssembly plugins run inside a `wasmi` sandbox with no WASI, filesystem, or network access, bounded by CPU fuel (`100M` instructions/call), memory (`64 MiB`), and IPC (`16 MiB`) limits. | |
| 19 | + | - Temporary directories are created with `0700` permissions on Unix, and Git subprocesses run with `-c core.hooksPath=/dev/null`, `GIT_TERMINAL_PROMPT=0`, and `--` argument separators. |
| @@ -0,0 +1,15 @@ | |||
| 1 | + | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" fill="none"> | |
| 2 | + | <!-- Borderless matte carbon app icon (zero gradients) --> | |
| 3 | + | <rect width="128" height="128" rx="30" fill="#111113"/> | |
| 4 | + | ||
| 5 | + | <g transform="translate(13 13) scale(0.8)"> | |
| 6 | + | <path d="M16 34C24 22 37 20 54 20" stroke="#F4F4F5" stroke-width="4" stroke-linecap="round"/> | |
| 7 | + | <circle cx="54" cy="48" r="28" stroke="#F4F4F5" stroke-width="4.2"/> | |
| 8 | + | <path d="M39 39C44 31.5 54.5 28.5 63 32.5" stroke="#A1A1AA" stroke-width="2.8" stroke-linecap="round"/> | |
| 9 | + | <circle cx="54" cy="48" r="7.5" stroke="#F4F4F5" stroke-width="3.6"/> | |
| 10 | + | <circle cx="96" cy="39" r="8" stroke="#E05A36" stroke-width="3.8"/> | |
| 11 | + | <path d="M54 76H105.5C108.6 76 110.5 79.4 108.9 82.1L100.8 95.5C99.7 97.3 97.8 98.4 95.7 98.4H31C24.9 98.4 20 93.5 20 87.4C20 82.3 23.6 78 28.5 76.8" stroke="#F4F4F5" stroke-width="4.2" stroke-linecap="round" stroke-linejoin="round"/> | |
| 12 | + | <path d="M41 87.5H71M79 87.5H90" stroke="#E05A36" stroke-width="3.4" stroke-linecap="round"/> | |
| 13 | + | <path d="M27 107.5H91.5C93.6 107.5 95.5 106.4 96.6 104.6L100 99" stroke="#71717A" stroke-width="3.4" stroke-linecap="round" stroke-linejoin="round"/> | |
| 14 | + | </g> | |
| 15 | + | </svg> |
assets/logo-mono.svg+11−0
| @@ -0,0 +1,11 @@ | |||
| 1 | + | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" fill="none"> | |
| 2 | + | <!-- Borderless monoline emblem (`currentColor`), mise-inspired --> | |
| 3 | + | <path d="M16 34C24 22 37 20 54 20" stroke="currentColor" stroke-width="3.6" stroke-linecap="round"/> | |
| 4 | + | <circle cx="54" cy="48" r="28" stroke="currentColor" stroke-width="3.8"/> | |
| 5 | + | <path d="M39 39C44 31.5 54.5 28.5 63 32.5" stroke="currentColor" stroke-width="2.8" stroke-linecap="round" opacity="0.65"/> | |
| 6 | + | <circle cx="54" cy="48" r="7.5" stroke="currentColor" stroke-width="3.4"/> | |
| 7 | + | <circle cx="96" cy="39" r="8" stroke="currentColor" stroke-width="3.5"/> | |
| 8 | + | <path d="M54 76H105.5C108.6 76 110.5 79.4 108.9 82.1L100.8 95.5C99.7 97.3 97.8 98.4 95.7 98.4H31C24.9 98.4 20 93.5 20 87.4C20 82.3 23.6 78 28.5 76.8" stroke="currentColor" stroke-width="3.8" stroke-linecap="round" stroke-linejoin="round"/> | |
| 9 | + | <path d="M41 87.5H71M79 87.5H90" stroke="currentColor" stroke-width="3" stroke-linecap="round" opacity="0.8"/> | |
| 10 | + | <path d="M27 107.5H91.5C93.6 107.5 95.5 106.4 96.6 104.6L100 99" stroke="currentColor" stroke-width="3.2" stroke-linecap="round" stroke-linejoin="round" opacity="0.55"/> | |
| 11 | + | </svg> |
assets/logo.svg+32−0
| @@ -0,0 +1,32 @@ | |||
| 1 | + | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" fill="none"> | |
| 2 | + | <style> | |
| 3 | + | .ink { stroke: #18181B; } | |
| 4 | + | .muted { stroke: #71717A; } | |
| 5 | + | .accent { stroke: #D14924; } | |
| 6 | + | @media (prefers-color-scheme: dark) { | |
| 7 | + | .ink { stroke: #F4F4F5; } | |
| 8 | + | .muted { stroke: #A1A1AA; } | |
| 9 | + | .accent { stroke: #E05A36; } | |
| 10 | + | } | |
| 11 | + | </style> | |
| 12 | + | ||
| 13 | + | <!-- Incoming template sheet curving onto the rotary drum --> | |
| 14 | + | <path class="ink" d="M16 34C24 22 37 20 54 20" stroke-width="3.6" stroke-linecap="round"/> | |
| 15 | + | ||
| 16 | + | <!-- Main rotary mimeograph drum --> | |
| 17 | + | <circle class="ink" cx="54" cy="48" r="28" stroke-width="3.8"/> | |
| 18 | + | <path class="muted" d="M39 39C44 31.5 54.5 28.5 63 32.5" stroke-width="2.6" stroke-linecap="round"/> | |
| 19 | + | <circle class="ink" cx="54" cy="48" r="7.5" stroke-width="3.4"/> | |
| 20 | + | ||
| 21 | + | <!-- Vermilion ink roller --> | |
| 22 | + | <circle class="accent" cx="96" cy="39" r="8" stroke-width="3.6"/> | |
| 23 | + | ||
| 24 | + | <!-- Primary printed sheet ejected tangentially --> | |
| 25 | + | <path class="ink" d="M54 76H105.5C108.6 76 110.5 79.4 108.9 82.1L100.8 95.5C99.7 97.3 97.8 98.4 95.7 98.4H31C24.9 98.4 20 93.5 20 87.4C20 82.3 23.6 78 28.5 76.8" stroke-width="3.8" stroke-linecap="round" stroke-linejoin="round"/> | |
| 26 | + | ||
| 27 | + | <!-- Freshly inked stencil lines --> | |
| 28 | + | <path class="accent" d="M41 87.5H71M79 87.5H90" stroke-width="3.2" stroke-linecap="round"/> | |
| 29 | + | ||
| 30 | + | <!-- Duplicated sheet underneath --> | |
| 31 | + | <path class="muted" d="M27 107.5H91.5C93.6 107.5 95.5 106.4 96.6 104.6L100 99" stroke-width="3.2" stroke-linecap="round" stroke-linejoin="round"/> | |
| 32 | + | </svg> |
| @@ -0,0 +1,41 @@ | |||
| 1 | + | # syntax=docker/dockerfile:1.7 | |
| 2 | + | ||
| 3 | + | # Static, stripped Linux binary artifact (`FROM scratch`, single `/roneo` file) | |
| 4 | + | # built by Forge's rootless BuildKit and promoted/signed at release time. | |
| 5 | + | # | |
| 6 | + | # --build-arg TARGET_TRIPLE=x86_64-unknown-linux-musl | |
| 7 | + | # --build-arg SOURCE_REVISION=<commit> | |
| 8 | + | ||
| 9 | + | FROM registry.cleyrop.tech/external/library/rust:1.100.0-slim-trixie@sha256:24516ae4487ab804e3db145c93f7240e58e225587ab9b7c62ea31a218727bf67 AS build | |
| 10 | + | ||
| 11 | + | ARG TARGET_TRIPLE=x86_64-unknown-linux-musl | |
| 12 | + | ARG SOURCE_REVISION=dev | |
| 13 | + | ||
| 14 | + | ENV RUSTUP_TOOLCHAIN=1.100.0 | |
| 15 | + | ||
| 16 | + | # hadolint ignore=DL3008 | |
| 17 | + | RUN apt-get update \ | |
| 18 | + | && apt-get install -y --no-install-recommends musl-tools \ | |
| 19 | + | && rm -rf /var/lib/apt/lists/* \ | |
| 20 | + | && rustup target add "${TARGET_TRIPLE}" | |
| 21 | + | ||
| 22 | + | WORKDIR /src | |
| 23 | + | COPY Cargo.toml Cargo.lock rust-toolchain.toml ./ | |
| 24 | + | COPY .cargo .cargo | |
| 25 | + | COPY crates crates | |
| 26 | + | ||
| 27 | + | RUN --mount=type=cache,target=/src/target \ | |
| 28 | + | --mount=type=cache,target=/usr/local/cargo/registry \ | |
| 29 | + | RUSTFLAGS="--remap-path-prefix=/usr/local/cargo=/build --remap-path-prefix=/src=/src -C link-arg=-s -C link-arg=-Wl,-z,relro,-z,now,-z,noexecstack -C target-feature=+crt-static" \ | |
| 30 | + | cargo build --release --locked --target "${TARGET_TRIPLE}" -p roneo-cli --bin roneo \ | |
| 31 | + | && mkdir /out \ | |
| 32 | + | && cp "target/${TARGET_TRIPLE}/release/roneo" /out/roneo | |
| 33 | + | ||
| 34 | + | FROM scratch | |
| 35 | + | ||
| 36 | + | LABEL org.opencontainers.image.title="roneo" \ | |
| 37 | + | org.opencontainers.image.description="Fast, standalone Rust port of Copier for scaffolding and updating Jinja2 project templates" \ | |
| 38 | + | org.opencontainers.image.licenses="MIT" \ | |
| 39 | + | org.opencontainers.image.source="https://code.cleyrop.tech/roneo" | |
| 40 | + | ||
| 41 | + | COPY --from=build --chmod=0755 /out/roneo /roneo |
| @@ -0,0 +1,8 @@ | |||
| 1 | + | * | |
| 2 | + | !Cargo.toml | |
| 3 | + | !Cargo.lock | |
| 4 | + | !rust-toolchain.toml | |
| 5 | + | !.cargo/ | |
| 6 | + | !.cargo/config.toml | |
| 7 | + | !crates/ | |
| 8 | + | !crates/** |
| @@ -0,0 +1,82 @@ | |||
| 1 | + | #!/usr/bin/env bash | |
| 2 | + | # Build, sign (Developer ID Application), and notarise the macOS arm64 binary | |
| 3 | + | # for Forge's `binaries-macos` protected landing job (mirroring Forge's own | |
| 4 | + | # signing flow on `forge-mac-1`). | |
| 5 | + | # | |
| 6 | + | # Usage: | |
| 7 | + | # ci/binaries/macos/build.sh <commit-sha> | |
| 8 | + | # | |
| 9 | + | # Environment: | |
| 10 | + | # FORGE_SIGNING "keychain" (Developer ID + notarytool) or "adhoc" (default) | |
| 11 | + | # FORGE_SIGNING_TEAM Apple Team ID (default: 4SKW2Z97A2) | |
| 12 | + | # FORGE_SIGNING_ID codesign identity (default: "Developer ID Application: Cleyrop ($FORGE_SIGNING_TEAM)") | |
| 13 | + | # NOTARY_PROFILE keychain profile for `xcrun notarytool` (default: forge-notary) | |
| 14 | + | # RONEO_MACOS_RECORD output metadata JSON (default: roneo-macos.json) | |
| 15 | + | # RONEO_NOTARISATIONS notarisation record JSON (default: notarisations.json) | |
| 16 | + | set -euo pipefail | |
| 17 | + | ||
| 18 | + | COMMIT="${1:-$(git rev-parse HEAD)}" | |
| 19 | + | TARGET_TRIPLE="aarch64-apple-darwin" | |
| 20 | + | SIGNING_MODE="${FORGE_SIGNING:-adhoc}" | |
| 21 | + | SIGNING_TEAM="${FORGE_SIGNING_TEAM:-4SKW2Z97A2}" | |
| 22 | + | SIGNING_ID="${FORGE_SIGNING_ID:-Developer ID Application: Cleyrop (${SIGNING_TEAM})}" | |
| 23 | + | NOTARY_PROFILE="${NOTARY_PROFILE:-forge-notary}" | |
| 24 | + | RECORD_PATH="${RONEO_MACOS_RECORD:-roneo-macos.json}" | |
| 25 | + | NOTARISATIONS_PATH="${RONEO_NOTARISATIONS:-notarisations.json}" | |
| 26 | + | BUNDLE_ID="com.cleyrop.roneo" | |
| 27 | + | ||
| 28 | + | printf '[]\n' > "$NOTARISATIONS_PATH" | |
| 29 | + | ||
| 30 | + | RUSTFLAGS="--remap-path-prefix=${HOME}=/build --remap-path-prefix=$(pwd)=/src -C link-arg=-Wl,-S,-x,-dead_strip" \ | |
| 31 | + | cargo build --release --locked --target "$TARGET_TRIPLE" -p roneo-cli --bin roneo | |
| 32 | + | ||
| 33 | + | BIN="target/${TARGET_TRIPLE}/release/roneo" | |
| 34 | + | test -x "$BIN" | |
| 35 | + | ||
| 36 | + | if [ "$SIGNING_MODE" = "keychain" ]; then | |
| 37 | + | codesign --force --options runtime --timestamp \ | |
| 38 | + | --identifier "$BUNDLE_ID" \ | |
| 39 | + | --sign "$SIGNING_ID" \ | |
| 40 | + | "$BIN" | |
| 41 | + | codesign --verify --strict --verbose=2 "$BIN" | |
| 42 | + | ||
| 43 | + | TMP_ZIP="$(mktemp -t roneo-notary.XXXXXX.zip)" | |
| 44 | + | trap 'rm -f "$TMP_ZIP"' EXIT | |
| 45 | + | ditto -c -k --keepParent "$BIN" "$TMP_ZIP" | |
| 46 | + | ||
| 47 | + | NOTARY_JSON="$(xcrun notarytool submit "$TMP_ZIP" \ | |
| 48 | + | --keychain-profile "$NOTARY_PROFILE" \ | |
| 49 | + | --wait \ | |
| 50 | + | --output-format json)" | |
| 51 | + | printf '[%s]\n' "$NOTARY_JSON" > "$NOTARISATIONS_PATH" | |
| 52 | + | ||
| 53 | + | STATUS="$(printf '%s' "$NOTARY_JSON" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("status",""))')" | |
| 54 | + | if [ "$STATUS" != "Accepted" ]; then | |
| 55 | + | printf 'error: Apple notarisation failed (status=%s)\n' "$STATUS" >&2 | |
| 56 | + | exit 1 | |
| 57 | + | fi | |
| 58 | + | else | |
| 59 | + | codesign --force --sign - --identifier "$BUNDLE_ID" "$BIN" | |
| 60 | + | codesign --verify --strict "$BIN" | |
| 61 | + | fi | |
| 62 | + | ||
| 63 | + | SHA256="$(shasum -a 256 "$BIN" | awk '{print $1}')" | |
| 64 | + | SIZE="$(stat -f%z "$BIN")" | |
| 65 | + | "$BIN" --version | |
| 66 | + | ||
| 67 | + | python3 - "$COMMIT" "$SHA256" "$SIZE" "$SIGNING_MODE" "$RECORD_PATH" <<'PY' | |
| 68 | + | import json, sys | |
| 69 | + | commit, sha256, size, mode, out_path = sys.argv[1:] | |
| 70 | + | record = { | |
| 71 | + | "commit": commit, | |
| 72 | + | "bin": "roneo", | |
| 73 | + | "os": "darwin", | |
| 74 | + | "arch": "arm64", | |
| 75 | + | "sha256": sha256, | |
| 76 | + | "size": int(size), | |
| 77 | + | "signing": mode, | |
| 78 | + | } | |
| 79 | + | with open(out_path, "w") as f: | |
| 80 | + | json.dump(record, f, indent=2) | |
| 81 | + | f.write("\n") | |
| 82 | + | PY |
ci/jobs.toml+105−0
| @@ -0,0 +1,105 @@ | |||
| 1 | + | # Native Forge CI for Ronéo (schema 2, Rust 1.100.0) | |
| 2 | + | # - [cargo]: format, clippy, tests planned per-crate by Forge's Cargo model | |
| 3 | + | # - [jobs.gitleaks]: required secret scan for public repository landings | |
| 4 | + | # - [jobs.binaries-linux-*]: rootless BuildKit static musl `FROM scratch` OCI | |
| 5 | + | # artifacts built once on protected landings for release promotion & signing | |
| 6 | + | schema = 2 | |
| 7 | + | ||
| 8 | + | [variables] | |
| 9 | + | CARGO_HOME = "$CI_PROJECT_DIR/.cache/forge-cargo" | |
| 10 | + | RUST_IMAGE = "registry.cleyrop.tech/external/library/rust:1.100.0-slim-trixie@sha256:24516ae4487ab804e3db145c93f7240e58e225587ab9b7c62ea31a218727bf67" | |
| 11 | + | ||
| 12 | + | [cargo] | |
| 13 | + | workspace = "" | |
| 14 | + | checks = ["format", "clippy", "tests"] | |
| 15 | + | reads = ["crates:public", "rust:dist"] | |
| 16 | + | tests_reads = ["apt:debian"] | |
| 17 | + | tests_warm = ["target", ".cache/forge-cargo/registry"] | |
| 18 | + | ||
| 19 | + | [cargo.job] | |
| 20 | + | image = "registry.cleyrop.tech/external/library/rust:1.100.0-slim-trixie@sha256:24516ae4487ab804e3db145c93f7240e58e225587ab9b7c62ea31a218727bf67" | |
| 21 | + | script = [ | |
| 22 | + | "rustup component add clippy rustfmt", | |
| 23 | + | "{argv}", | |
| 24 | + | ] | |
| 25 | + | ||
| 26 | + | [cargo.tests] | |
| 27 | + | image = "registry.cleyrop.tech/external/library/rust:1.100.0-slim-trixie@sha256:24516ae4487ab804e3db145c93f7240e58e225587ab9b7c62ea31a218727bf67" | |
| 28 | + | script = [ | |
| 29 | + | "command -v git >/dev/null || (apt-get update -qq && apt-get install -y -qq --no-install-recommends git >/dev/null)", | |
| 30 | + | "{argv}", | |
| 31 | + | ] | |
| 32 | + | ||
| 33 | + | # Required secret scan for every change on a published repository (PUBLIC-FORGE.md §6.5). | |
| 34 | + | [jobs.gitleaks] | |
| 35 | + | inputs = ["**"] | |
| 36 | + | image = "registry.cleyrop.tech/external/zricethezav/gitleaks:v8.24.2@sha256:b5918eb91b8d2473cec722f066abb4352e4ffdc4ec9f4283ec143aba9ec9ebc4" | |
| 37 | + | script = [ | |
| 38 | + | "gitleaks detect --source . --no-banner --redact", | |
| 39 | + | ] | |
| 40 | + | ||
| 41 | + | # Static Linux amd64 binary (`FROM scratch`, `/roneo`) built once on protected landings | |
| 42 | + | # and promoted/signed by digest by Forge's release worker (PUBLIC-FORGE.md §8). | |
| 43 | + | [jobs.binaries-linux-amd64] | |
| 44 | + | inputs = [ | |
| 45 | + | "Cargo.toml", | |
| 46 | + | "Cargo.lock", | |
| 47 | + | "rust-toolchain.toml", | |
| 48 | + | ".cargo/config.toml", | |
| 49 | + | "crates/**", | |
| 50 | + | "ci/binaries/Dockerfile", | |
| 51 | + | "ci/binaries/Dockerfile.dockerignore", | |
| 52 | + | ] | |
| 53 | + | on = { runs = ["landing"], trust = ["protected"] } | |
| 54 | + | outputs = ["DOCKER_DESTINATION"] | |
| 55 | + | provenance = ["CI_COMMIT_SHA", "CI_PROJECT_URL"] | |
| 56 | + | build = { context = ".", dockerfile = "ci/binaries/Dockerfile", platforms = ["linux/amd64"], args = { TARGET_TRIPLE = "x86_64-unknown-linux-musl", SOURCE_REVISION = "$CI_COMMIT_SHA" }, labels = { "org.opencontainers.image.revision" = "$CI_COMMIT_SHA", "org.opencontainers.image.source" = "$CI_PROJECT_URL" } } | |
| 57 | + | ||
| 58 | + | [jobs.binaries-linux-amd64.variables] | |
| 59 | + | DOCKER_DESTINATION = "$HARBOR_REGISTRY/public/roneo-binaries:linux-amd64-$CI_COMMIT_SHA" | |
| 60 | + | ||
| 61 | + | # Static Linux arm64 binary (`FROM scratch`, `/roneo`), scheduled on arm64 build hosts. | |
| 62 | + | [jobs.binaries-linux-arm64] | |
| 63 | + | inputs = [ | |
| 64 | + | "Cargo.toml", | |
| 65 | + | "Cargo.lock", | |
| 66 | + | "rust-toolchain.toml", | |
| 67 | + | ".cargo/config.toml", | |
| 68 | + | "crates/**", | |
| 69 | + | "ci/binaries/Dockerfile", | |
| 70 | + | "ci/binaries/Dockerfile.dockerignore", | |
| 71 | + | ] | |
| 72 | + | on = { runs = ["landing"], trust = ["protected"] } | |
| 73 | + | allow_failure = true | |
| 74 | + | outputs = ["DOCKER_DESTINATION"] | |
| 75 | + | provenance = ["CI_COMMIT_SHA", "CI_PROJECT_URL"] | |
| 76 | + | build = { context = ".", dockerfile = "ci/binaries/Dockerfile", platforms = ["linux/arm64"], args = { TARGET_TRIPLE = "aarch64-unknown-linux-musl", SOURCE_REVISION = "$CI_COMMIT_SHA" }, labels = { "org.opencontainers.image.revision" = "$CI_COMMIT_SHA", "org.opencontainers.image.source" = "$CI_PROJECT_URL" } } | |
| 77 | + | ||
| 78 | + | [jobs.binaries-linux-arm64.variables] | |
| 79 | + | DOCKER_DESTINATION = "$HARBOR_REGISTRY/public/roneo-binaries:linux-arm64-$CI_COMMIT_SHA" | |
| 80 | + | ||
| 81 | + | # Signed & notarised macOS arm64 binary built on Forge's macOS signing host (`forge-mac-1`). | |
| 82 | + | [jobs.binaries-macos] | |
| 83 | + | inputs = [ | |
| 84 | + | "Cargo.toml", | |
| 85 | + | "Cargo.lock", | |
| 86 | + | "rust-toolchain.toml", | |
| 87 | + | ".cargo/config.toml", | |
| 88 | + | "crates/**", | |
| 89 | + | "ci/binaries/macos/build.sh", | |
| 90 | + | ] | |
| 91 | + | on = { runs = ["landing"], trust = ["protected"] } | |
| 92 | + | detached = true | |
| 93 | + | allow_failure = true | |
| 94 | + | tags = ["platform:darwin/arm64"] | |
| 95 | + | resource_group = "macos-signing" | |
| 96 | + | image = "registry.cleyrop.tech/external/library/rust:1.100.0-slim-trixie@sha256:24516ae4487ab804e3db145c93f7240e58e225587ab9b7c62ea31a218727bf67" | |
| 97 | + | outputs = ["roneo-macos.json"] | |
| 98 | + | inline = ["roneo-macos.json"] | |
| 99 | + | artifacts = { paths = ["roneo-macos.json"] } | |
| 100 | + | notarisations = "notarisations.json" | |
| 101 | + | script = ["bash ci/binaries/macos/build.sh $CI_COMMIT_SHA"] | |
| 102 | + | ||
| 103 | + | [jobs.binaries-macos.variables] | |
| 104 | + | FORGE_SIGNING = "keychain" | |
| 105 | + | FORGE_SIGNING_TEAM = "4SKW2Z97A2" |
| @@ -0,0 +1,24 @@ | |||
| 1 | + | [package] | |
| 2 | + | name = "roneo-cli" | |
| 3 | + | version.workspace = true | |
| 4 | + | edition.workspace = true | |
| 5 | + | rust-version.workspace = true | |
| 6 | + | license.workspace = true | |
| 7 | + | repository.workspace = true | |
| 8 | + | keywords.workspace = true | |
| 9 | + | categories.workspace = true | |
| 10 | + | description = "Fast, nimble CLI for Roneo (Rust port of Copier)" | |
| 11 | + | ||
| 12 | + | [[bin]] | |
| 13 | + | name = "roneo" | |
| 14 | + | path = "src/main.rs" | |
| 15 | + | ||
| 16 | + | [lints] | |
| 17 | + | workspace = true | |
| 18 | + | ||
| 19 | + | [dependencies] | |
| 20 | + | clap.workspace = true | |
| 21 | + | indexmap.workspace = true | |
| 22 | + | inquire.workspace = true | |
| 23 | + | roneo-core = { version = "0.1.0", path = "../roneo-core" } | |
| 24 | + | serde_json.workspace = true |
| @@ -0,0 +1,882 @@ | |||
| 1 | + | mod prompter; | |
| 2 | + | mod reporter; | |
| 3 | + | mod style; | |
| 4 | + | ||
| 5 | + | use std::env; | |
| 6 | + | use std::fs; | |
| 7 | + | use std::io::{self, Write}; | |
| 8 | + | use std::path::{Path, PathBuf}; | |
| 9 | + | use std::process::ExitCode; | |
| 10 | + | ||
| 11 | + | use crate::prompter::TerminalPrompter; | |
| 12 | + | use crate::reporter::ConsoleReporter; | |
| 13 | + | use clap::{Args, Parser, Subcommand, ValueEnum}; | |
| 14 | + | use indexmap::IndexMap; | |
| 15 | + | use roneo_core::config::{json_display, parse_yaml_cli_value, parse_yaml_mapping}; | |
| 16 | + | use roneo_core::{ | |
| 17 | + | ConflictMode, CopyOptions, ExtensionRegistry, NonInteractivePrompter, OperationReport, | |
| 18 | + | Prompter, ResolvedTemplate, RoneoError, WasmExtension, check_update, copy, diff_update, recopy, | |
| 19 | + | update, | |
| 20 | + | }; | |
| 21 | + | ||
| 22 | + | #[derive(Debug, Parser)] | |
| 23 | + | #[command( | |
| 24 | + | name = "roneo", | |
| 25 | + | version, | |
| 26 | + | about = "Fast, nimble Rust port of Copier for scaffolding and updating project templates", | |
| 27 | + | propagate_version = true | |
| 28 | + | )] | |
| 29 | + | struct Cli { | |
| 30 | + | #[command(subcommand)] | |
| 31 | + | command: Commands, | |
| 32 | + | } | |
| 33 | + | ||
| 34 | + | #[derive(Debug, Subcommand)] | |
| 35 | + | enum Commands { | |
| 36 | + | /// Copy a template into a destination directory | |
| 37 | + | Copy { | |
| 38 | + | /// Template source (local path, git URL, `gh:owner/repo`, or `gl:owner/repo`) | |
| 39 | + | template: String, | |
| 40 | + | /// Destination directory (defaults to current directory) | |
| 41 | + | #[arg(default_value = ".")] | |
| 42 | + | destination: PathBuf, | |
| 43 | + | /// On error, do not delete the destination directory if it was created by Roneo (Copier `-C`) | |
| 44 | + | #[arg(short = 'C', long)] | |
| 45 | + | no_cleanup: bool, | |
| 46 | + | #[command(flatten)] | |
| 47 | + | opts: SharedOpts, | |
| 48 | + | }, | |
| 49 | + | ||
| 50 | + | /// Smart-update a git-tracked project from its template via 3-way merge | |
| 51 | + | Update { | |
| 52 | + | /// Destination project directory (defaults to current directory) | |
| 53 | + | #[arg(default_value = ".")] | |
| 54 | + | destination: PathBuf, | |
| 55 | + | /// How to record merge conflicts (`inline` markers or `.rej` files) | |
| 56 | + | #[arg(short = 'o', long, value_enum, default_value_t = CliConflictMode::Inline)] | |
| 57 | + | conflict: CliConflictMode, | |
| 58 | + | /// Lines of context to use for detecting conflicts (Copier `-c`, default 3) | |
| 59 | + | #[arg(short = 'c', long, default_value_t = 3)] | |
| 60 | + | context_lines: usize, | |
| 61 | + | /// Skip clean-working-tree git check (advanced) | |
| 62 | + | #[arg(long)] | |
| 63 | + | skip_git_check: bool, | |
| 64 | + | #[command(flatten)] | |
| 65 | + | opts: SharedOpts, | |
| 66 | + | }, | |
| 67 | + | ||
| 68 | + | /// Re-apply a template onto an existing project using saved answers (no 3-way merge) | |
| 69 | + | Recopy { | |
| 70 | + | /// Destination project directory (defaults to current directory) | |
| 71 | + | #[arg(default_value = ".")] | |
| 72 | + | destination: PathBuf, | |
| 73 | + | /// Optional template source override (defaults to `_src_path` in answers file) | |
| 74 | + | #[arg(long)] | |
| 75 | + | src: Option<String>, | |
| 76 | + | #[command(flatten)] | |
| 77 | + | opts: SharedOpts, | |
| 78 | + | }, | |
| 79 | + | ||
| 80 | + | /// Preview the 3-way unified diff that `roneo update` would apply without modifying files | |
| 81 | + | Diff { | |
| 82 | + | /// Destination project directory (defaults to current directory) | |
| 83 | + | #[arg(default_value = ".")] | |
| 84 | + | destination: PathBuf, | |
| 85 | + | /// Lines of context to include in the unified diff (default 3) | |
| 86 | + | #[arg(short = 'c', long, default_value_t = 3)] | |
| 87 | + | context_lines: usize, | |
| 88 | + | #[command(flatten)] | |
| 89 | + | opts: SharedOpts, | |
| 90 | + | }, | |
| 91 | + | ||
| 92 | + | /// Check if a project is using the latest version of its template (Copier `check-update`) | |
| 93 | + | CheckUpdate { | |
| 94 | + | /// Destination project directory (defaults to current directory) | |
| 95 | + | #[arg(default_value = ".")] | |
| 96 | + | destination: PathBuf, | |
| 97 | + | /// Custom answers file path relative to destination | |
| 98 | + | #[arg(short = 'a', long)] | |
| 99 | + | answers_file: Option<PathBuf>, | |
| 100 | + | /// Allow pre-release VCS tags (PEP 440) when comparing versions | |
| 101 | + | #[arg(short = 'g', long = "prereleases", alias = "use-prereleases")] | |
| 102 | + | prereleases: bool, | |
| 103 | + | /// Output format (`plain` or `json`) | |
| 104 | + | #[arg(long = "output-format", value_enum, default_value_t = CheckUpdateFormat::Plain)] | |
| 105 | + | output_format: CheckUpdateFormat, | |
| 106 | + | /// Suppress status output; exit with code 2 when a new template version is available | |
| 107 | + | #[arg(short = 'q', long)] | |
| 108 | + | quiet: bool, | |
| 109 | + | }, | |
| 110 | + | ||
| 111 | + | /// Inspect a template's configuration, questions, settings, and tasks without copying | |
| 112 | + | Inspect { | |
| 113 | + | /// Template source (local path, git URL, `gh:owner/repo`, or `gl:owner/repo`) | |
| 114 | + | template: String, | |
| 115 | + | /// Git ref (branch, tag, or commit) to inspect | |
| 116 | + | #[arg(short = 'r', long)] | |
| 117 | + | vcs_ref: Option<String>, | |
| 118 | + | /// Output machine-readable JSON | |
| 119 | + | #[arg(long)] | |
| 120 | + | json: bool, | |
| 121 | + | }, | |
| 122 | + | ||
| 123 | + | /// Manage standalone sandboxed WebAssembly (`.wasm`) plugins | |
| 124 | + | Plugin { | |
| 125 | + | #[command(subcommand)] | |
| 126 | + | action: PluginCommands, | |
| 127 | + | }, | |
| 128 | + | ||
| 129 | + | /// Print shell completion script (`bash`, `zsh`, or `fish`) | |
| 130 | + | Completions { | |
| 131 | + | /// Target shell | |
| 132 | + | #[arg(value_enum)] | |
| 133 | + | shell: CompletionShell, | |
| 134 | + | }, | |
| 135 | + | } | |
| 136 | + | ||
| 137 | + | #[derive(Debug, Subcommand)] | |
| 138 | + | enum PluginCommands { | |
| 139 | + | /// Install a `.wasm` plugin into the local Roneo plugin directory (`~/.config/roneo/plugins`) | |
| 140 | + | Install { | |
| 141 | + | /// Path to the `.wasm` file | |
| 142 | + | path: PathBuf, | |
| 143 | + | /// Optional short alias name (defaults to the plugin's manifest `name`) | |
| 144 | + | #[arg(long)] | |
| 145 | + | name: Option<String>, | |
| 146 | + | }, | |
| 147 | + | /// List installed `.wasm` plugins | |
| 148 | + | List, | |
| 149 | + | /// Inspect a `.wasm` plugin's manifest (by path or installed name) | |
| 150 | + | Inspect { | |
| 151 | + | /// Path to `.wasm` file or installed plugin name | |
| 152 | + | plugin: String, | |
| 153 | + | }, | |
| 154 | + | /// Remove an installed plugin by name | |
| 155 | + | Remove { | |
| 156 | + | /// Installed plugin name | |
| 157 | + | name: String, | |
| 158 | + | }, | |
| 159 | + | } | |
| 160 | + | ||
| 161 | + | #[derive(Debug, Clone, Copy, ValueEnum)] | |
| 162 | + | enum CheckUpdateFormat { | |
| 163 | + | Plain, | |
| 164 | + | Json, | |
| 165 | + | } | |
| 166 | + | ||
| 167 | + | #[derive(Debug, Clone, Copy, ValueEnum)] | |
| 168 | + | enum CompletionShell { | |
| 169 | + | Bash, | |
| 170 | + | Zsh, | |
| 171 | + | Fish, | |
| 172 | + | } | |
| 173 | + | ||
| 174 | + | #[derive(Debug, Clone, Copy, ValueEnum)] | |
| 175 | + | enum CliConflictMode { | |
| 176 | + | Inline, | |
| 177 | + | Rej, | |
| 178 | + | } | |
| 179 | + | ||
| 180 | + | impl From<CliConflictMode> for ConflictMode { | |
| 181 | + | fn from(value: CliConflictMode) -> Self { | |
| 182 | + | match value { | |
| 183 | + | CliConflictMode::Inline => Self::Inline, | |
| 184 | + | CliConflictMode::Rej => Self::Rej, | |
| 185 | + | } | |
| 186 | + | } | |
| 187 | + | } | |
| 188 | + | ||
| 189 | + | #[derive(Debug, Args)] | |
| 190 | + | struct SharedOpts { | |
| 191 | + | /// Git branch, tag, or commit to use from the template repository | |
| 192 | + | #[arg(short = 'r', long)] | |
| 193 | + | vcs_ref: Option<String>, | |
| 194 | + | ||
| 195 | + | /// Provide an answer directly (`key=value`); repeatable | |
| 196 | + | #[arg(short = 'd', long = "data", value_name = "KEY=VALUE")] | |
| 197 | + | data: Vec<String>, | |
| 198 | + | ||
| 199 | + | /// Load answers from a YAML or JSON file | |
| 200 | + | #[arg(long = "data-file", value_name = "PATH")] | |
| 201 | + | data_file: Option<PathBuf>, | |
| 202 | + | ||
| 203 | + | /// Custom answers file path relative to destination | |
| 204 | + | #[arg(short = 'a', long)] | |
| 205 | + | answers_file: Option<PathBuf>, | |
| 206 | + | ||
| 207 | + | /// Additional gitignore-style path patterns to exclude; repeatable | |
| 208 | + | #[arg(short = 'x', long = "exclude")] | |
| 209 | + | exclude: Vec<String>, | |
| 210 | + | ||
| 211 | + | /// Skip existing destination files matching this pattern (Copier `-s` / `--skip-if-exists`); repeatable | |
| 212 | + | #[arg(short = 's', long = "skip", alias = "skip-if-exists")] | |
| 213 | + | skip_if_exists: Vec<String>, | |
| 214 | + | ||
| 215 | + | /// Disable Copier's built-in default exclude rules | |
| 216 | + | #[arg(long)] | |
| 217 | + | no_default_excludes: bool, | |
| 218 | + | ||
| 219 | + | /// Allow selecting pre-release VCS tags (PEP 440) when `--vcs-ref` is omitted | |
| 220 | + | #[arg(short = 'g', long = "prereleases", alias = "use-prereleases")] | |
| 221 | + | prereleases: bool, | |
| 222 | + | ||
| 223 | + | /// Overwrite existing files without skipping | |
| 224 | + | #[arg(short = 'w', long)] | |
| 225 | + | overwrite: bool, | |
| 226 | + | ||
| 227 | + | /// Shorthand for `--defaults --overwrite` (Copier `-f` / `--force`) | |
| 228 | + | #[arg(short = 'f', long)] | |
| 229 | + | force: bool, | |
| 230 | + | ||
| 231 | + | /// Dry-run: show planned operations without writing any files or running tasks | |
| 232 | + | #[arg(short = 'n', long)] | |
| 233 | + | pretend: bool, | |
| 234 | + | ||
| 235 | + | /// Use default values for all questions without prompting interactively | |
| 236 | + | #[arg(short = 'l', long)] | |
| 237 | + | defaults: bool, | |
| 238 | + | ||
| 239 | + | /// Skip questions that already have saved answers during update/recopy | |
| 240 | + | #[arg(short = 'A', long)] | |
| 241 | + | skip_answered: bool, | |
| 242 | + | ||
| 243 | + | /// Force prompting for specific question(s), even with `--defaults`, `--skip-answered`, or `ask: false`; repeatable | |
| 244 | + | #[arg(long = "ask", value_name = "QUESTION")] | |
| 245 | + | ask: Vec<String>, | |
| 246 | + | ||
| 247 | + | /// Skip running `_tasks` and `_migrations` | |
| 248 | + | #[arg(short = 'T', long)] | |
| 249 | + | skip_tasks: bool, | |
| 250 | + | ||
| 251 | + | /// Allow running `_tasks` and `_migrations` defined by the template (alias: `--UNSAFE`) | |
| 252 | + | #[arg(long, alias = "UNSAFE")] | |
| 253 | + | trust: bool, | |
| 254 | + | ||
| 255 | + | /// Load a sandboxed WebAssembly plugin (`.wasm` file path or installed plugin name); repeatable | |
| 256 | + | #[arg(long = "plugin", value_name = "PATH_OR_NAME")] | |
| 257 | + | plugins: Vec<String>, | |
| 258 | + | ||
| 259 | + | /// Suppress non-error output | |
| 260 | + | #[arg(short = 'q', long)] | |
| 261 | + | quiet: bool, | |
| 262 | + | } | |
| 263 | + | ||
| 264 | + | fn main() -> ExitCode { | |
| 265 | + | let cli = Cli::parse(); | |
| 266 | + | match run(cli) { | |
| 267 | + | Ok(had_conflicts) => { | |
| 268 | + | if had_conflicts { | |
| 269 | + | ExitCode::from(2) | |
| 270 | + | } else { | |
| 271 | + | ExitCode::SUCCESS | |
| 272 | + | } | |
| 273 | + | } | |
| 274 | + | Err(RoneoError::UserAborted) => { | |
| 275 | + | eprintln!("{}", style::yellow("Aborted.")); | |
| 276 | + | ExitCode::from(130) | |
| 277 | + | } | |
| 278 | + | Err(err) => { | |
| 279 | + | eprintln!("{} {err}", style::red_bold("error:")); | |
| 280 | + | ExitCode::FAILURE | |
| 281 | + | } | |
| 282 | + | } | |
| 283 | + | } | |
| 284 | + | ||
| 285 | + | fn run(cli: Cli) -> roneo_core::Result<bool> { | |
| 286 | + | match cli.command { | |
| 287 | + | Commands::Copy { | |
| 288 | + | template, | |
| 289 | + | destination, | |
| 290 | + | no_cleanup, | |
| 291 | + | opts, | |
| 292 | + | } => { | |
| 293 | + | let mut copy_opts = build_options(&opts, ConflictMode::Inline, false)?; | |
| 294 | + | copy_opts.cleanup_on_error = !no_cleanup; | |
| 295 | + | let reporter = ConsoleReporter { | |
| 296 | + | quiet: opts.quiet, | |
| 297 | + | pretend: opts.pretend, | |
| 298 | + | }; | |
| 299 | + | let prompter = | |
| 300 | + | select_prompter(copy_opts.defaults && copy_opts.ask_questions.is_empty()); | |
| 301 | + | let report = copy( | |
| 302 | + | &template, | |
| 303 | + | &destination, | |
| 304 | + | ©_opts, | |
| 305 | + | prompter.as_ref(), | |
| 306 | + | &reporter, | |
| 307 | + | )?; | |
| 308 | + | if !opts.quiet { | |
| 309 | + | print_summary("Copied", &report, opts.pretend); | |
| 310 | + | } | |
| 311 | + | Ok(false) | |
| 312 | + | } | |
| 313 | + | ||
| 314 | + | Commands::Update { | |
| 315 | + | destination, | |
| 316 | + | conflict, | |
| 317 | + | context_lines, | |
| 318 | + | skip_git_check, | |
| 319 | + | opts, | |
| 320 | + | } => { | |
| 321 | + | let mut copy_opts = build_options(&opts, conflict.into(), skip_git_check)?; | |
| 322 | + | copy_opts.context_lines = context_lines; | |
| 323 | + | let reporter = ConsoleReporter { | |
| 324 | + | quiet: opts.quiet, | |
| 325 | + | pretend: opts.pretend, | |
| 326 | + | }; | |
| 327 | + | let prompter = | |
| 328 | + | select_prompter(copy_opts.defaults && copy_opts.ask_questions.is_empty()); | |
| 329 | + | let report = update(&destination, ©_opts, prompter.as_ref(), &reporter)?; | |
| 330 | + | if !opts.quiet { | |
| 331 | + | print_summary("Updated", &report, opts.pretend); | |
| 332 | + | } | |
| 333 | + | if !report.conflicts.is_empty() { | |
| 334 | + | eprintln!( | |
| 335 | + | "\n{} {} conflicted file(s) need manual resolution.", | |
| 336 | + | style::yellow_bold("warning:"), | |
| 337 | + | report.conflicts.len() | |
| 338 | + | ); | |
| 339 | + | return Ok(true); | |
| 340 | + | } | |
| 341 | + | Ok(false) | |
| 342 | + | } | |
| 343 | + | ||
| 344 | + | Commands::Recopy { | |
| 345 | + | destination, | |
| 346 | + | src, | |
| 347 | + | opts, | |
| 348 | + | } => { | |
| 349 | + | let copy_opts = build_options(&opts, ConflictMode::Inline, false)?; | |
| 350 | + | let reporter = ConsoleReporter { | |
| 351 | + | quiet: opts.quiet, | |
| 352 | + | pretend: opts.pretend, | |
| 353 | + | }; | |
| 354 | + | let prompter = | |
| 355 | + | select_prompter(copy_opts.defaults && copy_opts.ask_questions.is_empty()); | |
| 356 | + | let report = recopy( | |
| 357 | + | &destination, | |
| 358 | + | src.as_deref(), | |
| 359 | + | ©_opts, | |
| 360 | + | prompter.as_ref(), | |
| 361 | + | &reporter, | |
| 362 | + | )?; | |
| 363 | + | if !opts.quiet { | |
| 364 | + | print_summary("Recopied", &report, opts.pretend); | |
| 365 | + | } | |
| 366 | + | Ok(false) | |
| 367 | + | } | |
| 368 | + | ||
| 369 | + | Commands::Diff { | |
| 370 | + | destination, | |
| 371 | + | context_lines, | |
| 372 | + | opts, | |
| 373 | + | } => { | |
| 374 | + | let mut copy_opts = build_options(&opts, ConflictMode::Inline, true)?; | |
| 375 | + | copy_opts.context_lines = context_lines; | |
| 376 | + | let prompter = | |
| 377 | + | select_prompter(copy_opts.defaults && copy_opts.ask_questions.is_empty()); | |
| 378 | + | let diff = diff_update(&destination, ©_opts, prompter.as_ref())?; | |
| 379 | + | if diff.patch.trim().is_empty() { | |
| 380 | + | if !opts.quiet { | |
| 381 | + | println!("{}", style::dim("No template changes to apply.")); | |
| 382 | + | } | |
| 383 | + | } else { | |
| 384 | + | let mut stdout = io::stdout().lock(); | |
| 385 | + | if !opts.quiet { | |
| 386 | + | let to = diff.to_commit.as_deref().unwrap_or("HEAD"); | |
| 387 | + | if writeln!( | |
| 388 | + | stdout, | |
| 389 | + | "{} {} ({} -> {})\n", | |
| 390 | + | style::bold("Diff:"), | |
| 391 | + | diff.src_path, | |
| 392 | + | style::yellow(&diff.from_commit), | |
| 393 | + | style::green(to), | |
| 394 | + | ) | |
| 395 | + | .is_err() | |
| 396 | + | { | |
| 397 | + | return Ok(false); | |
| 398 | + | } | |
| 399 | + | } | |
| 400 | + | for line in diff.patch.lines() { | |
| 401 | + | let res = if line.starts_with("diff --git") { | |
| 402 | + | writeln!(stdout, "{}", style::bold(line)) | |
| 403 | + | } else if line.starts_with("@@") { | |
| 404 | + | writeln!(stdout, "{}", style::cyan(line)) | |
| 405 | + | } else if line.starts_with('+') && !line.starts_with("+++") { | |
| 406 | + | writeln!(stdout, "{}", style::green(line)) | |
| 407 | + | } else if line.starts_with('-') && !line.starts_with("---") { | |
| 408 | + | writeln!(stdout, "{}", style::red(line)) | |
| 409 | + | } else { | |
| 410 | + | writeln!(stdout, "{line}") | |
| 411 | + | }; | |
| 412 | + | if res.is_err() { | |
| 413 | + | break; | |
| 414 | + | } | |
| 415 | + | } | |
| 416 | + | } | |
| 417 | + | Ok(false) | |
| 418 | + | } | |
| 419 | + | ||
| 420 | + | Commands::CheckUpdate { | |
| 421 | + | destination, | |
| 422 | + | answers_file, | |
| 423 | + | prereleases, | |
| 424 | + | output_format, | |
| 425 | + | quiet, | |
| 426 | + | } => { | |
| 427 | + | let copy_opts = CopyOptions { | |
| 428 | + | answers_file, | |
| 429 | + | use_prereleases: prereleases, | |
| 430 | + | quiet, | |
| 431 | + | ..CopyOptions::default() | |
| 432 | + | }; | |
| 433 | + | let rep = check_update(&destination, ©_opts)?; | |
| 434 | + | if rep.update_available { | |
| 435 | + | if quiet { | |
| 436 | + | return Ok(true); | |
| 437 | + | } | |
| 438 | + | match output_format { | |
| 439 | + | CheckUpdateFormat::Json => { | |
| 440 | + | let payload = serde_json::json!({ | |
| 441 | + | "update_available": rep.update_available, | |
| 442 | + | "current_version": rep.current_version, | |
| 443 | + | "latest_version": rep.latest_version, | |
| 444 | + | }); | |
| 445 | + | println!("{payload}"); | |
| 446 | + | } | |
| 447 | + | CheckUpdateFormat::Plain => { | |
| 448 | + | println!( | |
| 449 | + | "New template version available.\nCurrent version is {}, latest version is {}.", | |
| 450 | + | rep.current_version, rep.latest_version | |
| 451 | + | ); | |
| 452 | + | } | |
| 453 | + | } | |
| 454 | + | } else if !quiet { | |
| 455 | + | match output_format { | |
| 456 | + | CheckUpdateFormat::Json => { | |
| 457 | + | let payload = serde_json::json!({ | |
| 458 | + | "update_available": rep.update_available, | |
| 459 | + | "current_version": rep.current_version, | |
| 460 | + | "latest_version": rep.latest_version, | |
| 461 | + | }); | |
| 462 | + | println!("{payload}"); | |
| 463 | + | } | |
| 464 | + | CheckUpdateFormat::Plain => { | |
| 465 | + | println!("Project is up-to-date!"); | |
| 466 | + | } | |
| 467 | + | } | |
| 468 | + | } | |
| 469 | + | Ok(false) | |
| 470 | + | } | |
| 471 | + | ||
| 472 | + | Commands::Inspect { | |
| 473 | + | template, | |
| 474 | + | vcs_ref, | |
| 475 | + | json, | |
| 476 | + | } => { | |
| 477 | + | let resolved = ResolvedTemplate::resolve(&template, vcs_ref.as_deref())?; | |
| 478 | + | if json { | |
| 479 | + | let payload = serde_json::json!({ | |
| 480 | + | "src_path": resolved.original_src, | |
| 481 | + | "resolved_src": resolved.resolved_src, | |
| 482 | + | "commit": resolved.commit, | |
| 483 | + | "commit_hash": resolved.commit_hash, | |
| 484 | + | "requires_trust": resolved.config.requires_trust(), | |
| 485 | + | "settings": resolved.config.settings, | |
| 486 | + | "questions": resolved.config.questions, | |
| 487 | + | }); | |
| 488 | + | let _ = writeln!(io::stdout(), "{}", serde_json::to_string_pretty(&payload)?); | |
| 489 | + | } else { | |
| 490 | + | print_inspect(&resolved); | |
| 491 | + | } | |
| 492 | + | Ok(false) | |
| 493 | + | } | |
| 494 | + | ||
| 495 | + | Commands::Plugin { action } => { | |
| 496 | + | handle_plugin_command(action)?; | |
| 497 | + | Ok(false) | |
| 498 | + | } | |
| 499 | + | ||
| 500 | + | Commands::Completions { shell } => { | |
| 501 | + | print_completions(shell); | |
| 502 | + | Ok(false) | |
| 503 | + | } | |
| 504 | + | } | |
| 505 | + | } | |
| 506 | + | ||
| 507 | + | fn plugin_dir() -> PathBuf { | |
| 508 | + | if let Ok(custom) = env::var("RONEO_PLUGIN_DIR") | |
| 509 | + | && !custom.trim().is_empty() | |
| 510 | + | { | |
| 511 | + | return PathBuf::from(custom); | |
| 512 | + | } | |
| 513 | + | let home = env::var("HOME") | |
| 514 | + | .or_else(|_| env::var("USERPROFILE")) | |
| 515 | + | .unwrap_or_else(|_| ".".into()); | |
| 516 | + | PathBuf::from(home).join(".config/roneo/plugins") | |
| 517 | + | } | |
| 518 | + | ||
| 519 | + | fn validate_plugin_alias(name: &str) -> roneo_core::Result<()> { | |
| 520 | + | let valid = !name.is_empty() | |
| 521 | + | && !name.starts_with('.') | |
| 522 | + | && !name.contains("..") | |
| 523 | + | && name | |
| 524 | + | .bytes() | |
| 525 | + | .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')); | |
| 526 | + | if !valid { | |
| 527 | + | return Err(RoneoError::Plugin(format!( | |
| 528 | + | "Invalid plugin alias '{name}': must contain only ASCII letters, digits, '.', '-', or '_' and must not traverse paths" | |
| 529 | + | ))); | |
| 530 | + | } | |
| 531 | + | Ok(()) | |
| 532 | + | } | |
| 533 | + | ||
| 534 | + | fn resolve_plugin_spec(spec: &str) -> roneo_core::Result<PathBuf> { | |
| 535 | + | let direct = Path::new(spec); | |
| 536 | + | if direct.is_file() { | |
| 537 | + | return Ok(direct.to_path_buf()); | |
| 538 | + | } | |
| 539 | + | validate_plugin_alias(spec)?; | |
| 540 | + | let dir = plugin_dir(); | |
| 541 | + | let candidate = if spec | |
| 542 | + | .rsplit('.') | |
| 543 | + | .next() | |
| 544 | + | .is_some_and(|ext| ext.eq_ignore_ascii_case("wasm")) | |
| 545 | + | { | |
| 546 | + | dir.join(spec) | |
| 547 | + | } else { | |
| 548 | + | dir.join(format!("{spec}.wasm")) | |
| 549 | + | }; | |
| 550 | + | if candidate.is_file() { | |
| 551 | + | return Ok(candidate); | |
| 552 | + | } | |
| 553 | + | Err(RoneoError::Plugin(format!( | |
| 554 | + | "Plugin '{spec}' not found as a file or in '{}'", | |
| 555 | + | dir.display() | |
| 556 | + | ))) | |
| 557 | + | } | |
| 558 | + | ||
| 559 | + | fn handle_plugin_command(action: PluginCommands) -> roneo_core::Result<()> { | |
| 560 | + | match action { | |
| 561 | + | PluginCommands::Install { path, name } => { | |
| 562 | + | let ext = WasmExtension::from_file(&path)?; | |
| 563 | + | let plugin_name = name.unwrap_or_else(|| ext.manifest().name.clone()); | |
| 564 | + | if plugin_name.is_empty() { | |
| 565 | + | return Err(RoneoError::Plugin( | |
| 566 | + | "Plugin manifest has an empty name; pass `--name <alias>`".into(), | |
| 567 | + | )); | |
| 568 | + | } | |
| 569 | + | validate_plugin_alias(&plugin_name)?; | |
| 570 | + | let dir = plugin_dir(); | |
| 571 | + | fs::create_dir_all(&dir).map_err(|e| RoneoError::io(&dir, e))?; | |
| 572 | + | let dst = dir.join(format!("{plugin_name}.wasm")); | |
| 573 | + | fs::copy(&path, &dst).map_err(|e| RoneoError::io(&dst, e))?; | |
| 574 | + | println!( | |
| 575 | + | "{} '{}' -> {}", | |
| 576 | + | style::green_bold("Installed plugin"), | |
| 577 | + | style::bold(&plugin_name), | |
| 578 | + | dst.display() | |
| 579 | + | ); | |
| 580 | + | } | |
| 581 | + | PluginCommands::List => { | |
| 582 | + | let dir = plugin_dir(); | |
| 583 | + | println!("{} {}", style::bold("Plugin directory:"), dir.display()); | |
| 584 | + | if !dir.is_dir() { | |
| 585 | + | println!(" (no plugins installed)"); | |
| 586 | + | return Ok(()); | |
| 587 | + | } | |
| 588 | + | let mut entries: Vec<PathBuf> = fs::read_dir(&dir) | |
| 589 | + | .map_err(|e| RoneoError::io(&dir, e))? | |
| 590 | + | .filter_map(Result::ok) | |
| 591 | + | .map(|e| e.path()) | |
| 592 | + | .filter(|p| { | |
| 593 | + | p.extension() | |
| 594 | + | .is_some_and(|ext| ext.eq_ignore_ascii_case("wasm")) | |
| 595 | + | }) | |
| 596 | + | .collect(); | |
| 597 | + | entries.sort(); | |
| 598 | + | if entries.is_empty() { | |
| 599 | + | println!(" (no plugins installed)"); | |
| 600 | + | return Ok(()); | |
| 601 | + | } | |
| 602 | + | for path in entries { | |
| 603 | + | let alias = path | |
| 604 | + | .file_stem() | |
| 605 | + | .map_or_default(|s| s.to_string_lossy().into_owned()); | |
| 606 | + | match WasmExtension::from_file(&path) { | |
| 607 | + | Ok(ext) => { | |
| 608 | + | let m = ext.manifest(); | |
| 609 | + | println!( | |
| 610 | + | " {} {} (filters: {}, functions: {}, tests: {}, context_hook: {})", | |
| 611 | + | style::cyan("•"), | |
| 612 | + | style::bold(&alias), | |
| 613 | + | m.filters.len(), | |
| 614 | + | m.functions.len(), | |
| 615 | + | m.tests.len(), | |
| 616 | + | m.has_context_hook | |
| 617 | + | ); | |
| 618 | + | } | |
| 619 | + | Err(e) => { | |
| 620 | + | let msg = e.to_string(); | |
| 621 | + | println!( | |
| 622 | + | " {} {} ({})", | |
| 623 | + | style::red("✗"), | |
| 624 | + | style::bold(&alias), | |
| 625 | + | style::red(&msg) | |
| 626 | + | ); | |
| 627 | + | } | |
| 628 | + | } | |
| 629 | + | } | |
| 630 | + | } | |
| 631 | + | PluginCommands::Inspect { plugin } => { | |
| 632 | + | let path = resolve_plugin_spec(&plugin)?; | |
| 633 | + | let ext = WasmExtension::from_file(&path)?; | |
| 634 | + | let m = ext.manifest(); | |
| 635 | + | println!("{} {}", style::bold("Plugin: "), m.name); | |
| 636 | + | println!("{} {}", style::bold("File: "), path.display()); | |
| 637 | + | println!("{} {}", style::bold("Strict: "), m.strict_undefined); | |
| 638 | + | println!("{} {}", style::bold("Hook: "), m.has_context_hook); | |
| 639 | + | println!("{} {:?}", style::bold("Filters: "), m.filters); | |
| 640 | + | println!("{} {:?}", style::bold("Funcs: "), m.functions); | |
| 641 | + | println!("{} {:?}", style::bold("Tests: "), m.tests); | |
| 642 | + | if !m.template_files.is_empty() { | |
| 643 | + | println!("{} {:?}", style::bold("Files: "), m.template_files); | |
| 644 | + | } | |
| 645 | + | } | |
| 646 | + | PluginCommands::Remove { name } => { | |
| 647 | + | validate_plugin_alias(&name)?; | |
| 648 | + | let path = plugin_dir().join(format!("{name}.wasm")); | |
| 649 | + | if !path.is_file() { | |
| 650 | + | return Err(RoneoError::Plugin(format!( | |
| 651 | + | "Installed plugin '{name}' not found at '{}'", | |
| 652 | + | path.display() | |
| 653 | + | ))); | |
| 654 | + | } | |
| 655 | + | fs::remove_file(&path).map_err(|e| RoneoError::io(&path, e))?; | |
| 656 | + | println!( | |
| 657 | + | "{} '{}'", | |
| 658 | + | style::yellow_bold("Removed plugin"), | |
| 659 | + | style::bold(&name) | |
| 660 | + | ); | |
| 661 | + | } | |
| 662 | + | } | |
| 663 | + | Ok(()) | |
| 664 | + | } | |
| 665 | + | ||
| 666 | + | fn select_prompter(use_defaults: bool) -> Box<dyn Prompter> { | |
| 667 | + | if use_defaults { | |
| 668 | + | Box::new(NonInteractivePrompter) | |
| 669 | + | } else { | |
| 670 | + | Box::new(TerminalPrompter) | |
| 671 | + | } | |
| 672 | + | } | |
| 673 | + | ||
| 674 | + | fn build_options( | |
| 675 | + | opts: &SharedOpts, | |
| 676 | + | conflict_mode: ConflictMode, | |
| 677 | + | skip_git_check: bool, | |
| 678 | + | ) -> roneo_core::Result<CopyOptions> { | |
| 679 | + | let mut data = IndexMap::new(); | |
| 680 | + | ||
| 681 | + | if let Some(path) = &opts.data_file { | |
| 682 | + | let raw = fs::read_to_string(path).map_err(|e| RoneoError::io(path, e))?; | |
| 683 | + | data.extend(parse_yaml_mapping(&raw)?); | |
| 684 | + | } | |
| 685 | + | ||
| 686 | + | for pair in &opts.data { | |
| 687 | + | let (k, raw_v) = pair.split_once('=').ok_or_else(|| { | |
| 688 | + | RoneoError::InvalidConfig(format!( | |
| 689 | + | "Invalid `--data` entry '{pair}'; expected KEY=VALUE" | |
| 690 | + | )) | |
| 691 | + | })?; | |
| 692 | + | data.insert(k.trim().to_string(), parse_yaml_cli_value(raw_v)); | |
| 693 | + | } | |
| 694 | + | ||
| 695 | + | let mut extensions = ExtensionRegistry::new(); | |
| 696 | + | for spec in &opts.plugins { | |
| 697 | + | let wasm_path = resolve_plugin_spec(spec)?; | |
| 698 | + | extensions.add_wasm_file(&wasm_path)?; | |
| 699 | + | } | |
| 700 | + | ||
| 701 | + | Ok(CopyOptions { | |
| 702 | + | vcs_ref: opts.vcs_ref.clone(), | |
| 703 | + | data, | |
| 704 | + | answers_file: opts.answers_file.clone(), | |
| 705 | + | exclude: opts.exclude.clone(), | |
| 706 | + | skip_if_exists: opts.skip_if_exists.clone(), | |
| 707 | + | use_default_excludes: !opts.no_default_excludes, | |
| 708 | + | use_prereleases: opts.prereleases, | |
| 709 | + | overwrite: opts.overwrite || opts.force, | |
| 710 | + | pretend: opts.pretend, | |
| 711 | + | defaults: opts.defaults || opts.force, | |
| 712 | + | skip_answered: opts.skip_answered, | |
| 713 | + | ask_questions: opts.ask.clone(), | |
| 714 | + | skip_tasks: opts.skip_tasks, | |
| 715 | + | trust: opts.trust, | |
| 716 | + | conflict_mode, | |
| 717 | + | context_lines: 3, | |
| 718 | + | cleanup_on_error: true, | |
| 719 | + | skip_git_check, | |
| 720 | + | quiet: opts.quiet, | |
| 721 | + | user_settings: None, | |
| 722 | + | extensions, | |
| 723 | + | }) | |
| 724 | + | } | |
| 725 | + | ||
| 726 | + | fn print_completions(shell: CompletionShell) { | |
| 727 | + | match shell { | |
| 728 | + | CompletionShell::Bash => print!( | |
| 729 | + | r#"# bash completion for roneo | |
| 730 | + | _roneo_completions() {{ | |
| 731 | + | local cur prev | |
| 732 | + | COMPREPLY=() | |
| 733 | + | cur="${{COMP_WORDS[COMP_CWORD]}}" | |
| 734 | + | prev="${{COMP_WORDS[COMP_CWORD-1]}}" | |
| 735 | + | if [[ ${{COMP_CWORD}} -eq 1 ]]; then | |
| 736 | + | COMPREPLY=( $(compgen -W "copy update diff recopy check-update inspect plugin completions help" -- "${{cur}}") ) | |
| 737 | + | return 0 | |
| 738 | + | fi | |
| 739 | + | if [[ "${{COMP_WORDS[1]}}" == "plugin" && ${{COMP_CWORD}} -eq 2 ]]; then | |
| 740 | + | COMPREPLY=( $(compgen -W "install list inspect remove" -- "${{cur}}") ) | |
| 741 | + | return 0 | |
| 742 | + | fi | |
| 743 | + | if [[ "${{cur}}" == -* ]]; then | |
| 744 | + | COMPREPLY=( $(compgen -W "-r --vcs-ref -d --data --data-file -a --answers-file -x --exclude -s --skip -g --prereleases -w --overwrite -f --force -n --pretend -l --defaults -A --skip-answered --ask -T --skip-tasks --trust --UNSAFE -C --no-cleanup -c --context-lines -o --conflict --output-format --plugin -q --quiet -h --help" -- "${{cur}}") ) | |
| 745 | + | return 0 | |
| 746 | + | fi | |
| 747 | + | }} | |
| 748 | + | complete -o default -F _roneo_completions roneo | |
| 749 | + | "# | |
| 750 | + | ), | |
| 751 | + | CompletionShell::Zsh => print!( | |
| 752 | + | r"#compdef roneo | |
| 753 | + | _roneo() {{ | |
| 754 | + | local -a commands | |
| 755 | + | commands=( | |
| 756 | + | 'copy:Copy a template into a destination directory' | |
| 757 | + | 'update:Smart-update a git-tracked project via 3-way merge' | |
| 758 | + | 'diff:Preview the 3-way unified diff for an update' | |
| 759 | + | 'recopy:Re-apply a template using saved answers' | |
| 760 | + | 'check-update:Check if a newer template version is available' | |
| 761 | + | 'inspect:Inspect template configuration and questions' | |
| 762 | + | 'plugin:Manage sandboxed WebAssembly (.wasm) plugins' | |
| 763 | + | 'completions:Print shell completion script' | |
| 764 | + | ) | |
| 765 | + | _arguments -C \ | |
| 766 | + | '1:command:->cmd' \ | |
| 767 | + | '*::arg:->args' | |
| 768 | + | case $state in | |
| 769 | + | cmd) _describe 'command' commands ;; | |
| 770 | + | args) _files ;; | |
| 771 | + | esac | |
| 772 | + | }} | |
| 773 | + | compdef _roneo roneo | |
| 774 | + | " | |
| 775 | + | ), | |
| 776 | + | CompletionShell::Fish => print!( | |
| 777 | + | r"# fish completion for roneo | |
| 778 | + | complete -c roneo -f -n '__fish_use_subcommand' -a copy -d 'Copy a template into a destination directory' | |
| 779 | + | complete -c roneo -f -n '__fish_use_subcommand' -a update -d 'Smart-update a git-tracked project via 3-way merge' | |
| 780 | + | complete -c roneo -f -n '__fish_use_subcommand' -a diff -d 'Preview the 3-way unified diff for an update' | |
| 781 | + | complete -c roneo -f -n '__fish_use_subcommand' -a recopy -d 'Re-apply a template using saved answers' | |
| 782 | + | complete -c roneo -f -n '__fish_use_subcommand' -a check-update -d 'Check if a newer template version is available' | |
| 783 | + | complete -c roneo -f -n '__fish_use_subcommand' -a inspect -d 'Inspect template configuration and questions' | |
| 784 | + | complete -c roneo -f -n '__fish_use_subcommand' -a plugin -d 'Manage sandboxed WebAssembly plugins' | |
| 785 | + | complete -c roneo -f -n '__fish_use_subcommand' -a completions -d 'Print shell completion script' | |
| 786 | + | " | |
| 787 | + | ), | |
| 788 | + | } | |
| 789 | + | } | |
| 790 | + | ||
| 791 | + | fn print_summary(verb: &str, report: &OperationReport, pretend: bool) { | |
| 792 | + | let commit_note = report | |
| 793 | + | .commit | |
| 794 | + | .as_deref() | |
| 795 | + | .map_or_default(|c| format!(" ({c})")); | |
| 796 | + | let mode = if pretend { " [dry-run]" } else { "" }; | |
| 797 | + | println!( | |
| 798 | + | "\n{} {}{} -> {} ({} created, {} updated, {} skipped){}", | |
| 799 | + | style::green_bold(verb), | |
| 800 | + | style::bold(&report.src_path), | |
| 801 | + | style::dim(&commit_note), | |
| 802 | + | report.dst_path.display(), | |
| 803 | + | report.created, | |
| 804 | + | report.updated, | |
| 805 | + | report.skipped, | |
| 806 | + | style::dim(mode), | |
| 807 | + | ); | |
| 808 | + | } | |
| 809 | + | ||
| 810 | + | fn print_inspect(resolved: &ResolvedTemplate) { | |
| 811 | + | let cfg = &resolved.config; | |
| 812 | + | println!("{} {}", style::bold("Template:"), resolved.original_src); | |
| 813 | + | if let Some(commit) = &resolved.commit { | |
| 814 | + | println!("{} {commit}", style::bold("Version: ")); | |
| 815 | + | } | |
| 816 | + | if let Some(sub) = &cfg.settings.subdirectory { | |
| 817 | + | println!("{} {sub}", style::bold("Subdir: ")); | |
| 818 | + | } | |
| 819 | + | println!("{} {}", style::bold("Answers: "), cfg.settings.answers_file); | |
| 820 | + | println!( | |
| 821 | + | "{} {}", | |
| 822 | + | style::bold("Suffix: "), | |
| 823 | + | if cfg.settings.templates_suffix.is_empty() { | |
| 824 | + | "(none)" | |
| 825 | + | } else { | |
| 826 | + | &cfg.settings.templates_suffix | |
| 827 | + | } | |
| 828 | + | ); | |
| 829 | + | if !cfg.settings.roneo_plugins.is_empty() { | |
| 830 | + | println!( | |
| 831 | + | "{} {}", | |
| 832 | + | style::bold("Plugins: "), | |
| 833 | + | cfg.settings.roneo_plugins.join(", ") | |
| 834 | + | ); | |
| 835 | + | } | |
| 836 | + | if cfg.requires_trust() { | |
| 837 | + | println!( | |
| 838 | + | "{} {} ({} task(s), {} migration(s))", | |
| 839 | + | style::bold("Trust: "), | |
| 840 | + | style::yellow_bold("required (--trust)"), | |
| 841 | + | cfg.settings.tasks.len(), | |
| 842 | + | cfg.settings.migrations.len() | |
| 843 | + | ); | |
| 844 | + | } | |
| 845 | + | ||
| 846 | + | println!( | |
| 847 | + | "\n{} ({})", | |
| 848 | + | style::bold_underlined("Questions"), | |
| 849 | + | cfg.questions.len() | |
| 850 | + | ); | |
| 851 | + | if cfg.questions.is_empty() { | |
| 852 | + | println!(" (none)"); | |
| 853 | + | } else { | |
| 854 | + | for (name, q) in &cfg.questions { | |
| 855 | + | let def = q | |
| 856 | + | .default | |
| 857 | + | .as_ref() | |
| 858 | + | .map_or_default(|d| format!(" [default: {}]", json_display(d))); | |
| 859 | + | let secret = if q.secret { " [secret]" } else { "" }; | |
| 860 | + | let cond = q | |
| 861 | + | .when | |
| 862 | + | .as_ref() | |
| 863 | + | .map_or_default(|w| format!(" [when: {}]", json_display(w))); | |
| 864 | + | println!( | |
| 865 | + | " {} {} ({:?}){}{}{}", | |
| 866 | + | style::cyan("•"), | |
| 867 | + | style::bold(name), | |
| 868 | + | q.kind, | |
| 869 | + | style::dim(&def), | |
| 870 | + | style::yellow(secret), | |
| 871 | + | style::dim(&cond), | |
| 872 | + | ); | |
| 873 | + | if let Some(help) = &q.help { | |
| 874 | + | println!(" {}", style::dim(help)); | |
| 875 | + | } | |
| 876 | + | if let Some(choices) = &q.choices { | |
| 877 | + | let labels: Vec<&str> = choices.iter().map(|c| c.label.as_str()).collect(); | |
| 878 | + | println!(" choices: {}", labels.join(", ")); | |
| 879 | + | } | |
| 880 | + | } | |
| 881 | + | } | |
| 882 | + | } |
| @@ -0,0 +1,143 @@ | |||
| 1 | + | use std::borrow::Cow; | |
| 2 | + | use std::path::Path; | |
| 3 | + | ||
| 4 | + | use inquire::error::InquireError; | |
| 5 | + | use inquire::{Confirm, Editor, MultiSelect, Password, Select, Text}; | |
| 6 | + | use roneo_core::config::ChoiceSpec; | |
| 7 | + | use roneo_core::{OverwriteChoice, PromptRequest, Prompter, Result, RoneoError}; | |
| 8 | + | use serde_json::Value as JsonValue; | |
| 9 | + | ||
| 10 | + | use crate::style; | |
| 11 | + | ||
| 12 | + | #[derive(Debug, Default)] | |
| 13 | + | pub struct TerminalPrompter; | |
| 14 | + | ||
| 15 | + | impl Prompter for TerminalPrompter { | |
| 16 | + | fn prompt_string(&self, req: &PromptRequest) -> Result<String> { | |
| 17 | + | let msg = format_prompt_message(req); | |
| 18 | + | if req.secret { | |
| 19 | + | let mut prompt = Password::new(&msg).without_confirmation(); | |
| 20 | + | if let Some(help) = &req.placeholder { | |
| 21 | + | prompt = prompt.with_help_message(help); | |
| 22 | + | } | |
| 23 | + | return prompt.prompt().map_err(map_inquire_err); | |
| 24 | + | } | |
| 25 | + | ||
| 26 | + | if req.multiline { | |
| 27 | + | let mut editor = Editor::new(&msg); | |
| 28 | + | if let Some(def) = &req.default_display { | |
| 29 | + | editor = editor.with_predefined_text(def); | |
| 30 | + | } | |
| 31 | + | return editor.prompt().map_err(map_inquire_err); | |
| 32 | + | } | |
| 33 | + | ||
| 34 | + | let mut prompt = Text::new(&msg); | |
| 35 | + | if let Some(def) = &req.default_display { | |
| 36 | + | prompt = prompt.with_default(def); | |
| 37 | + | } | |
| 38 | + | if let Some(ph) = &req.placeholder { | |
| 39 | + | prompt = prompt.with_placeholder(ph); | |
| 40 | + | } | |
| 41 | + | prompt.prompt().map_err(map_inquire_err) | |
| 42 | + | } | |
| 43 | + | ||
| 44 | + | fn prompt_bool(&self, req: &PromptRequest, default: bool) -> Result<bool> { | |
| 45 | + | let msg = format_prompt_message(req); | |
| 46 | + | Confirm::new(&msg) | |
| 47 | + | .with_default(default) | |
| 48 | + | .prompt() | |
| 49 | + | .map_err(map_inquire_err) | |
| 50 | + | } | |
| 51 | + | ||
| 52 | + | fn prompt_select( | |
| 53 | + | &self, | |
| 54 | + | req: &PromptRequest, | |
| 55 | + | choices: &[ChoiceSpec], | |
| 56 | + | default_idx: Option<usize>, | |
| 57 | + | ) -> Result<JsonValue> { | |
| 58 | + | let msg = format_prompt_message(req); | |
| 59 | + | let labels: Vec<&str> = choices.iter().map(|c| c.label.as_str()).collect(); | |
| 60 | + | let mut prompt = Select::new(&msg, labels); | |
| 61 | + | if let Some(idx) = default_idx { | |
| 62 | + | prompt = prompt.with_starting_cursor(idx); | |
| 63 | + | } | |
| 64 | + | let picked_label = prompt.prompt().map_err(map_inquire_err)?; | |
| 65 | + | let choice = choices | |
| 66 | + | .iter() | |
| 67 | + | .find(|c| c.label == picked_label) | |
| 68 | + | .ok_or_else(|| RoneoError::InvalidAnswer { | |
| 69 | + | question: req.name.clone(), | |
| 70 | + | message: "Selected choice not found".into(), | |
| 71 | + | })?; | |
| 72 | + | Ok(choice.value.clone()) | |
| 73 | + | } | |
| 74 | + | ||
| 75 | + | fn prompt_multiselect( | |
| 76 | + | &self, | |
| 77 | + | req: &PromptRequest, | |
| 78 | + | choices: &[ChoiceSpec], | |
| 79 | + | defaults: &[usize], | |
| 80 | + | ) -> Result<Vec<JsonValue>> { | |
| 81 | + | let msg = format_prompt_message(req); | |
| 82 | + | let labels: Vec<&str> = choices.iter().map(|c| c.label.as_str()).collect(); | |
| 83 | + | let prompt = MultiSelect::new(&msg, labels).with_default(defaults); | |
| 84 | + | let picked_labels = prompt.prompt().map_err(map_inquire_err)?; | |
| 85 | + | Ok(picked_labels | |
| 86 | + | .into_iter() | |
| 87 | + | .filter_map(|label| { | |
| 88 | + | choices | |
| 89 | + | .iter() | |
| 90 | + | .find(|c| c.label == label) | |
| 91 | + | .map(|c| c.value.clone()) | |
| 92 | + | }) | |
| 93 | + | .collect()) | |
| 94 | + | } | |
| 95 | + | ||
| 96 | + | fn show_validation_error(&self, question: &str, error: &str) { | |
| 97 | + | eprintln!( | |
| 98 | + | " {} {}: {}", | |
| 99 | + | style::red_bold("✗"), | |
| 100 | + | style::bold(question), | |
| 101 | + | style::red(error) | |
| 102 | + | ); | |
| 103 | + | } | |
| 104 | + | ||
| 105 | + | fn confirm_overwrite(&self, path: &Path) -> Result<OverwriteChoice> { | |
| 106 | + | let prompt = format!("Overwrite '{}'?", path.display()); | |
| 107 | + | let options = vec!["No (skip)", "Yes", "Yes to all", "Quit"]; | |
| 108 | + | let picked = Select::new(&prompt, options) | |
| 109 | + | .with_starting_cursor(0) | |
| 110 | + | .prompt() | |
| 111 | + | .map_err(map_inquire_err)?; | |
| 112 | + | Ok(match picked { | |
| 113 | + | "Yes" => OverwriteChoice::Yes, | |
| 114 | + | "Yes to all" => OverwriteChoice::All, | |
| 115 | + | "Quit" => OverwriteChoice::Quit, | |
| 116 | + | _ => OverwriteChoice::No, | |
| 117 | + | }) | |
| 118 | + | } | |
| 119 | + | } | |
| 120 | + | ||
| 121 | + | fn format_prompt_message(req: &PromptRequest) -> Cow<'_, str> { | |
| 122 | + | match req | |
| 123 | + | .qmark | |
| 124 | + | .as_deref() | |
| 125 | + | .map(str::trim) | |
| 126 | + | .filter(|s| !s.is_empty()) | |
| 127 | + | { | |
| 128 | + | Some(qmark) => Cow::Owned(format!("{qmark} {}", req.message)), | |
| 129 | + | None => Cow::Borrowed(&req.message), | |
| 130 | + | } | |
| 131 | + | } | |
| 132 | + | ||
| 133 | + | fn map_inquire_err(err: InquireError) -> RoneoError { | |
| 134 | + | match err { | |
| 135 | + | InquireError::OperationCanceled | InquireError::OperationInterrupted => { | |
| 136 | + | RoneoError::UserAborted | |
| 137 | + | } | |
| 138 | + | other => RoneoError::InvalidAnswer { | |
| 139 | + | question: "prompt".into(), | |
| 140 | + | message: other.to_string(), | |
| 141 | + | }, | |
| 142 | + | } | |
| 143 | + | } |
| @@ -0,0 +1,79 @@ | |||
| 1 | + | use roneo_core::{ActionEvent, Reporter}; | |
| 2 | + | ||
| 3 | + | use crate::style; | |
| 4 | + | ||
| 5 | + | #[derive(Debug, Clone, Copy)] | |
| 6 | + | pub struct ConsoleReporter { | |
| 7 | + | pub quiet: bool, | |
| 8 | + | pub pretend: bool, | |
| 9 | + | } | |
| 10 | + | ||
| 11 | + | impl Reporter for ConsoleReporter { | |
| 12 | + | fn emit(&self, event: ActionEvent) { | |
| 13 | + | if self.quiet { | |
| 14 | + | if let ActionEvent::Conflict(path) = event { | |
| 15 | + | eprintln!(" {:>10} {}", style::red_bold("conflict"), path.display()); | |
| 16 | + | } | |
| 17 | + | return; | |
| 18 | + | } | |
| 19 | + | ||
| 20 | + | let prefix = if self.pretend { | |
| 21 | + | format!("{} ", style::dim("[dry-run]")) | |
| 22 | + | } else { | |
| 23 | + | String::new() | |
| 24 | + | }; | |
| 25 | + | ||
| 26 | + | match event { | |
| 27 | + | ActionEvent::Create(p) => { | |
| 28 | + | println!( | |
| 29 | + | " {prefix}{:>10} {}", | |
| 30 | + | style::green_bold("create"), | |
| 31 | + | p.display() | |
| 32 | + | ); | |
| 33 | + | } | |
| 34 | + | ActionEvent::Overwrite(p) => { | |
| 35 | + | println!( | |
| 36 | + | " {prefix}{:>10} {}", | |
| 37 | + | style::yellow_bold("overwrite"), | |
| 38 | + | p.display() | |
| 39 | + | ); | |
| 40 | + | } | |
| 41 | + | ActionEvent::Update(p) => { | |
| 42 | + | println!( | |
| 43 | + | " {prefix}{:>10} {}", | |
| 44 | + | style::cyan_bold("update"), | |
| 45 | + | p.display() | |
| 46 | + | ); | |
| 47 | + | } | |
| 48 | + | ActionEvent::Delete(p) => { | |
| 49 | + | println!( | |
| 50 | + | " {prefix}{:>10} {}", | |
| 51 | + | style::red_bold("delete"), | |
| 52 | + | p.display() | |
| 53 | + | ); | |
| 54 | + | } | |
| 55 | + | ActionEvent::Identical(p) => { | |
| 56 | + | println!(" {prefix}{:>10} {}", style::dim("identical"), p.display()); | |
| 57 | + | } | |
| 58 | + | ActionEvent::Skip(p) => { | |
| 59 | + | println!(" {prefix}{:>10} {}", style::blue("skip"), p.display()); | |
| 60 | + | } | |
| 61 | + | ActionEvent::Conflict(p) => { | |
| 62 | + | eprintln!( | |
| 63 | + | " {prefix}{:>10} {}", | |
| 64 | + | style::red_bold("conflict"), | |
| 65 | + | p.display() | |
| 66 | + | ); | |
| 67 | + | } | |
| 68 | + | ActionEvent::RunTask(cmd) => { | |
| 69 | + | println!(" {prefix}{:>10} {}", style::magenta_bold("run"), cmd); | |
| 70 | + | } | |
| 71 | + | ActionEvent::Message(msg) => { | |
| 72 | + | println!("\n{msg}\n"); | |
| 73 | + | } | |
| 74 | + | ActionEvent::Warning(warn) => { | |
| 75 | + | eprintln!(" {:>10} {}", style::yellow_bold("warning"), warn); | |
| 76 | + | } | |
| 77 | + | } | |
| 78 | + | } | |
| 79 | + | } |
| @@ -0,0 +1,94 @@ | |||
| 1 | + | use std::io::IsTerminal; | |
| 2 | + | use std::sync::OnceLock; | |
| 3 | + | ||
| 4 | + | /// Zero-dependency ANSI terminal styler respecting `NO_COLOR` and TTY detection. | |
| 5 | + | #[derive(Debug, Clone, Copy)] | |
| 6 | + | pub struct Styled<'a> { | |
| 7 | + | text: &'a str, | |
| 8 | + | codes: &'static str, | |
| 9 | + | } | |
| 10 | + | ||
| 11 | + | fn color_enabled() -> bool { | |
| 12 | + | static ENABLED: OnceLock<bool> = OnceLock::new(); | |
| 13 | + | *ENABLED.get_or_init(|| { | |
| 14 | + | std::env::var_os("NO_COLOR").is_none() | |
| 15 | + | && (std::io::stdout().is_terminal() || std::io::stderr().is_terminal()) | |
| 16 | + | }) | |
| 17 | + | } | |
| 18 | + | ||
| 19 | + | impl std::fmt::Display for Styled<'_> { | |
| 20 | + | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| 21 | + | if color_enabled() && !self.codes.is_empty() { | |
| 22 | + | write!(f, "\x1b[{}m{}\x1b[0m", self.codes, self.text) | |
| 23 | + | } else { | |
| 24 | + | f.write_str(self.text) | |
| 25 | + | } | |
| 26 | + | } | |
| 27 | + | } | |
| 28 | + | ||
| 29 | + | pub fn bold(text: &str) -> Styled<'_> { | |
| 30 | + | Styled { text, codes: "1" } | |
| 31 | + | } | |
| 32 | + | ||
| 33 | + | pub fn bold_underlined(text: &str) -> Styled<'_> { | |
| 34 | + | Styled { text, codes: "1;4" } | |
| 35 | + | } | |
| 36 | + | ||
| 37 | + | pub fn dim(text: &str) -> Styled<'_> { | |
| 38 | + | Styled { text, codes: "2" } | |
| 39 | + | } | |
| 40 | + | ||
| 41 | + | pub fn green(text: &str) -> Styled<'_> { | |
| 42 | + | Styled { text, codes: "32" } | |
| 43 | + | } | |
| 44 | + | ||
| 45 | + | pub fn green_bold(text: &str) -> Styled<'_> { | |
| 46 | + | Styled { | |
| 47 | + | text, | |
| 48 | + | codes: "1;32", | |
| 49 | + | } | |
| 50 | + | } | |
| 51 | + | ||
| 52 | + | pub fn red(text: &str) -> Styled<'_> { | |
| 53 | + | Styled { text, codes: "31" } | |
| 54 | + | } | |
| 55 | + | ||
| 56 | + | pub fn red_bold(text: &str) -> Styled<'_> { | |
| 57 | + | Styled { | |
| 58 | + | text, | |
| 59 | + | codes: "1;31", | |
| 60 | + | } | |
| 61 | + | } | |
| 62 | + | ||
| 63 | + | pub fn yellow(text: &str) -> Styled<'_> { | |
| 64 | + | Styled { text, codes: "33" } | |
| 65 | + | } | |
| 66 | + | ||
| 67 | + | pub fn yellow_bold(text: &str) -> Styled<'_> { | |
| 68 | + | Styled { | |
| 69 | + | text, | |
| 70 | + | codes: "1;33", | |
| 71 | + | } | |
| 72 | + | } | |
| 73 | + | ||
| 74 | + | pub fn cyan(text: &str) -> Styled<'_> { | |
| 75 | + | Styled { text, codes: "36" } | |
| 76 | + | } | |
| 77 | + | ||
| 78 | + | pub fn cyan_bold(text: &str) -> Styled<'_> { | |
| 79 | + | Styled { | |
| 80 | + | text, | |
| 81 | + | codes: "1;36", | |
| 82 | + | } | |
| 83 | + | } | |
| 84 | + | ||
| 85 | + | pub fn blue(text: &str) -> Styled<'_> { | |
| 86 | + | Styled { text, codes: "34" } | |
| 87 | + | } | |
| 88 | + | ||
| 89 | + | pub fn magenta_bold(text: &str) -> Styled<'_> { | |
| 90 | + | Styled { | |
| 91 | + | text, | |
| 92 | + | codes: "1;35", | |
| 93 | + | } | |
| 94 | + | } |
| @@ -0,0 +1,24 @@ | |||
| 1 | + | [package] | |
| 2 | + | name = "roneo-core" | |
| 3 | + | version.workspace = true | |
| 4 | + | edition.workspace = true | |
| 5 | + | rust-version.workspace = true | |
| 6 | + | license.workspace = true | |
| 7 | + | repository.workspace = true | |
| 8 | + | keywords.workspace = true | |
| 9 | + | categories.workspace = true | |
| 10 | + | description = "Core template rendering, prompting, and 3-way update engine for Roneo (Rust port of Copier)" | |
| 11 | + | ||
| 12 | + | [lints] | |
| 13 | + | workspace = true | |
| 14 | + | ||
| 15 | + | [dependencies] | |
| 16 | + | gix.workspace = true | |
| 17 | + | indexmap.workspace = true | |
| 18 | + | minijinja.workspace = true | |
| 19 | + | minijinja-contrib.workspace = true | |
| 20 | + | rayon.workspace = true | |
| 21 | + | serde.workspace = true | |
| 22 | + | serde_json.workspace = true | |
| 23 | + | serde_yaml_ng.workspace = true | |
| 24 | + | wasmi.workspace = true |
| @@ -0,0 +1,153 @@ | |||
| 1 | + | use std::collections::HashSet; | |
| 2 | + | use std::fs; | |
| 3 | + | use std::path::{Path, PathBuf}; | |
| 4 | + | ||
| 5 | + | use indexmap::IndexMap; | |
| 6 | + | use serde_json::Value as JsonValue; | |
| 7 | + | ||
| 8 | + | use crate::config::{DEFAULT_ANSWERS_FILE, yaml_to_json}; | |
| 9 | + | use crate::error::{Result, RoneoError}; | |
| 10 | + | ||
| 11 | + | pub const ANSWERS_HEADER: &str = | |
| 12 | + | "# Changes here will be overwritten by Copier/Roneo; NEVER EDIT MANUALLY\n"; | |
| 13 | + | ||
| 14 | + | /// Represents answers collected from a user and/or loaded from `.copier-answers.yml`. | |
| 15 | + | #[derive(Debug, Clone, Default)] | |
| 16 | + | pub struct AnswersMap { | |
| 17 | + | /// User answers to asked questions (persisted to `.copier-answers.yml` unless secret). | |
| 18 | + | pub user: IndexMap<String, JsonValue>, | |
| 19 | + | /// Default values of skipped (`when: false`) questions: available in render context | |
| 20 | + | /// but NOT persisted to `.copier-answers.yml` (matching Copier's exact behavior). | |
| 21 | + | pub default_only: IndexMap<String, JsonValue>, | |
| 22 | + | /// Metadata keys (underscore-prefixed, notably `_commit` and `_src_path`). | |
| 23 | + | pub metadata: IndexMap<String, JsonValue>, | |
| 24 | + | /// Names of secret questions that must never be persisted to disk. | |
| 25 | + | pub secrets: HashSet<String>, | |
| 26 | + | } | |
| 27 | + | ||
| 28 | + | impl AnswersMap { | |
| 29 | + | pub fn load(path: &Path) -> Result<Self> { | |
| 30 | + | let raw = fs::read_to_string(path).map_err(|e| RoneoError::io(path, e))?; | |
| 31 | + | Self::parse_yaml(&raw) | |
| 32 | + | } | |
| 33 | + | ||
| 34 | + | pub fn parse_yaml(raw: &str) -> Result<Self> { | |
| 35 | + | if raw.trim().is_empty() { | |
| 36 | + | return Ok(Self::default()); | |
| 37 | + | } | |
| 38 | + | let yaml_val: serde_yaml_ng::Value = serde_yaml_ng::from_str(raw)?; | |
| 39 | + | let Some(mapping) = yaml_val.as_mapping() else { | |
| 40 | + | return Err(RoneoError::InvalidConfig( | |
| 41 | + | "Answers file must be a YAML mapping".into(), | |
| 42 | + | )); | |
| 43 | + | }; | |
| 44 | + | ||
| 45 | + | let mut answers = Self::default(); | |
| 46 | + | for (k, v) in mapping { | |
| 47 | + | let Some(key) = k.as_str() else { | |
| 48 | + | continue; | |
| 49 | + | }; | |
| 50 | + | let json_val = yaml_to_json(v)?; | |
| 51 | + | if key.starts_with('_') { | |
| 52 | + | answers.metadata.insert(key.to_string(), json_val); | |
| 53 | + | } else { | |
| 54 | + | answers.user.insert(key.to_string(), json_val); | |
| 55 | + | } | |
| 56 | + | } | |
| 57 | + | Ok(answers) | |
| 58 | + | } | |
| 59 | + | ||
| 60 | + | /// Locate an answers file inside `dst_dir` (checking `preferred` first, then `.copier-answers.yml`). | |
| 61 | + | pub fn find_in_dir(dst_dir: &Path, preferred: Option<&Path>) -> Option<PathBuf> { | |
| 62 | + | if let Some(p) = preferred { | |
| 63 | + | let candidate = if p.is_absolute() { | |
| 64 | + | p.to_path_buf() | |
| 65 | + | } else { | |
| 66 | + | dst_dir.join(p) | |
| 67 | + | }; | |
| 68 | + | if candidate.is_file() { | |
| 69 | + | return Some(candidate); | |
| 70 | + | } | |
| 71 | + | } | |
| 72 | + | ||
| 73 | + | let default = dst_dir.join(DEFAULT_ANSWERS_FILE); | |
| 74 | + | if default.is_file() { | |
| 75 | + | return Some(default); | |
| 76 | + | } | |
| 77 | + | ||
| 78 | + | // Also check `.copier-answers.yaml` as a convenient fallback. | |
| 79 | + | let alt = dst_dir.join(".copier-answers.yaml"); | |
| 80 | + | if alt.is_file() { | |
| 81 | + | return Some(alt); | |
| 82 | + | } | |
| 83 | + | ||
| 84 | + | None | |
| 85 | + | } | |
| 86 | + | ||
| 87 | + | pub fn src_path(&self) -> Option<&str> { | |
| 88 | + | self.metadata.get("_src_path").and_then(JsonValue::as_str) | |
| 89 | + | } | |
| 90 | + | ||
| 91 | + | pub fn commit(&self) -> Option<&str> { | |
| 92 | + | self.metadata.get("_commit").and_then(JsonValue::as_str) | |
| 93 | + | } | |
| 94 | + | ||
| 95 | + | pub fn set_src_path(&mut self, src_path: impl Into<String>) { | |
| 96 | + | self.metadata | |
| 97 | + | .insert("_src_path".into(), JsonValue::String(src_path.into())); | |
| 98 | + | } | |
| 99 | + | ||
| 100 | + | pub fn set_commit(&mut self, commit: impl Into<String>) { | |
| 101 | + | self.metadata | |
| 102 | + | .insert("_commit".into(), JsonValue::String(commit.into())); | |
| 103 | + | } | |
| 104 | + | ||
| 105 | + | /// Combine metadata + skipped-question defaults + user answers (including secrets) | |
| 106 | + | /// for template rendering context. | |
| 107 | + | pub fn combined(&self) -> IndexMap<String, JsonValue> { | |
| 108 | + | let mut out = self.metadata.clone(); | |
| 109 | + | for (k, v) in &self.default_only { | |
| 110 | + | out.insert(k.clone(), v.clone()); | |
| 111 | + | } | |
| 112 | + | for (k, v) in &self.user { | |
| 113 | + | out.insert(k.clone(), v.clone()); | |
| 114 | + | } | |
| 115 | + | out | |
| 116 | + | } | |
| 117 | + | ||
| 118 | + | /// Combine metadata + non-secret user answers for persisting to `.copier-answers.yml` | |
| 119 | + | /// and exposing as `_copier_answers` inside templates (sorted deterministically like Copier). | |
| 120 | + | pub fn persistable(&self) -> IndexMap<String, JsonValue> { | |
| 121 | + | let mut meta_entries: Vec<(&String, &JsonValue)> = self.metadata.iter().collect(); | |
| 122 | + | meta_entries.sort_unstable_by(|a, b| a.0.cmp(b.0)); | |
| 123 | + | ||
| 124 | + | let mut user_entries: Vec<(&String, &JsonValue)> = self | |
| 125 | + | .user | |
| 126 | + | .iter() | |
| 127 | + | .filter(|(k, _)| !self.secrets.contains(*k)) | |
| 128 | + | .collect(); | |
| 129 | + | user_entries.sort_unstable_by(|a, b| a.0.cmp(b.0)); | |
| 130 | + | ||
| 131 | + | let mut out = IndexMap::with_capacity(meta_entries.len() + user_entries.len()); | |
| 132 | + | for (k, v) in meta_entries.into_iter().chain(user_entries) { | |
| 133 | + | out.insert(k.clone(), v.clone()); | |
| 134 | + | } | |
| 135 | + | out | |
| 136 | + | } | |
| 137 | + | ||
| 138 | + | /// Render the answers file YAML string. | |
| 139 | + | pub fn to_yaml_string(&self) -> Result<String> { | |
| 140 | + | let map = self.persistable(); | |
| 141 | + | let yaml = serde_yaml_ng::to_string(&map)?; | |
| 142 | + | Ok(format!("{ANSWERS_HEADER}{yaml}")) | |
| 143 | + | } | |
| 144 | + | ||
| 145 | + | /// Save the answers file to disk. | |
| 146 | + | pub fn save(&self, path: &Path) -> Result<()> { | |
| 147 | + | if let Some(parent) = path.parent() { | |
| 148 | + | fs::create_dir_all(parent).map_err(|e| RoneoError::io(parent, e))?; | |
| 149 | + | } | |
| 150 | + | let content = self.to_yaml_string()?; | |
| 151 | + | fs::write(path, content).map_err(|e| RoneoError::io(path, e)) | |
| 152 | + | } | |
| 153 | + | } |
| @@ -0,0 +1,971 @@ | |||
| 1 | + | use std::fs; | |
| 2 | + | use std::path::{Path, PathBuf}; | |
| 3 | + | ||
| 4 | + | use indexmap::IndexMap; | |
| 5 | + | use serde::{Deserialize, Serialize}; | |
| 6 | + | use serde_yaml_ng::Value as YamlValue; | |
| 7 | + | ||
| 8 | + | use crate::error::{Result, RoneoError}; | |
| 9 | + | use crate::filter::match_glob_path; | |
| 10 | + | use crate::fs_util::walk_dir_sorted; | |
| 11 | + | ||
| 12 | + | /// List-valued settings that Copier merges (concatenates) across multi-document YAML & `!include`. | |
| 13 | + | const MERGE_LIST_KEYS: &[&str] = &[ | |
| 14 | + | "_exclude", | |
| 15 | + | "_skip_if_exists", | |
| 16 | + | "_secret_questions", | |
| 17 | + | "_jinja_extensions", | |
| 18 | + | "_roneo_plugins", | |
| 19 | + | "_tasks", | |
| 20 | + | "_migrations", | |
| 21 | + | ]; | |
| 22 | + | ||
| 23 | + | /// Candidate template configuration filenames in precedence order. | |
| 24 | + | pub const CONFIG_FILENAMES: &[&str] = &["roneo.yml", "roneo.yaml", "copier.yml", "copier.yaml"]; | |
| 25 | + | ||
| 26 | + | /// Default answers file name (100% Copier-compatible). | |
| 27 | + | pub const DEFAULT_ANSWERS_FILE: &str = ".copier-answers.yml"; | |
| 28 | + | ||
| 29 | + | /// Default template file suffix. | |
| 30 | + | pub const DEFAULT_TEMPLATES_SUFFIX: &str = ".jinja"; | |
| 31 | + | ||
| 32 | + | /// Default patterns always excluded unless negated with `!`. | |
| 33 | + | pub const DEFAULT_EXCLUDES: &[&str] = &[ | |
| 34 | + | "copier.yaml", | |
| 35 | + | "copier.yml", | |
| 36 | + | "roneo.yaml", | |
| 37 | + | "roneo.yml", | |
| 38 | + | "~*", | |
| 39 | + | "*.py[co]", | |
| 40 | + | "__pycache__", | |
| 41 | + | ".git", | |
| 42 | + | ".DS_Store", | |
| 43 | + | ".svn", | |
| 44 | + | ]; | |
| 45 | + | ||
| 46 | + | #[derive(Debug, Clone, Serialize, Deserialize)] | |
| 47 | + | pub struct TemplateConfig { | |
| 48 | + | pub settings: TemplateSettings, | |
| 49 | + | pub questions: IndexMap<String, Question>, | |
| 50 | + | pub config_path: Option<PathBuf>, | |
| 51 | + | } | |
| 52 | + | ||
| 53 | + | impl Default for TemplateConfig { | |
| 54 | + | fn default() -> Self { | |
| 55 | + | Self { | |
| 56 | + | settings: TemplateSettings::default(), | |
| 57 | + | questions: IndexMap::new(), | |
| 58 | + | config_path: None, | |
| 59 | + | } | |
| 60 | + | } | |
| 61 | + | } | |
| 62 | + | ||
| 63 | + | #[derive(Debug, Clone, Serialize, Deserialize)] | |
| 64 | + | pub struct TemplateSettings { | |
| 65 | + | pub subdirectory: Option<String>, | |
| 66 | + | pub answers_file: String, | |
| 67 | + | pub templates_suffix: String, | |
| 68 | + | pub exclude: Vec<String>, | |
| 69 | + | pub skip_if_exists: Vec<String>, | |
| 70 | + | pub preserve_symlinks: bool, | |
| 71 | + | pub secret_questions: Vec<String>, | |
| 72 | + | pub tasks: Vec<TaskSpec>, | |
| 73 | + | pub migrations: Vec<MigrationSpec>, | |
| 74 | + | pub envops: EnvOps, | |
| 75 | + | pub min_copier_version: Option<String>, | |
| 76 | + | pub message_before_copy: Option<String>, | |
| 77 | + | pub message_after_copy: Option<String>, | |
| 78 | + | pub message_before_update: Option<String>, | |
| 79 | + | pub message_after_update: Option<String>, | |
| 80 | + | pub jinja_extensions: Vec<String>, | |
| 81 | + | pub roneo_plugins: Vec<String>, | |
| 82 | + | pub external_data: IndexMap<String, String>, | |
| 83 | + | } | |
| 84 | + | ||
| 85 | + | impl Default for TemplateSettings { | |
| 86 | + | fn default() -> Self { | |
| 87 | + | Self { | |
| 88 | + | subdirectory: None, | |
| 89 | + | answers_file: DEFAULT_ANSWERS_FILE.to_string(), | |
| 90 | + | templates_suffix: DEFAULT_TEMPLATES_SUFFIX.to_string(), | |
| 91 | + | exclude: Vec::new(), | |
| 92 | + | skip_if_exists: Vec::new(), | |
| 93 | + | preserve_symlinks: false, | |
| 94 | + | secret_questions: Vec::new(), | |
| 95 | + | tasks: Vec::new(), | |
| 96 | + | migrations: Vec::new(), | |
| 97 | + | envops: EnvOps::default(), | |
| 98 | + | min_copier_version: None, | |
| 99 | + | message_before_copy: None, | |
| 100 | + | message_after_copy: None, | |
| 101 | + | message_before_update: None, | |
| 102 | + | message_after_update: None, | |
| 103 | + | jinja_extensions: Vec::new(), | |
| 104 | + | roneo_plugins: Vec::new(), | |
| 105 | + | external_data: IndexMap::new(), | |
| 106 | + | } | |
| 107 | + | } | |
| 108 | + | } | |
| 109 | + | ||
| 110 | + | #[derive(Debug, Clone, Serialize, Deserialize)] | |
| 111 | + | pub struct EnvOps { | |
| 112 | + | pub block_start_string: String, | |
| 113 | + | pub block_end_string: String, | |
| 114 | + | pub variable_start_string: String, | |
| 115 | + | pub variable_end_string: String, | |
| 116 | + | pub comment_start_string: String, | |
| 117 | + | pub comment_end_string: String, | |
| 118 | + | pub keep_trailing_newline: bool, | |
| 119 | + | pub trim_blocks: bool, | |
| 120 | + | pub lstrip_blocks: bool, | |
| 121 | + | } | |
| 122 | + | ||
| 123 | + | impl Default for EnvOps { | |
| 124 | + | fn default() -> Self { | |
| 125 | + | Self { | |
| 126 | + | block_start_string: "{%".to_string(), | |
| 127 | + | block_end_string: "%}".to_string(), | |
| 128 | + | variable_start_string: "{{".to_string(), | |
| 129 | + | variable_end_string: "}}".to_string(), | |
| 130 | + | comment_start_string: "{#".to_string(), | |
| 131 | + | comment_end_string: "#}".to_string(), | |
| 132 | + | keep_trailing_newline: true, | |
| 133 | + | trim_blocks: false, | |
| 134 | + | lstrip_blocks: false, | |
| 135 | + | } | |
| 136 | + | } | |
| 137 | + | } | |
| 138 | + | ||
| 139 | + | #[derive(Debug, Clone, Serialize, Deserialize)] | |
| 140 | + | pub enum CommandSpec { | |
| 141 | + | Shell(String), | |
| 142 | + | Args(Vec<String>), | |
| 143 | + | } | |
| 144 | + | ||
| 145 | + | #[derive(Debug, Clone, Serialize, Deserialize)] | |
| 146 | + | pub struct TaskSpec { | |
| 147 | + | pub command: CommandSpec, | |
| 148 | + | pub when: Option<String>, | |
| 149 | + | pub working_directory: Option<String>, | |
| 150 | + | #[serde(default)] | |
| 151 | + | pub extra_env: IndexMap<String, String>, | |
| 152 | + | } | |
| 153 | + | ||
| 154 | + | #[derive(Debug, Clone, Serialize, Deserialize)] | |
| 155 | + | pub struct MigrationSpec { | |
| 156 | + | pub version: Option<String>, | |
| 157 | + | pub before: Vec<TaskSpec>, | |
| 158 | + | pub after: Vec<TaskSpec>, | |
| 159 | + | pub command: Option<CommandSpec>, | |
| 160 | + | pub when: Option<String>, | |
| 161 | + | } | |
| 162 | + | ||
| 163 | + | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] | |
| 164 | + | #[serde(rename_all = "lowercase")] | |
| 165 | + | pub enum QuestionType { | |
| 166 | + | #[default] | |
| 167 | + | Str, | |
| 168 | + | Int, | |
| 169 | + | Float, | |
| 170 | + | Bool, | |
| 171 | + | Yaml, | |
| 172 | + | Json, | |
| 173 | + | } | |
| 174 | + | ||
| 175 | + | #[derive(Debug, Clone, Serialize, Deserialize)] | |
| 176 | + | pub struct ChoiceSpec { | |
| 177 | + | pub label: String, | |
| 178 | + | pub value: serde_json::Value, | |
| 179 | + | } | |
| 180 | + | ||
| 181 | + | #[derive(Debug, Clone, Serialize, Deserialize)] | |
| 182 | + | pub struct Question { | |
| 183 | + | pub name: String, | |
| 184 | + | pub kind: QuestionType, | |
| 185 | + | /// Optional Jinja template expression for dynamic `type:` (e.g. `"{% if flag %}int{% else %}str{% endif %}"`). | |
| 186 | + | pub type_template: Option<String>, | |
| 187 | + | pub help: Option<String>, | |
| 188 | + | pub default: Option<serde_json::Value>, | |
| 189 | + | pub choices: Option<Vec<ChoiceSpec>>, | |
| 190 | + | /// Optional Jinja template expression returning a YAML/JSON list or mapping for dynamic `choices:`. | |
| 191 | + | pub choices_template: Option<String>, | |
| 192 | + | pub validator: Option<String>, | |
| 193 | + | pub when: Option<serde_json::Value>, | |
| 194 | + | /// Optional opt-in prompt condition (`ask: false` or Jinja expr, Copier v9.19.0 `#2849`). | |
| 195 | + | pub ask: Option<serde_json::Value>, | |
| 196 | + | pub secret: bool, | |
| 197 | + | pub multiselect: bool, | |
| 198 | + | pub multiline: bool, | |
| 199 | + | /// Optional raw `multiline` specification (bool or Jinja template string; defaults to `true` for YAML/JSON). | |
| 200 | + | pub multiline_expr: Option<serde_json::Value>, | |
| 201 | + | pub placeholder: Option<String>, | |
| 202 | + | /// Optional custom question prefix mark (Copier `qmark`, e.g. `"🚀"`). | |
| 203 | + | pub qmark: Option<String>, | |
| 204 | + | } | |
| 205 | + | ||
| 206 | + | impl TemplateConfig { | |
| 207 | + | /// Locate and parse the template configuration inside `template_root`. | |
| 208 | + | /// If no config file is present, returns a default empty configuration (matching Copier). | |
| 209 | + | pub fn load_from_dir(template_root: &Path) -> Result<Self> { | |
| 210 | + | let mut found = None; | |
| 211 | + | for name in CONFIG_FILENAMES { | |
| 212 | + | let candidate = template_root.join(name); | |
| 213 | + | if candidate.is_file() { | |
| 214 | + | found = Some(candidate); | |
| 215 | + | break; | |
| 216 | + | } | |
| 217 | + | } | |
| 218 | + | ||
| 219 | + | let Some(config_path) = found else { | |
| 220 | + | return Ok(Self::default()); | |
| 221 | + | }; | |
| 222 | + | ||
| 223 | + | let raw = fs::read_to_string(&config_path).map_err(|e| RoneoError::io(&config_path, e))?; | |
| 224 | + | let mut cfg = Self::parse_str_with_base(&raw, Some(template_root))?; | |
| 225 | + | cfg.config_path = Some(config_path); | |
| 226 | + | Ok(cfg) | |
| 227 | + | } | |
| 228 | + | ||
| 229 | + | /// Locate and parse the template configuration using an abstract in-memory file reader | |
| 230 | + | /// (e.g. directly from a `gix` commit tree without extracting to disk). | |
| 231 | + | pub fn load_from_reader<F>(read_file: &F) -> Result<Self> | |
| 232 | + | where | |
| 233 | + | F: Fn(&str) -> Option<String>, | |
| 234 | + | { | |
| 235 | + | Self::load_from_reader_with_glob(read_file, &|_| Vec::new()) | |
| 236 | + | } | |
| 237 | + | ||
| 238 | + | /// Locate and parse the template configuration using an abstract file reader + glob expander. | |
| 239 | + | pub fn load_from_reader_with_glob<F, G>(read_file: &F, glob_files: &G) -> Result<Self> | |
| 240 | + | where | |
| 241 | + | F: Fn(&str) -> Option<String>, | |
| 242 | + | G: Fn(&str) -> Vec<String>, | |
| 243 | + | { | |
| 244 | + | for name in CONFIG_FILENAMES { | |
| 245 | + | if let Some(raw) = read_file(name) { | |
| 246 | + | let mut cfg = Self::parse_str_with_reader_and_glob(&raw, read_file, glob_files)?; | |
| 247 | + | cfg.config_path = Some(PathBuf::from(name)); | |
| 248 | + | return Ok(cfg); | |
| 249 | + | } | |
| 250 | + | } | |
| 251 | + | Ok(Self::default()) | |
| 252 | + | } | |
| 253 | + | ||
| 254 | + | /// Parse a Copier/Roneo YAML configuration string. | |
| 255 | + | pub fn parse_str(raw: &str) -> Result<Self> { | |
| 256 | + | Self::parse_str_with_base(raw, None) | |
| 257 | + | } | |
| 258 | + | ||
| 259 | + | /// Parse a Copier/Roneo YAML configuration string, resolving `!include <path>` directives | |
| 260 | + | /// (including glob patterns like `!include questions/*.yml`) relative to `base_dir`, | |
| 261 | + | /// rejecting any path or symlink escaping `base_dir` (Copier v9.17.2 security hardening). | |
| 262 | + | pub fn parse_str_with_base(raw: &str, base_dir: Option<&Path>) -> Result<Self> { | |
| 263 | + | let canon_base = base_dir.and_then(|b| fs::canonicalize(b).ok()); | |
| 264 | + | let reader = |rel: &str| -> Option<String> { | |
| 265 | + | let root = base_dir?; | |
| 266 | + | let candidate = root.join(rel); | |
| 267 | + | if let Some(ref base_canon) = canon_base { | |
| 268 | + | let cand_canon = fs::canonicalize(&candidate).ok()?; | |
| 269 | + | if !cand_canon.starts_with(base_canon) { | |
| 270 | + | return None; | |
| 271 | + | } | |
| 272 | + | } | |
| 273 | + | fs::read_to_string(candidate).ok() | |
| 274 | + | }; | |
| 275 | + | let globber = |pattern: &str| -> Vec<String> { | |
| 276 | + | let Some(root) = base_dir else { | |
| 277 | + | return Vec::new(); | |
| 278 | + | }; | |
| 279 | + | let mut matched = Vec::new(); | |
| 280 | + | let _ = walk_dir_sorted(root, false, |entry| { | |
| 281 | + | if !entry.is_dir && match_glob_path(pattern, &entry.rel_path) { | |
| 282 | + | if let Some(ref base_canon) = canon_base | |
| 283 | + | && let Ok(cand_canon) = fs::canonicalize(&entry.abs_path) | |
| 284 | + | && !cand_canon.starts_with(base_canon) | |
| 285 | + | { | |
| 286 | + | return Ok(true); | |
| 287 | + | } | |
| 288 | + | matched.push(entry.rel_path.to_string_lossy().replace('\\', "/")); | |
| 289 | + | } | |
| 290 | + | Ok(true) | |
| 291 | + | }); | |
| 292 | + | matched | |
| 293 | + | }; | |
| 294 | + | Self::parse_str_with_reader_and_glob(raw, &reader, &globber) | |
| 295 | + | } | |
| 296 | + | ||
| 297 | + | /// Parse a Copier/Roneo YAML configuration string, resolving `!include <path>` via `read_file`. | |
| 298 | + | pub fn parse_str_with_reader<F>(raw: &str, read_file: &F) -> Result<Self> | |
| 299 | + | where | |
| 300 | + | F: Fn(&str) -> Option<String>, | |
| 301 | + | { | |
| 302 | + | Self::parse_str_with_reader_and_glob(raw, read_file, &|_| Vec::new()) | |
| 303 | + | } | |
| 304 | + | ||
| 305 | + | /// Parse a Copier/Roneo YAML configuration string with both exact `!include` reading and glob expansion. | |
| 306 | + | pub fn parse_str_with_reader_and_glob<F, G>( | |
| 307 | + | raw: &str, | |
| 308 | + | read_file: &F, | |
| 309 | + | glob_files: &G, | |
| 310 | + | ) -> Result<Self> | |
| 311 | + | where | |
| 312 | + | F: Fn(&str) -> Option<String>, | |
| 313 | + | G: Fn(&str) -> Vec<String>, | |
| 314 | + | { | |
| 315 | + | let trimmed = raw.trim(); | |
| 316 | + | if trimmed.is_empty() { | |
| 317 | + | return Ok(Self::default()); | |
| 318 | + | } | |
| 319 | + | ||
| 320 | + | let mut merged: IndexMap<String, YamlValue> = IndexMap::new(); | |
| 321 | + | parse_yaml_docs_into(trimmed, read_file, glob_files, &mut merged, 0)?; | |
| 322 | + | ||
| 323 | + | let mut settings = TemplateSettings::default(); | |
| 324 | + | let mut questions = IndexMap::new(); | |
| 325 | + | ||
| 326 | + | for (key, value) in merged { | |
| 327 | + | if key.starts_with('_') { | |
| 328 | + | parse_setting(&key, &value, &mut settings)?; | |
| 329 | + | } else { | |
| 330 | + | let mut question = parse_question(&key, &value)?; | |
| 331 | + | if settings.secret_questions.contains(&key) { | |
| 332 | + | question.secret = true; | |
| 333 | + | } | |
| 334 | + | questions.insert(key, question); | |
| 335 | + | } | |
| 336 | + | } | |
| 337 | + | ||
| 338 | + | // Apply `_secret_questions` even if declared after the questions. | |
| 339 | + | for secret_name in &settings.secret_questions { | |
| 340 | + | if let Some(q) = questions.get_mut(secret_name) { | |
| 341 | + | q.secret = true; | |
| 342 | + | } | |
| 343 | + | } | |
| 344 | + | ||
| 345 | + | Ok(Self { | |
| 346 | + | settings, | |
| 347 | + | questions, | |
| 348 | + | config_path: None, | |
| 349 | + | }) | |
| 350 | + | } | |
| 351 | + | ||
| 352 | + | /// Returns whether this template requires `--trust` before running. | |
| 353 | + | pub fn requires_trust(&self) -> bool { | |
| 354 | + | !self.settings.tasks.is_empty() | |
| 355 | + | || !self.settings.migrations.is_empty() | |
| 356 | + | || !self.settings.jinja_extensions.is_empty() | |
| 357 | + | || !self.settings.roneo_plugins.is_empty() | |
| 358 | + | } | |
| 359 | + | } | |
| 360 | + | ||
| 361 | + | fn parse_yaml_docs_into<F, G>( | |
| 362 | + | raw: &str, | |
| 363 | + | read_file: &F, | |
| 364 | + | glob_files: &G, | |
| 365 | + | merged: &mut IndexMap<String, YamlValue>, | |
| 366 | + | depth: usize, | |
| 367 | + | ) -> Result<()> | |
| 368 | + | where | |
| 369 | + | F: Fn(&str) -> Option<String>, | |
| 370 | + | G: Fn(&str) -> Vec<String>, | |
| 371 | + | { | |
| 372 | + | if depth > 16 { | |
| 373 | + | return Err(RoneoError::InvalidConfig( | |
| 374 | + | "Maximum `!include` nesting depth exceeded".into(), | |
| 375 | + | )); | |
| 376 | + | } | |
| 377 | + | ||
| 378 | + | for doc in serde_yaml_ng::Deserializer::from_str(raw) { | |
| 379 | + | let value = YamlValue::deserialize(doc)?; | |
| 380 | + | if value.is_null() { | |
| 381 | + | continue; | |
| 382 | + | } | |
| 383 | + | // Handle Copier's `!include path/to/file.yml` and glob `!include questions/*.yml` YAML tags. | |
| 384 | + | if let YamlValue::Tagged(tagged) = &value | |
| 385 | + | && tagged.tag == "!include" | |
| 386 | + | && let Some(rel) = tagged.value.as_str() | |
| 387 | + | { | |
| 388 | + | let rel_path = Path::new(rel); | |
| 389 | + | if rel_path.is_absolute() | |
| 390 | + | || rel_path | |
| 391 | + | .components() | |
| 392 | + | .any(|c| matches!(c, std::path::Component::ParentDir)) | |
| 393 | + | { | |
| 394 | + | return Err(RoneoError::InvalidConfig(format!( | |
| 395 | + | "YAML `!include` path '{rel}' must stay inside the template root" | |
| 396 | + | ))); | |
| 397 | + | } | |
| 398 | + | if rel.contains(['*', '?', '[']) { | |
| 399 | + | let mut targets = glob_files(rel); | |
| 400 | + | targets.sort(); | |
| 401 | + | for target in targets { | |
| 402 | + | if let Some(include_raw) = read_file(&target) { | |
| 403 | + | parse_yaml_docs_into( | |
| 404 | + | &include_raw, | |
| 405 | + | read_file, | |
| 406 | + | glob_files, | |
| 407 | + | merged, | |
| 408 | + | depth + 1, | |
| 409 | + | )?; | |
| 410 | + | } | |
| 411 | + | } | |
| 412 | + | } else { | |
| 413 | + | let include_raw = read_file(rel).ok_or_else(|| { | |
| 414 | + | RoneoError::InvalidConfig(format!("Failed to read `!include {rel}`")) | |
| 415 | + | })?; | |
| 416 | + | parse_yaml_docs_into(&include_raw, read_file, glob_files, merged, depth + 1)?; | |
| 417 | + | } | |
| 418 | + | continue; | |
| 419 | + | } | |
| 420 | + | ||
| 421 | + | let mapping = value.as_mapping().ok_or_else(|| { | |
| 422 | + | RoneoError::InvalidConfig("Top-level configuration must be a YAML mapping".into()) | |
| 423 | + | })?; | |
| 424 | + | for (k, v) in mapping { | |
| 425 | + | let key = k.as_str().ok_or_else(|| { | |
| 426 | + | RoneoError::InvalidConfig("Top-level keys must be strings".into()) | |
| 427 | + | })?; | |
| 428 | + | // Concatenate Copier's list-valued settings across multi-doc YAML / `!include`. | |
| 429 | + | if MERGE_LIST_KEYS.contains(&key) | |
| 430 | + | && let Some(YamlValue::Sequence(existing)) = merged.get_mut(key) | |
| 431 | + | && let Some(incoming) = v.as_sequence() | |
| 432 | + | { | |
| 433 | + | existing.extend(incoming.iter().cloned()); | |
| 434 | + | continue; | |
| 435 | + | } | |
| 436 | + | merged.insert(key.to_string(), v.clone()); | |
| 437 | + | } | |
| 438 | + | } | |
| 439 | + | ||
| 440 | + | Ok(()) | |
| 441 | + | } | |
| 442 | + | ||
| 443 | + | fn parse_setting(key: &str, value: &YamlValue, settings: &mut TemplateSettings) -> Result<()> { | |
| 444 | + | match key { | |
| 445 | + | "_subdirectory" => { | |
| 446 | + | settings.subdirectory = yaml_to_opt_string(value, key)?; | |
| 447 | + | } | |
| 448 | + | "_answers_file" => { | |
| 449 | + | if let Some(s) = yaml_to_opt_string(value, key)? { | |
| 450 | + | settings.answers_file = s; | |
| 451 | + | } | |
| 452 | + | } | |
| 453 | + | "_templates_suffix" => { | |
| 454 | + | settings.templates_suffix = yaml_to_opt_string(value, key)?.unwrap_or_default(); | |
| 455 | + | } | |
| 456 | + | "_exclude" => { | |
| 457 | + | settings.exclude = yaml_to_string_list(value, key)?; | |
| 458 | + | } | |
| 459 | + | "_skip_if_exists" => { | |
| 460 | + | settings.skip_if_exists = yaml_to_string_list(value, key)?; | |
| 461 | + | } | |
| 462 | + | "_preserve_symlinks" => { | |
| 463 | + | settings.preserve_symlinks = value | |
| 464 | + | .as_bool() | |
| 465 | + | .ok_or_else(|| RoneoError::InvalidConfig(format!("'{key}' must be a boolean")))?; | |
| 466 | + | } | |
| 467 | + | "_secret_questions" => { | |
| 468 | + | settings.secret_questions = yaml_to_string_list(value, key)?; | |
| 469 | + | } | |
| 470 | + | "_tasks" => { | |
| 471 | + | settings.tasks = parse_task_list(value, key)?; | |
| 472 | + | } | |
| 473 | + | "_migrations" => { | |
| 474 | + | settings.migrations = parse_migrations(value)?; | |
| 475 | + | } | |
| 476 | + | "_envops" => { | |
| 477 | + | parse_envops(value, &mut settings.envops)?; | |
| 478 | + | } | |
| 479 | + | "_min_copier_version" => { | |
| 480 | + | settings.min_copier_version = yaml_to_opt_string(value, key)?; | |
| 481 | + | } | |
| 482 | + | "_message_before_copy" => { | |
| 483 | + | settings.message_before_copy = yaml_to_opt_string(value, key)?; | |
| 484 | + | } | |
| 485 | + | "_message_after_copy" => { | |
| 486 | + | settings.message_after_copy = yaml_to_opt_string(value, key)?; | |
| 487 | + | } | |
| 488 | + | "_message_before_update" => { | |
| 489 | + | settings.message_before_update = yaml_to_opt_string(value, key)?; | |
| 490 | + | } | |
| 491 | + | "_message_after_update" => { | |
| 492 | + | settings.message_after_update = yaml_to_opt_string(value, key)?; | |
| 493 | + | } | |
| 494 | + | "_jinja_extensions" => { | |
| 495 | + | settings.jinja_extensions = yaml_to_string_list(value, key)?; | |
| 496 | + | } | |
| 497 | + | "_roneo_plugins" => { | |
| 498 | + | settings.roneo_plugins = yaml_to_string_list(value, key)?; | |
| 499 | + | } | |
| 500 | + | "_external_data" => { | |
| 501 | + | if let Some(map) = value.as_mapping() { | |
| 502 | + | for (k, v) in map { | |
| 503 | + | if let (Some(name), Some(path_str)) = (k.as_str(), v.as_str()) { | |
| 504 | + | settings | |
| 505 | + | .external_data | |
| 506 | + | .insert(name.to_string(), path_str.to_string()); | |
| 507 | + | } | |
| 508 | + | } | |
| 509 | + | } else if !value.is_null() { | |
| 510 | + | return Err(RoneoError::InvalidConfig( | |
| 511 | + | "'_external_data' must be a mapping of key -> file path".into(), | |
| 512 | + | )); | |
| 513 | + | } | |
| 514 | + | } | |
| 515 | + | // Unknown `_` metadata keys (e.g. `_metadata`, `_external_data`) are preserved gracefully. | |
| 516 | + | _ => {} | |
| 517 | + | } | |
| 518 | + | Ok(()) | |
| 519 | + | } | |
| 520 | + | ||
| 521 | + | fn parse_envops(value: &YamlValue, envops: &mut EnvOps) -> Result<()> { | |
| 522 | + | let Some(map) = value.as_mapping() else { | |
| 523 | + | return Err(RoneoError::InvalidConfig( | |
| 524 | + | "'_envops' must be a mapping".into(), | |
| 525 | + | )); | |
| 526 | + | }; | |
| 527 | + | for (k, v) in map { | |
| 528 | + | let Some(key) = k.as_str() else { | |
| 529 | + | continue; | |
| 530 | + | }; | |
| 531 | + | match key { | |
| 532 | + | "block_start_string" => { | |
| 533 | + | if let Some(s) = v.as_str() { | |
| 534 | + | envops.block_start_string = s.to_string(); | |
| 535 | + | } | |
| 536 | + | } | |
| 537 | + | "block_end_string" => { | |
| 538 | + | if let Some(s) = v.as_str() { | |
| 539 | + | envops.block_end_string = s.to_string(); | |
| 540 | + | } | |
| 541 | + | } | |
| 542 | + | "variable_start_string" => { | |
| 543 | + | if let Some(s) = v.as_str() { | |
| 544 | + | envops.variable_start_string = s.to_string(); | |
| 545 | + | } | |
| 546 | + | } | |
| 547 | + | "variable_end_string" => { | |
| 548 | + | if let Some(s) = v.as_str() { | |
| 549 | + | envops.variable_end_string = s.to_string(); | |
| 550 | + | } | |
| 551 | + | } | |
| 552 | + | "comment_start_string" => { | |
| 553 | + | if let Some(s) = v.as_str() { | |
| 554 | + | envops.comment_start_string = s.to_string(); | |
| 555 | + | } | |
| 556 | + | } | |
| 557 | + | "comment_end_string" => { | |
| 558 | + | if let Some(s) = v.as_str() { | |
| 559 | + | envops.comment_end_string = s.to_string(); | |
| 560 | + | } | |
| 561 | + | } | |
| 562 | + | "keep_trailing_newline" => { | |
| 563 | + | if let Some(b) = v.as_bool() { | |
| 564 | + | envops.keep_trailing_newline = b; | |
| 565 | + | } | |
| 566 | + | } | |
| 567 | + | "trim_blocks" => { | |
| 568 | + | if let Some(b) = v.as_bool() { | |
| 569 | + | envops.trim_blocks = b; | |
| 570 | + | } | |
| 571 | + | } | |
| 572 | + | "lstrip_blocks" => { | |
| 573 | + | if let Some(b) = v.as_bool() { | |
| 574 | + | envops.lstrip_blocks = b; | |
| 575 | + | } | |
| 576 | + | } | |
| 577 | + | _ => {} | |
| 578 | + | } | |
| 579 | + | } | |
| 580 | + | Ok(()) | |
| 581 | + | } | |
| 582 | + | ||
| 583 | + | fn parse_task_list(value: &YamlValue, key: &str) -> Result<Vec<TaskSpec>> { | |
| 584 | + | if value.is_null() { | |
| 585 | + | return Ok(Vec::new()); | |
| 586 | + | } | |
| 587 | + | let seq = value | |
| 588 | + | .as_sequence() | |
| 589 | + | .ok_or_else(|| RoneoError::InvalidConfig(format!("'{key}' must be a list")))?; | |
| 590 | + | let mut tasks = Vec::with_capacity(seq.len()); | |
| 591 | + | for item in seq { | |
| 592 | + | tasks.push(parse_single_task(item, key)?); | |
| 593 | + | } | |
| 594 | + | Ok(tasks) | |
| 595 | + | } | |
| 596 | + | ||
| 597 | + | fn parse_single_task(item: &YamlValue, key: &str) -> Result<TaskSpec> { | |
| 598 | + | if let Some(cmd) = item.as_str() { | |
| 599 | + | return Ok(TaskSpec { | |
| 600 | + | command: CommandSpec::Shell(cmd.to_string()), | |
| 601 | + | when: None, | |
| 602 | + | working_directory: None, | |
| 603 | + | extra_env: IndexMap::new(), | |
| 604 | + | }); | |
| 605 | + | } | |
| 606 | + | if let Some(args) = item.as_sequence() { | |
| 607 | + | let parsed = args | |
| 608 | + | .iter() | |
| 609 | + | .map(|a| { | |
| 610 | + | a.as_str().map(ToOwned::to_owned).ok_or_else(|| { | |
| 611 | + | RoneoError::InvalidConfig(format!("Task argument in '{key}' must be a string")) | |
| 612 | + | }) | |
| 613 | + | }) | |
| 614 | + | .collect::<Result<Vec<_>>>()?; | |
| 615 | + | return Ok(TaskSpec { | |
| 616 | + | command: CommandSpec::Args(parsed), | |
| 617 | + | when: None, | |
| 618 | + | working_directory: None, | |
| 619 | + | extra_env: IndexMap::new(), | |
| 620 | + | }); | |
| 621 | + | } | |
| 622 | + | if let Some(map) = item.as_mapping() { | |
| 623 | + | let cmd_val = map | |
| 624 | + | .get(YamlValue::String("command".into())) | |
| 625 | + | .ok_or_else(|| { | |
| 626 | + | RoneoError::InvalidConfig(format!("Task mapping in '{key}' missing 'command'")) | |
| 627 | + | })?; | |
| 628 | + | let command = if let Some(s) = cmd_val.as_str() { | |
| 629 | + | CommandSpec::Shell(s.to_string()) | |
| 630 | + | } else if let Some(seq) = cmd_val.as_sequence() { | |
| 631 | + | CommandSpec::Args( | |
| 632 | + | seq.iter() | |
| 633 | + | .map(|v| { | |
| 634 | + | v.as_str().map(ToOwned::to_owned).ok_or_else(|| { | |
| 635 | + | RoneoError::InvalidConfig(format!( | |
| 636 | + | "Task 'command' sequence in '{key}' must contain strings" | |
| 637 | + | )) | |
| 638 | + | }) | |
| 639 | + | }) | |
| 640 | + | .collect::<Result<Vec<_>>>()?, | |
| 641 | + | ) | |
| 642 | + | } else { | |
| 643 | + | return Err(RoneoError::InvalidConfig(format!( | |
| 644 | + | "Task 'command' in '{key}' must be string or list of strings" | |
| 645 | + | ))); | |
| 646 | + | }; | |
| 647 | + | ||
| 648 | + | let when = map | |
| 649 | + | .get(YamlValue::String("when".into())) | |
| 650 | + | .and_then(yaml_scalar_to_string); | |
| 651 | + | let working_directory = map | |
| 652 | + | .get(YamlValue::String("working_directory".into())) | |
| 653 | + | .and_then(|v| v.as_str().map(ToOwned::to_owned)); | |
| 654 | + | let mut extra_env = IndexMap::new(); | |
| 655 | + | if let Some(env_map) = map | |
| 656 | + | .get(YamlValue::String("extra_env".into())) | |
| 657 | + | .and_then(YamlValue::as_mapping) | |
| 658 | + | { | |
| 659 | + | for (ek, ev) in env_map { | |
| 660 | + | if let (Some(k_str), Some(v_str)) = (ek.as_str(), yaml_scalar_to_string(ev)) { | |
| 661 | + | extra_env.insert(k_str.to_string(), v_str); | |
| 662 | + | } | |
| 663 | + | } | |
| 664 | + | } | |
| 665 | + | ||
| 666 | + | return Ok(TaskSpec { | |
| 667 | + | command, | |
| 668 | + | when, | |
| 669 | + | working_directory, | |
| 670 | + | extra_env, | |
| 671 | + | }); | |
| 672 | + | } | |
| 673 | + | ||
| 674 | + | Err(RoneoError::InvalidConfig(format!( | |
| 675 | + | "Unsupported task definition in '{key}'" | |
| 676 | + | ))) | |
| 677 | + | } | |
| 678 | + | ||
| 679 | + | fn parse_migrations(value: &YamlValue) -> Result<Vec<MigrationSpec>> { | |
| 680 | + | if value.is_null() { | |
| 681 | + | return Ok(Vec::new()); | |
| 682 | + | } | |
| 683 | + | let seq = value | |
| 684 | + | .as_sequence() | |
| 685 | + | .ok_or_else(|| RoneoError::InvalidConfig("'_migrations' must be a list".into()))?; | |
| 686 | + | let mut migrations = Vec::with_capacity(seq.len()); | |
| 687 | + | for item in seq { | |
| 688 | + | let map = item.as_mapping().ok_or_else(|| { | |
| 689 | + | RoneoError::InvalidConfig("Each entry in '_migrations' must be a mapping".into()) | |
| 690 | + | })?; | |
| 691 | + | let version = map | |
| 692 | + | .get(YamlValue::String("version".into())) | |
| 693 | + | .and_then(yaml_scalar_to_string); | |
| 694 | + | let before = map | |
| 695 | + | .get(YamlValue::String("before".into())) | |
| 696 | + | .map(|v| parse_task_list(v, "_migrations.before")) | |
| 697 | + | .transpose()? | |
| 698 | + | .unwrap_or_default(); | |
| 699 | + | let after = map | |
| 700 | + | .get(YamlValue::String("after".into())) | |
| 701 | + | .map(|v| parse_task_list(v, "_migrations.after")) | |
| 702 | + | .transpose()? | |
| 703 | + | .unwrap_or_default(); | |
| 704 | + | let command = map | |
| 705 | + | .get(YamlValue::String("command".into())) | |
| 706 | + | .map(|v| parse_single_task(v, "_migrations.command").map(|t| t.command)) | |
| 707 | + | .transpose()?; | |
| 708 | + | let when = map | |
| 709 | + | .get(YamlValue::String("when".into())) | |
| 710 | + | .and_then(yaml_scalar_to_string); | |
| 711 | + | ||
| 712 | + | migrations.push(MigrationSpec { | |
| 713 | + | version, | |
| 714 | + | before, | |
| 715 | + | after, | |
| 716 | + | command, | |
| 717 | + | when, | |
| 718 | + | }); | |
| 719 | + | } | |
| 720 | + | Ok(migrations) | |
| 721 | + | } | |
| 722 | + | ||
| 723 | + | fn parse_question(name: &str, value: &YamlValue) -> Result<Question> { | |
| 724 | + | if let Some(map) = value.as_mapping() { | |
| 725 | + | let default = map | |
| 726 | + | .get(YamlValue::String("default".into())) | |
| 727 | + | .map(yaml_to_json) | |
| 728 | + | .transpose()?; | |
| 729 | + | ||
| 730 | + | let (kind, type_template) = | |
| 731 | + | if let Some(type_val) = map.get(YamlValue::String("type".into())) { | |
| 732 | + | let raw_type = type_val.as_str().ok_or_else(|| { | |
| 733 | + | RoneoError::InvalidConfig(format!("Question '{name}' 'type' must be a string")) | |
| 734 | + | })?; | |
| 735 | + | if raw_type.contains("{{") || raw_type.contains("{%") { | |
| 736 | + | (QuestionType::Str, Some(raw_type.to_string())) | |
| 737 | + | } else { | |
| 738 | + | (parse_question_type(raw_type)?, None) | |
| 739 | + | } | |
| 740 | + | } else if let Some(def) = &default { | |
| 741 | + | (infer_type_from_json(def), None) | |
| 742 | + | } else { | |
| 743 | + | (QuestionType::Str, None) | |
| 744 | + | }; | |
| 745 | + | ||
| 746 | + | let help = map | |
| 747 | + | .get(YamlValue::String("help".into())) | |
| 748 | + | .and_then(|v| v.as_str().map(ToOwned::to_owned)); | |
| 749 | + | let validator = map | |
| 750 | + | .get(YamlValue::String("validator".into())) | |
| 751 | + | .and_then(|v| v.as_str().map(ToOwned::to_owned)); | |
| 752 | + | let when = map | |
| 753 | + | .get(YamlValue::String("when".into())) | |
| 754 | + | .map(yaml_to_json) | |
| 755 | + | .transpose()?; | |
| 756 | + | let ask = map | |
| 757 | + | .get(YamlValue::String("ask".into())) | |
| 758 | + | .map(yaml_to_json) | |
| 759 | + | .transpose()?; | |
| 760 | + | let secret = map | |
| 761 | + | .get(YamlValue::String("secret".into())) | |
| 762 | + | .and_then(YamlValue::as_bool) | |
| 763 | + | .unwrap_or(false); | |
| 764 | + | let multiselect = map | |
| 765 | + | .get(YamlValue::String("multiselect".into())) | |
| 766 | + | .and_then(YamlValue::as_bool) | |
| 767 | + | .unwrap_or(false); | |
| 768 | + | let multiline_expr = map | |
| 769 | + | .get(YamlValue::String("multiline".into())) | |
| 770 | + | .map(yaml_to_json) | |
| 771 | + | .transpose()?; | |
| 772 | + | let multiline = multiline_expr.as_ref().map_or( | |
| 773 | + | matches!(kind, QuestionType::Yaml | QuestionType::Json), | |
| 774 | + | |v| v.as_bool().unwrap_or(false), | |
| 775 | + | ); | |
| 776 | + | let placeholder = map | |
| 777 | + | .get(YamlValue::String("placeholder".into())) | |
| 778 | + | .and_then(|v| v.as_str().map(ToOwned::to_owned)); | |
| 779 | + | let qmark = map | |
| 780 | + | .get(YamlValue::String("qmark".into())) | |
| 781 | + | .and_then(|v| v.as_str().map(ToOwned::to_owned)); | |
| 782 | + | let (choices, choices_template) = | |
| 783 | + | if let Some(ch_val) = map.get(YamlValue::String("choices".into())) { | |
| 784 | + | if let Some(tpl) = ch_val.as_str() { | |
| 785 | + | (None, Some(tpl.to_string())) | |
| 786 | + | } else { | |
| 787 | + | (Some(parse_choices(name, ch_val)?), None) | |
| 788 | + | } | |
| 789 | + | } else { | |
| 790 | + | (None, None) | |
| 791 | + | }; | |
| 792 | + | ||
| 793 | + | Ok(Question { | |
| 794 | + | name: name.to_string(), | |
| 795 | + | kind, | |
| 796 | + | type_template, | |
| 797 | + | help, | |
| 798 | + | default, | |
| 799 | + | choices, | |
| 800 | + | choices_template, | |
| 801 | + | validator, | |
| 802 | + | when, | |
| 803 | + | ask, | |
| 804 | + | secret, | |
| 805 | + | multiselect, | |
| 806 | + | multiline, | |
| 807 | + | multiline_expr, | |
| 808 | + | placeholder, | |
| 809 | + | qmark, | |
| 810 | + | }) | |
| 811 | + | } else { | |
| 812 | + | // Short-form question: `project_name: my-project` | |
| 813 | + | let default = yaml_to_json(value)?; | |
| 814 | + | let kind = infer_type_from_json(&default); | |
| 815 | + | Ok(Question { | |
| 816 | + | name: name.to_string(), | |
| 817 | + | kind, | |
| 818 | + | type_template: None, | |
| 819 | + | help: None, | |
| 820 | + | default: Some(default), | |
| 821 | + | choices: None, | |
| 822 | + | choices_template: None, | |
| 823 | + | validator: None, | |
| 824 | + | when: None, | |
| 825 | + | ask: None, | |
| 826 | + | secret: false, | |
| 827 | + | multiselect: false, | |
| 828 | + | multiline: matches!(kind, QuestionType::Yaml | QuestionType::Json), | |
| 829 | + | multiline_expr: None, | |
| 830 | + | placeholder: None, | |
| 831 | + | qmark: None, | |
| 832 | + | }) | |
| 833 | + | } | |
| 834 | + | } | |
| 835 | + | ||
| 836 | + | pub fn parse_question_type(raw: &str) -> Result<QuestionType> { | |
| 837 | + | match raw.trim() { | |
| 838 | + | "str" | "string" => Ok(QuestionType::Str), | |
| 839 | + | "int" | "integer" => Ok(QuestionType::Int), | |
| 840 | + | "float" | "number" => Ok(QuestionType::Float), | |
| 841 | + | "bool" | "boolean" => Ok(QuestionType::Bool), | |
| 842 | + | "yaml" => Ok(QuestionType::Yaml), | |
| 843 | + | "json" => Ok(QuestionType::Json), | |
| 844 | + | other => Err(RoneoError::InvalidConfig(format!( | |
| 845 | + | "Unsupported question type '{other}'" | |
| 846 | + | ))), | |
| 847 | + | } | |
| 848 | + | } | |
| 849 | + | ||
| 850 | + | fn infer_type_from_json(val: &serde_json::Value) -> QuestionType { | |
| 851 | + | match val { | |
| 852 | + | serde_json::Value::Bool(_) => QuestionType::Bool, | |
| 853 | + | serde_json::Value::Number(n) => { | |
| 854 | + | if n.is_i64() || n.is_u64() { | |
| 855 | + | QuestionType::Int | |
| 856 | + | } else { | |
| 857 | + | QuestionType::Float | |
| 858 | + | } | |
| 859 | + | } | |
| 860 | + | serde_json::Value::Array(_) | serde_json::Value::Object(_) => QuestionType::Yaml, | |
| 861 | + | serde_json::Value::String(_) | serde_json::Value::Null => QuestionType::Str, | |
| 862 | + | } | |
| 863 | + | } | |
| 864 | + | ||
| 865 | + | pub fn parse_choices(name: &str, value: &YamlValue) -> Result<Vec<ChoiceSpec>> { | |
| 866 | + | if let Some(seq) = value.as_sequence() { | |
| 867 | + | let mut choices = Vec::with_capacity(seq.len()); | |
| 868 | + | for item in seq { | |
| 869 | + | if let Some(pair) = item.as_sequence() | |
| 870 | + | && pair.len() == 2 | |
| 871 | + | { | |
| 872 | + | let label = yaml_scalar_to_string(&pair[0]).unwrap_or_default(); | |
| 873 | + | let val = yaml_to_json(&pair[1])?; | |
| 874 | + | choices.push(ChoiceSpec { label, value: val }); | |
| 875 | + | continue; | |
| 876 | + | } | |
| 877 | + | let val = yaml_to_json(item)?; | |
| 878 | + | let label = json_display(&val); | |
| 879 | + | choices.push(ChoiceSpec { label, value: val }); | |
| 880 | + | } | |
| 881 | + | Ok(choices) | |
| 882 | + | } else if let Some(map) = value.as_mapping() { | |
| 883 | + | let mut choices = Vec::with_capacity(map.len()); | |
| 884 | + | for (k, v) in map { | |
| 885 | + | let label = yaml_scalar_to_string(k).unwrap_or_default(); | |
| 886 | + | let val = yaml_to_json(v)?; | |
| 887 | + | choices.push(ChoiceSpec { label, value: val }); | |
| 888 | + | } | |
| 889 | + | Ok(choices) | |
| 890 | + | } else { | |
| 891 | + | Err(RoneoError::InvalidConfig(format!( | |
| 892 | + | "Question '{name}' 'choices' must be a list or mapping" | |
| 893 | + | ))) | |
| 894 | + | } | |
| 895 | + | } | |
| 896 | + | ||
| 897 | + | pub fn yaml_to_json(value: &YamlValue) -> Result<serde_json::Value> { | |
| 898 | + | Ok(serde_json::to_value(value)?) | |
| 899 | + | } | |
| 900 | + | ||
| 901 | + | pub fn json_display(value: &serde_json::Value) -> String { | |
| 902 | + | match value { | |
| 903 | + | serde_json::Value::String(s) => s.clone(), | |
| 904 | + | serde_json::Value::Bool(b) => b.to_string(), | |
| 905 | + | serde_json::Value::Number(n) => n.to_string(), | |
| 906 | + | serde_json::Value::Null => String::new(), | |
| 907 | + | other => other.to_string(), | |
| 908 | + | } | |
| 909 | + | } | |
| 910 | + | ||
| 911 | + | fn yaml_scalar_to_string(v: &YamlValue) -> Option<String> { | |
| 912 | + | match v { | |
| 913 | + | YamlValue::String(s) => Some(s.clone()), | |
| 914 | + | YamlValue::Bool(b) => Some(b.to_string()), | |
| 915 | + | YamlValue::Number(n) => Some(n.to_string()), | |
| 916 | + | _ => None, | |
| 917 | + | } | |
| 918 | + | } | |
| 919 | + | ||
| 920 | + | fn yaml_to_opt_string(value: &YamlValue, key: &str) -> Result<Option<String>> { | |
| 921 | + | if value.is_null() { | |
| 922 | + | return Ok(None); | |
| 923 | + | } | |
| 924 | + | value | |
| 925 | + | .as_str() | |
| 926 | + | .map(|s| Some(s.to_string())) | |
| 927 | + | .ok_or_else(|| RoneoError::InvalidConfig(format!("'{key}' must be a string"))) | |
| 928 | + | } | |
| 929 | + | ||
| 930 | + | fn yaml_to_string_list(value: &YamlValue, key: &str) -> Result<Vec<String>> { | |
| 931 | + | if value.is_null() { | |
| 932 | + | return Ok(Vec::new()); | |
| 933 | + | } | |
| 934 | + | let seq = value | |
| 935 | + | .as_sequence() | |
| 936 | + | .ok_or_else(|| RoneoError::InvalidConfig(format!("'{key}' must be a list of strings")))?; | |
| 937 | + | seq.iter() | |
| 938 | + | .map(|item| { | |
| 939 | + | item.as_str().map(ToOwned::to_owned).ok_or_else(|| { | |
| 940 | + | RoneoError::InvalidConfig(format!("Items in '{key}' must be strings")) | |
| 941 | + | }) | |
| 942 | + | }) | |
| 943 | + | .collect() | |
| 944 | + | } | |
| 945 | + | ||
| 946 | + | /// Parse a YAML/JSON document expected to be a key/value mapping (e.g. `--data-file`). | |
| 947 | + | pub fn parse_yaml_mapping(raw: &str) -> Result<IndexMap<String, serde_json::Value>> { | |
| 948 | + | let yaml_val: YamlValue = serde_yaml_ng::from_str(raw)?; | |
| 949 | + | let Some(map) = yaml_val.as_mapping() else { | |
| 950 | + | return Err(RoneoError::InvalidConfig( | |
| 951 | + | "Expected a YAML/JSON mapping".into(), | |
| 952 | + | )); | |
| 953 | + | }; | |
| 954 | + | let mut out = IndexMap::with_capacity(map.len()); | |
| 955 | + | for (k, v) in map { | |
| 956 | + | if let Some(key) = k.as_str() { | |
| 957 | + | out.insert(key.to_string(), yaml_to_json(v)?); | |
| 958 | + | } | |
| 959 | + | } | |
| 960 | + | Ok(out) | |
| 961 | + | } | |
| 962 | + | ||
| 963 | + | /// Parse a single CLI `--data KEY=VALUE` scalar/collection as YAML, falling back to a plain string. | |
| 964 | + | pub fn parse_yaml_cli_value(raw: &str) -> serde_json::Value { | |
| 965 | + | if let Ok(yaml_val) = serde_yaml_ng::from_str::<YamlValue>(raw) | |
| 966 | + | && let Ok(json_val) = yaml_to_json(&yaml_val) | |
| 967 | + | { | |
| 968 | + | return json_val; | |
| 969 | + | } | |
| 970 | + | serde_json::Value::String(raw.to_string()) | |
| 971 | + | } |
| @@ -0,0 +1,154 @@ | |||
| 1 | + | use std::fmt; | |
| 2 | + | use std::path::PathBuf; | |
| 3 | + | ||
| 4 | + | pub type Result<T> = std::result::Result<T, RoneoError>; | |
| 5 | + | ||
| 6 | + | #[derive(Debug)] | |
| 7 | + | #[non_exhaustive] | |
| 8 | + | pub enum RoneoError { | |
| 9 | + | Io { | |
| 10 | + | path: Option<PathBuf>, | |
| 11 | + | source: std::io::Error, | |
| 12 | + | }, | |
| 13 | + | Yaml(serde_yaml_ng::Error), | |
| 14 | + | Json(serde_json::Error), | |
| 15 | + | TemplateRender { | |
| 16 | + | context: String, | |
| 17 | + | source: minijinja::Error, | |
| 18 | + | }, | |
| 19 | + | InvalidConfig(String), | |
| 20 | + | IncompatibleCopierVersion { | |
| 21 | + | required: String, | |
| 22 | + | supported: String, | |
| 23 | + | }, | |
| 24 | + | DowngradeNotSupported { | |
| 25 | + | from: String, | |
| 26 | + | to: String, | |
| 27 | + | }, | |
| 28 | + | InvalidAnswer { | |
| 29 | + | question: String, | |
| 30 | + | message: String, | |
| 31 | + | }, | |
| 32 | + | TemplateSource(String), | |
| 33 | + | Vcs(String), | |
| 34 | + | DirtyDestination(PathBuf), | |
| 35 | + | NotAGitRepo(PathBuf), | |
| 36 | + | MissingAnswersFile(PathBuf), | |
| 37 | + | UnsafeTemplate(String), | |
| 38 | + | TaskFailed { | |
| 39 | + | command: String, | |
| 40 | + | status: Option<i32>, | |
| 41 | + | stderr: String, | |
| 42 | + | }, | |
| 43 | + | Conflict(String), | |
| 44 | + | Plugin(String), | |
| 45 | + | UserAborted, | |
| 46 | + | } | |
| 47 | + | ||
| 48 | + | impl RoneoError { | |
| 49 | + | pub fn io(path: impl Into<PathBuf>, source: std::io::Error) -> Self { | |
| 50 | + | Self::Io { | |
| 51 | + | path: Some(path.into()), | |
| 52 | + | source, | |
| 53 | + | } | |
| 54 | + | } | |
| 55 | + | } | |
| 56 | + | ||
| 57 | + | impl fmt::Display for RoneoError { | |
| 58 | + | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
| 59 | + | match self { | |
| 60 | + | Self::Io { | |
| 61 | + | path: Some(p), | |
| 62 | + | source, | |
| 63 | + | } => write!(f, "I/O error at {}: {source}", p.display()), | |
| 64 | + | Self::Io { path: None, source } => write!(f, "I/O error: {source}"), | |
| 65 | + | Self::Yaml(e) => write!(f, "YAML error: {e}"), | |
| 66 | + | Self::Json(e) => write!(f, "JSON error: {e}"), | |
| 67 | + | Self::TemplateRender { context, source } => { | |
| 68 | + | write!(f, "Template rendering error ({context}): {source}") | |
| 69 | + | } | |
| 70 | + | Self::InvalidConfig(msg) => write!(f, "Invalid template configuration: {msg}"), | |
| 71 | + | Self::IncompatibleCopierVersion { | |
| 72 | + | required, | |
| 73 | + | supported, | |
| 74 | + | } => write!( | |
| 75 | + | f, | |
| 76 | + | "Template requires Copier >= {required}, but Roneo targets Copier {supported} compatibility" | |
| 77 | + | ), | |
| 78 | + | Self::DowngradeNotSupported { from, to } => write!( | |
| 79 | + | f, | |
| 80 | + | "Cannot downgrade template from '{from}' to '{to}' during `update` (downgrades are not supported; use `recopy` instead)" | |
| 81 | + | ), | |
| 82 | + | Self::InvalidAnswer { question, message } => { | |
| 83 | + | write!(f, "Invalid answer for '{question}': {message}") | |
| 84 | + | } | |
| 85 | + | Self::TemplateSource(msg) => write!(f, "Template source error: {msg}"), | |
| 86 | + | Self::Vcs(msg) => write!(f, "Git error: {msg}"), | |
| 87 | + | Self::DirtyDestination(p) => write!( | |
| 88 | + | f, | |
| 89 | + | "Destination repository '{}' has uncommitted changes. Commit or stash them before running `update`.", | |
| 90 | + | p.display() | |
| 91 | + | ), | |
| 92 | + | Self::NotAGitRepo(p) => write!( | |
| 93 | + | f, | |
| 94 | + | "Destination '{}' is not a git repository. Smart `update` requires git; use `recopy` instead.", | |
| 95 | + | p.display() | |
| 96 | + | ), | |
| 97 | + | Self::MissingAnswersFile(p) => write!( | |
| 98 | + | f, | |
| 99 | + | "No answers file found in '{}'. Cannot update or recopy without an existing answers file.", | |
| 100 | + | p.display() | |
| 101 | + | ), | |
| 102 | + | Self::UnsafeTemplate(msg) => write!( | |
| 103 | + | f, | |
| 104 | + | "Unsafe template: {msg}. Re-run with `--trust` if you trust this template." | |
| 105 | + | ), | |
| 106 | + | Self::TaskFailed { | |
| 107 | + | command, | |
| 108 | + | status: Some(code), | |
| 109 | + | stderr, | |
| 110 | + | } => write!( | |
| 111 | + | f, | |
| 112 | + | "Task failed (`{command}`) with exit code {code}: {stderr}" | |
| 113 | + | ), | |
| 114 | + | Self::TaskFailed { | |
| 115 | + | command, | |
| 116 | + | status: None, | |
| 117 | + | stderr, | |
| 118 | + | } => write!(f, "Task failed (`{command}`): {stderr}"), | |
| 119 | + | Self::Conflict(msg) => write!(f, "Merge conflict while updating: {msg}"), | |
| 120 | + | Self::Plugin(msg) => write!(f, "Plugin error: {msg}"), | |
| 121 | + | Self::UserAborted => f.write_str("Operation aborted by user"), | |
| 122 | + | } | |
| 123 | + | } | |
| 124 | + | } | |
| 125 | + | ||
| 126 | + | impl std::error::Error for RoneoError { | |
| 127 | + | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { | |
| 128 | + | match self { | |
| 129 | + | Self::Io { source, .. } => Some(source), | |
| 130 | + | Self::Yaml(e) => Some(e), | |
| 131 | + | Self::Json(e) => Some(e), | |
| 132 | + | Self::TemplateRender { source, .. } => Some(source), | |
| 133 | + | _ => None, | |
| 134 | + | } | |
| 135 | + | } | |
| 136 | + | } | |
| 137 | + | ||
| 138 | + | impl From<std::io::Error> for RoneoError { | |
| 139 | + | fn from(source: std::io::Error) -> Self { | |
| 140 | + | Self::Io { path: None, source } | |
| 141 | + | } | |
| 142 | + | } | |
| 143 | + | ||
| 144 | + | impl From<serde_yaml_ng::Error> for RoneoError { | |
| 145 | + | fn from(e: serde_yaml_ng::Error) -> Self { | |
| 146 | + | Self::Yaml(e) | |
| 147 | + | } | |
| 148 | + | } | |
| 149 | + | ||
| 150 | + | impl From<serde_json::Error> for RoneoError { | |
| 151 | + | fn from(e: serde_json::Error) -> Self { | |
| 152 | + | Self::Json(e) | |
| 153 | + | } | |
| 154 | + | } |
| @@ -0,0 +1,485 @@ | |||
| 1 | + | use std::borrow::Cow; | |
| 2 | + | use std::path::Path; | |
| 3 | + | ||
| 4 | + | use crate::config::DEFAULT_EXCLUDES; | |
| 5 | + | use crate::error::Result; | |
| 6 | + | ||
| 7 | + | /// Fast, zero-dependency gitignore-style path matcher (matching Copier's `pathspec` rules). | |
| 8 | + | /// | |
| 9 | + | /// Supports `*`, `**`, `?`, `[abc]` / `[!a-z]` character classes, `!negation`, leading `/` | |
| 10 | + | /// anchoring, trailing `/` directory-only matching, and parent-directory matching — without | |
| 11 | + | /// compiling heavy regex automatons or allocating per match. | |
| 12 | + | #[derive(Debug, Clone)] | |
| 13 | + | pub struct PathFilter { | |
| 14 | + | excludes: RuleSet, | |
| 15 | + | skip_if_exists: RuleSet, | |
| 16 | + | } | |
| 17 | + | ||
| 18 | + | #[derive(Debug, Clone)] | |
| 19 | + | struct RuleSet { | |
| 20 | + | rules: Vec<GlobRule>, | |
| 21 | + | has_negation: bool, | |
| 22 | + | } | |
| 23 | + | ||
| 24 | + | #[derive(Debug, Clone)] | |
| 25 | + | enum SegmentMatcher { | |
| 26 | + | /// `**` — matches zero or more path segments. | |
| 27 | + | GlobStar, | |
| 28 | + | /// Exact literal match (no wildcards) — simple byte equality. | |
| 29 | + | Literal(String), | |
| 30 | + | /// `*.ext` — simple suffix check. | |
| 31 | + | Suffix(String), | |
| 32 | + | /// `prefix*` — simple prefix check. | |
| 33 | + | Prefix(String), | |
| 34 | + | /// General wildcard pattern (`*`, `?`, `[...]`). | |
| 35 | + | Wildcard(String), | |
| 36 | + | } | |
| 37 | + | ||
| 38 | + | impl SegmentMatcher { | |
| 39 | + | fn compile(seg: &str) -> Self { | |
| 40 | + | if seg == "**" { | |
| 41 | + | return Self::GlobStar; | |
| 42 | + | } | |
| 43 | + | if !seg.contains(['*', '?', '[']) { | |
| 44 | + | return Self::Literal(seg.to_string()); | |
| 45 | + | } | |
| 46 | + | if let Some(suffix) = seg.strip_prefix('*') | |
| 47 | + | && !suffix.contains(['*', '?', '[']) | |
| 48 | + | { | |
| 49 | + | return Self::Suffix(suffix.to_string()); | |
| 50 | + | } | |
| 51 | + | if let Some(prefix) = seg.strip_suffix('*') | |
| 52 | + | && !prefix.contains(['*', '?', '[']) | |
| 53 | + | { | |
| 54 | + | return Self::Prefix(prefix.to_string()); | |
| 55 | + | } | |
| 56 | + | Self::Wildcard(seg.to_string()) | |
| 57 | + | } | |
| 58 | + | ||
| 59 | + | #[inline] | |
| 60 | + | fn matches(&self, text: &str) -> bool { | |
| 61 | + | match self { | |
| 62 | + | Self::GlobStar => true, | |
| 63 | + | Self::Literal(lit) => text == lit, | |
| 64 | + | Self::Suffix(suf) => text.ends_with(suf.as_str()), | |
| 65 | + | Self::Prefix(pre) => text.starts_with(pre.as_str()), | |
| 66 | + | Self::Wildcard(pat) => glob_match(pat, text), | |
| 67 | + | } | |
| 68 | + | } | |
| 69 | + | } | |
| 70 | + | ||
| 71 | + | #[derive(Debug, Clone)] | |
| 72 | + | struct GlobRule { | |
| 73 | + | negated: bool, | |
| 74 | + | dir_only: bool, | |
| 75 | + | anchored: bool, | |
| 76 | + | segments: Vec<SegmentMatcher>, | |
| 77 | + | } | |
| 78 | + | ||
| 79 | + | impl PathFilter { | |
| 80 | + | pub fn new( | |
| 81 | + | _root: &Path, | |
| 82 | + | extra_excludes: &[String], | |
| 83 | + | skip_if_exists: &[String], | |
| 84 | + | use_default_excludes: bool, | |
| 85 | + | ) -> Result<Self> { | |
| 86 | + | let mut excludes = Vec::with_capacity( | |
| 87 | + | extra_excludes.len() | |
| 88 | + | + if use_default_excludes { | |
| 89 | + | DEFAULT_EXCLUDES.len() | |
| 90 | + | } else { | |
| 91 | + | 0 | |
| 92 | + | }, | |
| 93 | + | ); | |
| 94 | + | if use_default_excludes { | |
| 95 | + | for pat in DEFAULT_EXCLUDES { | |
| 96 | + | if let Some(rule) = GlobRule::parse(pat) { | |
| 97 | + | excludes.push(rule); | |
| 98 | + | } | |
| 99 | + | } | |
| 100 | + | } | |
| 101 | + | for pat in extra_excludes { | |
| 102 | + | if let Some(rule) = GlobRule::parse(pat) { | |
| 103 | + | excludes.push(rule); | |
| 104 | + | } | |
| 105 | + | } | |
| 106 | + | ||
| 107 | + | let mut skip_rules = Vec::with_capacity(skip_if_exists.len()); | |
| 108 | + | for pat in skip_if_exists { | |
| 109 | + | if let Some(rule) = GlobRule::parse(pat) { | |
| 110 | + | skip_rules.push(rule); | |
| 111 | + | } | |
| 112 | + | } | |
| 113 | + | ||
| 114 | + | Ok(Self { | |
| 115 | + | excludes: RuleSet::new(excludes), | |
| 116 | + | skip_if_exists: RuleSet::new(skip_rules), | |
| 117 | + | }) | |
| 118 | + | } | |
| 119 | + | ||
| 120 | + | /// Returns `true` if `rel_path` (relative to template/destination root) should be excluded. | |
| 121 | + | pub fn is_excluded(&self, rel_path: &Path, is_dir: bool) -> bool { | |
| 122 | + | self.excludes.matches(rel_path, is_dir) | |
| 123 | + | } | |
| 124 | + | ||
| 125 | + | /// Returns `true` if `rel_path` matches `_skip_if_exists`. | |
| 126 | + | pub fn should_skip_if_exists(&self, rel_path: &Path, is_dir: bool) -> bool { | |
| 127 | + | self.skip_if_exists.matches(rel_path, is_dir) | |
| 128 | + | } | |
| 129 | + | } | |
| 130 | + | ||
| 131 | + | /// Match a single relative path against a glob pattern (e.g. `questions/*.yml`, `config/**/*.yml`). | |
| 132 | + | pub fn match_glob_path(pattern: &str, rel_path: &Path) -> bool { | |
| 133 | + | let Some(mut rule) = GlobRule::parse(pattern) else { | |
| 134 | + | return false; | |
| 135 | + | }; | |
| 136 | + | // Path globs like `*.yml` in `!include` are anchored relative to the template root. | |
| 137 | + | rule.anchored = true; | |
| 138 | + | let mut components: Vec<Cow<'_, str>> = Vec::with_capacity(8); | |
| 139 | + | for comp in rel_path.components() { | |
| 140 | + | if let std::path::Component::Normal(s) = comp { | |
| 141 | + | components.push(s.to_string_lossy()); | |
| 142 | + | } | |
| 143 | + | } | |
| 144 | + | if components.is_empty() { | |
| 145 | + | return false; | |
| 146 | + | } | |
| 147 | + | rule.matches(&components, false) | |
| 148 | + | } | |
| 149 | + | ||
| 150 | + | impl RuleSet { | |
| 151 | + | fn new(rules: Vec<GlobRule>) -> Self { | |
| 152 | + | let has_negation = rules.iter().any(|r| r.negated); | |
| 153 | + | Self { | |
| 154 | + | rules, | |
| 155 | + | has_negation, | |
| 156 | + | } | |
| 157 | + | } | |
| 158 | + | ||
| 159 | + | fn matches(&self, rel_path: &Path, is_dir: bool) -> bool { | |
| 160 | + | if self.rules.is_empty() { | |
| 161 | + | return false; | |
| 162 | + | } | |
| 163 | + | ||
| 164 | + | // Stack fast-path for typical paths (depth <= 16): ZERO heap allocation per check! | |
| 165 | + | let mut stack_buf: [Cow<'_, str>; 16] = std::array::from_fn(|_| Cow::Borrowed("")); | |
| 166 | + | let mut len = 0usize; | |
| 167 | + | let mut overflow: Vec<Cow<'_, str>> = Vec::new(); | |
| 168 | + | ||
| 169 | + | for comp in rel_path.components() { | |
| 170 | + | if let std::path::Component::Normal(s) = comp { | |
| 171 | + | let text = s.to_string_lossy(); | |
| 172 | + | if overflow.is_empty() && len < stack_buf.len() { | |
| 173 | + | stack_buf[len] = text; | |
| 174 | + | len += 1; | |
| 175 | + | } else { | |
| 176 | + | if overflow.is_empty() { | |
| 177 | + | overflow.reserve(len + 4); | |
| 178 | + | for slot in &mut stack_buf[..len] { | |
| 179 | + | overflow.push(std::mem::replace(slot, Cow::Borrowed(""))); | |
| 180 | + | } | |
| 181 | + | } | |
| 182 | + | overflow.push(text); | |
| 183 | + | } | |
| 184 | + | } | |
| 185 | + | } | |
| 186 | + | ||
| 187 | + | let components: &[Cow<'_, str>] = if overflow.is_empty() { | |
| 188 | + | &stack_buf[..len] | |
| 189 | + | } else { | |
| 190 | + | &overflow | |
| 191 | + | }; | |
| 192 | + | if components.is_empty() { | |
| 193 | + | return false; | |
| 194 | + | } | |
| 195 | + | ||
| 196 | + | // Check parents first (if any parent directory is ignored, its children are too unless negated). | |
| 197 | + | let mut ignored = false; | |
| 198 | + | for depth in 1..=components.len() { | |
| 199 | + | let slice = &components[..depth]; | |
| 200 | + | let slice_is_dir = depth < components.len() || is_dir; | |
| 201 | + | for rule in &self.rules { | |
| 202 | + | if rule.matches(slice, slice_is_dir) { | |
| 203 | + | ignored = !rule.negated; | |
| 204 | + | } | |
| 205 | + | } | |
| 206 | + | if ignored && depth < components.len() && !self.has_negation { | |
| 207 | + | return true; | |
| 208 | + | } | |
| 209 | + | } | |
| 210 | + | ignored | |
| 211 | + | } | |
| 212 | + | } | |
| 213 | + | ||
| 214 | + | impl GlobRule { | |
| 215 | + | fn parse(raw: &str) -> Option<Self> { | |
| 216 | + | let trimmed = raw.trim(); | |
| 217 | + | if trimmed.is_empty() || trimmed.starts_with('#') { | |
| 218 | + | return None; | |
| 219 | + | } | |
| 220 | + | let (negated, mut pat) = match trimmed.strip_prefix('!') { | |
| 221 | + | Some(rest) => (true, rest), | |
| 222 | + | None => (false, trimmed), | |
| 223 | + | }; | |
| 224 | + | if pat.is_empty() { | |
| 225 | + | return None; | |
| 226 | + | } | |
| 227 | + | ||
| 228 | + | let dir_only = pat.ends_with('/'); | |
| 229 | + | if dir_only { | |
| 230 | + | pat = pat.trim_end_matches('/'); | |
| 231 | + | } | |
| 232 | + | ||
| 233 | + | let had_leading_slash = pat.starts_with('/'); | |
| 234 | + | if had_leading_slash { | |
| 235 | + | pat = pat.trim_start_matches('/'); | |
| 236 | + | } | |
| 237 | + | if pat.is_empty() { | |
| 238 | + | return None; | |
| 239 | + | } | |
| 240 | + | ||
| 241 | + | // Gitignore rule: a pattern containing a `/` (other than trailing `/`) is anchored to root. | |
| 242 | + | let anchored = had_leading_slash || pat.contains('/'); | |
| 243 | + | let segments: Vec<SegmentMatcher> = pat | |
| 244 | + | .split('/') | |
| 245 | + | .filter(|s| !s.is_empty() && *s != ".") | |
| 246 | + | .map(SegmentMatcher::compile) | |
| 247 | + | .collect(); | |
| 248 | + | if segments.is_empty() { | |
| 249 | + | return None; | |
| 250 | + | } | |
| 251 | + | ||
| 252 | + | Some(Self { | |
| 253 | + | negated, | |
| 254 | + | dir_only, | |
| 255 | + | anchored, | |
| 256 | + | segments, | |
| 257 | + | }) | |
| 258 | + | } | |
| 259 | + | ||
| 260 | + | #[inline] | |
| 261 | + | fn matches(&self, path_segments: &[Cow<'_, str>], is_dir: bool) -> bool { | |
| 262 | + | if self.dir_only && !is_dir { | |
| 263 | + | return false; | |
| 264 | + | } | |
| 265 | + | if self.anchored { | |
| 266 | + | match_segments(&self.segments, path_segments) | |
| 267 | + | } else { | |
| 268 | + | // Unanchored single-segment pattern (e.g. `*.pyc`, `.DS_Store`, `node_modules`) | |
| 269 | + | // matches the basename (and since `RuleSet::matches` checks every prefix, it matches at any depth). | |
| 270 | + | path_segments | |
| 271 | + | .last() | |
| 272 | + | .is_some_and(|name| self.segments[0].matches(name)) | |
| 273 | + | } | |
| 274 | + | } | |
| 275 | + | } | |
| 276 | + | ||
| 277 | + | /// Match path segments supporting `**` (zero or more directory segments). | |
| 278 | + | fn match_segments(pattern: &[SegmentMatcher], path: &[Cow<'_, str>]) -> bool { | |
| 279 | + | match (pattern.first(), path.first()) { | |
| 280 | + | (None, None) => true, | |
| 281 | + | (Some(SegmentMatcher::GlobStar), _) => { | |
| 282 | + | // `**` matches zero segments OR consumes one path segment and stays on `**`. | |
| 283 | + | match_segments(&pattern[1..], path) | |
| 284 | + | || (!path.is_empty() && match_segments(pattern, &path[1..])) | |
| 285 | + | } | |
| 286 | + | (Some(p), Some(s)) => p.matches(s) && match_segments(&pattern[1..], &path[1..]), | |
| 287 | + | _ => false, | |
| 288 | + | } | |
| 289 | + | } | |
| 290 | + | ||
| 291 | + | /// Match a single path segment or identifier against a glob (`*`, `?`, `[abc]`, `[!a-z]`). | |
| 292 | + | pub(crate) fn glob_match(pattern: &str, text: &str) -> bool { | |
| 293 | + | if pattern.is_ascii() && text.is_ascii() { | |
| 294 | + | return glob_match_bytes(pattern.as_bytes(), text.as_bytes()); | |
| 295 | + | } | |
| 296 | + | let p: Vec<char> = pattern.chars().collect(); | |
| 297 | + | let t: Vec<char> = text.chars().collect(); | |
| 298 | + | glob_match_chars(&p, &t) | |
| 299 | + | } | |
| 300 | + | ||
| 301 | + | fn glob_match_bytes(p: &[u8], t: &[u8]) -> bool { | |
| 302 | + | let (mut pi, mut ti) = (0usize, 0usize); | |
| 303 | + | let mut star_pat: Option<usize> = None; | |
| 304 | + | let mut star_text = 0usize; | |
| 305 | + | ||
| 306 | + | while ti < t.len() { | |
| 307 | + | if pi < p.len() && p[pi] == b'*' { | |
| 308 | + | star_pat = Some(pi); | |
| 309 | + | pi += 1; | |
| 310 | + | star_text = ti; | |
| 311 | + | } else if pi < p.len() && p[pi] == b'?' { | |
| 312 | + | pi += 1; | |
| 313 | + | ti += 1; | |
| 314 | + | } else if pi < p.len() && p[pi] == b'[' { | |
| 315 | + | if let Some((matched, next_pi)) = match_byte_class(&p[pi..], t[ti]) { | |
| 316 | + | if matched { | |
| 317 | + | pi += next_pi; | |
| 318 | + | ti += 1; | |
| 319 | + | continue; | |
| 320 | + | } | |
| 321 | + | } else if p[pi] == t[ti] { | |
| 322 | + | pi += 1; | |
| 323 | + | ti += 1; | |
| 324 | + | continue; | |
| 325 | + | } | |
| 326 | + | if let Some(sp) = star_pat { | |
| 327 | + | pi = sp + 1; | |
| 328 | + | star_text += 1; | |
| 329 | + | ti = star_text; | |
| 330 | + | } else { | |
| 331 | + | return false; | |
| 332 | + | } | |
| 333 | + | } else if pi < p.len() && p[pi] == t[ti] { | |
| 334 | + | pi += 1; | |
| 335 | + | ti += 1; | |
| 336 | + | } else if let Some(sp) = star_pat { | |
| 337 | + | pi = sp + 1; | |
| 338 | + | star_text += 1; | |
| 339 | + | ti = star_text; | |
| 340 | + | } else { | |
| 341 | + | return false; | |
| 342 | + | } | |
| 343 | + | } | |
| 344 | + | ||
| 345 | + | while pi < p.len() && p[pi] == b'*' { | |
| 346 | + | pi += 1; | |
| 347 | + | } | |
| 348 | + | pi == p.len() | |
| 349 | + | } | |
| 350 | + | ||
| 351 | + | fn match_byte_class(p: &[u8], ch: u8) -> Option<(bool, usize)> { | |
| 352 | + | let mut i = 1; | |
| 353 | + | let negated = p.get(i).is_some_and(|&c| c == b'!' || c == b'^'); | |
| 354 | + | if negated { | |
| 355 | + | i += 1; | |
| 356 | + | } | |
| 357 | + | let mut found = false; | |
| 358 | + | while i < p.len() { | |
| 359 | + | if p[i] == b']' { | |
| 360 | + | return Some((if negated { !found } else { found }, i + 1)); | |
| 361 | + | } | |
| 362 | + | if i + 2 < p.len() && p[i + 1] == b'-' && p[i + 2] != b']' { | |
| 363 | + | if ch >= p[i] && ch <= p[i + 2] { | |
| 364 | + | found = true; | |
| 365 | + | } | |
| 366 | + | i += 3; | |
| 367 | + | } else { | |
| 368 | + | if ch == p[i] { | |
| 369 | + | found = true; | |
| 370 | + | } | |
| 371 | + | i += 1; | |
| 372 | + | } | |
| 373 | + | } | |
| 374 | + | None | |
| 375 | + | } | |
| 376 | + | ||
| 377 | + | fn glob_match_chars(p: &[char], t: &[char]) -> bool { | |
| 378 | + | let (mut pi, mut ti) = (0usize, 0usize); | |
| 379 | + | let mut star_pat: Option<usize> = None; | |
| 380 | + | let mut star_text = 0usize; | |
| 381 | + | ||
| 382 | + | while ti < t.len() { | |
| 383 | + | if pi < p.len() && p[pi] == '*' { | |
| 384 | + | star_pat = Some(pi); | |
| 385 | + | pi += 1; | |
| 386 | + | star_text = ti; | |
| 387 | + | } else if pi < p.len() && p[pi] == '?' { | |
| 388 | + | pi += 1; | |
| 389 | + | ti += 1; | |
| 390 | + | } else if pi < p.len() && p[pi] == '[' { | |
| 391 | + | if let Some((matched, next_pi)) = match_char_class(&p[pi..], t[ti]) { | |
| 392 | + | if matched { | |
| 393 | + | pi += next_pi; | |
| 394 | + | ti += 1; | |
| 395 | + | continue; | |
| 396 | + | } | |
| 397 | + | } else if p[pi] == t[ti] { | |
| 398 | + | pi += 1; | |
| 399 | + | ti += 1; | |
| 400 | + | continue; | |
| 401 | + | } | |
| 402 | + | if let Some(sp) = star_pat { | |
| 403 | + | pi = sp + 1; | |
| 404 | + | star_text += 1; | |
| 405 | + | ti = star_text; | |
| 406 | + | } else { | |
| 407 | + | return false; | |
| 408 | + | } | |
| 409 | + | } else if pi < p.len() && p[pi] == t[ti] { | |
| 410 | + | pi += 1; | |
| 411 | + | ti += 1; | |
| 412 | + | } else if let Some(sp) = star_pat { | |
| 413 | + | pi = sp + 1; | |
| 414 | + | star_text += 1; | |
| 415 | + | ti = star_text; | |
| 416 | + | } else { | |
| 417 | + | return false; | |
| 418 | + | } | |
| 419 | + | } | |
| 420 | + | ||
| 421 | + | while pi < p.len() && p[pi] == '*' { | |
| 422 | + | pi += 1; | |
| 423 | + | } | |
| 424 | + | pi == p.len() | |
| 425 | + | } | |
| 426 | + | ||
| 427 | + | fn match_char_class(p: &[char], ch: char) -> Option<(bool, usize)> { | |
| 428 | + | // p[0] == '[' | |
| 429 | + | let mut i = 1; | |
| 430 | + | let negated = p.get(i).is_some_and(|&c| c == '!' || c == '^'); | |
| 431 | + | if negated { | |
| 432 | + | i += 1; | |
| 433 | + | } | |
| 434 | + | let mut found = false; | |
| 435 | + | while i < p.len() { | |
| 436 | + | if p[i] == ']' { | |
| 437 | + | return Some((if negated { !found } else { found }, i + 1)); | |
| 438 | + | } | |
| 439 | + | if i + 2 < p.len() && p[i + 1] == '-' && p[i + 2] != ']' { | |
| 440 | + | if ch >= p[i] && ch <= p[i + 2] { | |
| 441 | + | found = true; | |
| 442 | + | } | |
| 443 | + | i += 3; | |
| 444 | + | } else { | |
| 445 | + | if ch == p[i] { | |
| 446 | + | found = true; | |
| 447 | + | } | |
| 448 | + | i += 1; | |
| 449 | + | } | |
| 450 | + | } | |
| 451 | + | None | |
| 452 | + | } | |
| 453 | + | ||
| 454 | + | #[cfg(test)] | |
| 455 | + | mod tests { | |
| 456 | + | use super::*; | |
| 457 | + | ||
| 458 | + | #[test] | |
| 459 | + | fn gitignore_patterns_and_negation() { | |
| 460 | + | let filter = PathFilter::new( | |
| 461 | + | Path::new(""), | |
| 462 | + | &[ | |
| 463 | + | "docs".into(), | |
| 464 | + | "docs/**".into(), | |
| 465 | + | "values/*/airgap-values.yaml.gotmpl".into(), | |
| 466 | + | "*.bak".into(), | |
| 467 | + | "!keep.bak".into(), | |
| 468 | + | ], | |
| 469 | + | &["secrets.yaml".into()], | |
| 470 | + | true, | |
| 471 | + | ) | |
| 472 | + | .unwrap(); | |
| 473 | + | ||
| 474 | + | assert!(filter.is_excluded(Path::new("copier.yml"), false)); | |
| 475 | + | assert!(filter.is_excluded(Path::new("foo.pyc"), false)); | |
| 476 | + | assert!(filter.is_excluded(Path::new("docs"), true)); | |
| 477 | + | assert!(filter.is_excluded(Path::new("docs/guide/index.md"), false)); | |
| 478 | + | assert!(filter.is_excluded(Path::new("values/iam/airgap-values.yaml.gotmpl"), false)); | |
| 479 | + | assert!(!filter.is_excluded(Path::new("values/iam/values.yaml.gotmpl"), false)); | |
| 480 | + | assert!(filter.is_excluded(Path::new("old.bak"), false)); | |
| 481 | + | assert!(!filter.is_excluded(Path::new("keep.bak"), false)); | |
| 482 | + | assert!(filter.should_skip_if_exists(Path::new("secrets.yaml"), false)); | |
| 483 | + | assert!(!filter.should_skip_if_exists(Path::new("other.yaml"), false)); | |
| 484 | + | } | |
| 485 | + | } |
| @@ -0,0 +1,179 @@ | |||
| 1 | + | use std::fs; | |
| 2 | + | use std::path::{Path, PathBuf}; | |
| 3 | + | use std::sync::atomic::{AtomicU64, Ordering}; | |
| 4 | + | ||
| 5 | + | use crate::error::{Result, RoneoError}; | |
| 6 | + | ||
| 7 | + | static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0); | |
| 8 | + | ||
| 9 | + | /// Lightweight zero-dependency RAII temporary directory (automatically deleted on `Drop`). | |
| 10 | + | #[derive(Debug)] | |
| 11 | + | pub struct TempDir { | |
| 12 | + | path: PathBuf, | |
| 13 | + | } | |
| 14 | + | ||
| 15 | + | impl TempDir { | |
| 16 | + | pub fn new() -> Result<Self> { | |
| 17 | + | Self::with_prefix("roneo") | |
| 18 | + | } | |
| 19 | + | ||
| 20 | + | pub fn with_prefix(prefix: &str) -> Result<Self> { | |
| 21 | + | let base = std::env::temp_dir(); | |
| 22 | + | let pid = std::process::id(); | |
| 23 | + | let nanos = std::time::SystemTime::now() | |
| 24 | + | .duration_since(std::time::UNIX_EPOCH) | |
| 25 | + | .map_or(0, |d| d.as_nanos()); | |
| 26 | + | ||
| 27 | + | for _ in 0..64 { | |
| 28 | + | let seq = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed); | |
| 29 | + | let candidate = base.join(format!("{prefix}-{pid}-{nanos:x}-{seq}")); | |
| 30 | + | match create_private_dir(&candidate) { | |
| 31 | + | Ok(()) => return Ok(Self { path: candidate }), | |
| 32 | + | Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} | |
| 33 | + | Err(e) => return Err(RoneoError::io(&candidate, e)), | |
| 34 | + | } | |
| 35 | + | } | |
| 36 | + | Err(RoneoError::TemplateSource( | |
| 37 | + | "Failed to allocate a unique temporary directory".into(), | |
| 38 | + | )) | |
| 39 | + | } | |
| 40 | + | ||
| 41 | + | pub fn path(&self) -> &Path { | |
| 42 | + | &self.path | |
| 43 | + | } | |
| 44 | + | } | |
| 45 | + | ||
| 46 | + | impl Drop for TempDir { | |
| 47 | + | fn drop(&mut self) { | |
| 48 | + | let _ = fs::remove_dir_all(&self.path); | |
| 49 | + | } | |
| 50 | + | } | |
| 51 | + | ||
| 52 | + | #[cfg(unix)] | |
| 53 | + | fn create_private_dir(path: &Path) -> std::io::Result<()> { | |
| 54 | + | use std::os::unix::fs::DirBuilderExt; | |
| 55 | + | fs::DirBuilder::new().mode(0o700).create(path) | |
| 56 | + | } | |
| 57 | + | ||
| 58 | + | #[cfg(not(unix))] | |
| 59 | + | fn create_private_dir(path: &Path) -> std::io::Result<()> { | |
| 60 | + | fs::create_dir(path) | |
| 61 | + | } | |
| 62 | + | ||
| 63 | + | /// Entry yielded while walking a directory tree on disk. | |
| 64 | + | #[derive(Debug, Clone)] | |
| 65 | + | pub struct DiskEntry { | |
| 66 | + | pub abs_path: PathBuf, | |
| 67 | + | pub rel_path: PathBuf, | |
| 68 | + | pub is_dir: bool, | |
| 69 | + | pub is_symlink: bool, | |
| 70 | + | } | |
| 71 | + | ||
| 72 | + | /// Recursively walk `root` in deterministic sorted filename order, calling `visitor` on each entry. | |
| 73 | + | /// When `visitor` returns `Ok(false)` for a directory, that directory's subtree is skipped. | |
| 74 | + | pub fn walk_dir_sorted<F>(root: &Path, follow_symlinks: bool, mut visitor: F) -> Result<()> | |
| 75 | + | where | |
| 76 | + | F: FnMut(DiskEntry) -> Result<bool>, | |
| 77 | + | { | |
| 78 | + | walk_recursive(root, root, follow_symlinks, &mut visitor) | |
| 79 | + | } | |
| 80 | + | ||
| 81 | + | fn walk_recursive<F>( | |
| 82 | + | root: &Path, | |
| 83 | + | current: &Path, | |
| 84 | + | follow_symlinks: bool, | |
| 85 | + | visitor: &mut F, | |
| 86 | + | ) -> Result<()> | |
| 87 | + | where | |
| 88 | + | F: FnMut(DiskEntry) -> Result<bool>, | |
| 89 | + | { | |
| 90 | + | let mut entries: Vec<_> = fs::read_dir(current) | |
| 91 | + | .map_err(|e| RoneoError::io(current, e))? | |
| 92 | + | .collect::<std::result::Result<Vec<_>, _>>() | |
| 93 | + | .map_err(|e| RoneoError::io(current, e))?; | |
| 94 | + | ||
| 95 | + | entries.sort_by_key(fs::DirEntry::file_name); | |
| 96 | + | ||
| 97 | + | for entry in entries { | |
| 98 | + | let abs_path = entry.path(); | |
| 99 | + | let rel_path = abs_path | |
| 100 | + | .strip_prefix(root) | |
| 101 | + | .map_or_else(|_| PathBuf::from(entry.file_name()), Path::to_path_buf); | |
| 102 | + | ||
| 103 | + | let sym_meta = fs::symlink_metadata(&abs_path).map_err(|e| RoneoError::io(&abs_path, e))?; | |
| 104 | + | let is_symlink = sym_meta.file_type().is_symlink(); | |
| 105 | + | let is_dir = if is_symlink && follow_symlinks { | |
| 106 | + | fs::metadata(&abs_path).is_ok_and(|m| m.is_dir()) | |
| 107 | + | } else { | |
| 108 | + | sym_meta.is_dir() | |
| 109 | + | }; | |
| 110 | + | ||
| 111 | + | let enter = visitor(DiskEntry { | |
| 112 | + | abs_path: abs_path.clone(), | |
| 113 | + | rel_path, | |
| 114 | + | is_dir, | |
| 115 | + | is_symlink, | |
| 116 | + | })?; | |
| 117 | + | ||
| 118 | + | if is_dir && enter { | |
| 119 | + | walk_recursive(root, &abs_path, follow_symlinks, visitor)?; | |
| 120 | + | } | |
| 121 | + | } | |
| 122 | + | Ok(()) | |
| 123 | + | } | |
| 124 | + | ||
| 125 | + | #[cfg(unix)] | |
| 126 | + | pub fn set_executable(dst: &Path) -> Result<()> { | |
| 127 | + | use std::os::unix::fs::PermissionsExt; | |
| 128 | + | fs::set_permissions(dst, fs::Permissions::from_mode(0o755)).map_err(|e| RoneoError::io(dst, e)) | |
| 129 | + | } | |
| 130 | + | ||
| 131 | + | #[cfg(not(unix))] | |
| 132 | + | pub fn set_executable(_dst: &Path) -> Result<()> { | |
| 133 | + | Ok(()) | |
| 134 | + | } | |
| 135 | + | ||
| 136 | + | #[cfg(unix)] | |
| 137 | + | pub fn file_mode_from_metadata(meta: &fs::Metadata) -> Option<u32> { | |
| 138 | + | use std::os::unix::fs::PermissionsExt; | |
| 139 | + | Some(meta.permissions().mode()) | |
| 140 | + | } | |
| 141 | + | ||
| 142 | + | #[cfg(not(unix))] | |
| 143 | + | pub fn file_mode_from_metadata(_meta: &fs::Metadata) -> Option<u32> { | |
| 144 | + | None | |
| 145 | + | } | |
| 146 | + | ||
| 147 | + | #[cfg(unix)] | |
| 148 | + | pub fn set_file_mode(dst: &Path, mode: u32) -> Result<()> { | |
| 149 | + | use std::os::unix::fs::PermissionsExt; | |
| 150 | + | fs::set_permissions(dst, fs::Permissions::from_mode(mode)).map_err(|e| RoneoError::io(dst, e)) | |
| 151 | + | } | |
| 152 | + | ||
| 153 | + | #[cfg(not(unix))] | |
| 154 | + | pub fn set_file_mode(_dst: &Path, _mode: u32) -> Result<()> { | |
| 155 | + | Ok(()) | |
| 156 | + | } | |
| 157 | + | ||
| 158 | + | #[cfg(unix)] | |
| 159 | + | pub fn copy_permissions(src: &Path, dst: &Path) -> Result<()> { | |
| 160 | + | let perms = fs::metadata(src) | |
| 161 | + | .map_err(|e| RoneoError::io(src, e))? | |
| 162 | + | .permissions(); | |
| 163 | + | fs::set_permissions(dst, perms).map_err(|e| RoneoError::io(dst, e)) | |
| 164 | + | } | |
| 165 | + | ||
| 166 | + | #[cfg(not(unix))] | |
| 167 | + | pub fn copy_permissions(_src: &Path, _dst: &Path) -> Result<()> { | |
| 168 | + | Ok(()) | |
| 169 | + | } | |
| 170 | + | ||
| 171 | + | #[cfg(unix)] | |
| 172 | + | pub fn create_symlink(target: &Path, link: &Path) -> Result<()> { | |
| 173 | + | std::os::unix::fs::symlink(target, link).map_err(|e| RoneoError::io(link, e)) | |
| 174 | + | } | |
| 175 | + | ||
| 176 | + | #[cfg(windows)] | |
| 177 | + | pub fn create_symlink(target: &Path, link: &Path) -> Result<()> { | |
| 178 | + | std::os::windows::fs::symlink_file(target, link).map_err(|e| RoneoError::io(link, e)) | |
| 179 | + | } |
| @@ -0,0 +1,30 @@ | |||
| 1 | + | pub mod answers; | |
| 2 | + | pub mod config; | |
| 3 | + | pub mod error; | |
| 4 | + | pub mod filter; | |
| 5 | + | pub mod fs_util; | |
| 6 | + | pub mod plugin; | |
| 7 | + | pub mod prompt; | |
| 8 | + | pub mod renderer; | |
| 9 | + | pub mod settings; | |
| 10 | + | pub mod tasks; | |
| 11 | + | pub mod template; | |
| 12 | + | pub mod vcs; | |
| 13 | + | pub mod version; | |
| 14 | + | pub mod worker; | |
| 15 | + | ||
| 16 | + | pub use answers::AnswersMap; | |
| 17 | + | pub use config::{Question, QuestionType, TemplateConfig, TemplateSettings}; | |
| 18 | + | pub use error::{Result, RoneoError}; | |
| 19 | + | pub use plugin::{ | |
| 20 | + | Extension, ExtensionInitContext, ExtensionRegistry, WasmExtension, WasmPluginManifest, | |
| 21 | + | }; | |
| 22 | + | pub use prompt::{NonInteractivePrompter, OverwriteChoice, PromptRequest, Prompter}; | |
| 23 | + | pub use settings::UserSettings; | |
| 24 | + | pub use template::ResolvedTemplate; | |
| 25 | + | pub use vcs::ConflictMode; | |
| 26 | + | pub use version::Pep440Version; | |
| 27 | + | pub use worker::{ | |
| 28 | + | ActionEvent, COPIER_COMPAT_VERSION, CheckUpdateReport, CopyOptions, NoopReporter, | |
| 29 | + | OperationReport, Reporter, UpdateDiff, check_update, copy, diff_update, recopy, update, | |
| 30 | + | }; |
| @@ -0,0 +1,643 @@ | |||
| 1 | + | use std::fs; | |
| 2 | + | use std::path::{Path, PathBuf}; | |
| 3 | + | use std::sync::{Arc, Mutex, RwLock}; | |
| 4 | + | ||
| 5 | + | use indexmap::IndexMap; | |
| 6 | + | use minijinja::value::{Kwargs, Rest, Serde, Value as MjValue}; | |
| 7 | + | use minijinja::{ | |
| 8 | + | Environment, Error as MjError, ErrorKind as MjErrorKind, State, UndefinedBehavior, | |
| 9 | + | }; | |
| 10 | + | use serde::{Deserialize, Serialize}; | |
| 11 | + | use serde_json::{Map as JsonMap, Value as JsonValue}; | |
| 12 | + | use wasmi::{ | |
| 13 | + | Config, Engine, Instance, Linker, Memory, Module, Store, StoreLimits, StoreLimitsBuilder, | |
| 14 | + | TypedFunc, | |
| 15 | + | }; | |
| 16 | + | ||
| 17 | + | /// Maximum linear memory allowed per sandboxed WASM plugin instance (64 MiB). | |
| 18 | + | const WASM_MAX_MEMORY_BYTES: usize = 64 * 1024 * 1024; | |
| 19 | + | /// Maximum single IPC payload accepted back from a WASM guest (16 MiB). | |
| 20 | + | const WASM_MAX_PAYLOAD_BYTES: usize = 16 * 1024 * 1024; | |
| 21 | + | /// Fuel budget per guest call (~100M instructions; prevents infinite loops). | |
| 22 | + | const WASM_CALL_FUEL_BUDGET: u64 = 100_000_000; | |
| 23 | + | ||
| 24 | + | use crate::error::{Result, RoneoError}; | |
| 25 | + | ||
| 26 | + | pub type TemplateFileReader = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>; | |
| 27 | + | ||
| 28 | + | /// Host metadata passed to extensions during registration (works for both disk and in-memory `gix` trees). | |
| 29 | + | #[derive(Clone)] | |
| 30 | + | pub struct ExtensionInitContext { | |
| 31 | + | pub template_root: PathBuf, | |
| 32 | + | pub dst_path: PathBuf, | |
| 33 | + | pub file_reader: TemplateFileReader, | |
| 34 | + | } | |
| 35 | + | ||
| 36 | + | impl std::fmt::Debug for ExtensionInitContext { | |
| 37 | + | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| 38 | + | f.debug_struct("ExtensionInitContext") | |
| 39 | + | .field("template_root", &self.template_root) | |
| 40 | + | .field("dst_path", &self.dst_path) | |
| 41 | + | .finish_non_exhaustive() | |
| 42 | + | } | |
| 43 | + | } | |
| 44 | + | ||
| 45 | + | /// Native or WASM template extension (equivalent to Copier's Jinja `Extension` + `ContextHook`). | |
| 46 | + | pub trait Extension: Send + Sync { | |
| 47 | + | fn name(&self) -> &str; | |
| 48 | + | ||
| 49 | + | /// Register custom filters, global functions/values, tests, or environment tweaks on `MiniJinja`. | |
| 50 | + | fn register(&self, env: &mut Environment<'static>, init: &ExtensionInitContext) -> Result<()>; | |
| 51 | + | ||
| 52 | + | /// Transform or validate the template context (`phase` is `"prompt"` or `"render"`). | |
| 53 | + | fn hook_context(&self, phase: &str, ctx: &mut IndexMap<String, JsonValue>) -> Result<()> { | |
| 54 | + | let _ = (phase, ctx); | |
| 55 | + | Ok(()) | |
| 56 | + | } | |
| 57 | + | } | |
| 58 | + | ||
| 59 | + | /// Collection of active extensions (native Rust and/or sandboxed WASM). | |
| 60 | + | #[derive(Clone, Default)] | |
| 61 | + | pub struct ExtensionRegistry { | |
| 62 | + | extensions: Vec<Arc<dyn Extension>>, | |
| 63 | + | } | |
| 64 | + | ||
| 65 | + | impl std::fmt::Debug for ExtensionRegistry { | |
| 66 | + | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| 67 | + | let names: Vec<&str> = self.extensions.iter().map(|e| e.name()).collect(); | |
| 68 | + | f.debug_struct("ExtensionRegistry") | |
| 69 | + | .field("extensions", &names) | |
| 70 | + | .finish() | |
| 71 | + | } | |
| 72 | + | } | |
| 73 | + | ||
| 74 | + | impl ExtensionRegistry { | |
| 75 | + | pub fn new() -> Self { | |
| 76 | + | Self::default() | |
| 77 | + | } | |
| 78 | + | ||
| 79 | + | pub fn add(&mut self, ext: Arc<dyn Extension>) { | |
| 80 | + | self.extensions.push(ext); | |
| 81 | + | } | |
| 82 | + | ||
| 83 | + | pub fn add_wasm_file(&mut self, path: impl AsRef<Path>) -> Result<()> { | |
| 84 | + | let wasm_ext = WasmExtension::from_file(path.as_ref())?; | |
| 85 | + | self.extensions.push(Arc::new(wasm_ext)); | |
| 86 | + | Ok(()) | |
| 87 | + | } | |
| 88 | + | ||
| 89 | + | pub fn add_wasm_bytes(&mut self, bytes: &[u8]) -> Result<()> { | |
| 90 | + | let wasm_ext = WasmExtension::from_bytes(bytes)?; | |
| 91 | + | self.extensions.push(Arc::new(wasm_ext)); | |
| 92 | + | Ok(()) | |
| 93 | + | } | |
| 94 | + | ||
| 95 | + | pub fn is_empty(&self) -> bool { | |
| 96 | + | self.extensions.is_empty() | |
| 97 | + | } | |
| 98 | + | ||
| 99 | + | pub fn names(&self) -> Vec<&str> { | |
| 100 | + | self.extensions.iter().map(|e| e.name()).collect() | |
| 101 | + | } | |
| 102 | + | ||
| 103 | + | pub fn register_all( | |
| 104 | + | &self, | |
| 105 | + | env: &mut Environment<'static>, | |
| 106 | + | init: &ExtensionInitContext, | |
| 107 | + | ) -> Result<()> { | |
| 108 | + | for ext in &self.extensions { | |
| 109 | + | ext.register(env, init)?; | |
| 110 | + | } | |
| 111 | + | Ok(()) | |
| 112 | + | } | |
| 113 | + | ||
| 114 | + | pub fn run_context_hooks( | |
| 115 | + | &self, | |
| 116 | + | phase: &str, | |
| 117 | + | ctx: &mut IndexMap<String, JsonValue>, | |
| 118 | + | ) -> Result<()> { | |
| 119 | + | for ext in &self.extensions { | |
| 120 | + | ext.hook_context(phase, ctx)?; | |
| 121 | + | } | |
| 122 | + | Ok(()) | |
| 123 | + | } | |
| 124 | + | } | |
| 125 | + | ||
| 126 | + | // --------------------------------------------------------------------------- | |
| 127 | + | // Sandboxed WebAssembly plugin runtime (`wasmi`) with lock-free parallel pool | |
| 128 | + | // --------------------------------------------------------------------------- | |
| 129 | + | ||
| 130 | + | /// Manifest returned by a WASM plugin's `roneo_manifest()` export. | |
| 131 | + | #[derive(Debug, Clone, Default, Serialize, Deserialize)] | |
| 132 | + | pub struct WasmPluginManifest { | |
| 133 | + | pub name: String, | |
| 134 | + | #[serde(default)] | |
| 135 | + | pub strict_undefined: bool, | |
| 136 | + | #[serde(default)] | |
| 137 | + | pub globals: IndexMap<String, JsonValue>, | |
| 138 | + | #[serde(default)] | |
| 139 | + | pub filters: Vec<String>, | |
| 140 | + | #[serde(default)] | |
| 141 | + | pub functions: Vec<String>, | |
| 142 | + | #[serde(default)] | |
| 143 | + | pub tests: Vec<String>, | |
| 144 | + | #[serde(default)] | |
| 145 | + | pub has_context_hook: bool, | |
| 146 | + | /// Optional list of template context keys to forward on filter/function calls. | |
| 147 | + | #[serde(default)] | |
| 148 | + | pub context_keys: Vec<String>, | |
| 149 | + | /// Optional relative paths inside `template_root` that the host reads and | |
| 150 | + | /// passes to `roneo_init` (keeps the WASM guest 100% sandboxed with zero FS access). | |
| 151 | + | #[serde(default)] | |
| 152 | + | pub template_files: Vec<String>, | |
| 153 | + | } | |
| 154 | + | ||
| 155 | + | #[derive(Debug, Clone, Serialize)] | |
| 156 | + | struct WasmInitPayload { | |
| 157 | + | template_files: IndexMap<String, String>, | |
| 158 | + | recorded_answers: JsonValue, | |
| 159 | + | dst_path: String, | |
| 160 | + | template_root: String, | |
| 161 | + | } | |
| 162 | + | ||
| 163 | + | #[derive(Debug, Serialize)] | |
| 164 | + | struct WasmCallRequest<'a> { | |
| 165 | + | kind: &'a str, | |
| 166 | + | name: &'a str, | |
| 167 | + | args: Vec<JsonValue>, | |
| 168 | + | kwargs: JsonMap<String, JsonValue>, | |
| 169 | + | context: JsonMap<String, JsonValue>, | |
| 170 | + | phase: &'a str, | |
| 171 | + | } | |
| 172 | + | ||
| 173 | + | #[derive(Debug, Deserialize)] | |
| 174 | + | #[serde(rename_all = "lowercase")] | |
| 175 | + | enum WasmCallResponse { | |
| 176 | + | Ok(JsonValue), | |
| 177 | + | Err(String), | |
| 178 | + | } | |
| 179 | + | ||
| 180 | + | struct WasmRuntime { | |
| 181 | + | store: Store<StoreLimits>, | |
| 182 | + | memory: Memory, | |
| 183 | + | alloc: TypedFunc<u32, u32>, | |
| 184 | + | dealloc: Option<TypedFunc<(u32, u32), ()>>, | |
| 185 | + | call_fn: TypedFunc<(u32, u32), u64>, | |
| 186 | + | init_fn: Option<TypedFunc<(u32, u32), u64>>, | |
| 187 | + | initialized: bool, | |
| 188 | + | } | |
| 189 | + | ||
| 190 | + | impl WasmRuntime { | |
| 191 | + | fn instantiate_from_module(engine: &Engine, module: &Module) -> Result<(Self, Instance)> { | |
| 192 | + | let limits = StoreLimitsBuilder::new() | |
| 193 | + | .memory_size(WASM_MAX_MEMORY_BYTES) | |
| 194 | + | .build(); | |
| 195 | + | let mut store = Store::new(engine, limits); | |
| 196 | + | store.limiter(|lim| lim); | |
| 197 | + | let _ = store.set_fuel(WASM_CALL_FUEL_BUDGET); | |
| 198 | + | let linker = Linker::<StoreLimits>::new(engine); | |
| 199 | + | let instance: Instance = linker | |
| 200 | + | .instantiate_and_start(&mut store, module) | |
| 201 | + | .map_err(|e| RoneoError::Plugin(format!("Failed to instantiate WASM module: {e}")))?; | |
| 202 | + | ||
| 203 | + | let memory = instance | |
| 204 | + | .get_memory(&store, "memory") | |
| 205 | + | .ok_or_else(|| RoneoError::Plugin("WASM plugin missing `memory` export".into()))?; | |
| 206 | + | let alloc = instance | |
| 207 | + | .get_typed_func::<u32, u32>(&store, "roneo_alloc") | |
| 208 | + | .map_err(|e| RoneoError::Plugin(format!("WASM plugin missing `roneo_alloc`: {e}")))?; | |
| 209 | + | let dealloc = instance | |
| 210 | + | .get_typed_func::<(u32, u32), ()>(&store, "roneo_dealloc") | |
| 211 | + | .ok(); | |
| 212 | + | let call_fn = instance | |
| 213 | + | .get_typed_func::<(u32, u32), u64>(&store, "roneo_call") | |
| 214 | + | .map_err(|e| RoneoError::Plugin(format!("WASM plugin missing `roneo_call`: {e}")))?; | |
| 215 | + | let init_fn = instance | |
| 216 | + | .get_typed_func::<(u32, u32), u64>(&store, "roneo_init") | |
| 217 | + | .ok(); | |
| 218 | + | ||
| 219 | + | Ok(( | |
| 220 | + | Self { | |
| 221 | + | store, | |
| 222 | + | memory, | |
| 223 | + | alloc, | |
| 224 | + | dealloc, | |
| 225 | + | call_fn, | |
| 226 | + | init_fn, | |
| 227 | + | initialized: false, | |
| 228 | + | }, | |
| 229 | + | instance, | |
| 230 | + | )) | |
| 231 | + | } | |
| 232 | + | ||
| 233 | + | fn read_manifest(&mut self, instance: Instance) -> Result<WasmPluginManifest> { | |
| 234 | + | let _ = self.store.set_fuel(WASM_CALL_FUEL_BUDGET); | |
| 235 | + | let manifest_fn = instance | |
| 236 | + | .get_typed_func::<(), u64>(&self.store, "roneo_manifest") | |
| 237 | + | .map_err(|e| { | |
| 238 | + | RoneoError::Plugin(format!("WASM plugin missing `roneo_manifest`: {e}")) | |
| 239 | + | })?; | |
| 240 | + | let packed = manifest_fn | |
| 241 | + | .call(&mut self.store, ()) | |
| 242 | + | .map_err(|e| RoneoError::Plugin(format!("WASM `roneo_manifest` trapped: {e}")))?; | |
| 243 | + | let manifest_bytes = read_packed(&self.store, self.memory, packed)?; | |
| 244 | + | serde_json::from_slice(&manifest_bytes).map_err(|e| { | |
| 245 | + | RoneoError::Plugin(format!("Invalid JSON from WASM `roneo_manifest`: {e}")) | |
| 246 | + | }) | |
| 247 | + | } | |
| 248 | + | ||
| 249 | + | fn write_guest(&mut self, bytes: &[u8]) -> Result<(u32, u32)> { | |
| 250 | + | let len = u32::try_from(bytes.len()) | |
| 251 | + | .map_err(|_| RoneoError::Plugin("Payload exceeds 4 GiB WASM address space".into()))?; | |
| 252 | + | let ptr = self | |
| 253 | + | .alloc | |
| 254 | + | .call(&mut self.store, len) | |
| 255 | + | .map_err(|e| RoneoError::Plugin(format!("WASM `roneo_alloc` failed: {e}")))?; | |
| 256 | + | self.memory | |
| 257 | + | .write(&mut self.store, ptr as usize, bytes) | |
| 258 | + | .map_err(|e| RoneoError::Plugin(format!("WASM memory write failed: {e}")))?; | |
| 259 | + | Ok((ptr, len)) | |
| 260 | + | } | |
| 261 | + | ||
| 262 | + | fn free_guest(&mut self, ptr: u32, len: u32) { | |
| 263 | + | if let Some(dealloc) = self.dealloc { | |
| 264 | + | let _ = dealloc.call(&mut self.store, (ptr, len)); | |
| 265 | + | } | |
| 266 | + | } | |
| 267 | + | ||
| 268 | + | fn send_init(&mut self, payload_bytes: &[u8]) -> Result<()> { | |
| 269 | + | let Some(init_fn) = self.init_fn else { | |
| 270 | + | self.initialized = true; | |
| 271 | + | return Ok(()); | |
| 272 | + | }; | |
| 273 | + | let _ = self.store.set_fuel(WASM_CALL_FUEL_BUDGET); | |
| 274 | + | let (ptr, len) = self.write_guest(payload_bytes)?; | |
| 275 | + | let packed = init_fn | |
| 276 | + | .call(&mut self.store, (ptr, len)) | |
| 277 | + | .map_err(|e| RoneoError::Plugin(format!("WASM `roneo_init` trapped: {e}")))?; | |
| 278 | + | self.free_guest(ptr, len); | |
| 279 | + | ||
| 280 | + | if packed != 0 { | |
| 281 | + | let resp_bytes = read_packed(&self.store, self.memory, packed)?; | |
| 282 | + | let (out_ptr, out_len) = unpack_ptr_len(packed); | |
| 283 | + | self.free_guest(out_ptr, out_len); | |
| 284 | + | let resp: WasmCallResponse = serde_json::from_slice(&resp_bytes)?; | |
| 285 | + | if let WasmCallResponse::Err(msg) = resp { | |
| 286 | + | return Err(RoneoError::Plugin(msg)); | |
| 287 | + | } | |
| 288 | + | } | |
| 289 | + | self.initialized = true; | |
| 290 | + | Ok(()) | |
| 291 | + | } | |
| 292 | + | ||
| 293 | + | fn invoke(&mut self, req: &WasmCallRequest<'_>) -> Result<JsonValue> { | |
| 294 | + | let _ = self.store.set_fuel(WASM_CALL_FUEL_BUDGET); | |
| 295 | + | let bytes = serde_json::to_vec(req)?; | |
| 296 | + | let (ptr, len) = self.write_guest(&bytes)?; | |
| 297 | + | let packed = self | |
| 298 | + | .call_fn | |
| 299 | + | .call(&mut self.store, (ptr, len)) | |
| 300 | + | .map_err(|e| RoneoError::Plugin(format!("WASM `roneo_call` trapped: {e}")))?; | |
| 301 | + | self.free_guest(ptr, len); | |
| 302 | + | ||
| 303 | + | let resp_bytes = read_packed(&self.store, self.memory, packed)?; | |
| 304 | + | let (out_ptr, out_len) = unpack_ptr_len(packed); | |
| 305 | + | self.free_guest(out_ptr, out_len); | |
| 306 | + | ||
| 307 | + | let resp: WasmCallResponse = serde_json::from_slice(&resp_bytes).map_err(|e| { | |
| 308 | + | RoneoError::Plugin(format!("Invalid JSON response from WASM plugin: {e}")) | |
| 309 | + | })?; | |
| 310 | + | match resp { | |
| 311 | + | WasmCallResponse::Ok(val) => Ok(val), | |
| 312 | + | WasmCallResponse::Err(msg) => Err(RoneoError::Plugin(msg)), | |
| 313 | + | } | |
| 314 | + | } | |
| 315 | + | } | |
| 316 | + | ||
| 317 | + | /// Thread-safe pool of initialized `WasmRuntime` instances so parallel `rayon` threads can | |
| 318 | + | /// execute WASM filters simultaneously with zero contention during guest execution. | |
| 319 | + | struct WasmPool { | |
| 320 | + | engine: Engine, | |
| 321 | + | module: Module, | |
| 322 | + | init_bytes: RwLock<Option<Vec<u8>>>, | |
| 323 | + | instances: Mutex<Vec<WasmRuntime>>, | |
| 324 | + | } | |
| 325 | + | ||
| 326 | + | impl WasmPool { | |
| 327 | + | fn new(wasm_bytes: &[u8]) -> Result<(Self, WasmPluginManifest)> { | |
| 328 | + | let mut cfg = Config::default(); | |
| 329 | + | cfg.consume_fuel(true); | |
| 330 | + | let engine = Engine::new(&cfg); | |
| 331 | + | let module = Module::new(&engine, wasm_bytes) | |
| 332 | + | .map_err(|e| RoneoError::Plugin(format!("Invalid WASM module: {e}")))?; | |
| 333 | + | let (mut rt, instance) = WasmRuntime::instantiate_from_module(&engine, &module)?; | |
| 334 | + | let manifest = rt.read_manifest(instance)?; | |
| 335 | + | Ok(( | |
| 336 | + | Self { | |
| 337 | + | engine, | |
| 338 | + | module, | |
| 339 | + | init_bytes: RwLock::new(None), | |
| 340 | + | instances: Mutex::new(vec![rt]), | |
| 341 | + | }, | |
| 342 | + | manifest, | |
| 343 | + | )) | |
| 344 | + | } | |
| 345 | + | ||
| 346 | + | fn set_init_payload(&self, payload: &WasmInitPayload) -> Result<()> { | |
| 347 | + | let bytes = serde_json::to_vec(payload)?; | |
| 348 | + | { | |
| 349 | + | let mut guard = self | |
| 350 | + | .init_bytes | |
| 351 | + | .write() | |
| 352 | + | .map_err(|_| RoneoError::Plugin("WASM init lock poisoned".into()))?; | |
| 353 | + | *guard = Some(bytes.clone()); | |
| 354 | + | } | |
| 355 | + | // Re-initialize any pooled instances already created. | |
| 356 | + | let mut pool = self | |
| 357 | + | .instances | |
| 358 | + | .lock() | |
| 359 | + | .map_err(|_| RoneoError::Plugin("WASM pool lock poisoned".into()))?; | |
| 360 | + | for rt in pool.iter_mut() { | |
| 361 | + | rt.send_init(&bytes)?; | |
| 362 | + | } | |
| 363 | + | Ok(()) | |
| 364 | + | } | |
| 365 | + | ||
| 366 | + | fn call(&self, req: &WasmCallRequest<'_>) -> Result<JsonValue> { | |
| 367 | + | let mut rt = { | |
| 368 | + | let mut pool = self | |
| 369 | + | .instances | |
| 370 | + | .lock() | |
| 371 | + | .map_err(|_| RoneoError::Plugin("WASM pool lock poisoned".into()))?; | |
| 372 | + | pool.pop() | |
| 373 | + | }; | |
| 374 | + | ||
| 375 | + | let mut runtime = if let Some(existing) = rt.take() { | |
| 376 | + | existing | |
| 377 | + | } else { | |
| 378 | + | let (mut fresh, _) = WasmRuntime::instantiate_from_module(&self.engine, &self.module)?; | |
| 379 | + | if let Ok(guard) = self.init_bytes.read() | |
| 380 | + | && let Some(bytes) = guard.as_deref() | |
| 381 | + | { | |
| 382 | + | fresh.send_init(bytes)?; | |
| 383 | + | } | |
| 384 | + | fresh | |
| 385 | + | }; | |
| 386 | + | ||
| 387 | + | if !runtime.initialized | |
| 388 | + | && let Ok(guard) = self.init_bytes.read() | |
| 389 | + | && let Some(bytes) = guard.as_deref() | |
| 390 | + | { | |
| 391 | + | runtime.send_init(bytes)?; | |
| 392 | + | } | |
| 393 | + | ||
| 394 | + | let res = runtime.invoke(req); | |
| 395 | + | ||
| 396 | + | if let Ok(mut pool) = self.instances.lock() { | |
| 397 | + | pool.push(runtime); | |
| 398 | + | } | |
| 399 | + | ||
| 400 | + | res | |
| 401 | + | } | |
| 402 | + | } | |
| 403 | + | ||
| 404 | + | fn unpack_ptr_len(packed: u64) -> (u32, u32) { | |
| 405 | + | #[allow(clippy::cast_possible_truncation)] | |
| 406 | + | let ptr = (packed >> 32) as u32; | |
| 407 | + | #[allow(clippy::cast_possible_truncation)] | |
| 408 | + | let len = (packed & 0xFFFF_FFFF) as u32; | |
| 409 | + | (ptr, len) | |
| 410 | + | } | |
| 411 | + | ||
| 412 | + | fn read_packed(store: &Store<StoreLimits>, memory: Memory, packed: u64) -> Result<Vec<u8>> { | |
| 413 | + | let (ptr, len) = unpack_ptr_len(packed); | |
| 414 | + | let len_usize = len as usize; | |
| 415 | + | let ptr_usize = ptr as usize; | |
| 416 | + | if len_usize > WASM_MAX_PAYLOAD_BYTES { | |
| 417 | + | return Err(RoneoError::Plugin(format!( | |
| 418 | + | "WASM guest payload ({len_usize} bytes) exceeds maximum allowed ({WASM_MAX_PAYLOAD_BYTES} bytes)" | |
| 419 | + | ))); | |
| 420 | + | } | |
| 421 | + | let mem_size = memory.data_size(store); | |
| 422 | + | if ptr_usize | |
| 423 | + | .checked_add(len_usize) | |
| 424 | + | .is_none_or(|end| end > mem_size) | |
| 425 | + | { | |
| 426 | + | return Err(RoneoError::Plugin( | |
| 427 | + | "WASM guest returned out-of-bounds memory slice".into(), | |
| 428 | + | )); | |
| 429 | + | } | |
| 430 | + | let mut buf = vec![0u8; len_usize]; | |
| 431 | + | memory | |
| 432 | + | .read(store, ptr_usize, &mut buf) | |
| 433 | + | .map_err(|e| RoneoError::Plugin(format!("WASM memory read failed: {e}")))?; | |
| 434 | + | Ok(buf) | |
| 435 | + | } | |
| 436 | + | ||
| 437 | + | /// A sandboxed WebAssembly plugin loaded into `roneo-core` via `wasmi`. | |
| 438 | + | pub struct WasmExtension { | |
| 439 | + | manifest: WasmPluginManifest, | |
| 440 | + | pool: Arc<WasmPool>, | |
| 441 | + | } | |
| 442 | + | ||
| 443 | + | impl WasmExtension { | |
| 444 | + | pub fn from_file(path: &Path) -> Result<Self> { | |
| 445 | + | let bytes = fs::read(path).map_err(|e| RoneoError::io(path, e))?; | |
| 446 | + | Self::from_bytes(&bytes) | |
| 447 | + | } | |
| 448 | + | ||
| 449 | + | pub fn from_bytes(wasm_bytes: &[u8]) -> Result<Self> { | |
| 450 | + | let (pool, manifest) = WasmPool::new(wasm_bytes)?; | |
| 451 | + | Ok(Self { | |
| 452 | + | manifest, | |
| 453 | + | pool: Arc::new(pool), | |
| 454 | + | }) | |
| 455 | + | } | |
| 456 | + | ||
| 457 | + | pub fn manifest(&self) -> &WasmPluginManifest { | |
| 458 | + | &self.manifest | |
| 459 | + | } | |
| 460 | + | } | |
| 461 | + | ||
| 462 | + | impl Extension for WasmExtension { | |
| 463 | + | fn name(&self) -> &str { | |
| 464 | + | &self.manifest.name | |
| 465 | + | } | |
| 466 | + | ||
| 467 | + | fn register(&self, env: &mut Environment<'static>, init: &ExtensionInitContext) -> Result<()> { | |
| 468 | + | if self.manifest.strict_undefined { | |
| 469 | + | env.set_undefined_behavior(UndefinedBehavior::Strict); | |
| 470 | + | } | |
| 471 | + | ||
| 472 | + | // Send sandboxed init payload (reading template_files via `file_reader` — zero disk I/O for GitTree!). | |
| 473 | + | let mut template_files = IndexMap::new(); | |
| 474 | + | for rel in &self.manifest.template_files { | |
| 475 | + | if let Some(content) = (init.file_reader)(rel) { | |
| 476 | + | template_files.insert(rel.clone(), content); | |
| 477 | + | } | |
| 478 | + | } | |
| 479 | + | let recorded_answers = load_recorded_answers_json(&init.dst_path); | |
| 480 | + | let payload = WasmInitPayload { | |
| 481 | + | template_files, | |
| 482 | + | recorded_answers, | |
| 483 | + | dst_path: init.dst_path.to_string_lossy().into_owned(), | |
| 484 | + | template_root: init.template_root.to_string_lossy().into_owned(), | |
| 485 | + | }; | |
| 486 | + | self.pool.set_init_payload(&payload)?; | |
| 487 | + | ||
| 488 | + | for (k, v) in &self.manifest.globals { | |
| 489 | + | env.add_global(k.clone(), MjValue::from(Serde(v))); | |
| 490 | + | } | |
| 491 | + | ||
| 492 | + | let ctx_keys = Arc::new(self.manifest.context_keys.clone()); | |
| 493 | + | ||
| 494 | + | for filter_name in &self.manifest.filters { | |
| 495 | + | let pool = Arc::clone(&self.pool); | |
| 496 | + | let fname = filter_name.clone(); | |
| 497 | + | let keys = Arc::clone(&ctx_keys); | |
| 498 | + | env.add_filter( | |
| 499 | + | filter_name.clone(), | |
| 500 | + | move |state: &State<'_, '_>, | |
| 501 | + | rest: Rest<MjValue>, | |
| 502 | + | kwargs: Kwargs| | |
| 503 | + | -> std::result::Result<MjValue, MjError> { | |
| 504 | + | invoke_wasm_callable(&pool, "filter", &fname, state, &rest.0, &kwargs, &keys) | |
| 505 | + | }, | |
| 506 | + | ); | |
| 507 | + | } | |
| 508 | + | ||
| 509 | + | for func_name in &self.manifest.functions { | |
| 510 | + | let pool = Arc::clone(&self.pool); | |
| 511 | + | let fname = func_name.clone(); | |
| 512 | + | let keys = Arc::clone(&ctx_keys); | |
| 513 | + | env.add_function( | |
| 514 | + | func_name.clone(), | |
| 515 | + | move |state: &State<'_, '_>, | |
| 516 | + | rest: Rest<MjValue>, | |
| 517 | + | kwargs: Kwargs| | |
| 518 | + | -> std::result::Result<MjValue, MjError> { | |
| 519 | + | invoke_wasm_callable(&pool, "function", &fname, state, &rest.0, &kwargs, &keys) | |
| 520 | + | }, | |
| 521 | + | ); | |
| 522 | + | } | |
| 523 | + | ||
| 524 | + | for test_name in &self.manifest.tests { | |
| 525 | + | let pool = Arc::clone(&self.pool); | |
| 526 | + | let tname = test_name.clone(); | |
| 527 | + | let keys = Arc::clone(&ctx_keys); | |
| 528 | + | env.add_test( | |
| 529 | + | test_name.clone(), | |
| 530 | + | move |state: &State<'_, '_>, | |
| 531 | + | rest: Rest<MjValue>, | |
| 532 | + | kwargs: Kwargs| | |
| 533 | + | -> std::result::Result<bool, MjError> { | |
| 534 | + | let val = invoke_wasm_callable( | |
| 535 | + | &pool, "test", &tname, state, &rest.0, &kwargs, &keys, | |
| 536 | + | )?; | |
| 537 | + | Ok(val.is_true()) | |
| 538 | + | }, | |
| 539 | + | ); | |
| 540 | + | } | |
| 541 | + | ||
| 542 | + | Ok(()) | |
| 543 | + | } | |
| 544 | + | ||
| 545 | + | fn hook_context(&self, phase: &str, ctx: &mut IndexMap<String, JsonValue>) -> Result<()> { | |
| 546 | + | if !self.manifest.has_context_hook { | |
| 547 | + | return Ok(()); | |
| 548 | + | } | |
| 549 | + | let mut context = JsonMap::with_capacity(ctx.len()); | |
| 550 | + | for (k, v) in ctx.iter() { | |
| 551 | + | context.insert(k.clone(), v.clone()); | |
| 552 | + | } | |
| 553 | + | let req = WasmCallRequest { | |
| 554 | + | kind: "hook_context", | |
| 555 | + | name: "hook", | |
| 556 | + | args: Vec::new(), | |
| 557 | + | kwargs: JsonMap::new(), | |
| 558 | + | context, | |
| 559 | + | phase, | |
| 560 | + | }; | |
| 561 | + | let result = self.pool.call(&req)?; | |
| 562 | + | if let JsonValue::Object(updates) = result { | |
| 563 | + | for (k, v) in updates { | |
| 564 | + | ctx.insert(k, v); | |
| 565 | + | } | |
| 566 | + | } | |
| 567 | + | Ok(()) | |
| 568 | + | } | |
| 569 | + | } | |
| 570 | + | ||
| 571 | + | fn invoke_wasm_callable( | |
| 572 | + | pool: &Arc<WasmPool>, | |
| 573 | + | kind: &str, | |
| 574 | + | name: &str, | |
| 575 | + | state: &State<'_, '_>, | |
| 576 | + | raw_args: &[MjValue], | |
| 577 | + | raw_kwargs: &Kwargs, | |
| 578 | + | context_keys: &[String], | |
| 579 | + | ) -> std::result::Result<MjValue, MjError> { | |
| 580 | + | let args = raw_args | |
| 581 | + | .iter() | |
| 582 | + | .map(|val| { | |
| 583 | + | serde_json::to_value(val) | |
| 584 | + | .map_err(|e| MjError::new(MjErrorKind::InvalidOperation, e.to_string())) | |
| 585 | + | }) | |
| 586 | + | .collect::<std::result::Result<Vec<_>, _>>()?; | |
| 587 | + | ||
| 588 | + | let mut kwargs = JsonMap::new(); | |
| 589 | + | for key in raw_kwargs.args() { | |
| 590 | + | let val: MjValue = raw_kwargs.get(key)?; | |
| 591 | + | let jv = serde_json::to_value(&val) | |
| 592 | + | .map_err(|e| MjError::new(MjErrorKind::InvalidOperation, e.to_string()))?; | |
| 593 | + | kwargs.insert(key.to_string(), jv); | |
| 594 | + | } | |
| 595 | + | ||
| 596 | + | let context = extract_state_context(state, context_keys); | |
| 597 | + | let req = WasmCallRequest { | |
| 598 | + | kind, | |
| 599 | + | name, | |
| 600 | + | args, | |
| 601 | + | kwargs, | |
| 602 | + | context, | |
| 603 | + | phase: "render", | |
| 604 | + | }; | |
| 605 | + | let val = pool | |
| 606 | + | .call(&req) | |
| 607 | + | .map_err(|e| MjError::new(MjErrorKind::InvalidOperation, e.to_string()))?; | |
| 608 | + | Ok(MjValue::from(Serde(&val))) | |
| 609 | + | } | |
| 610 | + | ||
| 611 | + | fn extract_state_context( | |
| 612 | + | state: &State<'_, '_>, | |
| 613 | + | context_keys: &[String], | |
| 614 | + | ) -> JsonMap<String, JsonValue> { | |
| 615 | + | let mut out = JsonMap::new(); | |
| 616 | + | for key in context_keys { | |
| 617 | + | if let Some(v) = state.lookup(key) | |
| 618 | + | && !v.is_undefined() | |
| 619 | + | && let Ok(jv) = serde_json::to_value(&v) | |
| 620 | + | { | |
| 621 | + | out.insert(key.clone(), jv); | |
| 622 | + | } | |
| 623 | + | } | |
| 624 | + | out | |
| 625 | + | } | |
| 626 | + | ||
| 627 | + | /// Read existing `.copier-answers.yml` in `dst_path` to populate `recorded_answers` for plugins. | |
| 628 | + | pub fn load_recorded_answers_json(dst_path: &Path) -> JsonValue { | |
| 629 | + | let path = dst_path.join(".copier-answers.yml"); | |
| 630 | + | if !path.is_file() { | |
| 631 | + | return JsonValue::Object(JsonMap::new()); | |
| 632 | + | } | |
| 633 | + | let Ok(raw) = fs::read_to_string(&path) else { | |
| 634 | + | return JsonValue::Object(JsonMap::new()); | |
| 635 | + | }; | |
| 636 | + | match serde_yaml_ng::from_str::<serde_yaml_ng::Value>(&raw) { | |
| 637 | + | Ok(y) => match serde_json::to_value(y) { | |
| 638 | + | Ok(JsonValue::Object(map)) if !map.is_empty() => JsonValue::Object(map), | |
| 639 | + | _ => serde_json::json!({ "_unreadable": true }), | |
| 640 | + | }, | |
| 641 | + | Err(_) => serde_json::json!({ "_unreadable": true }), | |
| 642 | + | } | |
| 643 | + | } |
| @@ -0,0 +1,585 @@ | |||
| 1 | + | use std::path::Path; | |
| 2 | + | ||
| 3 | + | use indexmap::IndexMap; | |
| 4 | + | use serde_json::Value as JsonValue; | |
| 5 | + | ||
| 6 | + | use crate::answers::AnswersMap; | |
| 7 | + | use crate::config::{ | |
| 8 | + | ChoiceSpec, Question, QuestionType, TemplateConfig, json_display, parse_choices, | |
| 9 | + | parse_question_type, | |
| 10 | + | }; | |
| 11 | + | use crate::error::{Result, RoneoError}; | |
| 12 | + | use crate::plugin::ExtensionRegistry; | |
| 13 | + | use crate::renderer::{TemplateRenderer, UNSET_SENTINEL, parse_truthy_str}; | |
| 14 | + | ||
| 15 | + | /// Details passed to a `Prompter` implementation when asking the user a question. | |
| 16 | + | #[derive(Debug, Clone)] | |
| 17 | + | pub struct PromptRequest { | |
| 18 | + | pub name: String, | |
| 19 | + | pub kind: QuestionType, | |
| 20 | + | pub message: String, | |
| 21 | + | pub default_display: Option<String>, | |
| 22 | + | pub placeholder: Option<String>, | |
| 23 | + | pub secret: bool, | |
| 24 | + | pub multiselect: bool, | |
| 25 | + | pub multiline: bool, | |
| 26 | + | pub qmark: Option<String>, | |
| 27 | + | } | |
| 28 | + | ||
| 29 | + | /// User response when asked whether to overwrite an existing destination file. | |
| 30 | + | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 31 | + | pub enum OverwriteChoice { | |
| 32 | + | Yes, | |
| 33 | + | No, | |
| 34 | + | All, | |
| 35 | + | Quit, | |
| 36 | + | } | |
| 37 | + | ||
| 38 | + | /// Interactive (or scripted/mock) prompt backend decoupled from `roneo-core`. | |
| 39 | + | pub trait Prompter { | |
| 40 | + | fn prompt_string(&self, req: &PromptRequest) -> Result<String>; | |
| 41 | + | fn prompt_bool(&self, req: &PromptRequest, default: bool) -> Result<bool>; | |
| 42 | + | fn prompt_select( | |
| 43 | + | &self, | |
| 44 | + | req: &PromptRequest, | |
| 45 | + | choices: &[ChoiceSpec], | |
| 46 | + | default_idx: Option<usize>, | |
| 47 | + | ) -> Result<JsonValue>; | |
| 48 | + | fn prompt_multiselect( | |
| 49 | + | &self, | |
| 50 | + | req: &PromptRequest, | |
| 51 | + | choices: &[ChoiceSpec], | |
| 52 | + | defaults: &[usize], | |
| 53 | + | ) -> Result<Vec<JsonValue>>; | |
| 54 | + | fn show_validation_error(&self, question: &str, error: &str); | |
| 55 | + | ||
| 56 | + | /// Ask whether to overwrite an existing differing file in interactive mode. | |
| 57 | + | fn confirm_overwrite(&self, _path: &Path) -> Result<OverwriteChoice> { | |
| 58 | + | Ok(OverwriteChoice::No) | |
| 59 | + | } | |
| 60 | + | } | |
| 61 | + | ||
| 62 | + | /// Non-interactive prompter that never touches stdin/stdout; always relies on defaults/data. | |
| 63 | + | #[derive(Debug, Default)] | |
| 64 | + | pub struct NonInteractivePrompter; | |
| 65 | + | ||
| 66 | + | impl Prompter for NonInteractivePrompter { | |
| 67 | + | fn prompt_string(&self, req: &PromptRequest) -> Result<String> { | |
| 68 | + | req.default_display | |
| 69 | + | .clone() | |
| 70 | + | .ok_or_else(|| RoneoError::InvalidAnswer { | |
| 71 | + | question: req.name.clone(), | |
| 72 | + | message: "No default value available in non-interactive mode (pass `-d key=value`)" | |
| 73 | + | .into(), | |
| 74 | + | }) | |
| 75 | + | } | |
| 76 | + | ||
| 77 | + | fn prompt_bool(&self, _req: &PromptRequest, default: bool) -> Result<bool> { | |
| 78 | + | Ok(default) | |
| 79 | + | } | |
| 80 | + | ||
| 81 | + | fn prompt_select( | |
| 82 | + | &self, | |
| 83 | + | req: &PromptRequest, | |
| 84 | + | choices: &[ChoiceSpec], | |
| 85 | + | default_idx: Option<usize>, | |
| 86 | + | ) -> Result<JsonValue> { | |
| 87 | + | let idx = default_idx.unwrap_or(0); | |
| 88 | + | choices | |
| 89 | + | .get(idx) | |
| 90 | + | .map(|c| c.value.clone()) | |
| 91 | + | .ok_or_else(|| RoneoError::InvalidAnswer { | |
| 92 | + | question: req.name.clone(), | |
| 93 | + | message: "No choices available".into(), | |
| 94 | + | }) | |
| 95 | + | } | |
| 96 | + | ||
| 97 | + | fn prompt_multiselect( | |
| 98 | + | &self, | |
| 99 | + | _req: &PromptRequest, | |
| 100 | + | choices: &[ChoiceSpec], | |
| 101 | + | defaults: &[usize], | |
| 102 | + | ) -> Result<Vec<JsonValue>> { | |
| 103 | + | Ok(defaults | |
| 104 | + | .iter() | |
| 105 | + | .filter_map(|&i| choices.get(i).map(|c| c.value.clone())) | |
| 106 | + | .collect()) | |
| 107 | + | } | |
| 108 | + | ||
| 109 | + | fn show_validation_error(&self, _question: &str, _error: &str) {} | |
| 110 | + | } | |
| 111 | + | ||
| 112 | + | pub struct AnswerCollectionOptions<'a> { | |
| 113 | + | pub data: &'a IndexMap<String, JsonValue>, | |
| 114 | + | pub previous_answers: Option<&'a AnswersMap>, | |
| 115 | + | pub user_defaults: Option<&'a IndexMap<String, JsonValue>>, | |
| 116 | + | pub initial_context: Option<&'a IndexMap<String, JsonValue>>, | |
| 117 | + | pub extensions: Option<&'a ExtensionRegistry>, | |
| 118 | + | pub use_defaults: bool, | |
| 119 | + | pub skip_answered: bool, | |
| 120 | + | pub ask_questions: &'a [String], | |
| 121 | + | } | |
| 122 | + | ||
| 123 | + | /// Evaluate all questions in `config` in order and produce a populated `AnswersMap`. | |
| 124 | + | pub fn collect_answers( | |
| 125 | + | config: &TemplateConfig, | |
| 126 | + | renderer: &TemplateRenderer, | |
| 127 | + | prompter: &dyn Prompter, | |
| 128 | + | opts: &AnswerCollectionOptions<'_>, | |
| 129 | + | ) -> Result<AnswersMap> { | |
| 130 | + | let mut answers = AnswersMap::default(); | |
| 131 | + | if let Some(prev) = opts.previous_answers { | |
| 132 | + | answers.metadata.clone_from(&prev.metadata); | |
| 133 | + | } | |
| 134 | + | ||
| 135 | + | // Track current rendering context as answers are collected. | |
| 136 | + | let mut ctx = IndexMap::<String, JsonValue>::new(); | |
| 137 | + | if let Some(init) = opts.initial_context { | |
| 138 | + | for (k, v) in init { | |
| 139 | + | ctx.insert(k.clone(), v.clone()); | |
| 140 | + | } | |
| 141 | + | } | |
| 142 | + | ctx.insert("_copier_phase".into(), JsonValue::String("prompt".into())); | |
| 143 | + | for (k, v) in opts.data { | |
| 144 | + | ctx.insert(k.clone(), v.clone()); | |
| 145 | + | } | |
| 146 | + | run_prompt_hooks(opts.extensions, &mut ctx)?; | |
| 147 | + | ||
| 148 | + | for (name, raw_question) in &config.questions { | |
| 149 | + | if raw_question.secret { | |
| 150 | + | answers.secrets.insert(name.clone()); | |
| 151 | + | } | |
| 152 | + | ||
| 153 | + | // Resolve dynamic templated `type:` if present. | |
| 154 | + | let mut effective_q: std::borrow::Cow<'_, Question> = | |
| 155 | + | std::borrow::Cow::Borrowed(raw_question); | |
| 156 | + | if let Some(type_tpl) = &raw_question.type_template { | |
| 157 | + | let rendered_type = | |
| 158 | + | renderer.render_str(type_tpl, &ctx, &format!("question:{name}.type"))?; | |
| 159 | + | let resolved_kind = parse_question_type(&rendered_type)?; | |
| 160 | + | effective_q.to_mut().kind = resolved_kind; | |
| 161 | + | } | |
| 162 | + | let question: &Question = &effective_q; | |
| 163 | + | ||
| 164 | + | // 1. Evaluate `when` condition. | |
| 165 | + | if let Some(when_val) = &question.when { | |
| 166 | + | let should_ask = | |
| 167 | + | renderer.eval_condition(when_val, &ctx, &format!("question:{name}.when"))?; | |
| 168 | + | if !should_ask { | |
| 169 | + | // Keep explicit override or rendered default in render context, but do NOT | |
| 170 | + | // persist skipped (`when: false`) question defaults into `.copier-answers.yml` | |
| 171 | + | // (matching Copier). | |
| 172 | + | let mut mutated = false; | |
| 173 | + | if let Some(provided) = opts.data.get(name) { | |
| 174 | + | let coerced = coerce_value(question, provided)?; | |
| 175 | + | ctx.insert(name.clone(), coerced.clone()); | |
| 176 | + | answers.user.insert(name.clone(), coerced); | |
| 177 | + | mutated = true; | |
| 178 | + | } else if let Some(def) = resolve_default(question, None, None, renderer, &ctx)? { | |
| 179 | + | ctx.insert(name.clone(), def.clone()); | |
| 180 | + | answers.default_only.insert(name.clone(), def); | |
| 181 | + | mutated = true; | |
| 182 | + | } | |
| 183 | + | if mutated { | |
| 184 | + | run_prompt_hooks(opts.extensions, &mut ctx)?; | |
| 185 | + | } | |
| 186 | + | continue; | |
| 187 | + | } | |
| 188 | + | } | |
| 189 | + | ||
| 190 | + | // 2. Render choices (choice labels and string values may contain Jinja). | |
| 191 | + | let rendered_choices = render_choices(question, renderer, &ctx)?; | |
| 192 | + | ||
| 193 | + | // 3. Resolve effective default (previous answer > user settings default > question default). | |
| 194 | + | let prev_val = opts.previous_answers.and_then(|p| p.user.get(name)); | |
| 195 | + | let user_def = opts.user_defaults.and_then(|d| d.get(name)); | |
| 196 | + | let default_val = resolve_default(question, prev_val, user_def, renderer, &ctx)?; | |
| 197 | + | ||
| 198 | + | // 4. Explicit CLI/data override? | |
| 199 | + | if let Some(provided) = opts.data.get(name) { | |
| 200 | + | let coerced = coerce_value(question, provided)?; | |
| 201 | + | validate_answer( | |
| 202 | + | question, | |
| 203 | + | &coerced, | |
| 204 | + | rendered_choices.as_deref(), | |
| 205 | + | renderer, | |
| 206 | + | &ctx, | |
| 207 | + | )?; | |
| 208 | + | ctx.insert(name.clone(), coerced.clone()); | |
| 209 | + | answers.user.insert(name.clone(), coerced); | |
| 210 | + | run_prompt_hooks(opts.extensions, &mut ctx)?; | |
| 211 | + | continue; | |
| 212 | + | } | |
| 213 | + | ||
| 214 | + | // 5. Auto-accept default if `--defaults`, `ask: false`, or `--skip-answered` with previous answer, | |
| 215 | + | // unless the user explicitly forced this question via `--ask <glob>` (Copier v9.17 / v9.19). | |
| 216 | + | let explicitly_asked = opts | |
| 217 | + | .ask_questions | |
| 218 | + | .iter() | |
| 219 | + | .any(|pat| crate::filter::glob_match(pat, name)); | |
| 220 | + | let should_ask = match &question.ask { | |
| 221 | + | Some(expr) => renderer.eval_condition(expr, &ctx, &format!("question:{name}.ask"))?, | |
| 222 | + | None => true, | |
| 223 | + | }; | |
| 224 | + | let auto_use_default = !explicitly_asked | |
| 225 | + | && (!should_ask || opts.use_defaults || (opts.skip_answered && prev_val.is_some())); | |
| 226 | + | if auto_use_default { | |
| 227 | + | let chosen = if let Some(val) = default_val { | |
| 228 | + | val | |
| 229 | + | } else if let Some(choices) = &rendered_choices | |
| 230 | + | && let Some(first) = choices.first() | |
| 231 | + | { | |
| 232 | + | if question.multiselect { | |
| 233 | + | JsonValue::Array(Vec::new()) | |
| 234 | + | } else { | |
| 235 | + | first.value.clone() | |
| 236 | + | } | |
| 237 | + | } else if question.kind == QuestionType::Bool { | |
| 238 | + | JsonValue::Bool(false) | |
| 239 | + | } else { | |
| 240 | + | return Err(RoneoError::InvalidAnswer { | |
| 241 | + | question: name.clone(), | |
| 242 | + | message: | |
| 243 | + | "Question has no default value; pass `-d key=value` or run interactively" | |
| 244 | + | .into(), | |
| 245 | + | }); | |
| 246 | + | }; | |
| 247 | + | validate_answer( | |
| 248 | + | question, | |
| 249 | + | &chosen, | |
| 250 | + | rendered_choices.as_deref(), | |
| 251 | + | renderer, | |
| 252 | + | &ctx, | |
| 253 | + | )?; | |
| 254 | + | ctx.insert(name.clone(), chosen.clone()); | |
| 255 | + | answers.user.insert(name.clone(), chosen); | |
| 256 | + | run_prompt_hooks(opts.extensions, &mut ctx)?; | |
| 257 | + | continue; | |
| 258 | + | } | |
| 259 | + | ||
| 260 | + | // 6. Ask interactively (looping on validation error). | |
| 261 | + | let help_msg = match &question.help { | |
| 262 | + | Some(h) => renderer.render_str(h, &ctx, &format!("question:{name}.help"))?, | |
| 263 | + | None => format!("{name}?"), | |
| 264 | + | }; | |
| 265 | + | let placeholder = match &question.placeholder { | |
| 266 | + | Some(p) => { | |
| 267 | + | Some(renderer.render_str(p, &ctx, &format!("question:{name}.placeholder"))?) | |
| 268 | + | } | |
| 269 | + | None => None, | |
| 270 | + | }; | |
| 271 | + | let multiline = match &question.multiline_expr { | |
| 272 | + | Some(expr) => { | |
| 273 | + | renderer.eval_condition(expr, &ctx, &format!("question:{name}.multiline"))? | |
| 274 | + | } | |
| 275 | + | None => matches!(question.kind, QuestionType::Yaml | QuestionType::Json), | |
| 276 | + | }; | |
| 277 | + | ||
| 278 | + | let req = PromptRequest { | |
| 279 | + | name: name.clone(), | |
| 280 | + | kind: question.kind, | |
| 281 | + | message: help_msg, | |
| 282 | + | default_display: default_val.as_ref().map(json_display), | |
| 283 | + | placeholder, | |
| 284 | + | secret: question.secret, | |
| 285 | + | multiselect: question.multiselect, | |
| 286 | + | multiline, | |
| 287 | + | qmark: question.qmark.clone(), | |
| 288 | + | }; | |
| 289 | + | ||
| 290 | + | let answer_val = loop { | |
| 291 | + | let candidate = if let Some(choices) = &rendered_choices { | |
| 292 | + | if question.multiselect { | |
| 293 | + | let default_indices = default_val | |
| 294 | + | .as_ref() | |
| 295 | + | .and_then(JsonValue::as_array) | |
| 296 | + | .map_or_default(|arr| { | |
| 297 | + | choices | |
| 298 | + | .iter() | |
| 299 | + | .enumerate() | |
| 300 | + | .filter_map(|(i, c)| arr.contains(&c.value).then_some(i)) | |
| 301 | + | .collect::<Vec<_>>() | |
| 302 | + | }); | |
| 303 | + | let picked = prompter.prompt_multiselect(&req, choices, &default_indices)?; | |
| 304 | + | JsonValue::Array(picked) | |
| 305 | + | } else { | |
| 306 | + | let default_idx = default_val | |
| 307 | + | .as_ref() | |
| 308 | + | .and_then(|d| choices.iter().position(|c| &c.value == d)); | |
| 309 | + | prompter.prompt_select(&req, choices, default_idx)? | |
| 310 | + | } | |
| 311 | + | } else if question.kind == QuestionType::Bool { | |
| 312 | + | let def_bool = default_val | |
| 313 | + | .as_ref() | |
| 314 | + | .and_then(JsonValue::as_bool) | |
| 315 | + | .unwrap_or(false); | |
| 316 | + | JsonValue::Bool(prompter.prompt_bool(&req, def_bool)?) | |
| 317 | + | } else { | |
| 318 | + | let raw = prompter.prompt_string(&req)?; | |
| 319 | + | match parse_raw_answer(question, &raw) { | |
| 320 | + | Ok(v) => v, | |
| 321 | + | Err(e) => { | |
| 322 | + | prompter.show_validation_error(name, &e.to_string()); | |
| 323 | + | continue; | |
| 324 | + | } | |
| 325 | + | } | |
| 326 | + | }; | |
| 327 | + | ||
| 328 | + | match validate_answer( | |
| 329 | + | question, | |
| 330 | + | &candidate, | |
| 331 | + | rendered_choices.as_deref(), | |
| 332 | + | renderer, | |
| 333 | + | &ctx, | |
| 334 | + | ) { | |
| 335 | + | Ok(()) => break candidate, | |
| 336 | + | Err(RoneoError::InvalidAnswer { message, .. }) => { | |
| 337 | + | prompter.show_validation_error(name, &message); | |
| 338 | + | } | |
| 339 | + | Err(e) => return Err(e), | |
| 340 | + | } | |
| 341 | + | }; | |
| 342 | + | ||
| 343 | + | ctx.insert(name.clone(), answer_val.clone()); | |
| 344 | + | answers.user.insert(name.clone(), answer_val); | |
| 345 | + | run_prompt_hooks(opts.extensions, &mut ctx)?; | |
| 346 | + | } | |
| 347 | + | ||
| 348 | + | // Preserve extra `-d` data keys that weren't declared as questions (Copier allows extra data). | |
| 349 | + | for (k, v) in opts.data { | |
| 350 | + | if !answers.user.contains_key(k) && !k.starts_with('_') { | |
| 351 | + | answers.user.insert(k.clone(), v.clone()); | |
| 352 | + | } | |
| 353 | + | } | |
| 354 | + | ||
| 355 | + | Ok(answers) | |
| 356 | + | } | |
| 357 | + | ||
| 358 | + | fn run_prompt_hooks( | |
| 359 | + | extensions: Option<&ExtensionRegistry>, | |
| 360 | + | ctx: &mut IndexMap<String, JsonValue>, | |
| 361 | + | ) -> Result<()> { | |
| 362 | + | if let Some(exts) = extensions | |
| 363 | + | && !exts.is_empty() | |
| 364 | + | { | |
| 365 | + | exts.run_context_hooks("prompt", ctx)?; | |
| 366 | + | } | |
| 367 | + | Ok(()) | |
| 368 | + | } | |
| 369 | + | ||
| 370 | + | fn resolve_default( | |
| 371 | + | question: &Question, | |
| 372 | + | prev_val: Option<&JsonValue>, | |
| 373 | + | user_def: Option<&JsonValue>, | |
| 374 | + | renderer: &TemplateRenderer, | |
| 375 | + | ctx: &IndexMap<String, JsonValue>, | |
| 376 | + | ) -> Result<Option<JsonValue>> { | |
| 377 | + | if let Some(prev) = prev_val { | |
| 378 | + | return Ok(Some(coerce_value(question, prev)?)); | |
| 379 | + | } | |
| 380 | + | if let Some(udef) = user_def { | |
| 381 | + | return Ok(Some(coerce_value(question, udef)?)); | |
| 382 | + | } | |
| 383 | + | let Some(def) = &question.default else { | |
| 384 | + | return Ok(None); | |
| 385 | + | }; | |
| 386 | + | let rendered_default = render_json_strings( | |
| 387 | + | def, | |
| 388 | + | renderer, | |
| 389 | + | ctx, | |
| 390 | + | &format!("question:{}.default", question.name), | |
| 391 | + | )?; | |
| 392 | + | if rendered_default.as_str() == Some(UNSET_SENTINEL) { | |
| 393 | + | return Ok(None); | |
| 394 | + | } | |
| 395 | + | Ok(Some(coerce_value(question, &rendered_default)?)) | |
| 396 | + | } | |
| 397 | + | ||
| 398 | + | fn render_choices( | |
| 399 | + | question: &Question, | |
| 400 | + | renderer: &TemplateRenderer, | |
| 401 | + | ctx: &IndexMap<String, JsonValue>, | |
| 402 | + | ) -> Result<Option<Vec<ChoiceSpec>>> { | |
| 403 | + | let dynamic_choices: Option<Vec<ChoiceSpec>> = if let Some(tpl) = &question.choices_template { | |
| 404 | + | let yaml_text = | |
| 405 | + | renderer.render_str(tpl, ctx, &format!("question:{}.choices", question.name))?; | |
| 406 | + | let yaml_val: serde_yaml_ng::Value = serde_yaml_ng::from_str(&yaml_text)?; | |
| 407 | + | Some(parse_choices(&question.name, &yaml_val)?) | |
| 408 | + | } else { | |
| 409 | + | None | |
| 410 | + | }; | |
| 411 | + | ||
| 412 | + | let Some(choices) = dynamic_choices.as_deref().or(question.choices.as_deref()) else { | |
| 413 | + | return Ok(None); | |
| 414 | + | }; | |
| 415 | + | let mut out = Vec::with_capacity(choices.len()); | |
| 416 | + | for (i, choice) in choices.iter().enumerate() { | |
| 417 | + | let label = renderer.render_str( | |
| 418 | + | &choice.label, | |
| 419 | + | ctx, | |
| 420 | + | &format!("question:{}.choices[{i}].label", question.name), | |
| 421 | + | )?; | |
| 422 | + | let value = render_json_strings( | |
| 423 | + | &choice.value, | |
| 424 | + | renderer, | |
| 425 | + | ctx, | |
| 426 | + | &format!("question:{}.choices[{i}].value", question.name), | |
| 427 | + | )?; | |
| 428 | + | let coerced = if question.multiselect { | |
| 429 | + | value | |
| 430 | + | } else { | |
| 431 | + | coerce_value(question, &value)? | |
| 432 | + | }; | |
| 433 | + | out.push(ChoiceSpec { | |
| 434 | + | label, | |
| 435 | + | value: coerced, | |
| 436 | + | }); | |
| 437 | + | } | |
| 438 | + | Ok(Some(out)) | |
| 439 | + | } | |
| 440 | + | ||
| 441 | + | fn render_json_strings( | |
| 442 | + | val: &JsonValue, | |
| 443 | + | renderer: &TemplateRenderer, | |
| 444 | + | ctx: &IndexMap<String, JsonValue>, | |
| 445 | + | label: &str, | |
| 446 | + | ) -> Result<JsonValue> { | |
| 447 | + | match val { | |
| 448 | + | JsonValue::String(s) => Ok(JsonValue::String(renderer.render_str(s, ctx, label)?)), | |
| 449 | + | JsonValue::Array(items) => { | |
| 450 | + | let mut out = Vec::with_capacity(items.len()); | |
| 451 | + | for item in items { | |
| 452 | + | out.push(render_json_strings(item, renderer, ctx, label)?); | |
| 453 | + | } | |
| 454 | + | Ok(JsonValue::Array(out)) | |
| 455 | + | } | |
| 456 | + | other => Ok(other.clone()), | |
| 457 | + | } | |
| 458 | + | } | |
| 459 | + | ||
| 460 | + | pub fn parse_raw_answer(question: &Question, raw: &str) -> Result<JsonValue> { | |
| 461 | + | let name = &question.name; | |
| 462 | + | match question.kind { | |
| 463 | + | QuestionType::Str => Ok(JsonValue::String(raw.to_string())), | |
| 464 | + | QuestionType::Int => { | |
| 465 | + | raw.trim() | |
| 466 | + | .parse::<i64>() | |
| 467 | + | .map(JsonValue::from) | |
| 468 | + | .map_err(|_| RoneoError::InvalidAnswer { | |
| 469 | + | question: name.clone(), | |
| 470 | + | message: format!("Expected an integer, got '{raw}'"), | |
| 471 | + | }) | |
| 472 | + | } | |
| 473 | + | QuestionType::Float => { | |
| 474 | + | raw.trim() | |
| 475 | + | .parse::<f64>() | |
| 476 | + | .map(JsonValue::from) | |
| 477 | + | .map_err(|_| RoneoError::InvalidAnswer { | |
| 478 | + | question: name.clone(), | |
| 479 | + | message: format!("Expected a number, got '{raw}'"), | |
| 480 | + | }) | |
| 481 | + | } | |
| 482 | + | QuestionType::Bool => Ok(JsonValue::Bool(parse_truthy_str(raw))), | |
| 483 | + | QuestionType::Yaml => { | |
| 484 | + | let y: serde_yaml_ng::Value = | |
| 485 | + | serde_yaml_ng::from_str(raw).map_err(|e| RoneoError::InvalidAnswer { | |
| 486 | + | question: name.clone(), | |
| 487 | + | message: format!("Invalid YAML: {e}"), | |
| 488 | + | })?; | |
| 489 | + | Ok(serde_json::to_value(y)?) | |
| 490 | + | } | |
| 491 | + | QuestionType::Json => serde_json::from_str(raw).map_err(|e| RoneoError::InvalidAnswer { | |
| 492 | + | question: name.clone(), | |
| 493 | + | message: format!("Invalid JSON: {e}"), | |
| 494 | + | }), | |
| 495 | + | } | |
| 496 | + | } | |
| 497 | + | ||
| 498 | + | fn coerce_value(question: &Question, value: &JsonValue) -> Result<JsonValue> { | |
| 499 | + | if question.multiselect { | |
| 500 | + | return match value { | |
| 501 | + | JsonValue::Array(_) => Ok(value.clone()), | |
| 502 | + | JsonValue::String(s) => { | |
| 503 | + | if let Ok(yaml_val) = serde_yaml_ng::from_str::<serde_yaml_ng::Value>(s) | |
| 504 | + | && let Ok(JsonValue::Array(arr)) = serde_json::to_value(yaml_val) | |
| 505 | + | { | |
| 506 | + | return Ok(JsonValue::Array(arr)); | |
| 507 | + | } | |
| 508 | + | Ok(JsonValue::Array(vec![value.clone()])) | |
| 509 | + | } | |
| 510 | + | other => Ok(JsonValue::Array(vec![other.clone()])), | |
| 511 | + | }; | |
| 512 | + | } | |
| 513 | + | ||
| 514 | + | if value.is_null() { | |
| 515 | + | return Ok(JsonValue::Null); | |
| 516 | + | } | |
| 517 | + | ||
| 518 | + | match (question.kind, value) { | |
| 519 | + | ( | |
| 520 | + | QuestionType::Yaml | QuestionType::Json | QuestionType::Int | QuestionType::Float, | |
| 521 | + | JsonValue::String(s), | |
| 522 | + | ) => parse_raw_answer(question, s), | |
| 523 | + | (QuestionType::Str, JsonValue::String(_)) | |
| 524 | + | | (QuestionType::Bool, JsonValue::Bool(_)) | |
| 525 | + | | (QuestionType::Float, JsonValue::Number(_)) | |
| 526 | + | | (QuestionType::Yaml | QuestionType::Json, _) => Ok(value.clone()), | |
| 527 | + | (QuestionType::Str, other) => Ok(JsonValue::String(json_display(other))), | |
| 528 | + | (QuestionType::Int, JsonValue::Number(n)) if n.is_i64() => Ok(value.clone()), | |
| 529 | + | (QuestionType::Bool, JsonValue::String(s)) => Ok(JsonValue::Bool(parse_truthy_str(s))), | |
| 530 | + | _ => parse_raw_answer(question, &json_display(value)), | |
| 531 | + | } | |
| 532 | + | } | |
| 533 | + | ||
| 534 | + | fn validate_answer( | |
| 535 | + | question: &Question, | |
| 536 | + | value: &JsonValue, | |
| 537 | + | choices: Option<&[ChoiceSpec]>, | |
| 538 | + | renderer: &TemplateRenderer, | |
| 539 | + | ctx: &IndexMap<String, JsonValue>, | |
| 540 | + | ) -> Result<()> { | |
| 541 | + | if let Some(allowed) = choices { | |
| 542 | + | if question.multiselect { | |
| 543 | + | if let Some(arr) = value.as_array() { | |
| 544 | + | for item in arr { | |
| 545 | + | if !allowed.iter().any(|c| &c.value == item) { | |
| 546 | + | return Err(RoneoError::InvalidAnswer { | |
| 547 | + | question: question.name.clone(), | |
| 548 | + | message: format!( | |
| 549 | + | "Value '{}' is not one of the allowed choices", | |
| 550 | + | json_display(item) | |
| 551 | + | ), | |
| 552 | + | }); | |
| 553 | + | } | |
| 554 | + | } | |
| 555 | + | } | |
| 556 | + | } else if !allowed.iter().any(|c| &c.value == value) { | |
| 557 | + | return Err(RoneoError::InvalidAnswer { | |
| 558 | + | question: question.name.clone(), | |
| 559 | + | message: format!( | |
| 560 | + | "Value '{}' is not one of the allowed choices", | |
| 561 | + | json_display(value) | |
| 562 | + | ), | |
| 563 | + | }); | |
| 564 | + | } | |
| 565 | + | } | |
| 566 | + | ||
| 567 | + | if let Some(validator_tpl) = &question.validator { | |
| 568 | + | let mut check_ctx = ctx.clone(); | |
| 569 | + | check_ctx.insert(question.name.clone(), value.clone()); | |
| 570 | + | let msg = renderer.render_str( | |
| 571 | + | validator_tpl, | |
| 572 | + | &check_ctx, | |
| 573 | + | &format!("question:{}.validator", question.name), | |
| 574 | + | )?; | |
| 575 | + | let trimmed = msg.trim(); | |
| 576 | + | if !trimmed.is_empty() { | |
| 577 | + | return Err(RoneoError::InvalidAnswer { | |
| 578 | + | question: question.name.clone(), | |
| 579 | + | message: trimmed.to_string(), | |
| 580 | + | }); | |
| 581 | + | } | |
| 582 | + | } | |
| 583 | + | ||
| 584 | + | Ok(()) | |
| 585 | + | } |
| @@ -0,0 +1,1021 @@ | |||
| 1 | + | use std::collections::HashMap; | |
| 2 | + | use std::fmt::Write as _; | |
| 3 | + | use std::path::{Component, Path, PathBuf}; | |
| 4 | + | use std::sync::RwLock; | |
| 5 | + | ||
| 6 | + | use indexmap::IndexMap; | |
| 7 | + | use minijinja::syntax::SyntaxConfig; | |
| 8 | + | use minijinja::{Environment, Value as MjValue}; | |
| 9 | + | use serde_json::Value as JsonValue; | |
| 10 | + | ||
| 11 | + | use crate::config::EnvOps; | |
| 12 | + | use crate::error::{Result, RoneoError}; | |
| 13 | + | use crate::plugin::{ExtensionInitContext, ExtensionRegistry, TemplateFileReader}; | |
| 14 | + | ||
| 15 | + | /// Sentinel global matching Copier's `{{ UNSET }}` in question `default:` templates. | |
| 16 | + | pub const UNSET_SENTINEL: &str = "__RONEO_COPIER_UNSET_SENTINEL__"; | |
| 17 | + | ||
| 18 | + | /// Metadata exposed as `_copier_conf` inside templates (Copier-compatible). | |
| 19 | + | #[derive(Debug, Clone, serde::Serialize)] | |
| 20 | + | pub struct CopierConf { | |
| 21 | + | pub src_path: String, | |
| 22 | + | pub dst_path: String, | |
| 23 | + | pub answers_file: String, | |
| 24 | + | pub vcs_ref: Option<String>, | |
| 25 | + | pub vcs_ref_hash: Option<String>, | |
| 26 | + | pub sep: String, | |
| 27 | + | pub os: String, | |
| 28 | + | pub stage: String, | |
| 29 | + | pub overwrite: bool, | |
| 30 | + | pub pretend: bool, | |
| 31 | + | pub quiet: bool, | |
| 32 | + | #[serde(rename = "unsafe")] | |
| 33 | + | pub r#unsafe: bool, | |
| 34 | + | pub cleanup_on_error: bool, | |
| 35 | + | pub context_lines: usize, | |
| 36 | + | pub exclude: Vec<String>, | |
| 37 | + | pub skip_if_exists: Vec<String>, | |
| 38 | + | } | |
| 39 | + | ||
| 40 | + | /// Result of rendering one path segment (supports Copier's `{% yield var from list %}` | |
| 41 | + | /// expanding a single template file or directory into multiple rendered destinations). | |
| 42 | + | #[derive(Debug, Clone)] | |
| 43 | + | pub struct RenderedSegment { | |
| 44 | + | pub name: String, | |
| 45 | + | pub is_template_file: bool, | |
| 46 | + | pub yield_binding: Option<(String, JsonValue)>, | |
| 47 | + | } | |
| 48 | + | ||
| 49 | + | /// Jinja2-compatible template rendering engine powered by `MiniJinja` + `pycompat`. | |
| 50 | + | pub struct TemplateRenderer { | |
| 51 | + | env: Environment<'static>, | |
| 52 | + | var_start: String, | |
| 53 | + | block_start: String, | |
| 54 | + | block_end: String, | |
| 55 | + | comment_start: String, | |
| 56 | + | keep_trailing_newline: bool, | |
| 57 | + | } | |
| 58 | + | ||
| 59 | + | impl TemplateRenderer { | |
| 60 | + | pub fn new(envops: &EnvOps) -> Result<Self> { | |
| 61 | + | Self::with_extensions(envops, None, None, None) | |
| 62 | + | } | |
| 63 | + | ||
| 64 | + | /// Create a renderer that supports `{% include "..." %}` via a cached file reader | |
| 65 | + | /// (works for both disk checkouts and in-memory `gix` trees) and optional extensions. | |
| 66 | + | pub fn with_extensions( | |
| 67 | + | envops: &EnvOps, | |
| 68 | + | file_reader: Option<TemplateFileReader>, | |
| 69 | + | extensions: Option<&ExtensionRegistry>, | |
| 70 | + | init_ctx: Option<&ExtensionInitContext>, | |
| 71 | + | ) -> Result<Self> { | |
| 72 | + | let mut env = Environment::new(); | |
| 73 | + | let syntax = SyntaxConfig::builder() | |
| 74 | + | .block_delimiters( | |
| 75 | + | envops.block_start_string.clone(), | |
| 76 | + | envops.block_end_string.clone(), | |
| 77 | + | ) | |
| 78 | + | .variable_delimiters( | |
| 79 | + | envops.variable_start_string.clone(), | |
| 80 | + | envops.variable_end_string.clone(), | |
| 81 | + | ) | |
| 82 | + | .comment_delimiters( | |
| 83 | + | envops.comment_start_string.clone(), | |
| 84 | + | envops.comment_end_string.clone(), | |
| 85 | + | ) | |
| 86 | + | .keep_trailing_newline(envops.keep_trailing_newline) | |
| 87 | + | .trim_blocks(envops.trim_blocks) | |
| 88 | + | .lstrip_blocks(envops.lstrip_blocks) | |
| 89 | + | .build() | |
| 90 | + | .map_err(|e| RoneoError::InvalidConfig(format!("Invalid `_envops`: {e}")))?; | |
| 91 | + | ||
| 92 | + | env.set_syntax(syntax); | |
| 93 | + | // Copier never auto-escapes template outputs (MiniJinja defaults to JSON-escaping `.yml`/`.yaml`). | |
| 94 | + | env.set_auto_escape_callback(|_| minijinja::AutoEscape::None); | |
| 95 | + | ||
| 96 | + | if let Some(reader) = file_reader { | |
| 97 | + | let cache: RwLock<HashMap<String, Option<String>>> = RwLock::new(HashMap::new()); | |
| 98 | + | env.set_loader(move |name| { | |
| 99 | + | if let Ok(guard) = cache.read() | |
| 100 | + | && let Some(cached) = guard.get(name) | |
| 101 | + | { | |
| 102 | + | return Ok(cached.clone()); | |
| 103 | + | } | |
| 104 | + | let loaded = reader(name); | |
| 105 | + | if let Ok(mut guard) = cache.write() { | |
| 106 | + | guard.insert(name.to_string(), loaded.clone()); | |
| 107 | + | } | |
| 108 | + | Ok(loaded) | |
| 109 | + | }); | |
| 110 | + | } | |
| 111 | + | ||
| 112 | + | // Enable Python-compatible string/list/dict methods & extra Jinja2 utilities. | |
| 113 | + | minijinja_contrib::add_to_environment(&mut env); | |
| 114 | + | env.set_unknown_method_callback(minijinja_contrib::pycompat::unknown_method_callback); | |
| 115 | + | ||
| 116 | + | // Register Copier-specific filters & globals. | |
| 117 | + | env.add_global("UNSET", UNSET_SENTINEL); | |
| 118 | + | env.add_function("pathjoin", func_pathjoin); | |
| 119 | + | env.add_function("now", func_now); | |
| 120 | + | env.add_filter("format", filter_printf_format); | |
| 121 | + | env.add_filter("to_nice_yaml", filter_to_nice_yaml); | |
| 122 | + | env.add_filter("to_yaml", filter_to_nice_yaml); | |
| 123 | + | env.add_filter("from_yaml", filter_from_yaml); | |
| 124 | + | env.add_filter("to_json", filter_to_json); | |
| 125 | + | env.add_filter("to_nice_json", filter_to_nice_json); | |
| 126 | + | env.add_filter("from_json", filter_from_json); | |
| 127 | + | env.add_filter("slugify", filter_slugify); | |
| 128 | + | env.add_filter("to_snake", filter_to_snake); | |
| 129 | + | env.add_filter("snake_case", filter_to_snake); | |
| 130 | + | env.add_filter("to_kebab", filter_to_kebab); | |
| 131 | + | env.add_filter("kebab_case", filter_to_kebab); | |
| 132 | + | env.add_filter("to_camel", filter_to_camel); | |
| 133 | + | env.add_filter("camel_case", filter_to_camel); | |
| 134 | + | env.add_filter("to_pascal", filter_to_pascal); | |
| 135 | + | env.add_filter("pascal_case", filter_to_pascal); | |
| 136 | + | env.add_filter("b64encode", filter_b64encode); | |
| 137 | + | env.add_filter("b64decode", filter_b64decode); | |
| 138 | + | env.add_filter("to_bool", filter_to_bool); | |
| 139 | + | env.add_filter("basename", filter_basename); | |
| 140 | + | env.add_filter("dirname", filter_dirname); | |
| 141 | + | env.add_filter("quote", filter_shell_quote); | |
| 142 | + | ||
| 143 | + | if let (Some(reg), Some(init)) = (extensions, init_ctx) { | |
| 144 | + | reg.register_all(&mut env, init)?; | |
| 145 | + | } | |
| 146 | + | ||
| 147 | + | Ok(Self { | |
| 148 | + | env, | |
| 149 | + | var_start: envops.variable_start_string.clone(), | |
| 150 | + | block_start: envops.block_start_string.clone(), | |
| 151 | + | block_end: envops.block_end_string.clone(), | |
| 152 | + | comment_start: envops.comment_start_string.clone(), | |
| 153 | + | keep_trailing_newline: envops.keep_trailing_newline, | |
| 154 | + | }) | |
| 155 | + | } | |
| 156 | + | ||
| 157 | + | /// Fast check: returns `true` when `template` contains none of the configured Jinja | |
| 158 | + | /// opening delimiters and therefore requires no parsing or evaluation. | |
| 159 | + | #[inline] | |
| 160 | + | fn is_plain_text(&self, template: &str) -> bool { | |
| 161 | + | !template.contains(self.var_start.as_str()) | |
| 162 | + | && !template.contains(self.block_start.as_str()) | |
| 163 | + | && !template.contains(self.comment_start.as_str()) | |
| 164 | + | } | |
| 165 | + | ||
| 166 | + | /// Pre-convert a JSON context map into a reusable, thread-safe `minijinja::Value` | |
| 167 | + | /// (avoids re-converting large contexts on every file/path render). | |
| 168 | + | pub fn compile_context(ctx: &IndexMap<String, JsonValue>) -> MjValue { | |
| 169 | + | MjValue::from(minijinja::value::Serde(ctx)) | |
| 170 | + | } | |
| 171 | + | ||
| 172 | + | /// Render a Jinja template string with the given context. | |
| 173 | + | pub fn render_str( | |
| 174 | + | &self, | |
| 175 | + | template: &str, | |
| 176 | + | ctx: &IndexMap<String, JsonValue>, | |
| 177 | + | label: &str, | |
| 178 | + | ) -> Result<String> { | |
| 179 | + | if self.is_plain_text(template) { | |
| 180 | + | return Ok(self.apply_plain_trailing_newline(template)); | |
| 181 | + | } | |
| 182 | + | let normalized = normalize_jinja2_printf_modulo(template); | |
| 183 | + | self.env | |
| 184 | + | .render_named_str(label, normalized.as_ref(), minijinja::value::Serde(ctx)) | |
| 185 | + | .map_err(|source| RoneoError::TemplateRender { | |
| 186 | + | context: label.to_string(), | |
| 187 | + | source, | |
| 188 | + | }) | |
| 189 | + | } | |
| 190 | + | ||
| 191 | + | /// Render a Jinja template string using a pre-converted `minijinja::Value` context. | |
| 192 | + | pub fn render_str_value(&self, template: &str, ctx: &MjValue, label: &str) -> Result<String> { | |
| 193 | + | if self.is_plain_text(template) { | |
| 194 | + | return Ok(self.apply_plain_trailing_newline(template)); | |
| 195 | + | } | |
| 196 | + | let normalized = normalize_jinja2_printf_modulo(template); | |
| 197 | + | self.env | |
| 198 | + | .render_named_str(label, normalized.as_ref(), ctx) | |
| 199 | + | .map_err(|source| RoneoError::TemplateRender { | |
| 200 | + | context: label.to_string(), | |
| 201 | + | source, | |
| 202 | + | }) | |
| 203 | + | } | |
| 204 | + | ||
| 205 | + | #[inline] | |
| 206 | + | fn apply_plain_trailing_newline(&self, template: &str) -> String { | |
| 207 | + | if self.keep_trailing_newline { | |
| 208 | + | template.to_string() | |
| 209 | + | } else { | |
| 210 | + | template | |
| 211 | + | .strip_suffix("\r\n") | |
| 212 | + | .or_else(|| template.strip_suffix('\n')) | |
| 213 | + | .unwrap_or(template) | |
| 214 | + | .to_string() | |
| 215 | + | } | |
| 216 | + | } | |
| 217 | + | ||
| 218 | + | /// Evaluate a `when` condition (boolean literal or Jinja template string). | |
| 219 | + | pub fn eval_condition( | |
| 220 | + | &self, | |
| 221 | + | when: &JsonValue, | |
| 222 | + | ctx: &IndexMap<String, JsonValue>, | |
| 223 | + | label: &str, | |
| 224 | + | ) -> Result<bool> { | |
| 225 | + | match when { | |
| 226 | + | JsonValue::Bool(b) => Ok(*b), | |
| 227 | + | JsonValue::Null => Ok(true), | |
| 228 | + | JsonValue::String(s) => self.eval_condition_str(s, ctx, label), | |
| 229 | + | other => Ok(is_truthy_json(other)), | |
| 230 | + | } | |
| 231 | + | } | |
| 232 | + | ||
| 233 | + | pub fn eval_condition_str( | |
| 234 | + | &self, | |
| 235 | + | expr: &str, | |
| 236 | + | ctx: &IndexMap<String, JsonValue>, | |
| 237 | + | label: &str, | |
| 238 | + | ) -> Result<bool> { | |
| 239 | + | let rendered = self.render_str(expr, ctx, label)?; | |
| 240 | + | Ok(parse_truthy_str(&rendered)) | |
| 241 | + | } | |
| 242 | + | ||
| 243 | + | /// Expand a single path segment, supporting Copier 9's `{% yield var from iterable %}...{% endyield %}` | |
| 244 | + | /// tag to generate multiple files/directories from one template entry. | |
| 245 | + | /// | |
| 246 | + | /// On ordinary segments (no `yield`), takes the zero-overhead single-segment fast path. | |
| 247 | + | #[allow(clippy::too_many_arguments)] | |
| 248 | + | pub fn render_segment_expanded_value( | |
| 249 | + | &self, | |
| 250 | + | raw_segment: &str, | |
| 251 | + | is_dir: bool, | |
| 252 | + | templates_suffix: &str, | |
| 253 | + | base_ctx: &IndexMap<String, JsonValue>, | |
| 254 | + | extra_vars: &[(String, JsonValue)], | |
| 255 | + | compiled_ctx: &MjValue, | |
| 256 | + | label: &str, | |
| 257 | + | ) -> Result<Vec<RenderedSegment>> { | |
| 258 | + | // Fast path: no `yield` keyword in segment. | |
| 259 | + | if !raw_segment.contains("yield") || !raw_segment.contains(self.block_start.as_str()) { | |
| 260 | + | let eff_ctx = if extra_vars.is_empty() { | |
| 261 | + | None | |
| 262 | + | } else { | |
| 263 | + | Some(Self::compile_context_with_extra(base_ctx, extra_vars)) | |
| 264 | + | }; | |
| 265 | + | let ctx_ref = eff_ctx.as_ref().unwrap_or(compiled_ctx); | |
| 266 | + | return match self.render_segment_value( | |
| 267 | + | raw_segment, | |
| 268 | + | is_dir, | |
| 269 | + | templates_suffix, | |
| 270 | + | ctx_ref, | |
| 271 | + | label, | |
| 272 | + | )? { | |
| 273 | + | Some((name, is_template_file)) => Ok(vec![RenderedSegment { | |
| 274 | + | name, | |
| 275 | + | is_template_file, | |
| 276 | + | yield_binding: None, | |
| 277 | + | }]), | |
| 278 | + | None => Ok(Vec::new()), | |
| 279 | + | }; | |
| 280 | + | } | |
| 281 | + | ||
| 282 | + | let Some(parsed) = parse_yield_segment(raw_segment, &self.block_start, &self.block_end)? | |
| 283 | + | else { | |
| 284 | + | let eff_ctx = if extra_vars.is_empty() { | |
| 285 | + | None | |
| 286 | + | } else { | |
| 287 | + | Some(Self::compile_context_with_extra(base_ctx, extra_vars)) | |
| 288 | + | }; | |
| 289 | + | let ctx_ref = eff_ctx.as_ref().unwrap_or(compiled_ctx); | |
| 290 | + | return match self.render_segment_value( | |
| 291 | + | raw_segment, | |
| 292 | + | is_dir, | |
| 293 | + | templates_suffix, | |
| 294 | + | ctx_ref, | |
| 295 | + | label, | |
| 296 | + | )? { | |
| 297 | + | Some((name, is_template_file)) => Ok(vec![RenderedSegment { | |
| 298 | + | name, | |
| 299 | + | is_template_file, | |
| 300 | + | yield_binding: None, | |
| 301 | + | }]), | |
| 302 | + | None => Ok(Vec::new()), | |
| 303 | + | }; | |
| 304 | + | }; | |
| 305 | + | ||
| 306 | + | let eval_ctx = if extra_vars.is_empty() { | |
| 307 | + | None | |
| 308 | + | } else { | |
| 309 | + | Some(Self::compile_context_with_extra(base_ctx, extra_vars)) | |
| 310 | + | }; | |
| 311 | + | let iter_mj = self | |
| 312 | + | .env | |
| 313 | + | .compile_expression(parsed.iterable_expr) | |
| 314 | + | .and_then(|expr| expr.eval(eval_ctx.as_ref().unwrap_or(compiled_ctx))) | |
| 315 | + | .map_err(|source| RoneoError::TemplateRender { | |
| 316 | + | context: label.to_string(), | |
| 317 | + | source, | |
| 318 | + | })?; | |
| 319 | + | ||
| 320 | + | let iter = iter_mj | |
| 321 | + | .try_iter() | |
| 322 | + | .map_err(|source| RoneoError::TemplateRender { | |
| 323 | + | context: label.to_string(), | |
| 324 | + | source, | |
| 325 | + | })?; | |
| 326 | + | ||
| 327 | + | let item_template = format!("{}{}{}", parsed.prefix, parsed.body, parsed.suffix); | |
| 328 | + | let mut results = Vec::new(); | |
| 329 | + | for item in iter { | |
| 330 | + | let item_json = serde_json::to_value(&item)?; | |
| 331 | + | let mut item_extra = extra_vars.to_vec(); | |
| 332 | + | item_extra.push((parsed.var_name.to_string(), item_json.clone())); | |
| 333 | + | let item_ctx = Self::compile_context_with_extra(base_ctx, &item_extra); | |
| 334 | + | if let Some((name, is_template_file)) = self.render_segment_value( | |
| 335 | + | &item_template, | |
| 336 | + | is_dir, | |
| 337 | + | templates_suffix, | |
| 338 | + | &item_ctx, | |
| 339 | + | label, | |
| 340 | + | )? { | |
| 341 | + | results.push(RenderedSegment { | |
| 342 | + | name, | |
| 343 | + | is_template_file, | |
| 344 | + | yield_binding: Some((parsed.var_name.to_string(), item_json)), | |
| 345 | + | }); | |
| 346 | + | } | |
| 347 | + | } | |
| 348 | + | Ok(results) | |
| 349 | + | } | |
| 350 | + | ||
| 351 | + | /// Build a `minijinja::Value` context overlaying `extra_vars` (from `{% yield %}`) onto `base_ctx`. | |
| 352 | + | pub fn compile_context_with_extra( | |
| 353 | + | base_ctx: &IndexMap<String, JsonValue>, | |
| 354 | + | extra_vars: &[(String, JsonValue)], | |
| 355 | + | ) -> MjValue { | |
| 356 | + | let mut merged = base_ctx.clone(); | |
| 357 | + | for (k, v) in extra_vars { | |
| 358 | + | merged.insert(k.clone(), v.clone()); | |
| 359 | + | } | |
| 360 | + | Self::compile_context(&merged) | |
| 361 | + | } | |
| 362 | + | ||
| 363 | + | /// Fast single-segment path renderer used during tree walks where parent directories | |
| 364 | + | /// have already been rendered once (avoids `O(files * depth)` re-rendering). | |
| 365 | + | pub fn render_segment_value( | |
| 366 | + | &self, | |
| 367 | + | raw_segment: &str, | |
| 368 | + | is_dir: bool, | |
| 369 | + | templates_suffix: &str, | |
| 370 | + | ctx: &MjValue, | |
| 371 | + | label: &str, | |
| 372 | + | ) -> Result<Option<(String, bool)>> { | |
| 373 | + | let mut rendered = if self.is_plain_text(raw_segment) { | |
| 374 | + | raw_segment.to_string() | |
| 375 | + | } else { | |
| 376 | + | self.render_str_value(raw_segment, ctx, label)? | |
| 377 | + | }; | |
| 378 | + | let mut is_template_file = false; | |
| 379 | + | if !is_dir | |
| 380 | + | && !templates_suffix.is_empty() | |
| 381 | + | && let Some(stripped) = rendered.strip_suffix(templates_suffix) | |
| 382 | + | { | |
| 383 | + | rendered = stripped.to_string(); | |
| 384 | + | is_template_file = true; | |
| 385 | + | } | |
| 386 | + | if rendered.is_empty() { | |
| 387 | + | return Ok(None); | |
| 388 | + | } | |
| 389 | + | // Security: never allow a rendered path segment to escape the destination directory. | |
| 390 | + | if rendered.contains('\0') { | |
| 391 | + | return Err(RoneoError::InvalidConfig(format!( | |
| 392 | + | "Rendered path '{rendered}' ({label}) contains a NUL byte" | |
| 393 | + | ))); | |
| 394 | + | } | |
| 395 | + | let seg_path = Path::new(&rendered); | |
| 396 | + | if seg_path.is_absolute() | |
| 397 | + | || seg_path.components().any(|c| { | |
| 398 | + | matches!( | |
| 399 | + | c, | |
| 400 | + | Component::ParentDir | Component::RootDir | Component::Prefix(_) | |
| 401 | + | ) | |
| 402 | + | }) | |
| 403 | + | { | |
| 404 | + | return Err(RoneoError::InvalidConfig(format!( | |
| 405 | + | "Rendered path '{rendered}' ({label}) escapes destination directory" | |
| 406 | + | ))); | |
| 407 | + | } | |
| 408 | + | Ok(Some((rendered, is_template_file))) | |
| 409 | + | } | |
| 410 | + | ||
| 411 | + | /// Render a relative template path segment-by-segment. | |
| 412 | + | /// | |
| 413 | + | /// Returns `Ok(None)` if any path component renders to an empty string (Copier convention | |
| 414 | + | /// for conditional files/directories like `{% if use_ci %}.github{% endif %}`). | |
| 415 | + | /// Also returns whether the final file had `templates_suffix` stripped. | |
| 416 | + | pub fn render_rel_path( | |
| 417 | + | &self, | |
| 418 | + | rel_path: &Path, | |
| 419 | + | is_dir: bool, | |
| 420 | + | templates_suffix: &str, | |
| 421 | + | ctx: &IndexMap<String, JsonValue>, | |
| 422 | + | ) -> Result<Option<(PathBuf, bool)>> { | |
| 423 | + | let compiled = Self::compile_context(ctx); | |
| 424 | + | self.render_rel_path_value(rel_path, is_dir, templates_suffix, &compiled) | |
| 425 | + | } | |
| 426 | + | ||
| 427 | + | /// Fast variant of `render_rel_path` accepting a pre-converted `minijinja::Value` context. | |
| 428 | + | pub fn render_rel_path_value( | |
| 429 | + | &self, | |
| 430 | + | rel_path: &Path, | |
| 431 | + | is_dir: bool, | |
| 432 | + | templates_suffix: &str, | |
| 433 | + | ctx: &MjValue, | |
| 434 | + | ) -> Result<Option<(PathBuf, bool)>> { | |
| 435 | + | let mut out = PathBuf::new(); | |
| 436 | + | let components: Vec<_> = rel_path.components().collect(); | |
| 437 | + | let last_idx = components.len().saturating_sub(1); | |
| 438 | + | let mut is_template_file = false; | |
| 439 | + | ||
| 440 | + | for (idx, comp) in components.iter().enumerate() { | |
| 441 | + | let Component::Normal(os_str) = comp else { | |
| 442 | + | continue; | |
| 443 | + | }; | |
| 444 | + | let raw = os_str.to_string_lossy(); | |
| 445 | + | let mut rendered = if self.is_plain_text(&raw) { | |
| 446 | + | raw.into_owned() | |
| 447 | + | } else { | |
| 448 | + | self.render_str_value(&raw, ctx, &format!("path:{}", rel_path.display()))? | |
| 449 | + | }; | |
| 450 | + | ||
| 451 | + | if !is_dir | |
| 452 | + | && idx == last_idx | |
| 453 | + | && !templates_suffix.is_empty() | |
| 454 | + | && let Some(stripped) = rendered.strip_suffix(templates_suffix) | |
| 455 | + | { | |
| 456 | + | rendered = stripped.to_string(); | |
| 457 | + | is_template_file = true; | |
| 458 | + | } | |
| 459 | + | ||
| 460 | + | if rendered.is_empty() { | |
| 461 | + | return Ok(None); | |
| 462 | + | } | |
| 463 | + | ||
| 464 | + | // A single rendered segment may itself expand to nested segments (e.g. `a/b`). | |
| 465 | + | out.push(rendered); | |
| 466 | + | } | |
| 467 | + | ||
| 468 | + | Ok(Some((out, is_template_file))) | |
| 469 | + | } | |
| 470 | + | } | |
| 471 | + | ||
| 472 | + | /// Build the full rendering context including `_copier_answers` and `_copier_conf`. | |
| 473 | + | pub fn build_render_context( | |
| 474 | + | combined_answers: &IndexMap<String, JsonValue>, | |
| 475 | + | persistable_answers: &IndexMap<String, JsonValue>, | |
| 476 | + | conf: &CopierConf, | |
| 477 | + | ) -> IndexMap<String, JsonValue> { | |
| 478 | + | let mut ctx = combined_answers.clone(); | |
| 479 | + | if let Ok(val) = serde_json::to_value(persistable_answers) { | |
| 480 | + | ctx.insert("_copier_answers".into(), val); | |
| 481 | + | } | |
| 482 | + | if let Ok(val) = serde_json::to_value(conf) { | |
| 483 | + | ctx.insert("_copier_conf".into(), val); | |
| 484 | + | } | |
| 485 | + | ctx | |
| 486 | + | } | |
| 487 | + | ||
| 488 | + | #[allow(clippy::needless_pass_by_value)] | |
| 489 | + | fn filter_printf_format(fmt: &str, args: minijinja::value::Rest<MjValue>) -> String { | |
| 490 | + | let mut out = String::with_capacity(fmt.len()); | |
| 491 | + | let mut chars = fmt.chars().peekable(); | |
| 492 | + | let mut arg_idx = 0usize; | |
| 493 | + | while let Some(ch) = chars.next() { | |
| 494 | + | if ch == '%' { | |
| 495 | + | match chars.peek().copied() { | |
| 496 | + | Some('%') => { | |
| 497 | + | chars.next(); | |
| 498 | + | out.push('%'); | |
| 499 | + | } | |
| 500 | + | Some('s' | 'd' | 'i' | 'f' | 'r') => { | |
| 501 | + | chars.next(); | |
| 502 | + | if let Some(val) = args.0.get(arg_idx) { | |
| 503 | + | out.push_str(&val.to_string()); | |
| 504 | + | } | |
| 505 | + | arg_idx += 1; | |
| 506 | + | } | |
| 507 | + | _ => out.push('%'), | |
| 508 | + | } | |
| 509 | + | } else { | |
| 510 | + | out.push(ch); | |
| 511 | + | } | |
| 512 | + | } | |
| 513 | + | out | |
| 514 | + | } | |
| 515 | + | ||
| 516 | + | /// Lightweight compatibility rewrite for Python-style string `%` formatting inside Jinja expressions | |
| 517 | + | /// (e.g. `'25m %dMi' % openfga_memory_mib` -> `('25m %dMi' | format(openfga_memory_mib))`), | |
| 518 | + | /// which Jinja2 inherits from Python but `MiniJinja` does not overload on strings. | |
| 519 | + | fn normalize_jinja2_printf_modulo(src: &str) -> std::borrow::Cow<'_, str> { | |
| 520 | + | if !src.contains("% ") { | |
| 521 | + | return std::borrow::Cow::Borrowed(src); | |
| 522 | + | } | |
| 523 | + | let bytes = src.as_bytes(); | |
| 524 | + | let mut out = String::with_capacity(src.len()); | |
| 525 | + | let mut i = 0usize; | |
| 526 | + | let mut changed = false; | |
| 527 | + | ||
| 528 | + | while i < bytes.len() { | |
| 529 | + | if (bytes[i] == b'\'' || bytes[i] == b'"') | |
| 530 | + | && let Some((lit_end, has_spec)) = scan_quoted_literal(src, i) | |
| 531 | + | && has_spec | |
| 532 | + | { | |
| 533 | + | let mut j = lit_end; | |
| 534 | + | while j < bytes.len() && bytes[j].is_ascii_whitespace() { | |
| 535 | + | j += 1; | |
| 536 | + | } | |
| 537 | + | if j < bytes.len() && bytes[j] == b'%' && bytes.get(j + 1) != Some(&b'}') { | |
| 538 | + | let mut k = j + 1; | |
| 539 | + | while k < bytes.len() && bytes[k].is_ascii_whitespace() { | |
| 540 | + | k += 1; | |
| 541 | + | } | |
| 542 | + | let expr_start = k; | |
| 543 | + | while k < bytes.len() | |
| 544 | + | && (bytes[k].is_ascii_alphanumeric() || matches!(bytes[k], b'_' | b'.')) | |
| 545 | + | { | |
| 546 | + | k += 1; | |
| 547 | + | } | |
| 548 | + | if k > expr_start { | |
| 549 | + | out.push('('); | |
| 550 | + | out.push_str(&src[i..lit_end]); | |
| 551 | + | out.push_str(" | format("); | |
| 552 | + | out.push_str(&src[expr_start..k]); | |
| 553 | + | out.push_str("))"); | |
| 554 | + | i = k; | |
| 555 | + | changed = true; | |
| 556 | + | continue; | |
| 557 | + | } | |
| 558 | + | } | |
| 559 | + | } | |
| 560 | + | let Some(ch) = src[i..].chars().next() else { | |
| 561 | + | break; | |
| 562 | + | }; | |
| 563 | + | out.push(ch); | |
| 564 | + | i += ch.len_utf8(); | |
| 565 | + | } | |
| 566 | + | ||
| 567 | + | if changed { | |
| 568 | + | std::borrow::Cow::Owned(out) | |
| 569 | + | } else { | |
| 570 | + | std::borrow::Cow::Borrowed(src) | |
| 571 | + | } | |
| 572 | + | } | |
| 573 | + | ||
| 574 | + | fn scan_quoted_literal(src: &str, start: usize) -> Option<(usize, bool)> { | |
| 575 | + | let bytes = src.as_bytes(); | |
| 576 | + | let quote = bytes[start]; | |
| 577 | + | let mut i = start + 1; | |
| 578 | + | let mut has_spec = false; | |
| 579 | + | while i < bytes.len() { | |
| 580 | + | let b = bytes[i]; | |
| 581 | + | if b == b'\\' { | |
| 582 | + | i += 2; | |
| 583 | + | continue; | |
| 584 | + | } | |
| 585 | + | if b == b'%' && matches!(bytes.get(i + 1), Some(b's' | b'd' | b'i' | b'f' | b'r')) { | |
| 586 | + | has_spec = true; | |
| 587 | + | } | |
| 588 | + | if b == quote { | |
| 589 | + | return Some((i + 1, has_spec)); | |
| 590 | + | } | |
| 591 | + | if b == b'\n' { | |
| 592 | + | return None; | |
| 593 | + | } | |
| 594 | + | i += 1; | |
| 595 | + | } | |
| 596 | + | None | |
| 597 | + | } | |
| 598 | + | ||
| 599 | + | fn func_pathjoin(parts: minijinja::value::Rest<String>) -> String { | |
| 600 | + | let mut path = PathBuf::new(); | |
| 601 | + | for part in parts.0 { | |
| 602 | + | path.push(part); | |
| 603 | + | } | |
| 604 | + | path.to_string_lossy().into_owned() | |
| 605 | + | } | |
| 606 | + | ||
| 607 | + | #[allow(clippy::needless_pass_by_value)] | |
| 608 | + | fn filter_to_nice_yaml( | |
| 609 | + | value: &MjValue, | |
| 610 | + | kwargs: minijinja::value::Kwargs, | |
| 611 | + | ) -> std::result::Result<String, minijinja::Error> { | |
| 612 | + | let indent: usize = kwargs.get::<Option<usize>>("indent")?.unwrap_or(2); | |
| 613 | + | let _sort_keys: Option<bool> = kwargs.get("sort_keys")?; | |
| 614 | + | let json_val = serde_json::to_value(value).map_err(|e| { | |
| 615 | + | minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string()) | |
| 616 | + | })?; | |
| 617 | + | let yaml = serde_yaml_ng::to_string(&json_val) | |
| 618 | + | .map(|s| s.trim_end().to_string()) | |
| 619 | + | .map_err(|e| { | |
| 620 | + | minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string()) | |
| 621 | + | })?; | |
| 622 | + | if indent == 2 || indent == 0 { | |
| 623 | + | return Ok(yaml); | |
| 624 | + | } | |
| 625 | + | // Scale 2-space leading indentation to custom `indent` (matches Copier `to_nice_yaml(indent=4)`). | |
| 626 | + | let mut scaled = String::with_capacity(yaml.len()); | |
| 627 | + | for (idx, line) in yaml.lines().enumerate() { | |
| 628 | + | if idx > 0 { | |
| 629 | + | scaled.push('\n'); | |
| 630 | + | } | |
| 631 | + | let spaces = line.bytes().take_while(|&b| b == b' ').count(); | |
| 632 | + | let levels = spaces / 2; | |
| 633 | + | let rem = spaces % 2; | |
| 634 | + | for _ in 0..(levels * indent + rem) { | |
| 635 | + | scaled.push(' '); | |
| 636 | + | } | |
| 637 | + | scaled.push_str(&line[spaces..]); | |
| 638 | + | } | |
| 639 | + | Ok(scaled) | |
| 640 | + | } | |
| 641 | + | ||
| 642 | + | fn filter_from_yaml(value: &str) -> std::result::Result<MjValue, minijinja::Error> { | |
| 643 | + | let y: serde_yaml_ng::Value = serde_yaml_ng::from_str(value).map_err(|e| { | |
| 644 | + | minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string()) | |
| 645 | + | })?; | |
| 646 | + | let j = serde_json::to_value(y).map_err(|e| { | |
| 647 | + | minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string()) | |
| 648 | + | })?; | |
| 649 | + | Ok(MjValue::from(minijinja::value::Serde(&j))) | |
| 650 | + | } | |
| 651 | + | ||
| 652 | + | fn filter_to_json(value: &MjValue) -> std::result::Result<String, minijinja::Error> { | |
| 653 | + | serde_json::to_string(value) | |
| 654 | + | .map_err(|e| minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string())) | |
| 655 | + | } | |
| 656 | + | ||
| 657 | + | fn filter_to_nice_json(value: &MjValue) -> std::result::Result<String, minijinja::Error> { | |
| 658 | + | serde_json::to_string_pretty(value) | |
| 659 | + | .map_err(|e| minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string())) | |
| 660 | + | } | |
| 661 | + | ||
| 662 | + | fn filter_from_json(value: &str) -> std::result::Result<MjValue, minijinja::Error> { | |
| 663 | + | let j: JsonValue = serde_json::from_str(value).map_err(|e| { | |
| 664 | + | minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string()) | |
| 665 | + | })?; | |
| 666 | + | Ok(MjValue::from(minijinja::value::Serde(&j))) | |
| 667 | + | } | |
| 668 | + | ||
| 669 | + | fn filter_slugify(value: &str) -> String { | |
| 670 | + | let mut out = String::with_capacity(value.len()); | |
| 671 | + | let mut prev_dash = true; | |
| 672 | + | for ch in value.chars() { | |
| 673 | + | if ch.is_ascii_alphanumeric() { | |
| 674 | + | out.push(ch.to_ascii_lowercase()); | |
| 675 | + | prev_dash = false; | |
| 676 | + | } else if !prev_dash { | |
| 677 | + | out.push('-'); | |
| 678 | + | prev_dash = true; | |
| 679 | + | } | |
| 680 | + | } | |
| 681 | + | while out.ends_with('-') { | |
| 682 | + | out.pop(); | |
| 683 | + | } | |
| 684 | + | out | |
| 685 | + | } | |
| 686 | + | ||
| 687 | + | fn filter_to_bool(value: &MjValue) -> bool { | |
| 688 | + | if let Ok(jv) = serde_json::to_value(value) { | |
| 689 | + | is_truthy_json(&jv) | |
| 690 | + | } else { | |
| 691 | + | value.is_true() | |
| 692 | + | } | |
| 693 | + | } | |
| 694 | + | ||
| 695 | + | fn filter_basename(value: String) -> String { | |
| 696 | + | Path::new(&value) | |
| 697 | + | .file_name() | |
| 698 | + | .map(|s| s.to_string_lossy().into_owned()) | |
| 699 | + | .unwrap_or(value) | |
| 700 | + | } | |
| 701 | + | ||
| 702 | + | fn filter_dirname(value: &str) -> String { | |
| 703 | + | Path::new(value) | |
| 704 | + | .parent() | |
| 705 | + | .map_or_default(|s| s.to_string_lossy().into_owned()) | |
| 706 | + | } | |
| 707 | + | ||
| 708 | + | fn filter_shell_quote(value: String) -> String { | |
| 709 | + | if value.is_empty() { | |
| 710 | + | return "''".to_string(); | |
| 711 | + | } | |
| 712 | + | if value | |
| 713 | + | .chars() | |
| 714 | + | .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | ':' | '@' | '+')) | |
| 715 | + | { | |
| 716 | + | return value; | |
| 717 | + | } | |
| 718 | + | format!("'{}'", value.replace('\'', "'\"'\"'")) | |
| 719 | + | } | |
| 720 | + | ||
| 721 | + | pub fn parse_truthy_str(s: &str) -> bool { | |
| 722 | + | let normalized = s.trim().to_ascii_lowercase(); | |
| 723 | + | !matches!( | |
| 724 | + | normalized.as_str(), | |
| 725 | + | "" | "0" | "false" | "no" | "n" | "off" | "none" | "null" | |
| 726 | + | ) | |
| 727 | + | } | |
| 728 | + | ||
| 729 | + | pub fn is_truthy_json(v: &JsonValue) -> bool { | |
| 730 | + | match v { | |
| 731 | + | JsonValue::Null => false, | |
| 732 | + | JsonValue::Bool(b) => *b, | |
| 733 | + | JsonValue::Number(n) => n.as_f64().is_some_and(|f| f != 0.0), | |
| 734 | + | JsonValue::String(s) => parse_truthy_str(s), | |
| 735 | + | JsonValue::Array(a) => !a.is_empty(), | |
| 736 | + | JsonValue::Object(m) => !m.is_empty(), | |
| 737 | + | } | |
| 738 | + | } | |
| 739 | + | ||
| 740 | + | struct ParsedYield<'a> { | |
| 741 | + | prefix: &'a str, | |
| 742 | + | var_name: &'a str, | |
| 743 | + | iterable_expr: &'a str, | |
| 744 | + | body: &'a str, | |
| 745 | + | suffix: &'a str, | |
| 746 | + | } | |
| 747 | + | ||
| 748 | + | /// Parse Copier's `{% yield <var> from <iterable> %}<body>{% endyield %}` tag in a path segment. | |
| 749 | + | fn parse_yield_segment<'a>( | |
| 750 | + | segment: &'a str, | |
| 751 | + | block_start: &str, | |
| 752 | + | block_end: &str, | |
| 753 | + | ) -> Result<Option<ParsedYield<'a>>> { | |
| 754 | + | let mut search_from = 0usize; | |
| 755 | + | let mut found: Option<ParsedYield<'a>> = None; | |
| 756 | + | ||
| 757 | + | while let Some(rel_open) = segment[search_from..].find(block_start) { | |
| 758 | + | let open_pos = search_from + rel_open; | |
| 759 | + | let inner_start = open_pos + block_start.len(); | |
| 760 | + | let Some(rel_close) = segment[inner_start..].find(block_end) else { | |
| 761 | + | break; | |
| 762 | + | }; | |
| 763 | + | let close_pos = inner_start + rel_close; | |
| 764 | + | let tag_body = segment[inner_start..close_pos] | |
| 765 | + | .trim() | |
| 766 | + | .trim_start_matches('-') | |
| 767 | + | .trim_end_matches('-') | |
| 768 | + | .trim(); | |
| 769 | + | let after_open = close_pos + block_end.len(); | |
| 770 | + | ||
| 771 | + | if let Some(rest) = tag_body.strip_prefix("yield") | |
| 772 | + | && rest.starts_with(char::is_whitespace) | |
| 773 | + | { | |
| 774 | + | if found.is_some() { | |
| 775 | + | return Err(RoneoError::InvalidConfig(format!( | |
| 776 | + | "Only one `yield` tag is allowed per path segment: '{segment}'" | |
| 777 | + | ))); | |
| 778 | + | } | |
| 779 | + | let rest = rest.trim(); | |
| 780 | + | let Some((var_part, iter_part)) = rest.split_once(" from ") else { | |
| 781 | + | return Err(RoneoError::InvalidConfig(format!( | |
| 782 | + | "Invalid `yield` syntax in '{segment}': expected `yield <var> from <iterable>`" | |
| 783 | + | ))); | |
| 784 | + | }; | |
| 785 | + | let var_name = var_part.trim(); | |
| 786 | + | let iterable_expr = iter_part.trim(); | |
| 787 | + | if var_name.is_empty() || iterable_expr.is_empty() { | |
| 788 | + | return Err(RoneoError::InvalidConfig(format!( | |
| 789 | + | "Invalid `yield` syntax in '{segment}': missing variable or iterable" | |
| 790 | + | ))); | |
| 791 | + | } | |
| 792 | + | ||
| 793 | + | // Locate matching `endyield` block. | |
| 794 | + | let mut end_search = after_open; | |
| 795 | + | let mut end_match: Option<(usize, usize)> = None; | |
| 796 | + | while let Some(end_open_offset) = segment[end_search..].find(block_start) { | |
| 797 | + | let end_open = end_search + end_open_offset; | |
| 798 | + | let end_inner = end_open + block_start.len(); | |
| 799 | + | let Some(end_close_offset) = segment[end_inner..].find(block_end) else { | |
| 800 | + | break; | |
| 801 | + | }; | |
| 802 | + | let end_close = end_inner + end_close_offset; | |
| 803 | + | let end_tag = segment[end_inner..end_close] | |
| 804 | + | .trim() | |
| 805 | + | .trim_start_matches('-') | |
| 806 | + | .trim_end_matches('-') | |
| 807 | + | .trim(); | |
| 808 | + | let end_after = end_close + block_end.len(); | |
| 809 | + | if end_tag == "endyield" { | |
| 810 | + | end_match = Some((end_open, end_after)); | |
| 811 | + | break; | |
| 812 | + | } | |
| 813 | + | end_search = end_after; | |
| 814 | + | } | |
| 815 | + | let Some((body_end, suffix_start)) = end_match else { | |
| 816 | + | return Err(RoneoError::InvalidConfig(format!( | |
| 817 | + | "Unclosed `yield` tag in path segment '{segment}' (missing `endyield`)" | |
| 818 | + | ))); | |
| 819 | + | }; | |
| 820 | + | ||
| 821 | + | found = Some(ParsedYield { | |
| 822 | + | prefix: &segment[..open_pos], | |
| 823 | + | var_name, | |
| 824 | + | iterable_expr, | |
| 825 | + | body: &segment[after_open..body_end], | |
| 826 | + | suffix: &segment[suffix_start..], | |
| 827 | + | }); | |
| 828 | + | search_from = suffix_start; | |
| 829 | + | continue; | |
| 830 | + | } | |
| 831 | + | search_from = after_open; | |
| 832 | + | } | |
| 833 | + | ||
| 834 | + | Ok(found) | |
| 835 | + | } | |
| 836 | + | ||
| 837 | + | fn split_words(input: &str) -> Vec<String> { | |
| 838 | + | let mut words = Vec::new(); | |
| 839 | + | let mut current = String::new(); | |
| 840 | + | let chars: Vec<char> = input.chars().collect(); | |
| 841 | + | for (i, &ch) in chars.iter().enumerate() { | |
| 842 | + | if !ch.is_alphanumeric() { | |
| 843 | + | if !current.is_empty() { | |
| 844 | + | words.push(std::mem::take(&mut current)); | |
| 845 | + | } | |
| 846 | + | continue; | |
| 847 | + | } | |
| 848 | + | let prev_lower = i > 0 && chars[i - 1].is_lowercase(); | |
| 849 | + | let next_lower = i + 1 < chars.len() && chars[i + 1].is_lowercase(); | |
| 850 | + | if ch.is_uppercase() && !current.is_empty() && (prev_lower || next_lower) { | |
| 851 | + | words.push(std::mem::take(&mut current)); | |
| 852 | + | } | |
| 853 | + | current.extend(ch.to_lowercase()); | |
| 854 | + | } | |
| 855 | + | if !current.is_empty() { | |
| 856 | + | words.push(current); | |
| 857 | + | } | |
| 858 | + | words | |
| 859 | + | } | |
| 860 | + | ||
| 861 | + | fn filter_to_snake(value: &str) -> String { | |
| 862 | + | split_words(value).join("_") | |
| 863 | + | } | |
| 864 | + | ||
| 865 | + | fn filter_to_kebab(value: &str) -> String { | |
| 866 | + | split_words(value).join("-") | |
| 867 | + | } | |
| 868 | + | ||
| 869 | + | fn filter_to_pascal(value: &str) -> String { | |
| 870 | + | let mut out = String::with_capacity(value.len()); | |
| 871 | + | for word in split_words(value) { | |
| 872 | + | let mut chars = word.chars(); | |
| 873 | + | if let Some(first) = chars.next() { | |
| 874 | + | out.extend(first.to_uppercase()); | |
| 875 | + | out.push_str(chars.as_str()); | |
| 876 | + | } | |
| 877 | + | } | |
| 878 | + | out | |
| 879 | + | } | |
| 880 | + | ||
| 881 | + | fn filter_to_camel(value: &str) -> String { | |
| 882 | + | let mut out = String::with_capacity(value.len()); | |
| 883 | + | for (idx, word) in split_words(value).into_iter().enumerate() { | |
| 884 | + | if idx == 0 { | |
| 885 | + | out.push_str(&word); | |
| 886 | + | } else { | |
| 887 | + | let mut chars = word.chars(); | |
| 888 | + | if let Some(first) = chars.next() { | |
| 889 | + | out.extend(first.to_uppercase()); | |
| 890 | + | out.push_str(chars.as_str()); | |
| 891 | + | } | |
| 892 | + | } | |
| 893 | + | } | |
| 894 | + | out | |
| 895 | + | } | |
| 896 | + | ||
| 897 | + | fn filter_b64encode(value: &str) -> String { | |
| 898 | + | const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | |
| 899 | + | let bytes = value.as_bytes(); | |
| 900 | + | let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); | |
| 901 | + | for chunk in bytes.chunks(3) { | |
| 902 | + | let b0 = u32::from(chunk[0]); | |
| 903 | + | let b1 = chunk.get(1).copied().map_or(0, u32::from); | |
| 904 | + | let b2 = chunk.get(2).copied().map_or(0, u32::from); | |
| 905 | + | let triple = (b0 << 16) | (b1 << 8) | b2; | |
| 906 | + | out.push(TABLE[((triple >> 18) & 0x3f) as usize] as char); | |
| 907 | + | out.push(TABLE[((triple >> 12) & 0x3f) as usize] as char); | |
| 908 | + | if chunk.len() > 1 { | |
| 909 | + | out.push(TABLE[((triple >> 6) & 0x3f) as usize] as char); | |
| 910 | + | } else { | |
| 911 | + | out.push('='); | |
| 912 | + | } | |
| 913 | + | if chunk.len() > 2 { | |
| 914 | + | out.push(TABLE[(triple & 0x3f) as usize] as char); | |
| 915 | + | } else { | |
| 916 | + | out.push('='); | |
| 917 | + | } | |
| 918 | + | } | |
| 919 | + | out | |
| 920 | + | } | |
| 921 | + | ||
| 922 | + | fn filter_b64decode(value: &str) -> std::result::Result<String, minijinja::Error> { | |
| 923 | + | let mut buf = Vec::with_capacity(value.len() * 3 / 4); | |
| 924 | + | let mut accum = 0u32; | |
| 925 | + | let mut bits = 0u8; | |
| 926 | + | for b in value.bytes() { | |
| 927 | + | if b.is_ascii_whitespace() || b == b'=' { | |
| 928 | + | continue; | |
| 929 | + | } | |
| 930 | + | let val = match b { | |
| 931 | + | b'A'..=b'Z' => b - b'A', | |
| 932 | + | b'a'..=b'z' => b - b'a' + 26, | |
| 933 | + | b'0'..=b'9' => b - b'0' + 52, | |
| 934 | + | b'+' => 62, | |
| 935 | + | b'/' => 63, | |
| 936 | + | _ => { | |
| 937 | + | return Err(minijinja::Error::new( | |
| 938 | + | minijinja::ErrorKind::InvalidOperation, | |
| 939 | + | format!("Invalid base64 byte: {b}"), | |
| 940 | + | )); | |
| 941 | + | } | |
| 942 | + | }; | |
| 943 | + | accum = (accum << 6) | u32::from(val); | |
| 944 | + | bits += 6; | |
| 945 | + | if bits >= 8 { | |
| 946 | + | bits -= 8; | |
| 947 | + | #[allow(clippy::cast_possible_truncation)] | |
| 948 | + | buf.push((accum >> bits) as u8); | |
| 949 | + | } | |
| 950 | + | } | |
| 951 | + | String::from_utf8(buf) | |
| 952 | + | .map_err(|e| minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string())) | |
| 953 | + | } | |
| 954 | + | ||
| 955 | + | /// Zero-dependency UTC `now(fmt="%Y-%m-%dT%H:%M:%SZ")` global using Howard Hinnant's | |
| 956 | + | /// civil-from-days algorithm. | |
| 957 | + | fn func_now(fmt: Option<&str>) -> String { | |
| 958 | + | let secs = std::time::SystemTime::now() | |
| 959 | + | .duration_since(std::time::UNIX_EPOCH) | |
| 960 | + | .map_or(0, |d| d.as_secs()); | |
| 961 | + | #[allow(clippy::cast_possible_wrap)] | |
| 962 | + | let days = (secs / 86_400) as i64; | |
| 963 | + | let day_secs = secs % 86_400; | |
| 964 | + | let hour = day_secs / 3_600; | |
| 965 | + | let minute = (day_secs % 3_600) / 60; | |
| 966 | + | let second = day_secs % 60; | |
| 967 | + | ||
| 968 | + | // Civil date from Unix epoch days (Howard Hinnant, public domain). | |
| 969 | + | let z = days + 719_468; | |
| 970 | + | let era = z.div_euclid(146_097); | |
| 971 | + | let doe = z.rem_euclid(146_097); | |
| 972 | + | let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; | |
| 973 | + | let y = yoe + era * 400; | |
| 974 | + | let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); | |
| 975 | + | let mp = (5 * doy + 2) / 153; | |
| 976 | + | let day = doy - (153 * mp + 2) / 5 + 1; | |
| 977 | + | let month = if mp < 10 { mp + 3 } else { mp - 9 }; | |
| 978 | + | let year = if month <= 2 { y + 1 } else { y }; | |
| 979 | + | ||
| 980 | + | let pattern = fmt.unwrap_or("%Y-%m-%dT%H:%M:%SZ"); | |
| 981 | + | let mut out = String::with_capacity(pattern.len() + 8); | |
| 982 | + | let mut chars = pattern.chars().peekable(); | |
| 983 | + | while let Some(ch) = chars.next() { | |
| 984 | + | if ch == '%' { | |
| 985 | + | match chars.peek().copied() { | |
| 986 | + | Some('Y') => { | |
| 987 | + | chars.next(); | |
| 988 | + | let _ = write!(out, "{year:04}"); | |
| 989 | + | } | |
| 990 | + | Some('m') => { | |
| 991 | + | chars.next(); | |
| 992 | + | let _ = write!(out, "{month:02}"); | |
| 993 | + | } | |
| 994 | + | Some('d') => { | |
| 995 | + | chars.next(); | |
| 996 | + | let _ = write!(out, "{day:02}"); | |
| 997 | + | } | |
| 998 | + | Some('H') => { | |
| 999 | + | chars.next(); | |
| 1000 | + | let _ = write!(out, "{hour:02}"); | |
| 1001 | + | } | |
| 1002 | + | Some('M') => { | |
| 1003 | + | chars.next(); | |
| 1004 | + | let _ = write!(out, "{minute:02}"); | |
| 1005 | + | } | |
| 1006 | + | Some('S') => { | |
| 1007 | + | chars.next(); | |
| 1008 | + | let _ = write!(out, "{second:02}"); | |
| 1009 | + | } | |
| 1010 | + | Some('%') => { | |
| 1011 | + | chars.next(); | |
| 1012 | + | out.push('%'); | |
| 1013 | + | } | |
| 1014 | + | _ => out.push('%'), | |
| 1015 | + | } | |
| 1016 | + | } else { | |
| 1017 | + | out.push(ch); | |
| 1018 | + | } | |
| 1019 | + | } | |
| 1020 | + | out | |
| 1021 | + | } |
| @@ -0,0 +1,321 @@ | |||
| 1 | + | use std::env; | |
| 2 | + | use std::fs; | |
| 3 | + | use std::path::{Path, PathBuf}; | |
| 4 | + | ||
| 5 | + | use indexmap::IndexMap; | |
| 6 | + | use serde_json::Value as JsonValue; | |
| 7 | + | ||
| 8 | + | use crate::config::yaml_to_json; | |
| 9 | + | use crate::error::{Result, RoneoError}; | |
| 10 | + | ||
| 11 | + | /// Copier-compatible user settings (`settings.yml`). | |
| 12 | + | /// | |
| 13 | + | /// Discovered from (in order): | |
| 14 | + | /// 1. `$RONEO_SETTINGS_PATH` | |
| 15 | + | /// 2. `$COPIER_SETTINGS_PATH` | |
| 16 | + | /// 3. `~/.config/roneo/settings.yml` | |
| 17 | + | /// 4. `~/.config/copier/settings.yml` | |
| 18 | + | #[derive(Debug, Clone, Default)] | |
| 19 | + | pub struct UserSettings { | |
| 20 | + | /// Global default answers applied whenever a question has no explicit CLI `-d` or previous answer. | |
| 21 | + | pub defaults: IndexMap<String, JsonValue>, | |
| 22 | + | /// Trusted template path/URL prefixes (exact match or prefix match ending with `/` or `:`). | |
| 23 | + | pub trust: Vec<String>, | |
| 24 | + | } | |
| 25 | + | ||
| 26 | + | impl UserSettings { | |
| 27 | + | /// Load user settings from the standard environment/config locations, if present. | |
| 28 | + | pub fn load_default() -> Self { | |
| 29 | + | let Some(path) = find_settings_path() else { | |
| 30 | + | return Self::default(); | |
| 31 | + | }; | |
| 32 | + | Self::load_from_file(&path).unwrap_or_default() | |
| 33 | + | } | |
| 34 | + | ||
| 35 | + | /// Load user settings from an explicit YAML file. | |
| 36 | + | pub fn load_from_file(path: &Path) -> Result<Self> { | |
| 37 | + | let raw = fs::read_to_string(path).map_err(|e| RoneoError::io(path, e))?; | |
| 38 | + | Self::parse_yaml(&raw) | |
| 39 | + | } | |
| 40 | + | ||
| 41 | + | pub fn parse_yaml(raw: &str) -> Result<Self> { | |
| 42 | + | if raw.trim().is_empty() { | |
| 43 | + | return Ok(Self::default()); | |
| 44 | + | } | |
| 45 | + | let val: serde_yaml_ng::Value = serde_yaml_ng::from_str(raw)?; | |
| 46 | + | let Some(map) = val.as_mapping() else { | |
| 47 | + | return Err(RoneoError::InvalidConfig( | |
| 48 | + | "User settings file must be a YAML mapping".into(), | |
| 49 | + | )); | |
| 50 | + | }; | |
| 51 | + | ||
| 52 | + | let mut settings = Self::default(); | |
| 53 | + | ||
| 54 | + | if let Some(defs) = map | |
| 55 | + | .get(serde_yaml_ng::Value::String("defaults".into())) | |
| 56 | + | .and_then(serde_yaml_ng::Value::as_mapping) | |
| 57 | + | { | |
| 58 | + | for (k, v) in defs { | |
| 59 | + | if let Some(key) = k.as_str() { | |
| 60 | + | settings.defaults.insert(key.to_string(), yaml_to_json(v)?); | |
| 61 | + | } | |
| 62 | + | } | |
| 63 | + | } | |
| 64 | + | ||
| 65 | + | if let Some(trust_seq) = map | |
| 66 | + | .get(serde_yaml_ng::Value::String("trust".into())) | |
| 67 | + | .and_then(serde_yaml_ng::Value::as_sequence) | |
| 68 | + | { | |
| 69 | + | for item in trust_seq { | |
| 70 | + | if let Some(s) = item.as_str() { | |
| 71 | + | settings.trust.push(s.to_string()); | |
| 72 | + | } | |
| 73 | + | } | |
| 74 | + | } | |
| 75 | + | ||
| 76 | + | Ok(settings) | |
| 77 | + | } | |
| 78 | + | ||
| 79 | + | /// Returns `true` if `original_src` or `resolved_src` matches any trusted repository rule, | |
| 80 | + | /// enforcing Copier v9.18.2 RFC 3986 §2.3 safe-URL validation and `..` path normalization | |
| 81 | + | /// to prevent trust bypass via URL traversal or percent-encoding. | |
| 82 | + | pub fn is_trusted(&self, original_src: &str, resolved_src: &str) -> bool { | |
| 83 | + | self.trust.iter().any(|rule| { | |
| 84 | + | matches_trust_rule(rule, original_src) || matches_trust_rule(rule, resolved_src) | |
| 85 | + | }) | |
| 86 | + | } | |
| 87 | + | } | |
| 88 | + | ||
| 89 | + | fn matches_trust_rule(rule: &str, candidate: &str) -> bool { | |
| 90 | + | if rule.is_empty() || candidate.is_empty() { | |
| 91 | + | return false; | |
| 92 | + | } | |
| 93 | + | if is_safe_url(candidate) && is_safe_url(rule) { | |
| 94 | + | let norm_cand = normalize_trust_ref(candidate); | |
| 95 | + | let norm_rule = normalize_trust_ref(rule); | |
| 96 | + | if rule.ends_with('/') || rule.ends_with(':') { | |
| 97 | + | norm_cand.starts_with(&norm_rule) | |
| 98 | + | } else { | |
| 99 | + | norm_cand == norm_rule | |
| 100 | + | } | |
| 101 | + | } else { | |
| 102 | + | // Unsafe URL characters (e.g., `%2e%2e`, `?`, `#`, `@` in path) require exact verbatim match. | |
| 103 | + | candidate == rule | |
| 104 | + | } | |
| 105 | + | } | |
| 106 | + | ||
| 107 | + | fn is_url_style(url: &str) -> bool { | |
| 108 | + | url.contains("://") | |
| 109 | + | || url.starts_with("gh:") | |
| 110 | + | || url.starts_with("gl:") | |
| 111 | + | || url.starts_with("git+") | |
| 112 | + | } | |
| 113 | + | ||
| 114 | + | /// Distinguish Git SCP-like remotes (`[user@]host:path`) from Windows drive paths (`C:\...`). | |
| 115 | + | fn is_scp_style(url: &str) -> bool { | |
| 116 | + | if is_url_style(url) { | |
| 117 | + | return false; | |
| 118 | + | } | |
| 119 | + | let bytes = url.as_bytes(); | |
| 120 | + | if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' { | |
| 121 | + | return false; | |
| 122 | + | } | |
| 123 | + | let Some((left, right)) = url.split_once(':') else { | |
| 124 | + | return false; | |
| 125 | + | }; | |
| 126 | + | !left.is_empty() | |
| 127 | + | && !right.is_empty() | |
| 128 | + | && !left.contains('/') | |
| 129 | + | && !left.contains('\\') | |
| 130 | + | && !left.chars().any(char::is_whitespace) | |
| 131 | + | } | |
| 132 | + | ||
| 133 | + | /// Copier v9.18.2 RFC 3986 §2.3 check: URL/SCP path segments may only contain unreserved | |
| 134 | + | /// characters (`A-Za-z0-9._~-`). Local filesystem paths are always considered safe. | |
| 135 | + | fn is_safe_url(url: &str) -> bool { | |
| 136 | + | let path = if is_url_style(url) { | |
| 137 | + | if let Some(idx) = url.find("://") { | |
| 138 | + | let after_scheme = &url[idx + 3..]; | |
| 139 | + | // Reject query/fragment in safe prefix check (force exact match). | |
| 140 | + | if after_scheme.contains('?') || after_scheme.contains('#') { | |
| 141 | + | return false; | |
| 142 | + | } | |
| 143 | + | match after_scheme.find('/') { | |
| 144 | + | Some(slash) => &after_scheme[slash..], | |
| 145 | + | None => "", | |
| 146 | + | } | |
| 147 | + | } else if let Some((_, rest)) = url.split_once(':') { | |
| 148 | + | if rest.contains('?') || rest.contains('#') { | |
| 149 | + | return false; | |
| 150 | + | } | |
| 151 | + | rest | |
| 152 | + | } else { | |
| 153 | + | "" | |
| 154 | + | } | |
| 155 | + | } else if is_scp_style(url) { | |
| 156 | + | let (_, rest) = url.split_once(':').unwrap_or(("", "")); | |
| 157 | + | if rest.contains('?') || rest.contains('#') { | |
| 158 | + | return false; | |
| 159 | + | } | |
| 160 | + | rest | |
| 161 | + | } else { | |
| 162 | + | return true; | |
| 163 | + | }; | |
| 164 | + | ||
| 165 | + | path.split('/').filter(|seg| !seg.is_empty()).all(|seg| { | |
| 166 | + | seg.bytes() | |
| 167 | + | .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'~' | b'-')) | |
| 168 | + | }) | |
| 169 | + | } | |
| 170 | + | ||
| 171 | + | fn normalize_trust_ref(url: &str) -> String { | |
| 172 | + | if is_url_style(url) { | |
| 173 | + | if let Some(idx) = url.find("://") { | |
| 174 | + | let prefix_end = idx + 3; | |
| 175 | + | let after_scheme = &url[prefix_end..]; | |
| 176 | + | return match after_scheme.find('/') { | |
| 177 | + | Some(slash) => { | |
| 178 | + | let host = &url[..prefix_end + slash]; | |
| 179 | + | let path = &after_scheme[slash..]; | |
| 180 | + | format!("{host}{}", normalize_posix_path(path)) | |
| 181 | + | } | |
| 182 | + | None => url.to_string(), | |
| 183 | + | }; | |
| 184 | + | } | |
| 185 | + | if let Some((alias, rest)) = url.split_once(':') { | |
| 186 | + | return format!("{alias}:{}", normalize_posix_path(rest)); | |
| 187 | + | } | |
| 188 | + | } | |
| 189 | + | if is_scp_style(url) | |
| 190 | + | && let Some((host, path)) = url.split_once(':') | |
| 191 | + | { | |
| 192 | + | return format!("{host}:{}", normalize_posix_path(path)); | |
| 193 | + | } | |
| 194 | + | let expanded = expand_tilde(url); | |
| 195 | + | normalize_posix_path(&expanded) | |
| 196 | + | } | |
| 197 | + | ||
| 198 | + | /// Collapse `.` and `..` segments and redundant `/` while preserving leading & trailing `/`. | |
| 199 | + | fn normalize_posix_path(path: &str) -> String { | |
| 200 | + | let leading_slash = path.starts_with('/'); | |
| 201 | + | let trailing_slash = path.ends_with('/') && path.len() > 1; | |
| 202 | + | let mut stack: Vec<&str> = Vec::new(); | |
| 203 | + | for seg in path.split('/') { | |
| 204 | + | match seg { | |
| 205 | + | "" | "." => {} | |
| 206 | + | ".." => { | |
| 207 | + | if let Some(&last) = stack.last() { | |
| 208 | + | if last != ".." { | |
| 209 | + | stack.pop(); | |
| 210 | + | } else if !leading_slash { | |
| 211 | + | stack.push(".."); | |
| 212 | + | } | |
| 213 | + | } else if !leading_slash { | |
| 214 | + | stack.push(".."); | |
| 215 | + | } | |
| 216 | + | } | |
| 217 | + | other => stack.push(other), | |
| 218 | + | } | |
| 219 | + | } | |
| 220 | + | let mut out = String::with_capacity(path.len()); | |
| 221 | + | if leading_slash { | |
| 222 | + | out.push('/'); | |
| 223 | + | } | |
| 224 | + | out.push_str(&stack.join("/")); | |
| 225 | + | if trailing_slash && !out.ends_with('/') { | |
| 226 | + | out.push('/'); | |
| 227 | + | } | |
| 228 | + | out | |
| 229 | + | } | |
| 230 | + | ||
| 231 | + | fn expand_tilde(path: &str) -> String { | |
| 232 | + | if let Some(rest) = path.strip_prefix("~/") | |
| 233 | + | && let Ok(home) = env::var("HOME") | |
| 234 | + | { | |
| 235 | + | return format!("{home}/{rest}"); | |
| 236 | + | } | |
| 237 | + | path.to_string() | |
| 238 | + | } | |
| 239 | + | ||
| 240 | + | fn find_settings_path() -> Option<PathBuf> { | |
| 241 | + | for var in ["RONEO_SETTINGS_PATH", "COPIER_SETTINGS_PATH"] { | |
| 242 | + | if let Ok(p) = env::var(var) | |
| 243 | + | && !p.trim().is_empty() | |
| 244 | + | { | |
| 245 | + | let pb = PathBuf::from(p); | |
| 246 | + | if pb.is_file() { | |
| 247 | + | return Some(pb); | |
| 248 | + | } | |
| 249 | + | } | |
| 250 | + | } | |
| 251 | + | let home = env::var("HOME").or_else(|_| env::var("USERPROFILE")).ok()?; | |
| 252 | + | for rel in [".config/roneo/settings.yml", ".config/copier/settings.yml"] { | |
| 253 | + | let candidate = PathBuf::from(&home).join(rel); | |
| 254 | + | if candidate.is_file() { | |
| 255 | + | return Some(candidate); | |
| 256 | + | } | |
| 257 | + | } | |
| 258 | + | None | |
| 259 | + | } | |
| 260 | + | ||
| 261 | + | #[cfg(test)] | |
| 262 | + | mod tests { | |
| 263 | + | use super::*; | |
| 264 | + | ||
| 265 | + | #[test] | |
| 266 | + | fn parses_defaults_and_trust_prefixes_with_security_checks() { | |
| 267 | + | let settings = UserSettings::parse_yaml( | |
| 268 | + | r" | |
| 269 | + | defaults: | |
| 270 | + | author: Alice | |
| 271 | + | year: 2026 | |
| 272 | + | trust: | |
| 273 | + | - /srv/trusted/ | |
| 274 | + | - gh:my-user/exact-repo | |
| 275 | + | - https://github.com/my-org/ | |
| 276 | + | - git@gitlab.com:my-org/ | |
| 277 | + | ", | |
| 278 | + | ) | |
| 279 | + | .unwrap(); | |
| 280 | + | ||
| 281 | + | assert_eq!( | |
| 282 | + | settings.defaults.get("author"), | |
| 283 | + | Some(&serde_json::json!("Alice")) | |
| 284 | + | ); | |
| 285 | + | assert!(settings.is_trusted("/srv/trusted/templates/app", "/srv/trusted/templates/app")); | |
| 286 | + | assert!(!settings.is_trusted("/srv/other/repo", "/srv/other/repo")); | |
| 287 | + | assert!(settings.is_trusted( | |
| 288 | + | "gh:my-user/exact-repo", | |
| 289 | + | "https://github.com/my-user/exact-repo.git" | |
| 290 | + | )); | |
| 291 | + | assert!(!settings.is_trusted( | |
| 292 | + | "gh:my-user/exact-repo-2", | |
| 293 | + | "https://github.com/my-user/exact-repo-2.git" | |
| 294 | + | )); | |
| 295 | + | ||
| 296 | + | // Security checks (Copier v9.17 / v9.18.2): | |
| 297 | + | // 1. Traversal via `..` must NOT bypass trusted prefix! | |
| 298 | + | assert!(!settings.is_trusted( | |
| 299 | + | "https://github.com/my-org/../evil/repo.git", | |
| 300 | + | "https://github.com/my-org/../evil/repo.git" | |
| 301 | + | )); | |
| 302 | + | assert!(!settings.is_trusted( | |
| 303 | + | "git@gitlab.com:my-org/../evil/repo.git", | |
| 304 | + | "git@gitlab.com:my-org/../evil/repo.git" | |
| 305 | + | )); | |
| 306 | + | // 2. Percent-encoded traversal (`%2e%2e`) is NOT RFC 3986 unreserved -> rejected! | |
| 307 | + | assert!(!settings.is_trusted( | |
| 308 | + | "https://github.com/my-org/%2e%2e/evil/repo.git", | |
| 309 | + | "https://github.com/my-org/%2e%2e/evil/repo.git" | |
| 310 | + | )); | |
| 311 | + | // 3. Valid URL under trusted prefix passes! | |
| 312 | + | assert!(settings.is_trusted( | |
| 313 | + | "https://github.com/my-org/good-template.git", | |
| 314 | + | "https://github.com/my-org/good-template.git" | |
| 315 | + | )); | |
| 316 | + | assert!(settings.is_trusted( | |
| 317 | + | "git@gitlab.com:my-org/good-template.git", | |
| 318 | + | "git@gitlab.com:my-org/good-template.git" | |
| 319 | + | )); | |
| 320 | + | } | |
| 321 | + | } |
| @@ -0,0 +1,263 @@ | |||
| 1 | + | use std::borrow::Cow; | |
| 2 | + | use std::path::Path; | |
| 3 | + | use std::process::Command; | |
| 4 | + | ||
| 5 | + | use indexmap::IndexMap; | |
| 6 | + | use serde_json::Value as JsonValue; | |
| 7 | + | ||
| 8 | + | use crate::config::{CommandSpec, MigrationSpec, TaskSpec}; | |
| 9 | + | use crate::error::{Result, RoneoError}; | |
| 10 | + | use crate::renderer::TemplateRenderer; | |
| 11 | + | use crate::version::Pep440Version; | |
| 12 | + | ||
| 13 | + | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 14 | + | pub enum MigrationStage { | |
| 15 | + | Before, | |
| 16 | + | After, | |
| 17 | + | } | |
| 18 | + | ||
| 19 | + | impl MigrationStage { | |
| 20 | + | pub fn as_str(self) -> &'static str { | |
| 21 | + | match self { | |
| 22 | + | Self::Before => "before", | |
| 23 | + | Self::After => "after", | |
| 24 | + | } | |
| 25 | + | } | |
| 26 | + | } | |
| 27 | + | ||
| 28 | + | /// Parameters controlling a migration stage execution (`before` or `after` update). | |
| 29 | + | pub struct MigrationRun<'a> { | |
| 30 | + | pub version_from: &'a str, | |
| 31 | + | pub version_to: &'a str, | |
| 32 | + | pub stage: MigrationStage, | |
| 33 | + | pub dst_path: &'a Path, | |
| 34 | + | pub renderer: &'a TemplateRenderer, | |
| 35 | + | pub ctx: &'a IndexMap<String, JsonValue>, | |
| 36 | + | pub pretend: bool, | |
| 37 | + | } | |
| 38 | + | ||
| 39 | + | /// Execute a list of post-copy/post-update tasks. | |
| 40 | + | pub fn run_tasks<F>( | |
| 41 | + | tasks: &[TaskSpec], | |
| 42 | + | dst_path: &Path, | |
| 43 | + | renderer: &TemplateRenderer, | |
| 44 | + | ctx: &IndexMap<String, JsonValue>, | |
| 45 | + | extra_env: &[(&str, &str)], | |
| 46 | + | pretend: bool, | |
| 47 | + | mut on_run: F, | |
| 48 | + | ) -> Result<()> | |
| 49 | + | where | |
| 50 | + | F: FnMut(&str), | |
| 51 | + | { | |
| 52 | + | if tasks.is_empty() { | |
| 53 | + | return Ok(()); | |
| 54 | + | } | |
| 55 | + | ||
| 56 | + | let task_ctx: Cow<'_, IndexMap<String, JsonValue>> = if ctx.contains_key("_stage") { | |
| 57 | + | Cow::Borrowed(ctx) | |
| 58 | + | } else { | |
| 59 | + | let mut cloned = ctx.clone(); | |
| 60 | + | cloned.insert("_stage".into(), JsonValue::String("task".into())); | |
| 61 | + | Cow::Owned(cloned) | |
| 62 | + | }; | |
| 63 | + | let stage_env = task_ctx | |
| 64 | + | .get("_stage") | |
| 65 | + | .and_then(JsonValue::as_str) | |
| 66 | + | .unwrap_or("task"); | |
| 67 | + | let operation_env = task_ctx | |
| 68 | + | .get("_copier_operation") | |
| 69 | + | .and_then(JsonValue::as_str) | |
| 70 | + | .unwrap_or(""); | |
| 71 | + | ||
| 72 | + | for (idx, task) in tasks.iter().enumerate() { | |
| 73 | + | if let Some(when_expr) = &task.when | |
| 74 | + | && !renderer.eval_condition_str(when_expr, &task_ctx, &format!("task[{idx}].when"))? | |
| 75 | + | { | |
| 76 | + | continue; | |
| 77 | + | } | |
| 78 | + | ||
| 79 | + | let work_dir = match &task.working_directory { | |
| 80 | + | Some(dir_tpl) => { | |
| 81 | + | let dir_str = renderer.render_str( | |
| 82 | + | dir_tpl, | |
| 83 | + | &task_ctx, | |
| 84 | + | &format!("task[{idx}].working_directory"), | |
| 85 | + | )?; | |
| 86 | + | let candidate = Path::new(&dir_str); | |
| 87 | + | if candidate.is_absolute() { | |
| 88 | + | candidate.to_path_buf() | |
| 89 | + | } else { | |
| 90 | + | dst_path.join(candidate) | |
| 91 | + | } | |
| 92 | + | } | |
| 93 | + | None => dst_path.to_path_buf(), | |
| 94 | + | }; | |
| 95 | + | ||
| 96 | + | let (display_cmd, mut cmd) = match &task.command { | |
| 97 | + | CommandSpec::Shell(script) => { | |
| 98 | + | let expanded = renderer.render_str(script, &task_ctx, &format!("task[{idx}]"))?; | |
| 99 | + | let cmd = shell_command(&expanded); | |
| 100 | + | (expanded, cmd) | |
| 101 | + | } | |
| 102 | + | CommandSpec::Args(args) => { | |
| 103 | + | let evaluated = render_args(args, renderer, &task_ctx, idx)?; | |
| 104 | + | let display = evaluated.join(" "); | |
| 105 | + | let Some((prog, rest)) = evaluated.split_first() else { | |
| 106 | + | continue; | |
| 107 | + | }; | |
| 108 | + | let mut cmd = Command::new(prog); | |
| 109 | + | cmd.args(rest); | |
| 110 | + | (display, cmd) | |
| 111 | + | } | |
| 112 | + | }; | |
| 113 | + | ||
| 114 | + | on_run(&display_cmd); | |
| 115 | + | if pretend { | |
| 116 | + | continue; | |
| 117 | + | } | |
| 118 | + | ||
| 119 | + | cmd.current_dir(&work_dir).env("STAGE", stage_env); | |
| 120 | + | if !operation_env.is_empty() { | |
| 121 | + | cmd.env("COPIER_OPERATION", operation_env); | |
| 122 | + | } | |
| 123 | + | for (k, v) in extra_env { | |
| 124 | + | cmd.env(k, v); | |
| 125 | + | } | |
| 126 | + | for (ek, ev_tpl) in &task.extra_env { | |
| 127 | + | let rendered_val = | |
| 128 | + | renderer.render_str(ev_tpl, &task_ctx, &format!("task[{idx}].extra_env.{ek}"))?; | |
| 129 | + | cmd.env(ek, rendered_val); | |
| 130 | + | } | |
| 131 | + | ||
| 132 | + | let output = cmd.output().map_err(|e| RoneoError::TaskFailed { | |
| 133 | + | command: display_cmd.clone(), | |
| 134 | + | status: None, | |
| 135 | + | stderr: e.to_string(), | |
| 136 | + | })?; | |
| 137 | + | ||
| 138 | + | if !output.status.success() { | |
| 139 | + | return Err(RoneoError::TaskFailed { | |
| 140 | + | command: display_cmd, | |
| 141 | + | status: output.status.code(), | |
| 142 | + | stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(), | |
| 143 | + | }); | |
| 144 | + | } | |
| 145 | + | } | |
| 146 | + | ||
| 147 | + | Ok(()) | |
| 148 | + | } | |
| 149 | + | ||
| 150 | + | /// Run applicable `_migrations` between `version_from` and `version_to` for the given stage. | |
| 151 | + | pub fn run_migrations<F>( | |
| 152 | + | migrations: &[MigrationSpec], | |
| 153 | + | run: &MigrationRun<'_>, | |
| 154 | + | mut on_run: F, | |
| 155 | + | ) -> Result<()> | |
| 156 | + | where | |
| 157 | + | F: FnMut(&str), | |
| 158 | + | { | |
| 159 | + | let from_ver = Pep440Version::parse(run.version_from); | |
| 160 | + | let to_ver = Pep440Version::parse(run.version_to); | |
| 161 | + | ||
| 162 | + | let mut applicable: Vec<(&MigrationSpec, Option<Pep440Version>)> = migrations | |
| 163 | + | .iter() | |
| 164 | + | .filter_map(|m| match &m.version { | |
| 165 | + | None => Some((m, None)), | |
| 166 | + | Some(ver_str) => { | |
| 167 | + | let v = Pep440Version::parse(ver_str)?; | |
| 168 | + | let (Some(from), Some(to)) = (&from_ver, &to_ver) else { | |
| 169 | + | return None; | |
| 170 | + | }; | |
| 171 | + | (to > from && v > *from && v <= *to).then_some((m, Some(v))) | |
| 172 | + | } | |
| 173 | + | }) | |
| 174 | + | .collect(); | |
| 175 | + | if applicable.is_empty() { | |
| 176 | + | return Ok(()); | |
| 177 | + | } | |
| 178 | + | applicable.sort_by(|a, b| a.1.cmp(&b.1)); | |
| 179 | + | ||
| 180 | + | let mut stage_ctx = run.ctx.clone(); | |
| 181 | + | stage_ctx.insert( | |
| 182 | + | "_stage".into(), | |
| 183 | + | JsonValue::String(run.stage.as_str().into()), | |
| 184 | + | ); | |
| 185 | + | ||
| 186 | + | for (migration, _) in applicable { | |
| 187 | + | if let Some(when_expr) = &migration.when | |
| 188 | + | && !run | |
| 189 | + | .renderer | |
| 190 | + | .eval_condition_str(when_expr, &stage_ctx, "migration.when")? | |
| 191 | + | { | |
| 192 | + | continue; | |
| 193 | + | } | |
| 194 | + | ||
| 195 | + | let current_ver = migration.version.as_deref().unwrap_or(""); | |
| 196 | + | let env = [ | |
| 197 | + | ("VERSION_FROM", run.version_from), | |
| 198 | + | ("VERSION_TO", run.version_to), | |
| 199 | + | ("VERSION_CURRENT", current_ver), | |
| 200 | + | ("STAGE", run.stage.as_str()), | |
| 201 | + | ]; | |
| 202 | + | ||
| 203 | + | let stage_tasks = match run.stage { | |
| 204 | + | MigrationStage::Before => &migration.before, | |
| 205 | + | MigrationStage::After => &migration.after, | |
| 206 | + | }; | |
| 207 | + | run_tasks( | |
| 208 | + | stage_tasks, | |
| 209 | + | run.dst_path, | |
| 210 | + | run.renderer, | |
| 211 | + | &stage_ctx, | |
| 212 | + | &env, | |
| 213 | + | run.pretend, | |
| 214 | + | &mut on_run, | |
| 215 | + | )?; | |
| 216 | + | ||
| 217 | + | if let Some(cmd) = &migration.command { | |
| 218 | + | let single = [TaskSpec { | |
| 219 | + | command: cmd.clone(), | |
| 220 | + | when: None, | |
| 221 | + | working_directory: None, | |
| 222 | + | extra_env: IndexMap::new(), | |
| 223 | + | }]; | |
| 224 | + | run_tasks( | |
| 225 | + | &single, | |
| 226 | + | run.dst_path, | |
| 227 | + | run.renderer, | |
| 228 | + | &stage_ctx, | |
| 229 | + | &env, | |
| 230 | + | run.pretend, | |
| 231 | + | &mut on_run, | |
| 232 | + | )?; | |
| 233 | + | } | |
| 234 | + | } | |
| 235 | + | ||
| 236 | + | Ok(()) | |
| 237 | + | } | |
| 238 | + | ||
| 239 | + | fn render_args( | |
| 240 | + | args: &[String], | |
| 241 | + | renderer: &TemplateRenderer, | |
| 242 | + | ctx: &IndexMap<String, JsonValue>, | |
| 243 | + | idx: usize, | |
| 244 | + | ) -> Result<Vec<String>> { | |
| 245 | + | args.iter() | |
| 246 | + | .enumerate() | |
| 247 | + | .map(|(j, a)| renderer.render_str(a, ctx, &format!("task[{idx}][{j}]"))) | |
| 248 | + | .collect() | |
| 249 | + | } | |
| 250 | + | ||
| 251 | + | #[cfg(unix)] | |
| 252 | + | fn shell_command(script: &str) -> Command { | |
| 253 | + | let mut cmd = Command::new("sh"); | |
| 254 | + | cmd.arg("-c").arg(script); | |
| 255 | + | cmd | |
| 256 | + | } | |
| 257 | + | ||
| 258 | + | #[cfg(windows)] | |
| 259 | + | fn shell_command(script: &str) -> Command { | |
| 260 | + | let mut cmd = Command::new("cmd"); | |
| 261 | + | cmd.arg("/C").arg(script); | |
| 262 | + | cmd | |
| 263 | + | } |
| @@ -0,0 +1,394 @@ | |||
| 1 | + | use std::path::{Path, PathBuf}; | |
| 2 | + | use std::sync::Arc; | |
| 3 | + | ||
| 4 | + | use crate::config::TemplateConfig; | |
| 5 | + | use crate::error::{Result, RoneoError}; | |
| 6 | + | use crate::fs_util::TempDir; | |
| 7 | + | use crate::plugin::TemplateFileReader; | |
| 8 | + | use crate::vcs::{self, InMemoryGitTree}; | |
| 9 | + | ||
| 10 | + | /// Backing storage for a resolved template: either a directory on disk or an in-memory `gix` tree | |
| 11 | + | /// (zero-TempDir, zero-clone reading for local Git repositories). | |
| 12 | + | #[derive(Debug)] | |
| 13 | + | pub enum TemplateBacking { | |
| 14 | + | Disk(PathBuf), | |
| 15 | + | GitTree(Arc<InMemoryGitTree>), | |
| 16 | + | } | |
| 17 | + | ||
| 18 | + | /// A resolved template ready for inspection or rendering. | |
| 19 | + | #[derive(Debug)] | |
| 20 | + | pub struct ResolvedTemplate { | |
| 21 | + | /// Original user-provided source string (preserved in `.copier-answers.yml` as `_src_path`). | |
| 22 | + | pub original_src: String, | |
| 23 | + | /// Normalized git URL or canonical local path. | |
| 24 | + | pub resolved_src: String, | |
| 25 | + | /// Local path on disk (for disk-backed templates, or the local repo path for git trees). | |
| 26 | + | pub local_path: PathBuf, | |
| 27 | + | /// Backing storage (`Disk` or zero-copy `GitTree`). | |
| 28 | + | pub backing: TemplateBacking, | |
| 29 | + | /// `_commit` value (e.g. `v1.0.0` or short hash) if template is backed by git. | |
| 30 | + | pub commit: Option<String>, | |
| 31 | + | /// Full 40-char commit hash if backed by git. | |
| 32 | + | pub commit_hash: Option<String>, | |
| 33 | + | /// Whether this template came from a remote URL (vs local path). | |
| 34 | + | pub is_remote: bool, | |
| 35 | + | /// Parsed `copier.yml` / `roneo.yml`. | |
| 36 | + | pub config: TemplateConfig, | |
| 37 | + | /// Keeps temporary clone alive for remote git templates (shared across sibling refs). | |
| 38 | + | temp_dir: Option<Arc<TempDir>>, | |
| 39 | + | } | |
| 40 | + | ||
| 41 | + | impl ResolvedTemplate { | |
| 42 | + | /// Resolve a template source (`local/dir`, `gh:owner/repo`, `gl:owner/repo`, or Git URL) | |
| 43 | + | /// at an optional `vcs_ref` (branch, tag, commit, or `HEAD`). | |
| 44 | + | pub fn resolve(src: &str, vcs_ref: Option<&str>) -> Result<Self> { | |
| 45 | + | Self::resolve_with_options(src, vcs_ref, false) | |
| 46 | + | } | |
| 47 | + | ||
| 48 | + | /// Resolve a template source with explicit prerelease tag selection control. | |
| 49 | + | pub fn resolve_with_options( | |
| 50 | + | src: &str, | |
| 51 | + | vcs_ref: Option<&str>, | |
| 52 | + | use_prereleases: bool, | |
| 53 | + | ) -> Result<Self> { | |
| 54 | + | let (normalized, is_remote) = normalize_source(src); | |
| 55 | + | ||
| 56 | + | if !is_remote { | |
| 57 | + | let path = PathBuf::from(&normalized); | |
| 58 | + | if !path.exists() { | |
| 59 | + | return Err(RoneoError::TemplateSource(format!( | |
| 60 | + | "Template path '{}' does not exist", | |
| 61 | + | path.display() | |
| 62 | + | ))); | |
| 63 | + | } | |
| 64 | + | if path.is_file() && vcs::is_git_bundle(&path) { | |
| 65 | + | return Self::clone_and_checkout(src, &normalized, false, vcs_ref, use_prereleases); | |
| 66 | + | } | |
| 67 | + | if !path.is_dir() { | |
| 68 | + | return Err(RoneoError::TemplateSource(format!( | |
| 69 | + | "Template path '{}' is not a directory", | |
| 70 | + | path.display() | |
| 71 | + | ))); | |
| 72 | + | } | |
| 73 | + | ||
| 74 | + | if !vcs::is_git_repo(&path) { | |
| 75 | + | let config = TemplateConfig::load_from_dir(&path)?; | |
| 76 | + | return Ok(Self { | |
| 77 | + | original_src: src.to_string(), | |
| 78 | + | resolved_src: normalized, | |
| 79 | + | backing: TemplateBacking::Disk(path.clone()), | |
| 80 | + | local_path: path, | |
| 81 | + | commit: None, | |
| 82 | + | commit_hash: None, | |
| 83 | + | is_remote: false, | |
| 84 | + | config, | |
| 85 | + | temp_dir: None, | |
| 86 | + | }); | |
| 87 | + | } | |
| 88 | + | ||
| 89 | + | // Local git repo: if no explicit `vcs_ref` is requested and working tree is dirty, | |
| 90 | + | // render from working tree directly (matching Copier's developer workflow). | |
| 91 | + | if vcs_ref.is_none() && !vcs::is_clean(&path).unwrap_or(true) { | |
| 92 | + | let (desc, hash) = | |
| 93 | + | vcs::describe_and_hash_head(&path).map_or((None, None), |(d, h)| (d, Some(h))); | |
| 94 | + | let commit = desc.map(|c| format!("{c}-dirty")); | |
| 95 | + | let config = TemplateConfig::load_from_dir(&path)?; | |
| 96 | + | return Ok(Self { | |
| 97 | + | original_src: src.to_string(), | |
| 98 | + | resolved_src: normalized, | |
| 99 | + | backing: TemplateBacking::Disk(path.clone()), | |
| 100 | + | local_path: path, | |
| 101 | + | commit, | |
| 102 | + | commit_hash: hash, | |
| 103 | + | is_remote: false, | |
| 104 | + | config, | |
| 105 | + | temp_dir: None, | |
| 106 | + | }); | |
| 107 | + | } | |
| 108 | + | ||
| 109 | + | // Fast zero-TempDir in-memory `gix` tree reading (no extraction to disk, no clone!). | |
| 110 | + | return Self::open_local_git_tree(src, &normalized, &path, vcs_ref, use_prereleases); | |
| 111 | + | } | |
| 112 | + | ||
| 113 | + | Self::clone_and_checkout(src, &normalized, true, vcs_ref, use_prereleases) | |
| 114 | + | } | |
| 115 | + | ||
| 116 | + | /// Resolve another VCS ref in the SAME template source, reusing the already-open | |
| 117 | + | /// `gix::ThreadSafeRepository` when backed by a local Git tree (eliminates reopening `.git` | |
| 118 | + | /// and re-reading pack indices during `update` / `diff`). | |
| 119 | + | pub fn resolve_sibling(&self, vcs_ref: Option<&str>, use_prereleases: bool) -> Result<Self> { | |
| 120 | + | if let TemplateBacking::GitTree(tree) = &self.backing { | |
| 121 | + | let sibling_tree = Arc::new(tree.open_sibling(vcs_ref, use_prereleases)?); | |
| 122 | + | let config = TemplateConfig::load_from_reader_with_glob( | |
| 123 | + | &|rel| sibling_tree.read_string(rel), | |
| 124 | + | &|pat| sibling_tree.list_matching_files(pat), | |
| 125 | + | )?; | |
| 126 | + | return Ok(Self { | |
| 127 | + | original_src: self.original_src.clone(), | |
| 128 | + | resolved_src: self.resolved_src.clone(), | |
| 129 | + | local_path: self.local_path.clone(), | |
| 130 | + | commit: sibling_tree.commit_describe.clone(), | |
| 131 | + | commit_hash: Some(sibling_tree.commit_hash.clone()), | |
| 132 | + | backing: TemplateBacking::GitTree(sibling_tree), | |
| 133 | + | is_remote: self.is_remote, | |
| 134 | + | config, | |
| 135 | + | temp_dir: self.temp_dir.clone(), | |
| 136 | + | }); | |
| 137 | + | } | |
| 138 | + | // For a freshly cloned remote/bundle repo without submodules, read the sibling ref | |
| 139 | + | // directly from the existing local clone in memory (avoids a second network fetch/clone). | |
| 140 | + | if vcs::is_git_repo(&self.local_path) && !self.local_path.join(".gitmodules").is_file() { | |
| 141 | + | let sibling_tree = Arc::new(InMemoryGitTree::open( | |
| 142 | + | &self.local_path, | |
| 143 | + | vcs_ref, | |
| 144 | + | use_prereleases, | |
| 145 | + | )?); | |
| 146 | + | let config = TemplateConfig::load_from_reader_with_glob( | |
| 147 | + | &|rel| sibling_tree.read_string(rel), | |
| 148 | + | &|pat| sibling_tree.list_matching_files(pat), | |
| 149 | + | )?; | |
| 150 | + | return Ok(Self { | |
| 151 | + | original_src: self.original_src.clone(), | |
| 152 | + | resolved_src: self.resolved_src.clone(), | |
| 153 | + | local_path: self.local_path.clone(), | |
| 154 | + | commit: sibling_tree.commit_describe.clone(), | |
| 155 | + | commit_hash: Some(sibling_tree.commit_hash.clone()), | |
| 156 | + | backing: TemplateBacking::GitTree(sibling_tree), | |
| 157 | + | is_remote: self.is_remote, | |
| 158 | + | config, | |
| 159 | + | temp_dir: self.temp_dir.clone(), | |
| 160 | + | }); | |
| 161 | + | } | |
| 162 | + | Self::resolve_with_options(&self.original_src, vcs_ref, use_prereleases) | |
| 163 | + | } | |
| 164 | + | ||
| 165 | + | fn open_local_git_tree( | |
| 166 | + | original_src: &str, | |
| 167 | + | resolved_src: &str, | |
| 168 | + | repo_path: &Path, | |
| 169 | + | vcs_ref: Option<&str>, | |
| 170 | + | use_prereleases: bool, | |
| 171 | + | ) -> Result<Self> { | |
| 172 | + | let tree = Arc::new(InMemoryGitTree::open(repo_path, vcs_ref, use_prereleases)?); | |
| 173 | + | let config = | |
| 174 | + | TemplateConfig::load_from_reader_with_glob(&|rel| tree.read_string(rel), &|pat| { | |
| 175 | + | tree.list_matching_files(pat) | |
| 176 | + | })?; | |
| 177 | + | ||
| 178 | + | Ok(Self { | |
| 179 | + | original_src: original_src.to_string(), | |
| 180 | + | resolved_src: resolved_src.to_string(), | |
| 181 | + | local_path: repo_path.to_path_buf(), | |
| 182 | + | commit: tree.commit_describe.clone(), | |
| 183 | + | commit_hash: Some(tree.commit_hash.clone()), | |
| 184 | + | backing: TemplateBacking::GitTree(tree), | |
| 185 | + | is_remote: false, | |
| 186 | + | config, | |
| 187 | + | temp_dir: None, | |
| 188 | + | }) | |
| 189 | + | } | |
| 190 | + | ||
| 191 | + | fn clone_and_checkout( | |
| 192 | + | original_src: &str, | |
| 193 | + | clone_url: &str, | |
| 194 | + | is_remote: bool, | |
| 195 | + | vcs_ref: Option<&str>, | |
| 196 | + | use_prereleases: bool, | |
| 197 | + | ) -> Result<Self> { | |
| 198 | + | let temp_dir = TempDir::new()?; | |
| 199 | + | let checkout_path = temp_dir.path().join("template"); | |
| 200 | + | if is_remote { | |
| 201 | + | vcs::clone_repo_cached(clone_url, &checkout_path)?; | |
| 202 | + | } else { | |
| 203 | + | vcs::clone_repo(clone_url, &checkout_path)?; | |
| 204 | + | } | |
| 205 | + | ||
| 206 | + | let target_ref = match vcs_ref { | |
| 207 | + | Some(r) => Some(r.to_string()), | |
| 208 | + | None => vcs::latest_version_tag(&checkout_path, use_prereleases)?, | |
| 209 | + | }; | |
| 210 | + | ||
| 211 | + | if let Some(ref git_ref) = target_ref { | |
| 212 | + | vcs::checkout_ref(&checkout_path, git_ref)?; | |
| 213 | + | } | |
| 214 | + | ||
| 215 | + | let commit = vcs::describe_commit(&checkout_path).ok(); | |
| 216 | + | let commit_hash = vcs::rev_parse_head(&checkout_path).ok(); | |
| 217 | + | let config = TemplateConfig::load_from_dir(&checkout_path)?; | |
| 218 | + | ||
| 219 | + | Ok(Self { | |
| 220 | + | original_src: original_src.to_string(), | |
| 221 | + | resolved_src: clone_url.to_string(), | |
| 222 | + | backing: TemplateBacking::Disk(checkout_path.clone()), | |
| 223 | + | local_path: checkout_path, | |
| 224 | + | commit, | |
| 225 | + | commit_hash, | |
| 226 | + | is_remote, | |
| 227 | + | config, | |
| 228 | + | temp_dir: Some(Arc::new(temp_dir)), | |
| 229 | + | }) | |
| 230 | + | } | |
| 231 | + | ||
| 232 | + | /// Return a closure that reads any file relative to template root (works for both `Disk` and `GitTree`), | |
| 233 | + | /// enforcing path containment so `{% include %}` symlinks or `../` cannot escape the template root | |
| 234 | + | /// (Copier v9.17.2 security hardening). | |
| 235 | + | pub fn file_reader(&self) -> TemplateFileReader { | |
| 236 | + | match &self.backing { | |
| 237 | + | TemplateBacking::Disk(root) => { | |
| 238 | + | let root = root.clone(); | |
| 239 | + | let canon_root = std::fs::canonicalize(&root).ok(); | |
| 240 | + | Arc::new(move |rel: &str| { | |
| 241 | + | let rel_path = Path::new(rel); | |
| 242 | + | if rel_path.is_absolute() | |
| 243 | + | || rel_path | |
| 244 | + | .components() | |
| 245 | + | .any(|c| matches!(c, std::path::Component::ParentDir)) | |
| 246 | + | { | |
| 247 | + | return None; | |
| 248 | + | } | |
| 249 | + | let candidate = root.join(rel_path); | |
| 250 | + | if let Some(ref base_canon) = canon_root { | |
| 251 | + | let cand_canon = std::fs::canonicalize(&candidate).ok()?; | |
| 252 | + | if !cand_canon.starts_with(base_canon) { | |
| 253 | + | return None; | |
| 254 | + | } | |
| 255 | + | } | |
| 256 | + | std::fs::read_to_string(candidate).ok() | |
| 257 | + | }) | |
| 258 | + | } | |
| 259 | + | TemplateBacking::GitTree(tree) => { | |
| 260 | + | let tree = Arc::clone(tree); | |
| 261 | + | Arc::new(move |rel: &str| { | |
| 262 | + | let rel_path = Path::new(rel); | |
| 263 | + | if rel_path.is_absolute() | |
| 264 | + | || rel_path | |
| 265 | + | .components() | |
| 266 | + | .any(|c| matches!(c, std::path::Component::ParentDir)) | |
| 267 | + | { | |
| 268 | + | return None; | |
| 269 | + | } | |
| 270 | + | tree.read_string(rel) | |
| 271 | + | }) | |
| 272 | + | } | |
| 273 | + | } | |
| 274 | + | } | |
| 275 | + | ||
| 276 | + | /// Read raw bytes of a file relative to template root (e.g. `.wasm` plugins declared via `_roneo_plugins`), | |
| 277 | + | /// enforcing strict path containment inside the template root. | |
| 278 | + | pub fn read_bytes(&self, rel: &str) -> Option<Vec<u8>> { | |
| 279 | + | if rel.contains('\0') { | |
| 280 | + | return None; | |
| 281 | + | } | |
| 282 | + | let rel_path = Path::new(rel); | |
| 283 | + | if rel_path.is_absolute() | |
| 284 | + | || rel_path.components().any(|c| { | |
| 285 | + | matches!( | |
| 286 | + | c, | |
| 287 | + | std::path::Component::ParentDir | |
| 288 | + | | std::path::Component::RootDir | |
| 289 | + | | std::path::Component::Prefix(_) | |
| 290 | + | ) | |
| 291 | + | }) | |
| 292 | + | { | |
| 293 | + | return None; | |
| 294 | + | } | |
| 295 | + | match &self.backing { | |
| 296 | + | TemplateBacking::Disk(root) => { | |
| 297 | + | let candidate = root.join(rel_path); | |
| 298 | + | let canon_root = std::fs::canonicalize(root).ok()?; | |
| 299 | + | let canon_cand = std::fs::canonicalize(&candidate).ok()?; | |
| 300 | + | if !canon_cand.starts_with(&canon_root) { | |
| 301 | + | return None; | |
| 302 | + | } | |
| 303 | + | std::fs::read(canon_cand).ok() | |
| 304 | + | } | |
| 305 | + | TemplateBacking::GitTree(tree) => tree.read_bytes(rel), | |
| 306 | + | } | |
| 307 | + | } | |
| 308 | + | ||
| 309 | + | /// Return the content root directory for `Disk`-backed templates (applying `_subdirectory` if set), | |
| 310 | + | /// rejecting any path or symlink that escapes the template root. | |
| 311 | + | pub fn disk_content_root(&self, rendered_subdirectory: Option<&str>) -> Result<PathBuf> { | |
| 312 | + | let Some(sub) = rendered_subdirectory.filter(|s| !s.trim().is_empty()) else { | |
| 313 | + | return Ok(self.local_path.clone()); | |
| 314 | + | }; | |
| 315 | + | let sub_path = Path::new(sub); | |
| 316 | + | if sub.contains('\0') | |
| 317 | + | || sub_path.is_absolute() | |
| 318 | + | || sub_path.components().any(|c| { | |
| 319 | + | matches!( | |
| 320 | + | c, | |
| 321 | + | std::path::Component::ParentDir | |
| 322 | + | | std::path::Component::RootDir | |
| 323 | + | | std::path::Component::Prefix(_) | |
| 324 | + | ) | |
| 325 | + | }) | |
| 326 | + | { | |
| 327 | + | return Err(RoneoError::TemplateSource(format!( | |
| 328 | + | "Template subdirectory '{sub}' escapes template root" | |
| 329 | + | ))); | |
| 330 | + | } | |
| 331 | + | let path = self.local_path.join(sub_path); | |
| 332 | + | if !path.is_dir() { | |
| 333 | + | return Err(RoneoError::TemplateSource(format!( | |
| 334 | + | "Template subdirectory '{}' does not exist in '{}'", | |
| 335 | + | sub, | |
| 336 | + | self.local_path.display() | |
| 337 | + | ))); | |
| 338 | + | } | |
| 339 | + | if let (Ok(canon_root), Ok(canon_sub)) = ( | |
| 340 | + | std::fs::canonicalize(&self.local_path), | |
| 341 | + | std::fs::canonicalize(&path), | |
| 342 | + | ) && !canon_sub.starts_with(&canon_root) | |
| 343 | + | { | |
| 344 | + | return Err(RoneoError::TemplateSource(format!( | |
| 345 | + | "Template subdirectory '{sub}' escapes template root via symlink" | |
| 346 | + | ))); | |
| 347 | + | } | |
| 348 | + | Ok(path) | |
| 349 | + | } | |
| 350 | + | } | |
| 351 | + | ||
| 352 | + | /// Expand Copier URL shorthands (`gh:`, `gl:`, `git+...`) and determine if source is remote. | |
| 353 | + | pub fn normalize_source(src: &str) -> (String, bool) { | |
| 354 | + | if let Some(rest) = src.strip_prefix("gh:") { | |
| 355 | + | let url = ensure_git_suffix(&format!("https://github.com/{rest}")); | |
| 356 | + | return (url, true); | |
| 357 | + | } | |
| 358 | + | if let Some(rest) = src.strip_prefix("gl:") { | |
| 359 | + | let url = ensure_git_suffix(&format!("https://gitlab.com/{rest}")); | |
| 360 | + | return (url, true); | |
| 361 | + | } | |
| 362 | + | if let Some(rest) = src.strip_prefix("git+") { | |
| 363 | + | return (rest.to_string(), true); | |
| 364 | + | } | |
| 365 | + | if src.starts_with("https://") | |
| 366 | + | || src.starts_with("http://") | |
| 367 | + | || src.starts_with("ssh://") | |
| 368 | + | || src.starts_with("git://") | |
| 369 | + | || src.starts_with("git@") | |
| 370 | + | { | |
| 371 | + | return (src.to_string(), true); | |
| 372 | + | } | |
| 373 | + | if let Some(file_path) = src.strip_prefix("file://") { | |
| 374 | + | return (file_path.to_string(), false); | |
| 375 | + | } | |
| 376 | + | let path = Path::new(src); | |
| 377 | + | if path.exists() | |
| 378 | + | && let Ok(canon) = path.canonicalize() | |
| 379 | + | { | |
| 380 | + | return (canon.to_string_lossy().into_owned(), false); | |
| 381 | + | } | |
| 382 | + | (src.to_string(), false) | |
| 383 | + | } | |
| 384 | + | ||
| 385 | + | fn ensure_git_suffix(url: &str) -> String { | |
| 386 | + | if Path::new(url) | |
| 387 | + | .extension() | |
| 388 | + | .is_some_and(|ext| ext.eq_ignore_ascii_case("git")) | |
| 389 | + | { | |
| 390 | + | url.to_string() | |
| 391 | + | } else { | |
| 392 | + | format!("{url}.git") | |
| 393 | + | } | |
| 394 | + | } |
crates/roneo-core/src/vcs.rs+1075−0
| @@ -0,0 +1,1075 @@ | |||
| 1 | + | use std::io::{Read, Write}; | |
| 2 | + | use std::path::{Path, PathBuf}; | |
| 3 | + | use std::process::{Command, Stdio}; | |
| 4 | + | ||
| 5 | + | use gix::bstr::ByteSlice; | |
| 6 | + | use gix::object::tree::EntryKind; | |
| 7 | + | use serde_json::Value as JsonValue; | |
| 8 | + | ||
| 9 | + | use crate::error::{Result, RoneoError}; | |
| 10 | + | use crate::filter::match_glob_path; | |
| 11 | + | use crate::version::Pep440Version; | |
| 12 | + | ||
| 13 | + | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] | |
| 14 | + | pub enum ConflictMode { | |
| 15 | + | /// Insert standard `<<<<<<<` / `=======` / `>>>>>>>` conflict markers via `git apply --3way`. | |
| 16 | + | #[default] | |
| 17 | + | Inline, | |
| 18 | + | /// Write `.rej` files alongside conflicted targets via `git apply --reject`. | |
| 19 | + | Rej, | |
| 20 | + | } | |
| 21 | + | ||
| 22 | + | #[derive(Debug, Clone)] | |
| 23 | + | pub struct ApplyResult { | |
| 24 | + | pub has_conflicts: bool, | |
| 25 | + | pub stderr: String, | |
| 26 | + | pub conflicted_files: Vec<String>, | |
| 27 | + | } | |
| 28 | + | ||
| 29 | + | /// Snapshot of a destination Git working tree obtained in ONE `git status` call. | |
| 30 | + | #[derive(Debug, Clone, Default)] | |
| 31 | + | pub struct WorkingTreeStatus { | |
| 32 | + | pub is_clean: bool, | |
| 33 | + | pub ignored_paths: Vec<String>, | |
| 34 | + | } | |
| 35 | + | ||
| 36 | + | fn open_gix_repo(dir: &Path) -> Result<gix::Repository> { | |
| 37 | + | gix::open_opts(dir, gix::open::Options::isolated()) | |
| 38 | + | .map_err(|e| RoneoError::Vcs(format!("Failed to open git repo '{}': {e}", dir.display()))) | |
| 39 | + | } | |
| 40 | + | ||
| 41 | + | /// Returns `true` if `dir` is the root of a git working tree (not merely a subdirectory of one), | |
| 42 | + | /// evaluated purely in-process via `gix`. | |
| 43 | + | pub fn is_git_repo(dir: &Path) -> bool { | |
| 44 | + | if !dir.is_dir() || !dir.join(".git").exists() { | |
| 45 | + | return false; | |
| 46 | + | } | |
| 47 | + | gix::open_opts(dir, gix::open::Options::isolated()).is_ok() | |
| 48 | + | } | |
| 49 | + | ||
| 50 | + | /// Fast zero-subprocess check for Git bundle files (`# v2 git bundle` / `# v3 git bundle`). | |
| 51 | + | pub fn is_git_bundle(path: &Path) -> bool { | |
| 52 | + | let Ok(mut f) = std::fs::File::open(path) else { | |
| 53 | + | return false; | |
| 54 | + | }; | |
| 55 | + | let mut header = [0u8; 20]; | |
| 56 | + | let Ok(n) = f.read(&mut header) else { | |
| 57 | + | return false; | |
| 58 | + | }; | |
| 59 | + | let slice = &header[..n]; | |
| 60 | + | slice.starts_with(b"# v2 git bundle\n") || slice.starts_with(b"# v3 git bundle\n") | |
| 61 | + | } | |
| 62 | + | ||
| 63 | + | /// Discover the enclosing Git working tree root for `dir` (supports updating a project that lives | |
| 64 | + | /// inside a subdirectory of a Git monorepo), evaluated purely in-process via `gix`. | |
| 65 | + | pub fn find_git_worktree_root(dir: &Path) -> Option<PathBuf> { | |
| 66 | + | let repo = gix::discover(dir).ok()?; | |
| 67 | + | repo.workdir().map(Path::to_path_buf) | |
| 68 | + | } | |
| 69 | + | ||
| 70 | + | /// Returns `true` if the working tree has no staged, unstaged, or untracked changes. | |
| 71 | + | pub fn is_clean(dir: &Path) -> Result<bool> { | |
| 72 | + | let status = run_git_checked(Some(dir), &["status", "--porcelain", "--no-renames"])?; | |
| 73 | + | Ok(status.is_empty()) | |
| 74 | + | } | |
| 75 | + | ||
| 76 | + | /// Check cleanliness AND collect `.gitignore`-ignored paths in ONE NUL-delimited (`-z`) | |
| 77 | + | /// `git status` invocation (Copier post-v9.19.1 `1b54bbeb`: safe for spaces/quotes/unicode). | |
| 78 | + | pub fn inspect_working_tree(repo_root: &Path) -> Result<WorkingTreeStatus> { | |
| 79 | + | let out = run_git( | |
| 80 | + | Some(repo_root), | |
| 81 | + | &[ | |
| 82 | + | "status", | |
| 83 | + | "--ignored=matching", | |
| 84 | + | "--porcelain", | |
| 85 | + | "-z", | |
| 86 | + | "--no-renames", | |
| 87 | + | ], | |
| 88 | + | )?; | |
| 89 | + | if !out.status.success() { | |
| 90 | + | let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string(); | |
| 91 | + | return Err(RoneoError::Vcs(format!("`git status` failed: {stderr}"))); | |
| 92 | + | } | |
| 93 | + | let mut is_clean = true; | |
| 94 | + | let mut ignored_paths = Vec::new(); | |
| 95 | + | for record in out.stdout.split(|&b| b == 0) { | |
| 96 | + | if record.is_empty() { | |
| 97 | + | continue; | |
| 98 | + | } | |
| 99 | + | let text = String::from_utf8_lossy(record); | |
| 100 | + | if let Some(rest) = text.strip_prefix("!! ") { | |
| 101 | + | if !rest.is_empty() { | |
| 102 | + | ignored_paths.push(rest.to_string()); | |
| 103 | + | } | |
| 104 | + | } else { | |
| 105 | + | is_clean = false; | |
| 106 | + | } | |
| 107 | + | } | |
| 108 | + | Ok(WorkingTreeStatus { | |
| 109 | + | is_clean, | |
| 110 | + | ignored_paths, | |
| 111 | + | }) | |
| 112 | + | } | |
| 113 | + | ||
| 114 | + | /// Read BOTH `describe` (tag/commit) and 40-char `HEAD` hash in a single `gix` repo open. | |
| 115 | + | pub fn describe_and_hash_head(repo_path: &Path) -> Result<(Option<String>, String)> { | |
| 116 | + | let repo = open_gix_repo(repo_path)?; | |
| 117 | + | let commit = repo | |
| 118 | + | .rev_parse_single("HEAD") | |
| 119 | + | .map_err(|e| RoneoError::Vcs(format!("Failed to resolve HEAD: {e}")))? | |
| 120 | + | .object() | |
| 121 | + | .map_err(|e| RoneoError::Vcs(format!("Failed to read HEAD object: {e}")))? | |
| 122 | + | .peel_to_commit() | |
| 123 | + | .map_err(|e| RoneoError::Vcs(format!("HEAD is not a commit: {e}")))?; | |
| 124 | + | let hash = commit.id.to_string(); | |
| 125 | + | let desc = fast_describe_commit(&repo, &commit).ok(); | |
| 126 | + | Ok((desc, hash)) | |
| 127 | + | } | |
| 128 | + | ||
| 129 | + | pub fn describe_commit(repo: &Path) -> Result<String> { | |
| 130 | + | describe_ref(repo, "HEAD") | |
| 131 | + | } | |
| 132 | + | ||
| 133 | + | /// Describe a git ref (`git describe --tags --always <ref>`) in-process via `gix`. | |
| 134 | + | pub fn describe_ref(repo_path: &Path, git_ref: &str) -> Result<String> { | |
| 135 | + | let repo = open_gix_repo(repo_path)?; | |
| 136 | + | let commit = repo | |
| 137 | + | .rev_parse_single(git_ref) | |
| 138 | + | .map_err(|e| RoneoError::Vcs(format!("Failed to resolve ref '{git_ref}': {e}")))? | |
| 139 | + | .object() | |
| 140 | + | .map_err(|e| RoneoError::Vcs(format!("Failed to read object for '{git_ref}': {e}")))? | |
| 141 | + | .peel_to_commit() | |
| 142 | + | .map_err(|e| RoneoError::Vcs(format!("Ref '{git_ref}' is not a commit: {e}")))?; | |
| 143 | + | ||
| 144 | + | fast_describe_commit(&repo, &commit) | |
| 145 | + | } | |
| 146 | + | ||
| 147 | + | /// Fast `git describe --tags --always` via `gix`: | |
| 148 | + | /// 1. First checks direct tag matches using `packed-refs` peeled OIDs (zero object decompression, | |
| 149 | + | /// ~2 ms even on monorepos with 8 000+ tags!). | |
| 150 | + | /// 2. Falls back to full `commit.describe()` graph walk only if the commit is not directly tagged. | |
| 151 | + | fn fast_describe_commit(repo: &gix::Repository, commit: &gix::Commit<'_>) -> Result<String> { | |
| 152 | + | if let Ok(refs) = repo.references() | |
| 153 | + | && let Ok(tags) = refs.tags() | |
| 154 | + | { | |
| 155 | + | let mut exact_matches: Vec<String> = Vec::new(); | |
| 156 | + | for tag_ref in tags.flatten() { | |
| 157 | + | let matches_peeled = tag_ref.inner().peeled == Some(commit.id); | |
| 158 | + | let matches_direct = tag_ref.target().try_id() == Some(commit.id.as_ref()); | |
| 159 | + | if matches_peeled || matches_direct { | |
| 160 | + | exact_matches.push(tag_ref.name().shorten().to_str_lossy().into_owned()); | |
| 161 | + | } | |
| 162 | + | } | |
| 163 | + | if !exact_matches.is_empty() { | |
| 164 | + | exact_matches.sort(); | |
| 165 | + | return Ok(exact_matches.swap_remove(0)); | |
| 166 | + | } | |
| 167 | + | } | |
| 168 | + | ||
| 169 | + | let formatted = commit | |
| 170 | + | .describe() | |
| 171 | + | .names(gix::commit::describe::SelectRef::AllTags) | |
| 172 | + | .id_as_fallback(true) | |
| 173 | + | .format() | |
| 174 | + | .map_err(|e| RoneoError::Vcs(format!("Failed to describe commit: {e}")))?; | |
| 175 | + | Ok(formatted.to_string()) | |
| 176 | + | } | |
| 177 | + | ||
| 178 | + | pub fn rev_parse_head(repo: &Path) -> Result<String> { | |
| 179 | + | rev_parse_ref(repo, "HEAD") | |
| 180 | + | } | |
| 181 | + | ||
| 182 | + | /// Resolve a git ref to its full 40-char commit hex ID in-process via `gix`. | |
| 183 | + | pub fn rev_parse_ref(repo_path: &Path, git_ref: &str) -> Result<String> { | |
| 184 | + | let repo = open_gix_repo(repo_path)?; | |
| 185 | + | let commit = repo | |
| 186 | + | .rev_parse_single(git_ref) | |
| 187 | + | .map_err(|e| RoneoError::Vcs(format!("Failed to resolve ref '{git_ref}': {e}")))? | |
| 188 | + | .object() | |
| 189 | + | .map_err(|e| RoneoError::Vcs(format!("Failed to read object for '{git_ref}': {e}")))? | |
| 190 | + | .peel_to_commit() | |
| 191 | + | .map_err(|e| RoneoError::Vcs(format!("Ref '{git_ref}' is not a commit: {e}")))?; | |
| 192 | + | Ok(commit.id.to_string()) | |
| 193 | + | } | |
| 194 | + | ||
| 195 | + | /// A blob or symlink entry discovered while walking a `gix::Tree` in memory. | |
| 196 | + | #[derive(Debug, Clone)] | |
| 197 | + | pub struct GitTreeFile { | |
| 198 | + | /// Source path relative to the walked root (`_subdirectory` or repo root). | |
| 199 | + | pub rel_path: PathBuf, | |
| 200 | + | /// Already-rendered destination parent directory (computed once per directory, not per file). | |
| 201 | + | pub rendered_parent: PathBuf, | |
| 202 | + | /// Raw leaf filename (the only segment left to render for this entry). | |
| 203 | + | pub file_name: String, | |
| 204 | + | /// Any `{% yield var from list %}` bindings inherited from parent directories (empty in 99.9% of cases). | |
| 205 | + | pub extra_vars: Vec<(String, JsonValue)>, | |
| 206 | + | pub oid: gix::ObjectId, | |
| 207 | + | pub is_executable: bool, | |
| 208 | + | pub is_symlink: bool, | |
| 209 | + | } | |
| 210 | + | ||
| 211 | + | /// Thread-safe, zero-TempDir handle to a specific commit tree inside a local Git repository. | |
| 212 | + | /// Allows reading `copier.yml`, `!include` files, Jinja `{% include %}` partials, plugin files, | |
| 213 | + | /// and template blobs directly from Git packfiles in memory. | |
| 214 | + | pub struct InMemoryGitTree { | |
| 215 | + | sync_repo: gix::ThreadSafeRepository, | |
| 216 | + | pub tree_oid: gix::ObjectId, | |
| 217 | + | pub commit_describe: Option<String>, | |
| 218 | + | pub commit_hash: String, | |
| 219 | + | } | |
| 220 | + | ||
| 221 | + | impl std::fmt::Debug for InMemoryGitTree { | |
| 222 | + | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| 223 | + | f.debug_struct("InMemoryGitTree") | |
| 224 | + | .field("commit_describe", &self.commit_describe) | |
| 225 | + | .field("commit_hash", &self.commit_hash) | |
| 226 | + | .finish_non_exhaustive() | |
| 227 | + | } | |
| 228 | + | } | |
| 229 | + | ||
| 230 | + | impl InMemoryGitTree { | |
| 231 | + | /// Open a local git repo ONCE via `gix` and resolve `vcs_ref` (or latest PEP 440 tag / `HEAD`). | |
| 232 | + | pub fn open(repo_path: &Path, vcs_ref: Option<&str>, use_prereleases: bool) -> Result<Self> { | |
| 233 | + | let repo = open_gix_repo(repo_path)?; | |
| 234 | + | Self::from_repo(repo, vcs_ref, use_prereleases) | |
| 235 | + | } | |
| 236 | + | ||
| 237 | + | /// Resolve another ref in the SAME repository without reopening `.git` or reloading pack indices. | |
| 238 | + | pub fn open_sibling(&self, vcs_ref: Option<&str>, use_prereleases: bool) -> Result<Self> { | |
| 239 | + | let repo = self.sync_repo.to_thread_local(); | |
| 240 | + | Self::from_repo(repo, vcs_ref, use_prereleases) | |
| 241 | + | } | |
| 242 | + | ||
| 243 | + | fn from_repo( | |
| 244 | + | repo: gix::Repository, | |
| 245 | + | vcs_ref: Option<&str>, | |
| 246 | + | use_prereleases: bool, | |
| 247 | + | ) -> Result<Self> { | |
| 248 | + | let target_ref = match vcs_ref { | |
| 249 | + | Some(r) => { | |
| 250 | + | if r.starts_with('-') { | |
| 251 | + | return Err(RoneoError::Vcs(format!( | |
| 252 | + | "Invalid git ref '{r}': refs may not start with '-'" | |
| 253 | + | ))); | |
| 254 | + | } | |
| 255 | + | r.to_string() | |
| 256 | + | } | |
| 257 | + | None => latest_version_tag_in_repo(&repo, use_prereleases)? | |
| 258 | + | .unwrap_or_else(|| "HEAD".to_string()), | |
| 259 | + | }; | |
| 260 | + | ||
| 261 | + | let commit = repo | |
| 262 | + | .rev_parse_single(target_ref.as_str()) | |
| 263 | + | .map_err(|e| RoneoError::Vcs(format!("Failed to resolve ref '{target_ref}': {e}")))? | |
| 264 | + | .object() | |
| 265 | + | .map_err(|e| RoneoError::Vcs(format!("Failed to read object '{target_ref}': {e}")))? | |
| 266 | + | .peel_to_commit() | |
| 267 | + | .map_err(|e| RoneoError::Vcs(format!("Ref '{target_ref}' is not a commit: {e}")))?; | |
| 268 | + | ||
| 269 | + | let commit_hash = commit.id.to_string(); | |
| 270 | + | let commit_describe = fast_describe_commit(&repo, &commit).ok(); | |
| 271 | + | let tree_oid = commit | |
| 272 | + | .tree_id() | |
| 273 | + | .map_err(|e| RoneoError::Vcs(format!("Failed to get commit tree id: {e}")))? | |
| 274 | + | .detach(); | |
| 275 | + | drop(commit); | |
| 276 | + | ||
| 277 | + | Ok(Self { | |
| 278 | + | sync_repo: repo.into_sync(), | |
| 279 | + | tree_oid, | |
| 280 | + | commit_describe, | |
| 281 | + | commit_hash, | |
| 282 | + | }) | |
| 283 | + | } | |
| 284 | + | ||
| 285 | + | /// Obtain a thread-local `gix::Repository` handle (reusable across many blob reads on one thread). | |
| 286 | + | pub fn thread_local_repo(&self) -> gix::Repository { | |
| 287 | + | self.sync_repo.to_thread_local() | |
| 288 | + | } | |
| 289 | + | ||
| 290 | + | /// Read raw bytes of a blob using an already-acquired thread-local `gix::Repository`. | |
| 291 | + | pub fn read_blob_with_repo(repo: &gix::Repository, oid: gix::ObjectId) -> Result<Vec<u8>> { | |
| 292 | + | let obj = repo | |
| 293 | + | .find_object(oid) | |
| 294 | + | .map_err(|e| RoneoError::Vcs(format!("Failed reading blob {oid}: {e}")))?; | |
| 295 | + | Ok(obj.data.clone()) | |
| 296 | + | } | |
| 297 | + | ||
| 298 | + | /// Read a blob by relative path from the repo root directly in memory. | |
| 299 | + | pub fn read_bytes(&self, rel_path: &str) -> Option<Vec<u8>> { | |
| 300 | + | let repo = self.sync_repo.to_thread_local(); | |
| 301 | + | let tree = repo.find_object(self.tree_oid).ok()?.into_tree(); | |
| 302 | + | let entry = tree.lookup_entry_by_path(rel_path).ok()??; | |
| 303 | + | let obj = entry.object().ok()?; | |
| 304 | + | (obj.kind == gix::object::Kind::Blob).then(|| obj.data.clone()) | |
| 305 | + | } | |
| 306 | + | ||
| 307 | + | /// Read a UTF-8 file by relative path from the repo root directly in memory. | |
| 308 | + | pub fn read_string(&self, rel_path: &str) -> Option<String> { | |
| 309 | + | String::from_utf8(self.read_bytes(rel_path)?).ok() | |
| 310 | + | } | |
| 311 | + | ||
| 312 | + | /// Read raw bytes of a blob by its `ObjectId` (used on parallel worker threads). | |
| 313 | + | pub fn read_blob_oid(&self, oid: gix::ObjectId) -> Result<Vec<u8>> { | |
| 314 | + | let repo = self.sync_repo.to_thread_local(); | |
| 315 | + | let obj = repo | |
| 316 | + | .find_object(oid) | |
| 317 | + | .map_err(|e| RoneoError::Vcs(format!("Failed reading blob {oid}: {e}")))?; | |
| 318 | + | Ok(obj.data.clone()) | |
| 319 | + | } | |
| 320 | + | ||
| 321 | + | /// List all relative file paths in the commit tree matching a glob pattern (e.g. `questions/*.yml`), | |
| 322 | + | /// pruning non-matching leading literal directory prefixes automatically. | |
| 323 | + | pub fn list_matching_files(&self, pattern: &str) -> Vec<String> { | |
| 324 | + | let repo = self.sync_repo.to_thread_local(); | |
| 325 | + | let Ok(root_obj) = repo.find_object(self.tree_oid) else { | |
| 326 | + | return Vec::new(); | |
| 327 | + | }; | |
| 328 | + | let root_tree = root_obj.into_tree(); | |
| 329 | + | ||
| 330 | + | // Narrow the walk to the longest static directory prefix before any wildcard. | |
| 331 | + | let mut static_prefix = PathBuf::new(); | |
| 332 | + | for seg in pattern.trim_start_matches('/').split('/') { | |
| 333 | + | if seg.contains(['*', '?', '[']) || seg.is_empty() { | |
| 334 | + | break; | |
| 335 | + | } | |
| 336 | + | static_prefix.push(seg); | |
| 337 | + | } | |
| 338 | + | let (start_tree, base_prefix) = if static_prefix.as_os_str().is_empty() { | |
| 339 | + | (root_tree, PathBuf::new()) | |
| 340 | + | } else if let Ok(Some(entry)) = root_tree.lookup_entry_by_path(&static_prefix) | |
| 341 | + | && entry.mode().kind() == EntryKind::Tree | |
| 342 | + | && let Ok(obj) = entry.object() | |
| 343 | + | { | |
| 344 | + | (obj.into_tree(), static_prefix) | |
| 345 | + | } else { | |
| 346 | + | return Vec::new(); | |
| 347 | + | }; | |
| 348 | + | ||
| 349 | + | let mut matches = Vec::new(); | |
| 350 | + | collect_matching_in_tree(&repo, &start_tree, &base_prefix, pattern, &mut matches); | |
| 351 | + | matches.sort(); | |
| 352 | + | matches | |
| 353 | + | } | |
| 354 | + | ||
| 355 | + | /// Walk `subdir` (or root tree) in memory, invoking `enter_dir` once per directory to prune | |
| 356 | + | /// excluded subtrees BEFORE touching their entries or decompressing any blobs, and expanding | |
| 357 | + | /// `{% yield %}` directories into multiple `(rendered_dir, extra_vars)` branches. | |
| 358 | + | pub fn walk_files<F>(&self, subdir: Option<&str>, mut enter_dir: F) -> Result<Vec<GitTreeFile>> | |
| 359 | + | where | |
| 360 | + | F: FnMut( | |
| 361 | + | &Path, | |
| 362 | + | &Path, | |
| 363 | + | &str, | |
| 364 | + | &[(String, JsonValue)], | |
| 365 | + | ) -> Result<Vec<(PathBuf, Vec<(String, JsonValue)>)>>, | |
| 366 | + | { | |
| 367 | + | let repo = self.sync_repo.to_thread_local(); | |
| 368 | + | let root_tree = repo | |
| 369 | + | .find_object(self.tree_oid) | |
| 370 | + | .map_err(|e| RoneoError::Vcs(format!("Failed to load root tree: {e}")))? | |
| 371 | + | .into_tree(); | |
| 372 | + | ||
| 373 | + | let start_tree = match subdir.filter(|s| !s.trim().is_empty()) { | |
| 374 | + | Some(sub) => { | |
| 375 | + | let entry = root_tree | |
| 376 | + | .lookup_entry_by_path(sub) | |
| 377 | + | .map_err(|e| RoneoError::Vcs(format!("Failed looking up '{sub}': {e}")))? | |
| 378 | + | .ok_or_else(|| { | |
| 379 | + | RoneoError::TemplateSource(format!( | |
| 380 | + | "Template subdirectory '{sub}' does not exist in git tree" | |
| 381 | + | )) | |
| 382 | + | })?; | |
| 383 | + | if entry.mode().kind() != EntryKind::Tree { | |
| 384 | + | return Err(RoneoError::TemplateSource(format!( | |
| 385 | + | "Template subdirectory '{sub}' is not a directory" | |
| 386 | + | ))); | |
| 387 | + | } | |
| 388 | + | entry | |
| 389 | + | .object() | |
| 390 | + | .map_err(|e| RoneoError::Vcs(format!("Failed reading tree '{sub}': {e}")))? | |
| 391 | + | .into_tree() | |
| 392 | + | } | |
| 393 | + | None => root_tree, | |
| 394 | + | }; | |
| 395 | + | ||
| 396 | + | let mut files = Vec::new(); | |
| 397 | + | walk_tree_in_memory( | |
| 398 | + | &repo, | |
| 399 | + | &start_tree, | |
| 400 | + | Path::new(""), | |
| 401 | + | Path::new(""), | |
| 402 | + | &[], | |
| 403 | + | &mut enter_dir, | |
| 404 | + | &mut files, | |
| 405 | + | )?; | |
| 406 | + | files.sort_by(|a, b| { | |
| 407 | + | a.rendered_parent | |
| 408 | + | .cmp(&b.rendered_parent) | |
| 409 | + | .then_with(|| a.rel_path.cmp(&b.rel_path)) | |
| 410 | + | }); | |
| 411 | + | Ok(files) | |
| 412 | + | } | |
| 413 | + | } | |
| 414 | + | ||
| 415 | + | fn collect_matching_in_tree( | |
| 416 | + | repo: &gix::Repository, | |
| 417 | + | tree: &gix::Tree<'_>, | |
| 418 | + | prefix: &Path, | |
| 419 | + | pattern: &str, | |
| 420 | + | out: &mut Vec<String>, | |
| 421 | + | ) { | |
| 422 | + | for entry_res in tree.iter() { | |
| 423 | + | let Ok(entry) = entry_res else { | |
| 424 | + | continue; | |
| 425 | + | }; | |
| 426 | + | let name = entry.filename().to_str_lossy(); | |
| 427 | + | let rel = if prefix.as_os_str().is_empty() { | |
| 428 | + | PathBuf::from(name.as_ref()) | |
| 429 | + | } else { | |
| 430 | + | prefix.join(name.as_ref()) | |
| 431 | + | }; | |
| 432 | + | match entry.mode().kind() { | |
| 433 | + | EntryKind::Tree => { | |
| 434 | + | if let Ok(obj) = repo.find_object(entry.id().detach()) { | |
| 435 | + | collect_matching_in_tree(repo, &obj.into_tree(), &rel, pattern, out); | |
| 436 | + | } | |
| 437 | + | } | |
| 438 | + | EntryKind::Blob | EntryKind::BlobExecutable => { | |
| 439 | + | if match_glob_path(pattern, &rel) { | |
| 440 | + | out.push(rel.to_string_lossy().replace('\\', "/")); | |
| 441 | + | } | |
| 442 | + | } | |
| 443 | + | EntryKind::Link | EntryKind::Commit => {} | |
| 444 | + | } | |
| 445 | + | } | |
| 446 | + | } | |
| 447 | + | ||
| 448 | + | fn walk_tree_in_memory<F>( | |
| 449 | + | repo: &gix::Repository, | |
| 450 | + | tree: &gix::Tree<'_>, | |
| 451 | + | src_prefix: &Path, | |
| 452 | + | rendered_prefix: &Path, | |
| 453 | + | extra_vars: &[(String, JsonValue)], | |
| 454 | + | enter_dir: &mut F, | |
| 455 | + | out: &mut Vec<GitTreeFile>, | |
| 456 | + | ) -> Result<()> | |
| 457 | + | where | |
| 458 | + | F: FnMut( | |
| 459 | + | &Path, | |
| 460 | + | &Path, | |
| 461 | + | &str, | |
| 462 | + | &[(String, JsonValue)], | |
| 463 | + | ) -> Result<Vec<(PathBuf, Vec<(String, JsonValue)>)>>, | |
| 464 | + | { | |
| 465 | + | for entry_res in tree.iter() { | |
| 466 | + | let entry = | |
| 467 | + | entry_res.map_err(|e| RoneoError::Vcs(format!("Failed iterating git tree: {e}")))?; | |
| 468 | + | let name = entry.filename().to_str_lossy(); | |
| 469 | + | let rel = if src_prefix.as_os_str().is_empty() { | |
| 470 | + | PathBuf::from(name.as_ref()) | |
| 471 | + | } else { | |
| 472 | + | src_prefix.join(name.as_ref()) | |
| 473 | + | }; | |
| 474 | + | match entry.mode().kind() { | |
| 475 | + | EntryKind::Tree => { | |
| 476 | + | let branches = enter_dir(&rel, rendered_prefix, name.as_ref(), extra_vars)?; | |
| 477 | + | if branches.is_empty() { | |
| 478 | + | continue; | |
| 479 | + | } | |
| 480 | + | let sub = repo | |
| 481 | + | .find_object(entry.id().detach()) | |
| 482 | + | .map_err(|e| RoneoError::Vcs(format!("Failed reading subtree: {e}")))? | |
| 483 | + | .into_tree(); | |
| 484 | + | for (next_rendered, next_vars) in branches { | |
| 485 | + | walk_tree_in_memory( | |
| 486 | + | repo, | |
| 487 | + | &sub, | |
| 488 | + | &rel, | |
| 489 | + | &next_rendered, | |
| 490 | + | &next_vars, | |
| 491 | + | enter_dir, | |
| 492 | + | out, | |
| 493 | + | )?; | |
| 494 | + | } | |
| 495 | + | } | |
| 496 | + | EntryKind::Blob => { | |
| 497 | + | out.push(GitTreeFile { | |
| 498 | + | rel_path: rel, | |
| 499 | + | rendered_parent: rendered_prefix.to_path_buf(), | |
| 500 | + | file_name: name.into_owned(), | |
| 501 | + | extra_vars: extra_vars.to_vec(), | |
| 502 | + | oid: entry.id().detach(), | |
| 503 | + | is_executable: false, | |
| 504 | + | is_symlink: false, | |
| 505 | + | }); | |
| 506 | + | } | |
| 507 | + | EntryKind::BlobExecutable => { | |
| 508 | + | out.push(GitTreeFile { | |
| 509 | + | rel_path: rel, | |
| 510 | + | rendered_parent: rendered_prefix.to_path_buf(), | |
| 511 | + | file_name: name.into_owned(), | |
| 512 | + | extra_vars: extra_vars.to_vec(), | |
| 513 | + | oid: entry.id().detach(), | |
| 514 | + | is_executable: true, | |
| 515 | + | is_symlink: false, | |
| 516 | + | }); | |
| 517 | + | } | |
| 518 | + | EntryKind::Link => { | |
| 519 | + | out.push(GitTreeFile { | |
| 520 | + | rel_path: rel, | |
| 521 | + | rendered_parent: rendered_prefix.to_path_buf(), | |
| 522 | + | file_name: name.into_owned(), | |
| 523 | + | extra_vars: extra_vars.to_vec(), | |
| 524 | + | oid: entry.id().detach(), | |
| 525 | + | is_executable: false, | |
| 526 | + | is_symlink: true, | |
| 527 | + | }); | |
| 528 | + | } | |
| 529 | + | EntryKind::Commit => {} | |
| 530 | + | } | |
| 531 | + | } | |
| 532 | + | Ok(()) | |
| 533 | + | } | |
| 534 | + | ||
| 535 | + | fn latest_version_tag_in_repo( | |
| 536 | + | repo: &gix::Repository, | |
| 537 | + | use_prereleases: bool, | |
| 538 | + | ) -> Result<Option<String>> { | |
| 539 | + | let refs = repo | |
| 540 | + | .references() | |
| 541 | + | .map_err(|e| RoneoError::Vcs(format!("Failed to list references: {e}")))?; | |
| 542 | + | let tags = refs | |
| 543 | + | .tags() | |
| 544 | + | .map_err(|e| RoneoError::Vcs(format!("Failed to list tags: {e}")))?; | |
| 545 | + | ||
| 546 | + | let mut all_parsed: Vec<(Pep440Version, String)> = Vec::new(); | |
| 547 | + | for tag_ref in tags.flatten() { | |
| 548 | + | let short = tag_ref.name().shorten().to_str_lossy(); | |
| 549 | + | if let Some(ver) = Pep440Version::parse(&short) { | |
| 550 | + | all_parsed.push((ver, short.into_owned())); | |
| 551 | + | } | |
| 552 | + | } | |
| 553 | + | ||
| 554 | + | if !use_prereleases { | |
| 555 | + | let mut stable: Vec<(Pep440Version, String)> = all_parsed | |
| 556 | + | .iter() | |
| 557 | + | .filter(|(v, _)| !v.is_prerelease()) | |
| 558 | + | .cloned() | |
| 559 | + | .collect(); | |
| 560 | + | if !stable.is_empty() { | |
| 561 | + | stable.sort_by(|a, b| a.0.cmp(&b.0)); | |
| 562 | + | return Ok(stable.pop().map(|(_, tag)| tag)); | |
| 563 | + | } | |
| 564 | + | } | |
| 565 | + | ||
| 566 | + | all_parsed.sort_by(|a, b| a.0.cmp(&b.0)); | |
| 567 | + | Ok(all_parsed.pop().map(|(_, tag)| tag)) | |
| 568 | + | } | |
| 569 | + | ||
| 570 | + | /// Return the highest PEP 440 tag in `repo`, evaluated purely in-process via `gix`. | |
| 571 | + | pub fn latest_version_tag(repo_path: &Path, use_prereleases: bool) -> Result<Option<String>> { | |
| 572 | + | let repo = open_gix_repo(repo_path)?; | |
| 573 | + | latest_version_tag_in_repo(&repo, use_prereleases) | |
| 574 | + | } | |
| 575 | + | ||
| 576 | + | // --------------------------------------------------------------------------- | |
| 577 | + | // Git CLI helpers for remote cloning & 3-way merge patching (`update` / `diff`) | |
| 578 | + | // --------------------------------------------------------------------------- | |
| 579 | + | ||
| 580 | + | fn run_git(cwd: Option<&Path>, args: &[&str]) -> Result<std::process::Output> { | |
| 581 | + | let mut cmd = Command::new("git"); | |
| 582 | + | if let Some(dir) = cwd { | |
| 583 | + | cmd.current_dir(dir); | |
| 584 | + | } | |
| 585 | + | cmd.env("GIT_TERMINAL_PROMPT", "0"); | |
| 586 | + | cmd.args(args); | |
| 587 | + | cmd.output() | |
| 588 | + | .map_err(|e| RoneoError::Vcs(format!("Failed to execute `git {}`: {e}", args.join(" ")))) | |
| 589 | + | } | |
| 590 | + | ||
| 591 | + | fn run_git_checked(cwd: Option<&Path>, args: &[&str]) -> Result<String> { | |
| 592 | + | let out = run_git(cwd, args)?; | |
| 593 | + | if !out.status.success() { | |
| 594 | + | let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string(); | |
| 595 | + | return Err(RoneoError::Vcs(format!( | |
| 596 | + | "`git {}` failed: {stderr}", | |
| 597 | + | args.join(" ") | |
| 598 | + | ))); | |
| 599 | + | } | |
| 600 | + | Ok(String::from_utf8_lossy(&out.stdout).trim().to_string()) | |
| 601 | + | } | |
| 602 | + | ||
| 603 | + | pub fn clone_repo(src: &str, dst: &Path) -> Result<()> { | |
| 604 | + | let dst_str = dst | |
| 605 | + | .to_str() | |
| 606 | + | .ok_or_else(|| RoneoError::Vcs("Non-UTF-8 temporary path".into()))?; | |
| 607 | + | let no_hooks = format!("core.hooksPath={}", null_device_path()); | |
| 608 | + | run_git_checked( | |
| 609 | + | None, | |
| 610 | + | &["-c", &no_hooks, "clone", "--quiet", "--", src, dst_str], | |
| 611 | + | )?; | |
| 612 | + | if dst.join(".gitmodules").is_file() { | |
| 613 | + | let _ = run_git_checked( | |
| 614 | + | Some(dst), | |
| 615 | + | &[ | |
| 616 | + | "-c", | |
| 617 | + | &no_hooks, | |
| 618 | + | "submodule", | |
| 619 | + | "update", | |
| 620 | + | "--init", | |
| 621 | + | "--recursive", | |
| 622 | + | "--quiet", | |
| 623 | + | ], | |
| 624 | + | ); | |
| 625 | + | } | |
| 626 | + | Ok(()) | |
| 627 | + | } | |
| 628 | + | ||
| 629 | + | /// Clone a remote repository using a persistent local bare mirror cache (`~/.cache/roneo/repos/<hash>`, | |
| 630 | + | /// matching Copier v9.16.0 `#2720`). Falls back to a direct clone if caching is disabled via | |
| 631 | + | /// `RONEO_NO_CACHE=1` or unavailable. | |
| 632 | + | pub fn clone_repo_cached(src: &str, dst: &Path) -> Result<()> { | |
| 633 | + | if std::env::var_os("RONEO_NO_CACHE").is_some_and(|v| v == "1" || v == "true") { | |
| 634 | + | return clone_repo(src, dst); | |
| 635 | + | } | |
| 636 | + | let Some(cache_root) = remote_mirror_cache_dir() else { | |
| 637 | + | return clone_repo(src, dst); | |
| 638 | + | }; | |
| 639 | + | if std::fs::create_dir_all(&cache_root).is_err() { | |
| 640 | + | return clone_repo(src, dst); | |
| 641 | + | } | |
| 642 | + | ||
| 643 | + | let cache_key = strip_url_credentials(src); | |
| 644 | + | let mirror_dir = cache_root.join(format!("{:016x}.git", fnv1a_64(cache_key.as_bytes()))); | |
| 645 | + | let mirror_str = mirror_dir.to_string_lossy().into_owned(); | |
| 646 | + | let no_hooks = format!("core.hooksPath={}", null_device_path()); | |
| 647 | + | let mirror_ready = if mirror_dir.join("HEAD").is_file() { | |
| 648 | + | run_git_checked( | |
| 649 | + | Some(&mirror_dir), | |
| 650 | + | &[ | |
| 651 | + | "-c", &no_hooks, "fetch", "--prune", "--tags", "--quiet", "origin", | |
| 652 | + | ], | |
| 653 | + | ) | |
| 654 | + | .is_ok() | |
| 655 | + | } else { | |
| 656 | + | if mirror_dir.exists() { | |
| 657 | + | let _ = std::fs::remove_dir_all(&mirror_dir); | |
| 658 | + | } | |
| 659 | + | let ok = run_git_checked( | |
| 660 | + | None, | |
| 661 | + | &[ | |
| 662 | + | "-c", | |
| 663 | + | &no_hooks, | |
| 664 | + | "clone", | |
| 665 | + | "--mirror", | |
| 666 | + | "--quiet", | |
| 667 | + | "--", | |
| 668 | + | src, | |
| 669 | + | &mirror_str, | |
| 670 | + | ], | |
| 671 | + | ) | |
| 672 | + | .is_ok(); | |
| 673 | + | if !ok { | |
| 674 | + | let _ = std::fs::remove_dir_all(&mirror_dir); | |
| 675 | + | } | |
| 676 | + | ok | |
| 677 | + | }; | |
| 678 | + | ||
| 679 | + | if mirror_ready { | |
| 680 | + | let dst_str = dst | |
| 681 | + | .to_str() | |
| 682 | + | .ok_or_else(|| RoneoError::Vcs("Non-UTF-8 temporary path".into()))?; | |
| 683 | + | if run_git_checked( | |
| 684 | + | None, | |
| 685 | + | &[ | |
| 686 | + | "-c", | |
| 687 | + | &no_hooks, | |
| 688 | + | "clone", | |
| 689 | + | "--shared", | |
| 690 | + | "--quiet", | |
| 691 | + | "--", | |
| 692 | + | &mirror_str, | |
| 693 | + | dst_str, | |
| 694 | + | ], | |
| 695 | + | ) | |
| 696 | + | .is_ok() | |
| 697 | + | { | |
| 698 | + | if dst.join(".gitmodules").is_file() { | |
| 699 | + | let _ = run_git_checked( | |
| 700 | + | Some(dst), | |
| 701 | + | &[ | |
| 702 | + | "-c", | |
| 703 | + | &no_hooks, | |
| 704 | + | "submodule", | |
| 705 | + | "update", | |
| 706 | + | "--init", | |
| 707 | + | "--recursive", | |
| 708 | + | "--quiet", | |
| 709 | + | ], | |
| 710 | + | ); | |
| 711 | + | } | |
| 712 | + | return Ok(()); | |
| 713 | + | } | |
| 714 | + | } | |
| 715 | + | ||
| 716 | + | clone_repo(src, dst) | |
| 717 | + | } | |
| 718 | + | ||
| 719 | + | fn remote_mirror_cache_dir() -> Option<PathBuf> { | |
| 720 | + | if let Ok(custom) = std::env::var("RONEO_CACHE_DIR") | |
| 721 | + | && !custom.trim().is_empty() | |
| 722 | + | { | |
| 723 | + | return Some(PathBuf::from(custom).join("repos")); | |
| 724 | + | } | |
| 725 | + | if let Ok(xdg) = std::env::var("XDG_CACHE_HOME") | |
| 726 | + | && !xdg.trim().is_empty() | |
| 727 | + | { | |
| 728 | + | return Some(PathBuf::from(xdg).join("roneo/repos")); | |
| 729 | + | } | |
| 730 | + | let home = std::env::var("HOME") | |
| 731 | + | .or_else(|_| std::env::var("USERPROFILE")) | |
| 732 | + | .ok()?; | |
| 733 | + | Some(PathBuf::from(home).join(".cache/roneo/repos")) | |
| 734 | + | } | |
| 735 | + | ||
| 736 | + | /// Remove embedded `user:pass@` credentials from an HTTP(S)/SSH URL before hashing it for | |
| 737 | + | /// the local bare mirror cache key (matches Copier v9.16 `_strip_credentials`). | |
| 738 | + | fn strip_url_credentials(url: &str) -> std::borrow::Cow<'_, str> { | |
| 739 | + | let Some(scheme_end) = url.find("://") else { | |
| 740 | + | return std::borrow::Cow::Borrowed(url); | |
| 741 | + | }; | |
| 742 | + | let rest = &url[scheme_end + 3..]; | |
| 743 | + | let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); | |
| 744 | + | let authority = &rest[..authority_end]; | |
| 745 | + | let Some(at_pos) = authority.rfind('@') else { | |
| 746 | + | return std::borrow::Cow::Borrowed(url); | |
| 747 | + | }; | |
| 748 | + | let mut cleaned = String::with_capacity(url.len() - at_pos - 1); | |
| 749 | + | cleaned.push_str(&url[..scheme_end + 3]); | |
| 750 | + | cleaned.push_str(&rest[at_pos + 1..]); | |
| 751 | + | std::borrow::Cow::Owned(cleaned) | |
| 752 | + | } | |
| 753 | + | ||
| 754 | + | fn fnv1a_64(bytes: &[u8]) -> u64 { | |
| 755 | + | let mut hash: u64 = 0xcbf2_9ce4_8422_2325; | |
| 756 | + | for &b in bytes { | |
| 757 | + | hash ^= u64::from(b); | |
| 758 | + | hash = hash.wrapping_mul(0x0100_0000_01b3); | |
| 759 | + | } | |
| 760 | + | hash | |
| 761 | + | } | |
| 762 | + | ||
| 763 | + | pub fn checkout_ref(repo: &Path, git_ref: &str) -> Result<()> { | |
| 764 | + | if git_ref.starts_with('-') { | |
| 765 | + | return Err(RoneoError::Vcs(format!( | |
| 766 | + | "Invalid git ref '{git_ref}': refs may not start with '-'" | |
| 767 | + | ))); | |
| 768 | + | } | |
| 769 | + | let no_hooks = format!("core.hooksPath={}", null_device_path()); | |
| 770 | + | run_git_checked( | |
| 771 | + | Some(repo), | |
| 772 | + | &[ | |
| 773 | + | "-c", &no_hooks, "checkout", "--quiet", "--detach", git_ref, "--", | |
| 774 | + | ], | |
| 775 | + | )?; | |
| 776 | + | if repo.join(".gitmodules").is_file() { | |
| 777 | + | let _ = run_git_checked( | |
| 778 | + | Some(repo), | |
| 779 | + | &[ | |
| 780 | + | "-c", | |
| 781 | + | &no_hooks, | |
| 782 | + | "submodule", | |
| 783 | + | "update", | |
| 784 | + | "--init", | |
| 785 | + | "--recursive", | |
| 786 | + | "--force", | |
| 787 | + | "--quiet", | |
| 788 | + | ], | |
| 789 | + | ); | |
| 790 | + | } | |
| 791 | + | Ok(()) | |
| 792 | + | } | |
| 793 | + | ||
| 794 | + | /// Produce a binary unified diff between sibling directories `old_name` (`a`) and `new_name` (`b`) | |
| 795 | + | /// inside `parent_dir` in ONE `git diff --no-index` call — zero `git init`, zero `git add`, | |
| 796 | + | /// zero `git commit`, zero working-tree copy/delete. | |
| 797 | + | pub fn diff_directories( | |
| 798 | + | parent_dir: &Path, | |
| 799 | + | old_name: &str, | |
| 800 | + | new_name: &str, | |
| 801 | + | context_lines: usize, | |
| 802 | + | ) -> Result<Vec<u8>> { | |
| 803 | + | let unified = format!("--unified={context_lines}"); | |
| 804 | + | let out = run_git( | |
| 805 | + | Some(parent_dir), | |
| 806 | + | &[ | |
| 807 | + | "diff", | |
| 808 | + | "--no-index", | |
| 809 | + | "--no-prefix", | |
| 810 | + | "--no-renames", | |
| 811 | + | "--binary", | |
| 812 | + | "--full-index", | |
| 813 | + | "--no-ext-diff", | |
| 814 | + | "--no-color", | |
| 815 | + | &unified, | |
| 816 | + | "--", | |
| 817 | + | old_name, | |
| 818 | + | new_name, | |
| 819 | + | ], | |
| 820 | + | )?; | |
| 821 | + | // `git diff --no-index` exits 0 (no changes), 1 (changes found), or >1 (error). | |
| 822 | + | if matches!(out.status.code(), Some(0 | 1)) { | |
| 823 | + | Ok(out.stdout) | |
| 824 | + | } else { | |
| 825 | + | let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string(); | |
| 826 | + | Err(RoneoError::Vcs(format!( | |
| 827 | + | "`git diff --no-index` failed: {stderr}" | |
| 828 | + | ))) | |
| 829 | + | } | |
| 830 | + | } | |
| 831 | + | ||
| 832 | + | /// Apply a binary unified diff patch to `repo_root` (optionally scoped to `subproject_subdir` | |
| 833 | + | /// when updating a project nested inside a Git monorepo) using 3-way merge (`--3way`) or `--reject`. | |
| 834 | + | /// | |
| 835 | + | /// When `mode == ConflictMode::Inline` and `git apply --3way` cannot locate base blobs in the | |
| 836 | + | /// destination ODB (e.g., after a squash merge, rebase, or fresh `git init`), automatically falls | |
| 837 | + | /// back to Copier's `git apply --reject` + `git merge-file` using `merge_snapshots` (`old_dir`, `new_dir`). | |
| 838 | + | pub fn apply_patch( | |
| 839 | + | repo_root: &Path, | |
| 840 | + | subproject_subdir: Option<&Path>, | |
| 841 | + | patch: &[u8], | |
| 842 | + | mode: ConflictMode, | |
| 843 | + | exclude_paths: &[String], | |
| 844 | + | merge_snapshots: Option<(&Path, &Path)>, | |
| 845 | + | ) -> Result<ApplyResult> { | |
| 846 | + | if patch.is_empty() { | |
| 847 | + | return Ok(ApplyResult { | |
| 848 | + | has_conflicts: false, | |
| 849 | + | stderr: String::new(), | |
| 850 | + | conflicted_files: Vec::new(), | |
| 851 | + | }); | |
| 852 | + | } | |
| 853 | + | ||
| 854 | + | let flag = match mode { | |
| 855 | + | ConflictMode::Inline => "--3way", | |
| 856 | + | ConflictMode::Rej => "--reject", | |
| 857 | + | }; | |
| 858 | + | ||
| 859 | + | let out = run_git_apply(repo_root, subproject_subdir, patch, flag, exclude_paths)?; | |
| 860 | + | let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string(); | |
| 861 | + | if out.status.success() { | |
| 862 | + | return Ok(ApplyResult { | |
| 863 | + | has_conflicts: false, | |
| 864 | + | stderr, | |
| 865 | + | conflicted_files: Vec::new(), | |
| 866 | + | }); | |
| 867 | + | } | |
| 868 | + | ||
| 869 | + | let strip_subdir = |repo_rel: &str| -> String { | |
| 870 | + | if let Some(sub) = subproject_subdir | |
| 871 | + | && !sub.as_os_str().is_empty() | |
| 872 | + | { | |
| 873 | + | let prefix = format!("{}/", sub.to_string_lossy().replace('\\', "/")); | |
| 874 | + | repo_rel | |
| 875 | + | .strip_prefix(&prefix) | |
| 876 | + | .unwrap_or(repo_rel) | |
| 877 | + | .to_string() | |
| 878 | + | } else { | |
| 879 | + | repo_rel.to_string() | |
| 880 | + | } | |
| 881 | + | }; | |
| 882 | + | ||
| 883 | + | if mode == ConflictMode::Inline { | |
| 884 | + | let mut conflicted_files: Vec<String> = | |
| 885 | + | run_git_checked(Some(repo_root), &["diff", "--name-only", "--diff-filter=U"]) | |
| 886 | + | .unwrap_or_default() | |
| 887 | + | .lines() | |
| 888 | + | .filter(|l| !l.trim().is_empty()) | |
| 889 | + | .map(&strip_subdir) | |
| 890 | + | .collect(); | |
| 891 | + | ||
| 892 | + | // Squash / missing-ODB fallback: `git apply --3way` failed without producing index | |
| 893 | + | // conflicts (e.g. `sha1 information is lacking or useless`). Run `git apply --reject` | |
| 894 | + | // followed by `git merge-file` directly against `(old_dir, new_dir)` snapshots (Copier). | |
| 895 | + | if conflicted_files.is_empty() | |
| 896 | + | && let Some((old_dir, new_dir)) = merge_snapshots | |
| 897 | + | { | |
| 898 | + | let rej_out = run_git_apply( | |
| 899 | + | repo_root, | |
| 900 | + | subproject_subdir, | |
| 901 | + | patch, | |
| 902 | + | "--reject", | |
| 903 | + | exclude_paths, | |
| 904 | + | )?; | |
| 905 | + | let rej_stderr = String::from_utf8_lossy(&rej_out.stderr).trim().to_string(); | |
| 906 | + | let status_out = run_git( | |
| 907 | + | Some(repo_root), | |
| 908 | + | &[ | |
| 909 | + | "status", | |
| 910 | + | "--porcelain", | |
| 911 | + | "-z", | |
| 912 | + | "--untracked-files=all", | |
| 913 | + | "--ignored=matching", | |
| 914 | + | "--no-renames", | |
| 915 | + | ], | |
| 916 | + | )?; | |
| 917 | + | for record in status_out.stdout.split(|&b| b == 0) { | |
| 918 | + | if record.is_empty() { | |
| 919 | + | continue; | |
| 920 | + | } | |
| 921 | + | let text = String::from_utf8_lossy(record); | |
| 922 | + | // Match both untracked (`?? `) and gitignored (`!! `) `.rej` files (Copier v9.15.2 `#2668`). | |
| 923 | + | let raw_path = text | |
| 924 | + | .strip_prefix("?? ") | |
| 925 | + | .or_else(|| text.strip_prefix("!! ")); | |
| 926 | + | let Some(path_str) = raw_path else { | |
| 927 | + | continue; | |
| 928 | + | }; | |
| 929 | + | let Some(repo_rel_file) = path_str.strip_suffix(".rej") else { | |
| 930 | + | continue; | |
| 931 | + | }; | |
| 932 | + | let rej_abs = repo_root.join(path_str); | |
| 933 | + | let _ = std::fs::remove_file(&rej_abs); | |
| 934 | + | ||
| 935 | + | let sub_rel = strip_subdir(repo_rel_file); | |
| 936 | + | let dst_abs = repo_root.join(repo_rel_file); | |
| 937 | + | let old_abs = old_dir.join(&sub_rel); | |
| 938 | + | let new_abs = new_dir.join(&sub_rel); | |
| 939 | + | ||
| 940 | + | if old_abs.is_file() && new_abs.is_file() && dst_abs.is_file() { | |
| 941 | + | // Undo any partial hunks before performing a clean 3-way `git merge-file`. | |
| 942 | + | let null_hooks = format!("core.hooksPath={}", null_device_path()); | |
| 943 | + | let _ = run_git( | |
| 944 | + | Some(repo_root), | |
| 945 | + | &["-c", &null_hooks, "checkout", "--", repo_rel_file], | |
| 946 | + | ); | |
| 947 | + | let merge_out = run_git( | |
| 948 | + | Some(repo_root), | |
| 949 | + | &[ | |
| 950 | + | "merge-file", | |
| 951 | + | "-L", | |
| 952 | + | "before updating", | |
| 953 | + | "-L", | |
| 954 | + | "last update", | |
| 955 | + | "-L", | |
| 956 | + | "after updating", | |
| 957 | + | "--", | |
| 958 | + | &dst_abs.to_string_lossy(), | |
| 959 | + | &old_abs.to_string_lossy(), | |
| 960 | + | &new_abs.to_string_lossy(), | |
| 961 | + | ], | |
| 962 | + | )?; | |
| 963 | + | if !merge_out.status.success() { | |
| 964 | + | conflicted_files.push(sub_rel); | |
| 965 | + | } | |
| 966 | + | } else { | |
| 967 | + | conflicted_files.push(sub_rel); | |
| 968 | + | } | |
| 969 | + | } | |
| 970 | + | return Ok(ApplyResult { | |
| 971 | + | has_conflicts: !conflicted_files.is_empty(), | |
| 972 | + | stderr: if conflicted_files.is_empty() { | |
| 973 | + | String::new() | |
| 974 | + | } else { | |
| 975 | + | rej_stderr | |
| 976 | + | }, | |
| 977 | + | conflicted_files, | |
| 978 | + | }); | |
| 979 | + | } | |
| 980 | + | ||
| 981 | + | return Ok(ApplyResult { | |
| 982 | + | has_conflicts: true, | |
| 983 | + | stderr, | |
| 984 | + | conflicted_files, | |
| 985 | + | }); | |
| 986 | + | } | |
| 987 | + | ||
| 988 | + | let conflicted_files = stderr | |
| 989 | + | .lines() | |
| 990 | + | .filter_map(|line| { | |
| 991 | + | line.strip_prefix("Applying patch ") | |
| 992 | + | .and_then(|rest| rest.split(" with ").next()) | |
| 993 | + | .map(ToOwned::to_owned) | |
| 994 | + | }) | |
| 995 | + | .collect(); | |
| 996 | + | ||
| 997 | + | Ok(ApplyResult { | |
| 998 | + | has_conflicts: true, | |
| 999 | + | stderr, | |
| 1000 | + | conflicted_files, | |
| 1001 | + | }) | |
| 1002 | + | } | |
| 1003 | + | ||
| 1004 | + | fn run_git_apply( | |
| 1005 | + | repo_root: &Path, | |
| 1006 | + | subproject_subdir: Option<&Path>, | |
| 1007 | + | patch: &[u8], | |
| 1008 | + | flag: &str, | |
| 1009 | + | exclude_paths: &[String], | |
| 1010 | + | ) -> Result<std::process::Output> { | |
| 1011 | + | let mut args: Vec<String> = vec!["apply".into(), flag.into(), "--whitespace=nowarn".into()]; | |
| 1012 | + | if let Some(sub) = subproject_subdir | |
| 1013 | + | && !sub.as_os_str().is_empty() | |
| 1014 | + | { | |
| 1015 | + | args.push(format!( | |
| 1016 | + | "--directory={}", | |
| 1017 | + | sub.to_string_lossy().replace('\\', "/") | |
| 1018 | + | )); | |
| 1019 | + | } | |
| 1020 | + | for pat in exclude_paths { | |
| 1021 | + | args.push("--exclude".into()); | |
| 1022 | + | args.push(pat.clone()); | |
| 1023 | + | } | |
| 1024 | + | args.push("-".into()); | |
| 1025 | + | ||
| 1026 | + | let mut child = Command::new("git") | |
| 1027 | + | .current_dir(repo_root) | |
| 1028 | + | .args(&args) | |
| 1029 | + | .stdin(Stdio::piped()) | |
| 1030 | + | .stdout(Stdio::piped()) | |
| 1031 | + | .stderr(Stdio::piped()) | |
| 1032 | + | .spawn() | |
| 1033 | + | .map_err(|e| RoneoError::Vcs(format!("Failed to spawn `git apply`: {e}")))?; | |
| 1034 | + | ||
| 1035 | + | if let Some(mut stdin) = child.stdin.take() { | |
| 1036 | + | stdin | |
| 1037 | + | .write_all(patch) | |
| 1038 | + | .map_err(|e| RoneoError::Vcs(format!("Failed to write patch to `git apply`: {e}")))?; | |
| 1039 | + | } | |
| 1040 | + | ||
| 1041 | + | child | |
| 1042 | + | .wait_with_output() | |
| 1043 | + | .map_err(|e| RoneoError::Vcs(format!("Failed waiting for `git apply`: {e}"))) | |
| 1044 | + | } | |
| 1045 | + | ||
| 1046 | + | #[cfg(unix)] | |
| 1047 | + | fn null_device_path() -> &'static str { | |
| 1048 | + | "/dev/null" | |
| 1049 | + | } | |
| 1050 | + | ||
| 1051 | + | #[cfg(windows)] | |
| 1052 | + | fn null_device_path() -> &'static str { | |
| 1053 | + | "NUL" | |
| 1054 | + | } | |
| 1055 | + | ||
| 1056 | + | #[cfg(test)] | |
| 1057 | + | mod tests { | |
| 1058 | + | use super::strip_url_credentials; | |
| 1059 | + | ||
| 1060 | + | #[test] | |
| 1061 | + | fn strip_url_credentials_keeps_host_and_path() { | |
| 1062 | + | assert_eq!( | |
| 1063 | + | strip_url_credentials("https://user:secret@github.com/org/repo.git"), | |
| 1064 | + | "https://github.com/org/repo.git" | |
| 1065 | + | ); | |
| 1066 | + | assert_eq!( | |
| 1067 | + | strip_url_credentials("https://github.com/org/repo.git"), | |
| 1068 | + | "https://github.com/org/repo.git" | |
| 1069 | + | ); | |
| 1070 | + | assert_eq!( | |
| 1071 | + | strip_url_credentials("git@github.com:org/repo.git"), | |
| 1072 | + | "git@github.com:org/repo.git" | |
| 1073 | + | ); | |
| 1074 | + | } | |
| 1075 | + | } |
| @@ -0,0 +1,309 @@ | |||
| 1 | + | use std::cmp::Ordering; | |
| 2 | + | ||
| 3 | + | /// Copier-compatible PEP 440 version parser & comparator (matches `packaging.version.Version`). | |
| 4 | + | /// | |
| 5 | + | /// Supports optional leading `v`/`V`, epochs (`1!2.0.0`), arbitrary-length numeric release | |
| 6 | + | /// segments (`2026.01`, `1.2.3.4`), pre-releases (`a`/`alpha`, `b`/`beta`, `rc`/`c`), | |
| 7 | + | /// post-releases (`.post1`, `-post1`), dev releases (`.dev0`), and local segments (`+foo`). | |
| 8 | + | #[derive(Debug, Clone, PartialEq, Eq)] | |
| 9 | + | pub struct Pep440Version { | |
| 10 | + | pub epoch: u64, | |
| 11 | + | pub release: Vec<u64>, | |
| 12 | + | pub pre: Option<(PreKind, u64)>, | |
| 13 | + | pub post: Option<u64>, | |
| 14 | + | pub dev: Option<u64>, | |
| 15 | + | pub local: Option<String>, | |
| 16 | + | } | |
| 17 | + | ||
| 18 | + | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] | |
| 19 | + | pub enum PreKind { | |
| 20 | + | Alpha = 0, | |
| 21 | + | Beta = 1, | |
| 22 | + | Rc = 2, | |
| 23 | + | } | |
| 24 | + | ||
| 25 | + | impl Pep440Version { | |
| 26 | + | /// Parse a PEP 440 version string (allowing optional leading `v`/`V` and hyphen separators). | |
| 27 | + | pub fn parse(raw: &str) -> Option<Self> { | |
| 28 | + | let mut s = raw.trim(); | |
| 29 | + | if s.is_empty() { | |
| 30 | + | return None; | |
| 31 | + | } | |
| 32 | + | if let Some(rest) = s.strip_prefix('v').or_else(|| s.strip_prefix('V')) { | |
| 33 | + | s = rest; | |
| 34 | + | } | |
| 35 | + | ||
| 36 | + | // Split local version (`+...`) | |
| 37 | + | let (main_part, local) = match s.split_once('+') { | |
| 38 | + | Some((m, l)) if !l.is_empty() => (m, Some(l.to_ascii_lowercase())), | |
| 39 | + | Some(_) => return None, | |
| 40 | + | None => (s, None), | |
| 41 | + | }; | |
| 42 | + | ||
| 43 | + | // Split epoch (`N!...`) | |
| 44 | + | let (epoch, mut rest) = match main_part.split_once('!') { | |
| 45 | + | Some((ep, r)) => (ep.parse::<u64>().ok()?, r), | |
| 46 | + | None => (0, main_part), | |
| 47 | + | }; | |
| 48 | + | ||
| 49 | + | // Parse numeric release segment: `digits(.digits)*` | |
| 50 | + | let rel_end = scan_release_end(rest); | |
| 51 | + | if rel_end == 0 { | |
| 52 | + | return None; | |
| 53 | + | } | |
| 54 | + | let release_str = &rest[..rel_end]; | |
| 55 | + | let release: Vec<u64> = release_str | |
| 56 | + | .split('.') | |
| 57 | + | .map(|seg| seg.parse::<u64>().ok()) | |
| 58 | + | .collect::<Option<Vec<_>>>()?; | |
| 59 | + | if release.is_empty() { | |
| 60 | + | return None; | |
| 61 | + | } | |
| 62 | + | rest = &rest[rel_end..]; | |
| 63 | + | ||
| 64 | + | let lower = rest.to_ascii_lowercase(); | |
| 65 | + | let mut rem = lower.as_str(); | |
| 66 | + | let mut pre = None; | |
| 67 | + | let mut post = None; | |
| 68 | + | let mut dev = None; | |
| 69 | + | ||
| 70 | + | // Optional pre-release: `[._-]?(alpha|beta|preview|pre|rc|a|b|c)[._-]?N?` | |
| 71 | + | if !rem.is_empty() | |
| 72 | + | && let Some((parsed_pre, after)) = try_parse_pre(rem) | |
| 73 | + | { | |
| 74 | + | pre = Some(parsed_pre); | |
| 75 | + | rem = after; | |
| 76 | + | } | |
| 77 | + | ||
| 78 | + | // Optional post-release: `([._-]?(post|rev|r)[._-]?N? | -N)` | |
| 79 | + | if !rem.is_empty() | |
| 80 | + | && let Some((parsed_post, after)) = try_parse_post(rem) | |
| 81 | + | { | |
| 82 | + | post = Some(parsed_post); | |
| 83 | + | rem = after; | |
| 84 | + | } | |
| 85 | + | ||
| 86 | + | // Optional dev-release: `[._-]?dev[._-]?N?` | |
| 87 | + | if !rem.is_empty() | |
| 88 | + | && let Some((parsed_dev, after)) = try_parse_dev(rem) | |
| 89 | + | { | |
| 90 | + | dev = Some(parsed_dev); | |
| 91 | + | rem = after; | |
| 92 | + | } | |
| 93 | + | ||
| 94 | + | if !rem.is_empty() { | |
| 95 | + | return None; | |
| 96 | + | } | |
| 97 | + | ||
| 98 | + | Some(Self { | |
| 99 | + | epoch, | |
| 100 | + | release, | |
| 101 | + | pre, | |
| 102 | + | post, | |
| 103 | + | dev, | |
| 104 | + | local, | |
| 105 | + | }) | |
| 106 | + | } | |
| 107 | + | ||
| 108 | + | pub fn is_prerelease(&self) -> bool { | |
| 109 | + | self.pre.is_some() || self.dev.is_some() | |
| 110 | + | } | |
| 111 | + | ||
| 112 | + | /// Normalize release tuple by stripping trailing zeros (PEP 440: `1.0 == 1.0.0`). | |
| 113 | + | fn normalized_release(&self) -> &[u64] { | |
| 114 | + | let mut end = self.release.len(); | |
| 115 | + | while end > 1 && self.release[end - 1] == 0 { | |
| 116 | + | end -= 1; | |
| 117 | + | } | |
| 118 | + | &self.release[..end] | |
| 119 | + | } | |
| 120 | + | } | |
| 121 | + | ||
| 122 | + | impl Ord for Pep440Version { | |
| 123 | + | fn cmp(&self, other: &Self) -> Ordering { | |
| 124 | + | self.epoch | |
| 125 | + | .cmp(&other.epoch) | |
| 126 | + | .then_with(|| self.normalized_release().cmp(other.normalized_release())) | |
| 127 | + | .then_with(|| cmp_phase(self, other)) | |
| 128 | + | .then_with(|| self.local.cmp(&other.local)) | |
| 129 | + | } | |
| 130 | + | } | |
| 131 | + | ||
| 132 | + | impl PartialOrd for Pep440Version { | |
| 133 | + | fn partial_cmp(&self, other: &Self) -> Option<Ordering> { | |
| 134 | + | Some(self.cmp(other)) | |
| 135 | + | } | |
| 136 | + | } | |
| 137 | + | ||
| 138 | + | /// PEP 440 ordering within the same `(epoch, release)`: | |
| 139 | + | /// 1. Pure dev (`1.0.dev0`) < pre-release (`1.0a1`) < final (`1.0`) < post-release (`1.0.post1`) | |
| 140 | + | /// 2. Within a pre/post release: dev < non-dev < post | |
| 141 | + | fn cmp_phase(a: &Pep440Version, b: &Pep440Version) -> Ordering { | |
| 142 | + | phase_key(a).cmp(&phase_key(b)) | |
| 143 | + | } | |
| 144 | + | ||
| 145 | + | fn phase_key(v: &Pep440Version) -> (u8, u8, u64, u8, u64, u8, u64) { | |
| 146 | + | // Primary rank: | |
| 147 | + | // 0: pure dev (no pre, no post, has dev) -> `1.0.dev0` | |
| 148 | + | // 1: pre-release -> `1.0a1`, `1.0a1.dev0`, `1.0a1.post1` | |
| 149 | + | // 2: final or post-release -> `1.0`, `1.0.post1`, `1.0.post1.dev0` | |
| 150 | + | if v.pre.is_none() && v.post.is_none() && v.dev.is_some() { | |
| 151 | + | return (0, 0, 0, 0, 0, 0, v.dev.unwrap_or(0)); | |
| 152 | + | } | |
| 153 | + | ||
| 154 | + | let (rank, pre_kind, pre_num) = match v.pre { | |
| 155 | + | Some((k, n)) => (1, k as u8, n), | |
| 156 | + | None => (2, 0, 0), | |
| 157 | + | }; | |
| 158 | + | ||
| 159 | + | // Post-release comes after non-post (0 = no post, 1 = has post). | |
| 160 | + | let (has_post, post_num) = match v.post { | |
| 161 | + | Some(n) => (1, n), | |
| 162 | + | None => (0, 0), | |
| 163 | + | }; | |
| 164 | + | ||
| 165 | + | // Dev comes BEFORE non-dev (0 = has dev, 1 = no dev). | |
| 166 | + | let (non_dev, dev_num) = match v.dev { | |
| 167 | + | Some(n) => (0, n), | |
| 168 | + | None => (1, 0), | |
| 169 | + | }; | |
| 170 | + | ||
| 171 | + | ( | |
| 172 | + | rank, pre_kind, pre_num, has_post, post_num, non_dev, dev_num, | |
| 173 | + | ) | |
| 174 | + | } | |
| 175 | + | ||
| 176 | + | fn scan_release_end(s: &str) -> usize { | |
| 177 | + | let bytes = s.as_bytes(); | |
| 178 | + | let mut i = 0; | |
| 179 | + | while i < bytes.len() && bytes[i].is_ascii_digit() { | |
| 180 | + | i += 1; | |
| 181 | + | } | |
| 182 | + | if i == 0 { | |
| 183 | + | return 0; | |
| 184 | + | } | |
| 185 | + | while i < bytes.len() && bytes[i] == b'.' { | |
| 186 | + | let mut j = i + 1; | |
| 187 | + | while j < bytes.len() && bytes[j].is_ascii_digit() { | |
| 188 | + | j += 1; | |
| 189 | + | } | |
| 190 | + | if j == i + 1 { | |
| 191 | + | break; | |
| 192 | + | } | |
| 193 | + | i = j; | |
| 194 | + | } | |
| 195 | + | i | |
| 196 | + | } | |
| 197 | + | ||
| 198 | + | fn strip_optional_sep(s: &str) -> &str { | |
| 199 | + | s.strip_prefix('.') | |
| 200 | + | .or_else(|| s.strip_prefix('-')) | |
| 201 | + | .or_else(|| s.strip_prefix('_')) | |
| 202 | + | .unwrap_or(s) | |
| 203 | + | } | |
| 204 | + | ||
| 205 | + | fn take_optional_number(s: &str) -> (u64, &str) { | |
| 206 | + | let s2 = strip_optional_sep(s); | |
| 207 | + | let end = s2.bytes().take_while(u8::is_ascii_digit).count(); | |
| 208 | + | if end == 0 { | |
| 209 | + | (0, s) | |
| 210 | + | } else { | |
| 211 | + | let num = s2[..end].parse::<u64>().unwrap_or(0); | |
| 212 | + | (num, &s2[end..]) | |
| 213 | + | } | |
| 214 | + | } | |
| 215 | + | ||
| 216 | + | fn try_parse_pre(s: &str) -> Option<((PreKind, u64), &str)> { | |
| 217 | + | let trimmed = strip_optional_sep(s); | |
| 218 | + | let labels: &[(&str, PreKind)] = &[ | |
| 219 | + | ("alpha", PreKind::Alpha), | |
| 220 | + | ("beta", PreKind::Beta), | |
| 221 | + | ("preview", PreKind::Rc), | |
| 222 | + | ("pre", PreKind::Rc), | |
| 223 | + | ("rc", PreKind::Rc), | |
| 224 | + | ("a", PreKind::Alpha), | |
| 225 | + | ("b", PreKind::Beta), | |
| 226 | + | ("c", PreKind::Rc), | |
| 227 | + | ]; | |
| 228 | + | for &(label, kind) in labels { | |
| 229 | + | if let Some(after) = trimmed.strip_prefix(label) { | |
| 230 | + | // Avoid matching words like `post` or `dev` or alphabetic identifiers. | |
| 231 | + | if after.chars().next().is_some_and(char::is_alphabetic) { | |
| 232 | + | continue; | |
| 233 | + | } | |
| 234 | + | let (num, rest) = take_optional_number(after); | |
| 235 | + | return Some(((kind, num), rest)); | |
| 236 | + | } | |
| 237 | + | } | |
| 238 | + | None | |
| 239 | + | } | |
| 240 | + | ||
| 241 | + | fn try_parse_post(s: &str) -> Option<(u64, &str)> { | |
| 242 | + | if let Some(after_dash) = s.strip_prefix('-') { | |
| 243 | + | let end = after_dash.bytes().take_while(u8::is_ascii_digit).count(); | |
| 244 | + | if end > 0 { | |
| 245 | + | let num = after_dash[..end].parse::<u64>().ok()?; | |
| 246 | + | return Some((num, &after_dash[end..])); | |
| 247 | + | } | |
| 248 | + | } | |
| 249 | + | let trimmed = strip_optional_sep(s); | |
| 250 | + | for label in ["post", "rev", "r"] { | |
| 251 | + | if let Some(after) = trimmed.strip_prefix(label) { | |
| 252 | + | if after.chars().next().is_some_and(char::is_alphabetic) { | |
| 253 | + | continue; | |
| 254 | + | } | |
| 255 | + | let (num, rest) = take_optional_number(after); | |
| 256 | + | return Some((num, rest)); | |
| 257 | + | } | |
| 258 | + | } | |
| 259 | + | None | |
| 260 | + | } | |
| 261 | + | ||
| 262 | + | fn try_parse_dev(s: &str) -> Option<(u64, &str)> { | |
| 263 | + | let trimmed = strip_optional_sep(s); | |
| 264 | + | if let Some(after) = trimmed.strip_prefix("dev") { | |
| 265 | + | if after.chars().next().is_some_and(char::is_alphabetic) { | |
| 266 | + | return None; | |
| 267 | + | } | |
| 268 | + | let (num, rest) = take_optional_number(after); | |
| 269 | + | return Some((num, rest)); | |
| 270 | + | } | |
| 271 | + | None | |
| 272 | + | } | |
| 273 | + | ||
| 274 | + | #[cfg(test)] | |
| 275 | + | mod tests { | |
| 276 | + | use super::*; | |
| 277 | + | ||
| 278 | + | #[test] | |
| 279 | + | fn pep440_ordering_matches_spec() { | |
| 280 | + | let ordered = [ | |
| 281 | + | "1.0.0.dev0", | |
| 282 | + | "1.0.0a1", | |
| 283 | + | "1.0.0a2", | |
| 284 | + | "1.0.0b1", | |
| 285 | + | "1.0.0rc1", | |
| 286 | + | "1.0.0", | |
| 287 | + | "1.0.0.post1", | |
| 288 | + | "1.1", | |
| 289 | + | "1.1.1", | |
| 290 | + | "2026.01", | |
| 291 | + | "1!0.1.0", | |
| 292 | + | ]; | |
| 293 | + | let parsed: Vec<Pep440Version> = ordered | |
| 294 | + | .iter() | |
| 295 | + | .map(|s| Pep440Version::parse(s).unwrap_or_else(|| panic!("failed to parse {s}"))) | |
| 296 | + | .collect(); | |
| 297 | + | for win in parsed.windows(2) { | |
| 298 | + | assert!(win[0] < win[1], "expected {:?} < {:?}", win[0], win[1]); | |
| 299 | + | } | |
| 300 | + | assert!(Pep440Version::parse("v1.0.0rc1").unwrap().is_prerelease()); | |
| 301 | + | assert!(!Pep440Version::parse("v1.0.0").unwrap().is_prerelease()); | |
| 302 | + | assert_eq!( | |
| 303 | + | Pep440Version::parse("1.0") | |
| 304 | + | .unwrap() | |
| 305 | + | .cmp(&Pep440Version::parse("1.0.0").unwrap()), | |
| 306 | + | Ordering::Equal | |
| 307 | + | ); | |
| 308 | + | } | |
| 309 | + | } |
| @@ -0,0 +1,1979 @@ | |||
| 1 | + | use std::collections::HashSet; | |
| 2 | + | use std::fs; | |
| 3 | + | use std::path::{Path, PathBuf}; | |
| 4 | + | use std::sync::Arc; | |
| 5 | + | ||
| 6 | + | use indexmap::IndexMap; | |
| 7 | + | use rayon::prelude::*; | |
| 8 | + | use serde_json::Value as JsonValue; | |
| 9 | + | ||
| 10 | + | use crate::answers::AnswersMap; | |
| 11 | + | use crate::config::TemplateConfig; | |
| 12 | + | use crate::error::{Result, RoneoError}; | |
| 13 | + | use crate::filter::PathFilter; | |
| 14 | + | use crate::fs_util::{ | |
| 15 | + | TempDir, copy_permissions, create_symlink, file_mode_from_metadata, set_executable, | |
| 16 | + | set_file_mode, | |
| 17 | + | }; | |
| 18 | + | use crate::plugin::{ExtensionInitContext, ExtensionRegistry}; | |
| 19 | + | use crate::prompt::{ | |
| 20 | + | AnswerCollectionOptions, NonInteractivePrompter, OverwriteChoice, Prompter, collect_answers, | |
| 21 | + | }; | |
| 22 | + | use crate::renderer::{CopierConf, TemplateRenderer, build_render_context}; | |
| 23 | + | use crate::settings::UserSettings; | |
| 24 | + | use crate::tasks::{MigrationRun, MigrationStage, run_migrations, run_tasks}; | |
| 25 | + | use crate::template::{ResolvedTemplate, TemplateBacking}; | |
| 26 | + | use crate::vcs::{self, ConflictMode, InMemoryGitTree}; | |
| 27 | + | use crate::version::Pep440Version; | |
| 28 | + | ||
| 29 | + | /// Highest Copier specification version that Ronéo declares compatibility with | |
| 30 | + | /// when validating `_min_copier_version`. | |
| 31 | + | pub const COPIER_COMPAT_VERSION: &str = "9.19.1"; | |
| 32 | + | ||
| 33 | + | /// Options controlling `copy`, `recopy`, and `update`. | |
| 34 | + | #[derive(Debug, Clone)] | |
| 35 | + | pub struct CopyOptions { | |
| 36 | + | pub vcs_ref: Option<String>, | |
| 37 | + | pub data: IndexMap<String, JsonValue>, | |
| 38 | + | pub answers_file: Option<PathBuf>, | |
| 39 | + | pub exclude: Vec<String>, | |
| 40 | + | pub skip_if_exists: Vec<String>, | |
| 41 | + | pub use_default_excludes: bool, | |
| 42 | + | pub use_prereleases: bool, | |
| 43 | + | pub overwrite: bool, | |
| 44 | + | pub pretend: bool, | |
| 45 | + | pub defaults: bool, | |
| 46 | + | pub skip_answered: bool, | |
| 47 | + | pub ask_questions: Vec<String>, | |
| 48 | + | pub skip_tasks: bool, | |
| 49 | + | pub trust: bool, | |
| 50 | + | pub conflict_mode: ConflictMode, | |
| 51 | + | pub context_lines: usize, | |
| 52 | + | pub cleanup_on_error: bool, | |
| 53 | + | pub skip_git_check: bool, | |
| 54 | + | pub quiet: bool, | |
| 55 | + | pub user_settings: Option<UserSettings>, | |
| 56 | + | pub extensions: ExtensionRegistry, | |
| 57 | + | } | |
| 58 | + | ||
| 59 | + | impl Default for CopyOptions { | |
| 60 | + | fn default() -> Self { | |
| 61 | + | Self { | |
| 62 | + | vcs_ref: None, | |
| 63 | + | data: IndexMap::new(), | |
| 64 | + | answers_file: None, | |
| 65 | + | exclude: Vec::new(), | |
| 66 | + | skip_if_exists: Vec::new(), | |
| 67 | + | use_default_excludes: true, | |
| 68 | + | use_prereleases: false, | |
| 69 | + | overwrite: false, | |
| 70 | + | pretend: false, | |
| 71 | + | defaults: false, | |
| 72 | + | skip_answered: false, | |
| 73 | + | ask_questions: Vec::new(), | |
| 74 | + | skip_tasks: false, | |
| 75 | + | trust: false, | |
| 76 | + | conflict_mode: ConflictMode::Inline, | |
| 77 | + | context_lines: 3, | |
| 78 | + | cleanup_on_error: true, | |
| 79 | + | skip_git_check: false, | |
| 80 | + | quiet: false, | |
| 81 | + | user_settings: None, | |
| 82 | + | extensions: ExtensionRegistry::new(), | |
| 83 | + | } | |
| 84 | + | } | |
| 85 | + | } | |
| 86 | + | ||
| 87 | + | /// High-level events emitted during copy/recopy/update for UI/CLI reporting. | |
| 88 | + | #[derive(Debug, Clone)] | |
| 89 | + | pub enum ActionEvent { | |
| 90 | + | Create(PathBuf), | |
| 91 | + | Overwrite(PathBuf), | |
| 92 | + | Update(PathBuf), | |
| 93 | + | Delete(PathBuf), | |
| 94 | + | Identical(PathBuf), | |
| 95 | + | Skip(PathBuf), | |
| 96 | + | Conflict(PathBuf), | |
| 97 | + | RunTask(String), | |
| 98 | + | Message(String), | |
| 99 | + | Warning(String), | |
| 100 | + | } | |
| 101 | + | ||
| 102 | + | pub trait Reporter { | |
| 103 | + | fn emit(&self, event: ActionEvent); | |
| 104 | + | } | |
| 105 | + | ||
| 106 | + | #[derive(Debug, Default)] | |
| 107 | + | pub struct NoopReporter; | |
| 108 | + | ||
| 109 | + | impl Reporter for NoopReporter { | |
| 110 | + | fn emit(&self, _event: ActionEvent) {} | |
| 111 | + | } | |
| 112 | + | ||
| 113 | + | /// Summary returned after `copy`, `recopy`, or `update`. | |
| 114 | + | #[derive(Debug, Clone)] | |
| 115 | + | pub struct OperationReport { | |
| 116 | + | pub src_path: String, | |
| 117 | + | pub dst_path: PathBuf, | |
| 118 | + | pub commit: Option<String>, | |
| 119 | + | pub answers_file: PathBuf, | |
| 120 | + | pub created: usize, | |
| 121 | + | pub updated: usize, | |
| 122 | + | pub skipped: usize, | |
| 123 | + | pub conflicts: Vec<String>, | |
| 124 | + | } | |
| 125 | + | ||
| 126 | + | /// Result of previewing a 3-way template update via `diff_update`. | |
| 127 | + | #[derive(Debug, Clone)] | |
| 128 | + | pub struct UpdateDiff { | |
| 129 | + | pub src_path: String, | |
| 130 | + | pub from_commit: String, | |
| 131 | + | pub to_commit: Option<String>, | |
| 132 | + | pub patch: String, | |
| 133 | + | pub created: Vec<String>, | |
| 134 | + | pub modified: Vec<String>, | |
| 135 | + | pub deleted: Vec<String>, | |
| 136 | + | } | |
| 137 | + | ||
| 138 | + | /// Result of checking whether a newer template version is available (`roneo check-update`). | |
| 139 | + | #[derive(Debug, Clone, serde::Serialize)] | |
| 140 | + | pub struct CheckUpdateReport { | |
| 141 | + | pub src_path: String, | |
| 142 | + | pub current_version: String, | |
| 143 | + | pub latest_version: String, | |
| 144 | + | pub update_available: bool, | |
| 145 | + | } | |
| 146 | + | ||
| 147 | + | /// Check whether a newer template version is available for an existing project without | |
| 148 | + | /// modifying any files (matching Copier's `check-update` / `get_update_data`). | |
| 149 | + | pub fn check_update(dst_path: &Path, options: &CopyOptions) -> Result<CheckUpdateReport> { | |
| 150 | + | let answers_path = AnswersMap::find_in_dir(dst_path, options.answers_file.as_deref()) | |
| 151 | + | .ok_or_else(|| RoneoError::MissingAnswersFile(dst_path.to_path_buf()))?; | |
| 152 | + | let previous = AnswersMap::load(&answers_path)?; | |
| 153 | + | ||
| 154 | + | let src = previous | |
| 155 | + | .src_path() | |
| 156 | + | .ok_or_else(|| RoneoError::InvalidConfig("Answers file is missing `_src_path`".into()))? | |
| 157 | + | .to_string(); | |
| 158 | + | let current_commit = previous | |
| 159 | + | .commit() | |
| 160 | + | .ok_or_else(|| { | |
| 161 | + | RoneoError::InvalidConfig( | |
| 162 | + | "Answers file is missing `_commit`. Cannot check updates for a non-git template." | |
| 163 | + | .into(), | |
| 164 | + | ) | |
| 165 | + | })? | |
| 166 | + | .to_string(); | |
| 167 | + | ||
| 168 | + | let current_tpl = ResolvedTemplate::resolve(&src, Some(¤t_commit))?; | |
| 169 | + | let latest_tpl = current_tpl.resolve_sibling(None, options.use_prereleases)?; | |
| 170 | + | let latest_commit = latest_tpl | |
| 171 | + | .commit | |
| 172 | + | .clone() | |
| 173 | + | .or_else(|| latest_tpl.commit_hash.clone()) | |
| 174 | + | .unwrap_or_else(|| "HEAD".to_string()); | |
| 175 | + | ||
| 176 | + | let update_available = match ( | |
| 177 | + | Pep440Version::parse(¤t_commit), | |
| 178 | + | Pep440Version::parse(&latest_commit), | |
| 179 | + | ) { | |
| 180 | + | (Some(cur_ver), Some(lat_ver)) => lat_ver > cur_ver, | |
| 181 | + | _ => match (¤t_tpl.commit_hash, &latest_tpl.commit_hash) { | |
| 182 | + | (Some(c), Some(l)) => c != l, | |
| 183 | + | _ => current_commit != latest_commit, | |
| 184 | + | }, | |
| 185 | + | }; | |
| 186 | + | ||
| 187 | + | Ok(CheckUpdateReport { | |
| 188 | + | src_path: src, | |
| 189 | + | current_version: current_commit, | |
| 190 | + | latest_version: latest_commit, | |
| 191 | + | update_available, | |
| 192 | + | }) | |
| 193 | + | } | |
| 194 | + | ||
| 195 | + | /// Render a new project from `src_path` into `dst_path`. | |
| 196 | + | /// | |
| 197 | + | /// If `dst_path` did not exist prior to `copy` and an error occurs, `dst_path` is automatically | |
| 198 | + | /// removed unless `options.cleanup_on_error` is `false` (Copier's `--no-cleanup`). | |
| 199 | + | pub fn copy( | |
| 200 | + | src_path: &str, | |
| 201 | + | dst_path: &Path, | |
| 202 | + | options: &CopyOptions, | |
| 203 | + | prompter: &dyn Prompter, | |
| 204 | + | reporter: &dyn Reporter, | |
| 205 | + | ) -> Result<OperationReport> { | |
| 206 | + | let dst_existed = dst_path.exists(); | |
| 207 | + | let result = copy_inner(src_path, dst_path, options, prompter, reporter); | |
| 208 | + | if result.is_err() | |
| 209 | + | && !dst_existed | |
| 210 | + | && options.cleanup_on_error | |
| 211 | + | && !options.pretend | |
| 212 | + | && dst_path.exists() | |
| 213 | + | { | |
| 214 | + | let _ = fs::remove_dir_all(dst_path); | |
| 215 | + | } | |
| 216 | + | result | |
| 217 | + | } | |
| 218 | + | ||
| 219 | + | fn copy_inner( | |
| 220 | + | src_path: &str, | |
| 221 | + | dst_path: &Path, | |
| 222 | + | options: &CopyOptions, | |
| 223 | + | prompter: &dyn Prompter, | |
| 224 | + | reporter: &dyn Reporter, | |
| 225 | + | ) -> Result<OperationReport> { | |
| 226 | + | let resolved = ResolvedTemplate::resolve_with_options( | |
| 227 | + | src_path, | |
| 228 | + | options.vcs_ref.as_deref(), | |
| 229 | + | options.use_prereleases, | |
| 230 | + | )?; | |
| 231 | + | check_min_copier_version(&resolved.config, reporter)?; | |
| 232 | + | let user_settings = resolve_user_settings(options); | |
| 233 | + | let is_trusted_pre = | |
| 234 | + | options.trust || user_settings.is_trusted(&resolved.original_src, &resolved.resolved_src); | |
| 235 | + | let active_exts = build_active_extensions(&resolved, options, is_trusted_pre)?; | |
| 236 | + | let is_trusted = check_trust(&resolved, options, &user_settings, &active_exts, reporter)?; | |
| 237 | + | ||
| 238 | + | let file_reader = resolved.file_reader(); | |
| 239 | + | let init_ctx = ExtensionInitContext { | |
| 240 | + | template_root: resolved.local_path.clone(), | |
| 241 | + | dst_path: dst_path.to_path_buf(), | |
| 242 | + | file_reader: Arc::clone(&file_reader), | |
| 243 | + | }; | |
| 244 | + | let renderer = TemplateRenderer::with_extensions( | |
| 245 | + | &resolved.config.settings.envops, | |
| 246 | + | Some(file_reader), | |
| 247 | + | Some(&active_exts), | |
| 248 | + | Some(&init_ctx), | |
| 249 | + | )?; | |
| 250 | + | ||
| 251 | + | if let Some(msg) = &resolved.config.settings.message_before_copy { | |
| 252 | + | let banner = renderer.render_str(msg, &options.data, "_message_before_copy")?; | |
| 253 | + | if !banner.trim().is_empty() { | |
| 254 | + | reporter.emit(ActionEvent::Message(banner)); | |
| 255 | + | } | |
| 256 | + | } | |
| 257 | + | ||
| 258 | + | let prompt_init_ctx = | |
| 259 | + | build_prompt_initial_context(&resolved, dst_path, &renderer, options, "copy", is_trusted)?; | |
| 260 | + | let mut answers = collect_answers( | |
| 261 | + | &resolved.config, | |
| 262 | + | &renderer, | |
| 263 | + | prompter, | |
| 264 | + | &AnswerCollectionOptions { | |
| 265 | + | data: &options.data, | |
| 266 | + | previous_answers: None, | |
| 267 | + | user_defaults: Some(&user_settings.defaults), | |
| 268 | + | initial_context: Some(&prompt_init_ctx), | |
| 269 | + | extensions: Some(&active_exts), | |
| 270 | + | use_defaults: options.defaults, | |
| 271 | + | skip_answered: options.skip_answered, | |
| 272 | + | ask_questions: &options.ask_questions, | |
| 273 | + | }, | |
| 274 | + | )?; | |
| 275 | + | ||
| 276 | + | answers.set_src_path(&resolved.original_src); | |
| 277 | + | if let Some(commit) = &resolved.commit { | |
| 278 | + | answers.set_commit(commit); | |
| 279 | + | } | |
| 280 | + | ||
| 281 | + | let (report, ctx) = render_into_destination( | |
| 282 | + | &resolved, | |
| 283 | + | dst_path, | |
| 284 | + | &answers, | |
| 285 | + | &renderer, | |
| 286 | + | &active_exts, | |
| 287 | + | options, | |
| 288 | + | "copy", | |
| 289 | + | is_trusted, | |
| 290 | + | Some(prompter), | |
| 291 | + | reporter, | |
| 292 | + | )?; | |
| 293 | + | ||
| 294 | + | if !options.skip_tasks && !resolved.config.settings.tasks.is_empty() { | |
| 295 | + | run_tasks( | |
| 296 | + | &resolved.config.settings.tasks, | |
| 297 | + | dst_path, | |
| 298 | + | &renderer, | |
| 299 | + | &ctx, | |
| 300 | + | &[], | |
| 301 | + | options.pretend, | |
| 302 | + | |cmd| reporter.emit(ActionEvent::RunTask(cmd.to_string())), | |
| 303 | + | )?; | |
| 304 | + | } | |
| 305 | + | ||
| 306 | + | if let Some(msg) = &resolved.config.settings.message_after_copy { | |
| 307 | + | let banner = renderer.render_str(msg, &ctx, "_message_after_copy")?; | |
| 308 | + | if !banner.trim().is_empty() { | |
| 309 | + | reporter.emit(ActionEvent::Message(banner)); | |
| 310 | + | } | |
| 311 | + | } | |
| 312 | + | ||
| 313 | + | Ok(report) | |
| 314 | + | } | |
| 315 | + | ||
| 316 | + | /// Re-apply a template onto an existing project using saved answers, without 3-way diffing. | |
| 317 | + | pub fn recopy( | |
| 318 | + | dst_path: &Path, | |
| 319 | + | src_override: Option<&str>, | |
| 320 | + | options: &CopyOptions, | |
| 321 | + | prompter: &dyn Prompter, | |
| 322 | + | reporter: &dyn Reporter, | |
| 323 | + | ) -> Result<OperationReport> { | |
| 324 | + | let answers_path = AnswersMap::find_in_dir(dst_path, options.answers_file.as_deref()) | |
| 325 | + | .ok_or_else(|| RoneoError::MissingAnswersFile(dst_path.to_path_buf()))?; | |
| 326 | + | let previous = AnswersMap::load(&answers_path)?; | |
| 327 | + | ||
| 328 | + | let src = src_override | |
| 329 | + | .or_else(|| previous.src_path()) | |
| 330 | + | .ok_or_else(|| { | |
| 331 | + | RoneoError::InvalidConfig( | |
| 332 | + | "Answers file is missing `_src_path`; pass a template source explicitly".into(), | |
| 333 | + | ) | |
| 334 | + | })?; | |
| 335 | + | ||
| 336 | + | let resolved = ResolvedTemplate::resolve_with_options( | |
| 337 | + | src, | |
| 338 | + | options.vcs_ref.as_deref(), | |
| 339 | + | options.use_prereleases, | |
| 340 | + | )?; | |
| 341 | + | check_min_copier_version(&resolved.config, reporter)?; | |
| 342 | + | let user_settings = resolve_user_settings(options); | |
| 343 | + | let is_trusted_pre = | |
| 344 | + | options.trust || user_settings.is_trusted(&resolved.original_src, &resolved.resolved_src); | |
| 345 | + | let active_exts = build_active_extensions(&resolved, options, is_trusted_pre)?; | |
| 346 | + | let is_trusted = check_trust(&resolved, options, &user_settings, &active_exts, reporter)?; | |
| 347 | + | ||
| 348 | + | let file_reader = resolved.file_reader(); | |
| 349 | + | let init_ctx = ExtensionInitContext { | |
| 350 | + | template_root: resolved.local_path.clone(), | |
| 351 | + | dst_path: dst_path.to_path_buf(), | |
| 352 | + | file_reader: Arc::clone(&file_reader), | |
| 353 | + | }; | |
| 354 | + | let renderer = TemplateRenderer::with_extensions( | |
| 355 | + | &resolved.config.settings.envops, | |
| 356 | + | Some(file_reader), | |
| 357 | + | Some(&active_exts), | |
| 358 | + | Some(&init_ctx), | |
| 359 | + | )?; | |
| 360 | + | ||
| 361 | + | let prompt_init_ctx = build_prompt_initial_context( | |
| 362 | + | &resolved, dst_path, &renderer, options, "recopy", is_trusted, | |
| 363 | + | )?; | |
| 364 | + | let mut answers = collect_answers( | |
| 365 | + | &resolved.config, | |
| 366 | + | &renderer, | |
| 367 | + | prompter, | |
| 368 | + | &AnswerCollectionOptions { | |
| 369 | + | data: &options.data, | |
| 370 | + | previous_answers: Some(&previous), | |
| 371 | + | user_defaults: Some(&user_settings.defaults), | |
| 372 | + | initial_context: Some(&prompt_init_ctx), | |
| 373 | + | extensions: Some(&active_exts), | |
| 374 | + | use_defaults: options.defaults, | |
| 375 | + | skip_answered: options.skip_answered, | |
| 376 | + | ask_questions: &options.ask_questions, | |
| 377 | + | }, | |
| 378 | + | )?; | |
| 379 | + | ||
| 380 | + | answers.set_src_path(&resolved.original_src); | |
| 381 | + | if let Some(commit) = &resolved.commit { | |
| 382 | + | answers.set_commit(commit); | |
| 383 | + | } | |
| 384 | + | ||
| 385 | + | let mut recopy_opts = options.clone(); | |
| 386 | + | recopy_opts.overwrite = true; | |
| 387 | + | ||
| 388 | + | let (report, ctx) = render_into_destination( | |
| 389 | + | &resolved, | |
| 390 | + | dst_path, | |
| 391 | + | &answers, | |
| 392 | + | &renderer, | |
| 393 | + | &active_exts, | |
| 394 | + | &recopy_opts, | |
| 395 | + | "recopy", | |
| 396 | + | is_trusted, | |
| 397 | + | None, | |
| 398 | + | reporter, | |
| 399 | + | )?; | |
| 400 | + | ||
| 401 | + | if !options.skip_tasks && !resolved.config.settings.tasks.is_empty() { | |
| 402 | + | run_tasks( | |
| 403 | + | &resolved.config.settings.tasks, | |
| 404 | + | dst_path, | |
| 405 | + | &renderer, | |
| 406 | + | &ctx, | |
| 407 | + | &[], | |
| 408 | + | options.pretend, | |
| 409 | + | |cmd| reporter.emit(ActionEvent::RunTask(cmd.to_string())), | |
| 410 | + | )?; | |
| 411 | + | } | |
| 412 | + | ||
| 413 | + | Ok(report) | |
| 414 | + | } | |
| 415 | + | ||
| 416 | + | /// Update an existing git-tracked project to a newer template version via 3-way merge, | |
| 417 | + | /// preserving local user edits cleanly (Copier's smart update algorithm). | |
| 418 | + | /// | |
| 419 | + | /// Works both when `dst_path` is a Git repository root and when it is a subdirectory inside | |
| 420 | + | /// a Git monorepo. | |
| 421 | + | pub fn update( | |
| 422 | + | dst_path: &Path, | |
| 423 | + | options: &CopyOptions, | |
| 424 | + | prompter: &dyn Prompter, | |
| 425 | + | reporter: &dyn Reporter, | |
| 426 | + | ) -> Result<OperationReport> { | |
| 427 | + | let (git_root, subproject_subdir) = resolve_git_destination(dst_path, options)?; | |
| 428 | + | let wt_status = if options.skip_git_check { | |
| 429 | + | vcs::WorkingTreeStatus { | |
| 430 | + | is_clean: true, | |
| 431 | + | ignored_paths: Vec::new(), | |
| 432 | + | } | |
| 433 | + | } else { | |
| 434 | + | let status = vcs::inspect_working_tree(&git_root)?; | |
| 435 | + | if !options.pretend && !status.is_clean { | |
| 436 | + | return Err(RoneoError::DirtyDestination(dst_path.to_path_buf())); | |
| 437 | + | } | |
| 438 | + | status | |
| 439 | + | }; | |
| 440 | + | ||
| 441 | + | let prepared = prepare_update_patch(dst_path, options, prompter, reporter, true)?; | |
| 442 | + | ||
| 443 | + | // Reject downgrades on PEP 440 versioned templates (matching Copier's DowngradeError). | |
| 444 | + | let new_commit_str = prepared.new_template.commit.as_deref().unwrap_or(""); | |
| 445 | + | if let (Some(old_ver), Some(new_ver)) = ( | |
| 446 | + | Pep440Version::parse(&prepared.old_commit), | |
| 447 | + | Pep440Version::parse(new_commit_str), | |
| 448 | + | ) && new_ver < old_ver | |
| 449 | + | { | |
| 450 | + | return Err(RoneoError::DowngradeNotSupported { | |
| 451 | + | from: prepared.old_commit, | |
| 452 | + | to: new_commit_str.to_string(), | |
| 453 | + | }); | |
| 454 | + | } | |
| 455 | + | ||
| 456 | + | let diff_summary = summarize_patch(&prepared.patch); | |
| 457 | + | for path in &diff_summary.created { | |
| 458 | + | reporter.emit(ActionEvent::Create(PathBuf::from(path))); | |
| 459 | + | } | |
| 460 | + | for path in &diff_summary.modified { | |
| 461 | + | reporter.emit(ActionEvent::Update(PathBuf::from(path))); | |
| 462 | + | } | |
| 463 | + | for path in &diff_summary.deleted { | |
| 464 | + | reporter.emit(ActionEvent::Delete(PathBuf::from(path))); | |
| 465 | + | } | |
| 466 | + | ||
| 467 | + | if !options.skip_tasks && !prepared.new_template.config.settings.migrations.is_empty() { | |
| 468 | + | run_migrations( | |
| 469 | + | &prepared.new_template.config.settings.migrations, | |
| 470 | + | &MigrationRun { | |
| 471 | + | version_from: &prepared.old_commit, | |
| 472 | + | version_to: new_commit_str, | |
| 473 | + | stage: MigrationStage::Before, | |
| 474 | + | dst_path, | |
| 475 | + | renderer: &prepared.new_renderer, | |
| 476 | + | ctx: &prepared.new_ctx, | |
| 477 | + | pretend: options.pretend, | |
| 478 | + | }, | |
| 479 | + | |cmd| reporter.emit(ActionEvent::RunTask(cmd.to_string())), | |
| 480 | + | )?; | |
| 481 | + | } | |
| 482 | + | ||
| 483 | + | // Honor `_skip_if_exists` / `-s`, `.gitignore`-ignored files, AND exclude `.copier-answers.yml` | |
| 484 | + | // from `git apply` (written cleanly afterwards to prevent spurious merge conflicts, matching Copier). | |
| 485 | + | let mut apply_excludes = collect_update_skip_excludes( | |
| 486 | + | dst_path, | |
| 487 | + | subproject_subdir.as_deref(), | |
| 488 | + | &diff_summary, | |
| 489 | + | &prepared.new_skip_filter, | |
| 490 | + | ); | |
| 491 | + | let skipped_count = apply_excludes.len(); | |
| 492 | + | for ignored in &wt_status.ignored_paths { | |
| 493 | + | apply_excludes.push(ignored.clone()); | |
| 494 | + | } | |
| 495 | + | let format_repo_rel = |rel: &Path| -> String { | |
| 496 | + | match subproject_subdir.as_deref() { | |
| 497 | + | Some(sub) if !sub.as_os_str().is_empty() => { | |
| 498 | + | sub.join(rel).to_string_lossy().replace('\\', "/") | |
| 499 | + | } | |
| 500 | + | _ => rel.to_string_lossy().replace('\\', "/"), | |
| 501 | + | } | |
| 502 | + | }; | |
| 503 | + | apply_excludes.push(format_repo_rel(&prepared.new_answers_rel)); | |
| 504 | + | if let Ok(old_rel) = prepared.old_answers_path.strip_prefix(dst_path) | |
| 505 | + | && old_rel != prepared.new_answers_rel | |
| 506 | + | { | |
| 507 | + | apply_excludes.push(format_repo_rel(old_rel)); | |
| 508 | + | } | |
| 509 | + | ||
| 510 | + | let old_snapshot_dir = prepared.diff_root.path().join("a"); | |
| 511 | + | let new_snapshot_dir = prepared.diff_root.path().join("b"); | |
| 512 | + | let mut conflicts = Vec::new(); | |
| 513 | + | if !options.pretend && !prepared.patch.is_empty() { | |
| 514 | + | let apply_res = vcs::apply_patch( | |
| 515 | + | &git_root, | |
| 516 | + | subproject_subdir.as_deref(), | |
| 517 | + | &prepared.patch, | |
| 518 | + | options.conflict_mode, | |
| 519 | + | &apply_excludes, | |
| 520 | + | Some((&old_snapshot_dir, &new_snapshot_dir)), | |
| 521 | + | )?; | |
| 522 | + | if apply_res.has_conflicts { | |
| 523 | + | for c in &apply_res.conflicted_files { | |
| 524 | + | reporter.emit(ActionEvent::Conflict(PathBuf::from(c))); | |
| 525 | + | } | |
| 526 | + | if apply_res.conflicted_files.is_empty() && !apply_res.stderr.is_empty() { | |
| 527 | + | reporter.emit(ActionEvent::Warning(apply_res.stderr.clone())); | |
| 528 | + | } | |
| 529 | + | conflicts = apply_res.conflicted_files; | |
| 530 | + | } | |
| 531 | + | } | |
| 532 | + | ||
| 533 | + | // Write the updated answers file directly (never conflicted by `git apply`), and clean up | |
| 534 | + | // the previous answers file if `_answers_file` was renamed between template versions. | |
| 535 | + | let answers_dst = dst_path.join(&prepared.new_answers_rel); | |
| 536 | + | if !options.pretend | |
| 537 | + | && let Some(bytes) = &prepared.new_answers_bytes | |
| 538 | + | { | |
| 539 | + | if let Some(parent) = answers_dst.parent() { | |
| 540 | + | fs::create_dir_all(parent).map_err(|e| RoneoError::io(parent, e))?; | |
| 541 | + | } | |
| 542 | + | fs::write(&answers_dst, bytes).map_err(|e| RoneoError::io(&answers_dst, e))?; | |
| 543 | + | ||
| 544 | + | let old_canon = fs::canonicalize(&prepared.old_answers_path).ok(); | |
| 545 | + | let new_canon = fs::canonicalize(&answers_dst).ok(); | |
| 546 | + | if old_canon != new_canon && prepared.old_answers_path.is_file() { | |
| 547 | + | let _ = fs::remove_file(&prepared.old_answers_path); | |
| 548 | + | if let Ok(rel) = prepared.old_answers_path.strip_prefix(dst_path) { | |
| 549 | + | reporter.emit(ActionEvent::Delete(rel.to_path_buf())); | |
| 550 | + | } | |
| 551 | + | } | |
| 552 | + | } | |
| 553 | + | ||
| 554 | + | if !options.skip_tasks { | |
| 555 | + | if !prepared.new_template.config.settings.migrations.is_empty() { | |
| 556 | + | run_migrations( | |
| 557 | + | &prepared.new_template.config.settings.migrations, | |
| 558 | + | &MigrationRun { | |
| 559 | + | version_from: &prepared.old_commit, | |
| 560 | + | version_to: new_commit_str, | |
| 561 | + | stage: MigrationStage::After, | |
| 562 | + | dst_path, | |
| 563 | + | renderer: &prepared.new_renderer, | |
| 564 | + | ctx: &prepared.new_ctx, | |
| 565 | + | pretend: options.pretend, | |
| 566 | + | }, | |
| 567 | + | |cmd| reporter.emit(ActionEvent::RunTask(cmd.to_string())), | |
| 568 | + | )?; | |
| 569 | + | } | |
| 570 | + | if !prepared.new_template.config.settings.tasks.is_empty() { | |
| 571 | + | run_tasks( | |
| 572 | + | &prepared.new_template.config.settings.tasks, | |
| 573 | + | dst_path, | |
| 574 | + | &prepared.new_renderer, | |
| 575 | + | &prepared.new_ctx, | |
| 576 | + | &[], | |
| 577 | + | options.pretend, | |
| 578 | + | |cmd| reporter.emit(ActionEvent::RunTask(cmd.to_string())), | |
| 579 | + | )?; | |
| 580 | + | } | |
| 581 | + | } | |
| 582 | + | ||
| 583 | + | if let Some(msg) = &prepared.new_template.config.settings.message_after_update { | |
| 584 | + | let banner = | |
| 585 | + | prepared | |
| 586 | + | .new_renderer | |
| 587 | + | .render_str(msg, &prepared.new_ctx, "_message_after_update")?; | |
| 588 | + | if !banner.trim().is_empty() { | |
| 589 | + | reporter.emit(ActionEvent::Message(banner)); | |
| 590 | + | } | |
| 591 | + | } | |
| 592 | + | ||
| 593 | + | Ok(OperationReport { | |
| 594 | + | src_path: prepared.src, | |
| 595 | + | dst_path: dst_path.to_path_buf(), | |
| 596 | + | commit: prepared.new_template.commit, | |
| 597 | + | answers_file: answers_dst, | |
| 598 | + | created: diff_summary.created.len(), | |
| 599 | + | updated: diff_summary.modified.len() + diff_summary.deleted.len(), | |
| 600 | + | skipped: skipped_count, | |
| 601 | + | conflicts, | |
| 602 | + | }) | |
| 603 | + | } | |
| 604 | + | ||
| 605 | + | /// Preview the exact unified diff that `update` would apply, without modifying `dst_path`. | |
| 606 | + | pub fn diff_update( | |
| 607 | + | dst_path: &Path, | |
| 608 | + | options: &CopyOptions, | |
| 609 | + | prompter: &dyn Prompter, | |
| 610 | + | ) -> Result<UpdateDiff> { | |
| 611 | + | let noop = NoopReporter; | |
| 612 | + | let prepared = prepare_update_patch(dst_path, options, prompter, &noop, false)?; | |
| 613 | + | let summary = summarize_patch(&prepared.patch); | |
| 614 | + | ||
| 615 | + | Ok(UpdateDiff { | |
| 616 | + | src_path: prepared.src, | |
| 617 | + | from_commit: prepared.old_commit, | |
| 618 | + | to_commit: prepared.new_template.commit, | |
| 619 | + | patch: String::from_utf8_lossy(&prepared.patch).into_owned(), | |
| 620 | + | created: summary.created, | |
| 621 | + | modified: summary.modified, | |
| 622 | + | deleted: summary.deleted, | |
| 623 | + | }) | |
| 624 | + | } | |
| 625 | + | ||
| 626 | + | struct PreparedUpdate { | |
| 627 | + | src: String, | |
| 628 | + | old_commit: String, | |
| 629 | + | old_answers_path: PathBuf, | |
| 630 | + | new_template: ResolvedTemplate, | |
| 631 | + | new_renderer: TemplateRenderer, | |
| 632 | + | new_answers_rel: PathBuf, | |
| 633 | + | new_answers_bytes: Option<Vec<u8>>, | |
| 634 | + | new_ctx: IndexMap<String, JsonValue>, | |
| 635 | + | new_skip_filter: PathFilter, | |
| 636 | + | diff_root: TempDir, | |
| 637 | + | patch: Vec<u8>, | |
| 638 | + | } | |
| 639 | + | ||
| 640 | + | fn resolve_git_destination( | |
| 641 | + | dst_path: &Path, | |
| 642 | + | options: &CopyOptions, | |
| 643 | + | ) -> Result<(PathBuf, Option<PathBuf>)> { | |
| 644 | + | if let Some(root) = vcs::find_git_worktree_root(dst_path) { | |
| 645 | + | let canon_root = fs::canonicalize(&root).unwrap_or(root); | |
| 646 | + | let canon_dst = fs::canonicalize(dst_path).unwrap_or_else(|_| dst_path.to_path_buf()); | |
| 647 | + | let subdir = canon_dst | |
| 648 | + | .strip_prefix(&canon_root) | |
| 649 | + | .ok() | |
| 650 | + | .filter(|p| !p.as_os_str().is_empty()) | |
| 651 | + | .map(Path::to_path_buf); | |
| 652 | + | return Ok((canon_root, subdir)); | |
| 653 | + | } | |
| 654 | + | if options.skip_git_check { | |
| 655 | + | return Ok((dst_path.to_path_buf(), None)); | |
| 656 | + | } | |
| 657 | + | Err(RoneoError::NotAGitRepo(dst_path.to_path_buf())) | |
| 658 | + | } | |
| 659 | + | ||
| 660 | + | fn collect_update_skip_excludes( | |
| 661 | + | dst_path: &Path, | |
| 662 | + | subproject_subdir: Option<&Path>, | |
| 663 | + | summary: &PatchSummary, | |
| 664 | + | skip_filter: &PathFilter, | |
| 665 | + | ) -> Vec<String> { | |
| 666 | + | let mut out = Vec::new(); | |
| 667 | + | for rel in summary.modified.iter().chain(summary.deleted.iter()) { | |
| 668 | + | let rel_path = Path::new(rel); | |
| 669 | + | if dst_path.join(rel_path).exists() && skip_filter.should_skip_if_exists(rel_path, false) { | |
| 670 | + | let full = match subproject_subdir { | |
| 671 | + | Some(sub) if !sub.as_os_str().is_empty() => { | |
| 672 | + | sub.join(rel_path).to_string_lossy().replace('\\', "/") | |
| 673 | + | } | |
| 674 | + | _ => rel.clone(), | |
| 675 | + | }; | |
| 676 | + | out.push(full); | |
| 677 | + | } | |
| 678 | + | } | |
| 679 | + | out | |
| 680 | + | } | |
| 681 | + | ||
| 682 | + | /// Shared fast-path engine for both `update` and `diff_update`: | |
| 683 | + | /// - Reuses one `gix::ThreadSafeRepository` for both old & new commits (`resolve_sibling`). | |
| 684 | + | /// - Renders `old_template` into `tmp/a` and `new_template` into `tmp/b` in parallel via `rayon::join`. | |
| 685 | + | /// - Produces the binary unified patch in ONE `git diff --no-index --no-prefix` call (zero `git init/add/commit` | |
| 686 | + | /// and zero working-tree copy/delete). | |
| 687 | + | fn prepare_update_patch( | |
| 688 | + | dst_path: &Path, | |
| 689 | + | options: &CopyOptions, | |
| 690 | + | prompter: &dyn Prompter, | |
| 691 | + | reporter: &dyn Reporter, | |
| 692 | + | enforce_trust: bool, | |
| 693 | + | ) -> Result<PreparedUpdate> { | |
| 694 | + | let answers_path = AnswersMap::find_in_dir(dst_path, options.answers_file.as_deref()) | |
| 695 | + | .ok_or_else(|| RoneoError::MissingAnswersFile(dst_path.to_path_buf()))?; | |
| 696 | + | let previous = AnswersMap::load(&answers_path)?; | |
| 697 | + | ||
| 698 | + | let src = previous | |
| 699 | + | .src_path() | |
| 700 | + | .ok_or_else(|| RoneoError::InvalidConfig("Answers file is missing `_src_path`".into()))? | |
| 701 | + | .to_string(); | |
| 702 | + | let old_commit = previous | |
| 703 | + | .commit() | |
| 704 | + | .ok_or_else(|| { | |
| 705 | + | RoneoError::InvalidConfig( | |
| 706 | + | "Answers file is missing `_commit`. Cannot smart-update a non-git template; use `recopy`." | |
| 707 | + | .into(), | |
| 708 | + | ) | |
| 709 | + | })? | |
| 710 | + | .to_string(); | |
| 711 | + | ||
| 712 | + | let old_template = ResolvedTemplate::resolve(&src, Some(&old_commit))?; | |
| 713 | + | let target_ref = if options.vcs_ref.as_deref() == Some(":current:") { | |
| 714 | + | Some(old_commit.as_str()) | |
| 715 | + | } else { | |
| 716 | + | options.vcs_ref.as_deref() | |
| 717 | + | }; | |
| 718 | + | let new_template = old_template.resolve_sibling(target_ref, options.use_prereleases)?; | |
| 719 | + | check_min_copier_version(&new_template.config, reporter)?; | |
| 720 | + | let user_settings = resolve_user_settings(options); | |
| 721 | + | let is_trusted_pre = options.trust | |
| 722 | + | || user_settings.is_trusted(&new_template.original_src, &new_template.resolved_src); | |
| 723 | + | let old_exts = build_active_extensions(&old_template, options, is_trusted_pre)?; | |
| 724 | + | let new_exts = build_active_extensions(&new_template, options, is_trusted_pre)?; | |
| 725 | + | let is_trusted = if enforce_trust { | |
| 726 | + | check_trust(&new_template, options, &user_settings, &new_exts, reporter)? | |
| 727 | + | } else { | |
| 728 | + | is_trusted_pre | |
| 729 | + | }; | |
| 730 | + | ||
| 731 | + | let old_reader = old_template.file_reader(); | |
| 732 | + | let new_reader = new_template.file_reader(); | |
| 733 | + | let old_init = ExtensionInitContext { | |
| 734 | + | template_root: old_template.local_path.clone(), | |
| 735 | + | dst_path: dst_path.to_path_buf(), | |
| 736 | + | file_reader: Arc::clone(&old_reader), | |
| 737 | + | }; | |
| 738 | + | let new_init = ExtensionInitContext { | |
| 739 | + | template_root: new_template.local_path.clone(), | |
| 740 | + | dst_path: dst_path.to_path_buf(), | |
| 741 | + | file_reader: Arc::clone(&new_reader), | |
| 742 | + | }; | |
| 743 | + | let old_renderer = TemplateRenderer::with_extensions( | |
| 744 | + | &old_template.config.settings.envops, | |
| 745 | + | Some(old_reader), | |
| 746 | + | Some(&old_exts), | |
| 747 | + | Some(&old_init), | |
| 748 | + | )?; | |
| 749 | + | let new_renderer = TemplateRenderer::with_extensions( | |
| 750 | + | &new_template.config.settings.envops, | |
| 751 | + | Some(new_reader), | |
| 752 | + | Some(&new_exts), | |
| 753 | + | Some(&new_init), | |
| 754 | + | )?; | |
| 755 | + | ||
| 756 | + | if enforce_trust && let Some(msg) = &new_template.config.settings.message_before_update { | |
| 757 | + | let banner = | |
| 758 | + | new_renderer.render_str(msg, &previous.combined(), "_message_before_update")?; | |
| 759 | + | if !banner.trim().is_empty() { | |
| 760 | + | reporter.emit(ActionEvent::Message(banner)); | |
| 761 | + | } | |
| 762 | + | } | |
| 763 | + | ||
| 764 | + | let prompt_init_ctx = build_prompt_initial_context( | |
| 765 | + | &new_template, | |
| 766 | + | dst_path, | |
| 767 | + | &new_renderer, | |
| 768 | + | options, | |
| 769 | + | "update", | |
| 770 | + | is_trusted, | |
| 771 | + | )?; | |
| 772 | + | let mut new_answers = collect_answers( | |
| 773 | + | &new_template.config, | |
| 774 | + | &new_renderer, | |
| 775 | + | prompter, | |
| 776 | + | &AnswerCollectionOptions { | |
| 777 | + | data: &options.data, | |
| 778 | + | previous_answers: Some(&previous), | |
| 779 | + | user_defaults: Some(&user_settings.defaults), | |
| 780 | + | initial_context: Some(&prompt_init_ctx), | |
| 781 | + | extensions: Some(&new_exts), | |
| 782 | + | use_defaults: options.defaults, | |
| 783 | + | skip_answered: options.skip_answered, | |
| 784 | + | ask_questions: &options.ask_questions, | |
| 785 | + | }, | |
| 786 | + | )?; | |
| 787 | + | new_answers.set_src_path(&src); | |
| 788 | + | if let Some(commit) = &new_template.commit { | |
| 789 | + | new_answers.set_commit(commit); | |
| 790 | + | } | |
| 791 | + | ||
| 792 | + | // One TempDir with sibling `a/` (old snapshot) and `b/` (new snapshot) rendered in parallel. | |
| 793 | + | let diff_root = TempDir::with_prefix("roneo-diff")?; | |
| 794 | + | let old_dir = diff_root.path().join("a"); | |
| 795 | + | let new_dir = diff_root.path().join("b"); | |
| 796 | + | fs::create_dir(&old_dir).map_err(|e| RoneoError::io(&old_dir, e))?; | |
| 797 | + | fs::create_dir(&new_dir).map_err(|e| RoneoError::io(&new_dir, e))?; | |
| 798 | + | ||
| 799 | + | let mut new_temp_opts = options.clone(); | |
| 800 | + | new_temp_opts.overwrite = true; | |
| 801 | + | new_temp_opts.pretend = false; | |
| 802 | + | new_temp_opts.skip_tasks = true; | |
| 803 | + | ||
| 804 | + | // Copier discussion #2345: also apply the new template's `_exclude` patterns when rendering | |
| 805 | + | // the old snapshot so newly excluded files are not treated as deleted in the diff. | |
| 806 | + | let mut old_temp_opts = new_temp_opts.clone(); | |
| 807 | + | for pat in &new_template.config.settings.exclude { | |
| 808 | + | if !pat.contains("{{") && !pat.contains("{%") { | |
| 809 | + | for line in pat.lines() { | |
| 810 | + | let trimmed = line.trim(); | |
| 811 | + | if !trimmed.is_empty() { | |
| 812 | + | old_temp_opts.exclude.push(trimmed.to_string()); | |
| 813 | + | } | |
| 814 | + | } | |
| 815 | + | } | |
| 816 | + | } | |
| 817 | + | ||
| 818 | + | // Reconstruct full `old_answers` (including `when: false` defaults for strict-undefined | |
| 819 | + | // templates) AND render `old_template` IN PARALLEL with rendering `new_template`! | |
| 820 | + | let noop = NoopReporter; | |
| 821 | + | let (old_res, new_res) = rayon::join( | |
| 822 | + | || -> Result<()> { | |
| 823 | + | let old_prompt_init_ctx = build_prompt_initial_context( | |
| 824 | + | &old_template, | |
| 825 | + | dst_path, | |
| 826 | + | &old_renderer, | |
| 827 | + | options, | |
| 828 | + | "update", | |
| 829 | + | is_trusted, | |
| 830 | + | )?; | |
| 831 | + | let mut old_answers = collect_answers( | |
| 832 | + | &old_template.config, | |
| 833 | + | &old_renderer, | |
| 834 | + | &NonInteractivePrompter, | |
| 835 | + | &AnswerCollectionOptions { | |
| 836 | + | data: &previous.user, | |
| 837 | + | previous_answers: Some(&previous), | |
| 838 | + | user_defaults: Some(&user_settings.defaults), | |
| 839 | + | initial_context: Some(&old_prompt_init_ctx), | |
| 840 | + | extensions: Some(&old_exts), | |
| 841 | + | use_defaults: true, | |
| 842 | + | skip_answered: true, | |
| 843 | + | ask_questions: &[], | |
| 844 | + | }, | |
| 845 | + | )?; | |
| 846 | + | old_answers.metadata.clone_from(&previous.metadata); | |
| 847 | + | ||
| 848 | + | render_into_destination( | |
| 849 | + | &old_template, | |
| 850 | + | &old_dir, | |
| 851 | + | &old_answers, | |
| 852 | + | &old_renderer, | |
| 853 | + | &old_exts, | |
| 854 | + | &old_temp_opts, | |
| 855 | + | "update", | |
| 856 | + | is_trusted, | |
| 857 | + | None, | |
| 858 | + | &noop, | |
| 859 | + | )?; | |
| 860 | + | Ok(()) | |
| 861 | + | }, | |
| 862 | + | || { | |
| 863 | + | render_into_destination( | |
| 864 | + | &new_template, | |
| 865 | + | &new_dir, | |
| 866 | + | &new_answers, | |
| 867 | + | &new_renderer, | |
| 868 | + | &new_exts, | |
| 869 | + | &new_temp_opts, | |
| 870 | + | "update", | |
| 871 | + | is_trusted, | |
| 872 | + | None, | |
| 873 | + | &noop, | |
| 874 | + | ) | |
| 875 | + | }, | |
| 876 | + | ); | |
| 877 | + | old_res?; | |
| 878 | + | let (new_render_report, new_ctx) = new_res?; | |
| 879 | + | ||
| 880 | + | let new_answers_rel = new_render_report | |
| 881 | + | .answers_file | |
| 882 | + | .strip_prefix(&new_dir) | |
| 883 | + | .map_or_else( | |
| 884 | + | |_| { | |
| 885 | + | PathBuf::from( | |
| 886 | + | new_render_report | |
| 887 | + | .answers_file | |
| 888 | + | .file_name() | |
| 889 | + | .unwrap_or_default(), | |
| 890 | + | ) | |
| 891 | + | }, | |
| 892 | + | Path::to_path_buf, | |
| 893 | + | ); | |
| 894 | + | let new_answers_bytes = fs::read(&new_render_report.answers_file).ok(); | |
| 895 | + | ||
| 896 | + | let mut all_skip = Vec::with_capacity( | |
| 897 | + | new_template.config.settings.skip_if_exists.len() + options.skip_if_exists.len(), | |
| 898 | + | ); | |
| 899 | + | for pat in &new_template.config.settings.skip_if_exists { | |
| 900 | + | let expanded = new_renderer.render_str(pat, &new_ctx, "_skip_if_exists")?; | |
| 901 | + | for line in expanded.lines() { | |
| 902 | + | let trimmed = line.trim(); | |
| 903 | + | if !trimmed.is_empty() { | |
| 904 | + | all_skip.push(trimmed.to_string()); | |
| 905 | + | } | |
| 906 | + | } | |
| 907 | + | } | |
| 908 | + | all_skip.extend(options.skip_if_exists.iter().cloned()); | |
| 909 | + | let new_skip_filter = PathFilter::new(Path::new(""), &[], &all_skip, false)?; | |
| 910 | + | ||
| 911 | + | let patch = vcs::diff_directories(diff_root.path(), "a", "b", options.context_lines)?; | |
| 912 | + | ||
| 913 | + | Ok(PreparedUpdate { | |
| 914 | + | src, | |
| 915 | + | old_commit, | |
| 916 | + | old_answers_path: answers_path, | |
| 917 | + | new_template, | |
| 918 | + | new_renderer, | |
| 919 | + | new_answers_rel, | |
| 920 | + | new_answers_bytes, | |
| 921 | + | new_ctx, | |
| 922 | + | new_skip_filter, | |
| 923 | + | diff_root, | |
| 924 | + | patch, | |
| 925 | + | }) | |
| 926 | + | } | |
| 927 | + | ||
| 928 | + | fn resolve_user_settings(options: &CopyOptions) -> UserSettings { | |
| 929 | + | options | |
| 930 | + | .user_settings | |
| 931 | + | .clone() | |
| 932 | + | .unwrap_or_else(UserSettings::load_default) | |
| 933 | + | } | |
| 934 | + | ||
| 935 | + | fn check_min_copier_version(config: &TemplateConfig, reporter: &dyn Reporter) -> Result<()> { | |
| 936 | + | let Some(required_raw) = config.settings.min_copier_version.as_deref() else { | |
| 937 | + | return Ok(()); | |
| 938 | + | }; | |
| 939 | + | let trimmed = required_raw.trim(); | |
| 940 | + | if trimmed.is_empty() { | |
| 941 | + | return Ok(()); | |
| 942 | + | } | |
| 943 | + | if let (Some(required), Some(supported)) = ( | |
| 944 | + | Pep440Version::parse(trimmed), | |
| 945 | + | Pep440Version::parse(COPIER_COMPAT_VERSION), | |
| 946 | + | ) { | |
| 947 | + | if required > supported { | |
| 948 | + | return Err(RoneoError::IncompatibleCopierVersion { | |
| 949 | + | required: trimmed.to_string(), | |
| 950 | + | supported: COPIER_COMPAT_VERSION.to_string(), | |
| 951 | + | }); | |
| 952 | + | } | |
| 953 | + | if required.release.first() < supported.release.first() { | |
| 954 | + | reporter.emit(ActionEvent::Warning(format!( | |
| 955 | + | "Template targets older Copier {trimmed} (Roneo targets Copier {COPIER_COMPAT_VERSION})." | |
| 956 | + | ))); | |
| 957 | + | } | |
| 958 | + | } | |
| 959 | + | Ok(()) | |
| 960 | + | } | |
| 961 | + | ||
| 962 | + | fn folder_name_for(dst_path: &Path) -> String { | |
| 963 | + | dst_path | |
| 964 | + | .file_name() | |
| 965 | + | .map(|s| s.to_string_lossy().into_owned()) | |
| 966 | + | .or_else(|| { | |
| 967 | + | fs::canonicalize(dst_path) | |
| 968 | + | .or_else(|_| std::env::current_dir()) | |
| 969 | + | .ok() | |
| 970 | + | .and_then(|p| p.file_name().map(|s| s.to_string_lossy().into_owned())) | |
| 971 | + | }) | |
| 972 | + | .unwrap_or_default() | |
| 973 | + | } | |
| 974 | + | ||
| 975 | + | fn build_active_extensions( | |
| 976 | + | resolved: &ResolvedTemplate, | |
| 977 | + | options: &CopyOptions, | |
| 978 | + | is_trusted: bool, | |
| 979 | + | ) -> Result<ExtensionRegistry> { | |
| 980 | + | let mut reg = options.extensions.clone(); | |
| 981 | + | if resolved.config.settings.roneo_plugins.is_empty() { | |
| 982 | + | return Ok(reg); | |
| 983 | + | } | |
| 984 | + | if !is_trusted { | |
| 985 | + | return Err(RoneoError::UnsafeTemplate( | |
| 986 | + | "Template declares `_roneo_plugins` (WebAssembly extensions)".into(), | |
| 987 | + | )); | |
| 988 | + | } | |
| 989 | + | for rel_plugin in &resolved.config.settings.roneo_plugins { | |
| 990 | + | if Path::new(rel_plugin).is_absolute() { | |
| 991 | + | return Err(RoneoError::Plugin(format!( | |
| 992 | + | "Template plugin '{rel_plugin}' must be a relative path inside the template" | |
| 993 | + | ))); | |
| 994 | + | } | |
| 995 | + | if let Some(bytes) = resolved.read_bytes(rel_plugin) { | |
| 996 | + | reg.add_wasm_bytes(&bytes)?; | |
| 997 | + | } else { | |
| 998 | + | return Err(RoneoError::Plugin(format!( | |
| 999 | + | "Template plugin '{rel_plugin}' not found inside template" | |
| 1000 | + | ))); | |
| 1001 | + | } | |
| 1002 | + | } | |
| 1003 | + | Ok(reg) | |
| 1004 | + | } | |
| 1005 | + | ||
| 1006 | + | fn build_prompt_initial_context( | |
| 1007 | + | resolved: &ResolvedTemplate, | |
| 1008 | + | dst_path: &Path, | |
| 1009 | + | renderer: &TemplateRenderer, | |
| 1010 | + | options: &CopyOptions, | |
| 1011 | + | operation: &str, | |
| 1012 | + | is_trusted: bool, | |
| 1013 | + | ) -> Result<IndexMap<String, JsonValue>> { | |
| 1014 | + | let mut init = IndexMap::new(); | |
| 1015 | + | let answers_file = options.answers_file.as_ref().map_or_else( | |
| 1016 | + | || resolved.config.settings.answers_file.clone(), | |
| 1017 | + | |p| p.to_string_lossy().into_owned(), | |
| 1018 | + | ); | |
| 1019 | + | let conf = CopierConf { | |
| 1020 | + | src_path: resolved.local_path.to_string_lossy().into_owned(), | |
| 1021 | + | dst_path: dst_path.to_string_lossy().into_owned(), | |
| 1022 | + | answers_file, | |
| 1023 | + | vcs_ref: resolved.commit.clone(), | |
| 1024 | + | vcs_ref_hash: resolved.commit_hash.clone(), | |
| 1025 | + | sep: std::path::MAIN_SEPARATOR.to_string(), | |
| 1026 | + | os: std::env::consts::OS.to_string(), | |
| 1027 | + | stage: "prompt".to_string(), | |
| 1028 | + | overwrite: options.overwrite, | |
| 1029 | + | pretend: options.pretend, | |
| 1030 | + | quiet: options.quiet, | |
| 1031 | + | r#unsafe: is_trusted, | |
| 1032 | + | cleanup_on_error: options.cleanup_on_error, | |
| 1033 | + | context_lines: options.context_lines, | |
| 1034 | + | exclude: options.exclude.clone(), | |
| 1035 | + | skip_if_exists: options.skip_if_exists.clone(), | |
| 1036 | + | }; | |
| 1037 | + | if let Ok(val) = serde_json::to_value(&conf) { | |
| 1038 | + | init.insert("_copier_conf".into(), val); | |
| 1039 | + | } | |
| 1040 | + | init.insert("_copier_python".into(), JsonValue::String("python3".into())); | |
| 1041 | + | init.insert( | |
| 1042 | + | "_copier_operation".into(), | |
| 1043 | + | JsonValue::String(operation.to_string()), | |
| 1044 | + | ); | |
| 1045 | + | init.insert( | |
| 1046 | + | "_folder_name".into(), | |
| 1047 | + | JsonValue::String(folder_name_for(dst_path)), | |
| 1048 | + | ); | |
| 1049 | + | ||
| 1050 | + | if !resolved.config.settings.external_data.is_empty() { | |
| 1051 | + | let mut seed = init.clone(); | |
| 1052 | + | for (k, v) in &options.data { | |
| 1053 | + | seed.insert(k.clone(), v.clone()); | |
| 1054 | + | } | |
| 1055 | + | let ext_data = load_external_data(resolved, dst_path, renderer, &seed, is_trusted)?; | |
| 1056 | + | init.insert("_external_data".into(), ext_data); | |
| 1057 | + | } | |
| 1058 | + | Ok(init) | |
| 1059 | + | } | |
| 1060 | + | ||
| 1061 | + | /// Load `_external_data` YAML/JSON files (matching Copier 9's `_external_data` setting). | |
| 1062 | + | /// Untrusted templates are confined to files inside the template root or destination directory. | |
| 1063 | + | fn load_external_data( | |
| 1064 | + | resolved: &ResolvedTemplate, | |
| 1065 | + | dst_path: &Path, | |
| 1066 | + | renderer: &TemplateRenderer, | |
| 1067 | + | ctx: &IndexMap<String, JsonValue>, | |
| 1068 | + | is_trusted: bool, | |
| 1069 | + | ) -> Result<JsonValue> { | |
| 1070 | + | let mut out = serde_json::Map::new(); | |
| 1071 | + | let reader = resolved.file_reader(); | |
| 1072 | + | for (key, path_tpl) in &resolved.config.settings.external_data { | |
| 1073 | + | let resolved_path = renderer.render_str(path_tpl, ctx, &format!("_external_data.{key}"))?; | |
| 1074 | + | let trimmed = resolved_path.trim(); | |
| 1075 | + | if trimmed.is_empty() { | |
| 1076 | + | continue; | |
| 1077 | + | } | |
| 1078 | + | let raw_opt = reader(trimmed).or_else(|| { | |
| 1079 | + | let p = Path::new(trimmed); | |
| 1080 | + | let escapes = trimmed.contains('\0') | |
| 1081 | + | || p.is_absolute() | |
| 1082 | + | || p.components().any(|c| { | |
| 1083 | + | matches!( | |
| 1084 | + | c, | |
| 1085 | + | std::path::Component::ParentDir | |
| 1086 | + | | std::path::Component::RootDir | |
| 1087 | + | | std::path::Component::Prefix(_) | |
| 1088 | + | ) | |
| 1089 | + | }); | |
| 1090 | + | if escapes && !is_trusted { | |
| 1091 | + | return None; | |
| 1092 | + | } | |
| 1093 | + | if p.is_absolute() { | |
| 1094 | + | fs::read_to_string(p).ok() | |
| 1095 | + | } else { | |
| 1096 | + | let in_dst = dst_path.join(p); | |
| 1097 | + | let dst_ok = if is_trusted { | |
| 1098 | + | true | |
| 1099 | + | } else { | |
| 1100 | + | fs::canonicalize(dst_path) | |
| 1101 | + | .ok() | |
| 1102 | + | .zip(fs::canonicalize(&in_dst).ok()) | |
| 1103 | + | .is_some_and(|(root, cand)| cand.starts_with(root)) | |
| 1104 | + | }; | |
| 1105 | + | if dst_ok { | |
| 1106 | + | fs::read_to_string(&in_dst).ok() | |
| 1107 | + | } else { | |
| 1108 | + | None | |
| 1109 | + | } | |
| 1110 | + | .or_else(|| is_trusted.then(|| fs::read_to_string(p).ok()).flatten()) | |
| 1111 | + | } | |
| 1112 | + | }); | |
| 1113 | + | let Some(raw) = raw_opt else { | |
| 1114 | + | return Err(RoneoError::InvalidConfig(format!( | |
| 1115 | + | "Failed to load `_external_data.{key}` from '{trimmed}'" | |
| 1116 | + | ))); | |
| 1117 | + | }; | |
| 1118 | + | let yaml_val: serde_yaml_ng::Value = serde_yaml_ng::from_str(&raw)?; | |
| 1119 | + | let json_val = serde_json::to_value(yaml_val)?; | |
| 1120 | + | out.insert(key.clone(), json_val); | |
| 1121 | + | } | |
| 1122 | + | Ok(JsonValue::Object(out)) | |
| 1123 | + | } | |
| 1124 | + | ||
| 1125 | + | fn check_trust( | |
| 1126 | + | resolved: &ResolvedTemplate, | |
| 1127 | + | options: &CopyOptions, | |
| 1128 | + | user_settings: &UserSettings, | |
| 1129 | + | active_exts: &ExtensionRegistry, | |
| 1130 | + | reporter: &dyn Reporter, | |
| 1131 | + | ) -> Result<bool> { | |
| 1132 | + | let config = &resolved.config; | |
| 1133 | + | if !config.settings.jinja_extensions.is_empty() && active_exts.is_empty() { | |
| 1134 | + | reporter.emit(ActionEvent::Warning(format!( | |
| 1135 | + | "Template requests Python Jinja extensions ({}) which are not executed in native Rust mode (load a WASM plugin via `--plugin`).", | |
| 1136 | + | config.settings.jinja_extensions.join(", ") | |
| 1137 | + | ))); | |
| 1138 | + | } | |
| 1139 | + | let is_trusted = | |
| 1140 | + | options.trust || user_settings.is_trusted(&resolved.original_src, &resolved.resolved_src); | |
| 1141 | + | if !options.skip_tasks && config.requires_trust() && !is_trusted { | |
| 1142 | + | return Err(RoneoError::UnsafeTemplate( | |
| 1143 | + | "Template defines `_tasks` or `_migrations` that execute shell commands".into(), | |
| 1144 | + | )); | |
| 1145 | + | } | |
| 1146 | + | Ok(is_trusted) | |
| 1147 | + | } | |
| 1148 | + | ||
| 1149 | + | /// Source descriptor for a single file scheduled for parallel rendering & writing. | |
| 1150 | + | enum RenderItemSource { | |
| 1151 | + | Disk { | |
| 1152 | + | src_path: PathBuf, | |
| 1153 | + | is_symlink: bool, | |
| 1154 | + | file_mode: Option<u32>, | |
| 1155 | + | }, | |
| 1156 | + | GitBlob { | |
| 1157 | + | tree: Arc<InMemoryGitTree>, | |
| 1158 | + | oid: gix::ObjectId, | |
| 1159 | + | is_executable: bool, | |
| 1160 | + | is_symlink: bool, | |
| 1161 | + | }, | |
| 1162 | + | } | |
| 1163 | + | ||
| 1164 | + | struct PlannedFile { | |
| 1165 | + | rel_src: PathBuf, | |
| 1166 | + | rendered_rel: PathBuf, | |
| 1167 | + | is_template_file: bool, | |
| 1168 | + | extra_vars: Vec<(String, JsonValue)>, | |
| 1169 | + | source: RenderItemSource, | |
| 1170 | + | } | |
| 1171 | + | ||
| 1172 | + | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 1173 | + | enum OverwritePolicy { | |
| 1174 | + | Force, | |
| 1175 | + | Prompt, | |
| 1176 | + | Skip, | |
| 1177 | + | } | |
| 1178 | + | ||
| 1179 | + | #[derive(Debug)] | |
| 1180 | + | enum PendingContent { | |
| 1181 | + | File { | |
| 1182 | + | bytes: Vec<u8>, | |
| 1183 | + | src_for_perms: Option<PathBuf>, | |
| 1184 | + | is_executable: bool, | |
| 1185 | + | }, | |
| 1186 | + | Symlink { | |
| 1187 | + | target: String, | |
| 1188 | + | }, | |
| 1189 | + | } | |
| 1190 | + | ||
| 1191 | + | #[derive(Debug)] | |
| 1192 | + | struct PendingOverwrite { | |
| 1193 | + | rel: PathBuf, | |
| 1194 | + | dst_entry_path: PathBuf, | |
| 1195 | + | content: PendingContent, | |
| 1196 | + | } | |
| 1197 | + | ||
| 1198 | + | #[derive(Debug)] | |
| 1199 | + | enum FileOutcome { | |
| 1200 | + | Created(PathBuf), | |
| 1201 | + | Overwritten(PathBuf), | |
| 1202 | + | Identical(PathBuf), | |
| 1203 | + | Skipped(PathBuf), | |
| 1204 | + | NeedsOverwriteConfirm(PendingOverwrite), | |
| 1205 | + | } | |
| 1206 | + | ||
| 1207 | + | #[allow(clippy::too_many_arguments)] | |
| 1208 | + | fn render_into_destination( | |
| 1209 | + | resolved: &ResolvedTemplate, | |
| 1210 | + | dst_path: &Path, | |
| 1211 | + | answers: &AnswersMap, | |
| 1212 | + | renderer: &TemplateRenderer, | |
| 1213 | + | extensions: &ExtensionRegistry, | |
| 1214 | + | options: &CopyOptions, | |
| 1215 | + | stage: &str, | |
| 1216 | + | is_trusted: bool, | |
| 1217 | + | prompter: Option<&dyn Prompter>, | |
| 1218 | + | reporter: &dyn Reporter, | |
| 1219 | + | ) -> Result<(OperationReport, IndexMap<String, JsonValue>)> { | |
| 1220 | + | let settings = &resolved.config.settings; | |
| 1221 | + | let combined = answers.combined(); | |
| 1222 | + | let persistable = answers.persistable(); | |
| 1223 | + | ||
| 1224 | + | let answers_rel_str = match &options.answers_file { | |
| 1225 | + | Some(p) => p.to_string_lossy().into_owned(), | |
| 1226 | + | None => renderer.render_str(&settings.answers_file, &combined, "_answers_file")?, | |
| 1227 | + | }; | |
| 1228 | + | let answers_rel = PathBuf::from(&answers_rel_str); | |
| 1229 | + | if options.answers_file.is_none() | |
| 1230 | + | && (answers_rel_str.contains('\0') | |
| 1231 | + | || answers_rel.is_absolute() | |
| 1232 | + | || answers_rel.components().any(|c| { | |
| 1233 | + | matches!( | |
| 1234 | + | c, | |
| 1235 | + | std::path::Component::ParentDir | |
| 1236 | + | | std::path::Component::RootDir | |
| 1237 | + | | std::path::Component::Prefix(_) | |
| 1238 | + | ) | |
| 1239 | + | })) | |
| 1240 | + | { | |
| 1241 | + | return Err(RoneoError::InvalidConfig(format!( | |
| 1242 | + | "`_answers_file` '{answers_rel_str}' escapes destination directory" | |
| 1243 | + | ))); | |
| 1244 | + | } | |
| 1245 | + | ||
| 1246 | + | let rendered_subdir = match &settings.subdirectory { | |
| 1247 | + | Some(sub_tpl) => Some(renderer.render_str(sub_tpl, &combined, "_subdirectory")?), | |
| 1248 | + | None => None, | |
| 1249 | + | }; | |
| 1250 | + | ||
| 1251 | + | let conf = CopierConf { | |
| 1252 | + | src_path: resolved.local_path.to_string_lossy().into_owned(), | |
| 1253 | + | dst_path: dst_path.to_string_lossy().into_owned(), | |
| 1254 | + | answers_file: answers_rel_str, | |
| 1255 | + | vcs_ref: resolved.commit.clone(), | |
| 1256 | + | vcs_ref_hash: resolved.commit_hash.clone(), | |
| 1257 | + | sep: std::path::MAIN_SEPARATOR.to_string(), | |
| 1258 | + | os: std::env::consts::OS.to_string(), | |
| 1259 | + | stage: stage.to_string(), | |
| 1260 | + | overwrite: options.overwrite, | |
| 1261 | + | pretend: options.pretend, | |
| 1262 | + | quiet: options.quiet, | |
| 1263 | + | r#unsafe: is_trusted, | |
| 1264 | + | cleanup_on_error: options.cleanup_on_error, | |
| 1265 | + | context_lines: options.context_lines, | |
| 1266 | + | exclude: options.exclude.clone(), | |
| 1267 | + | skip_if_exists: options.skip_if_exists.clone(), | |
| 1268 | + | }; | |
| 1269 | + | ||
| 1270 | + | let mut ctx = build_render_context(&combined, &persistable, &conf); | |
| 1271 | + | ctx.insert("_copier_phase".into(), JsonValue::String("render".into())); | |
| 1272 | + | ctx.insert("_copier_python".into(), JsonValue::String("python3".into())); | |
| 1273 | + | ctx.insert( | |
| 1274 | + | "_copier_operation".into(), | |
| 1275 | + | JsonValue::String(stage.to_string()), | |
| 1276 | + | ); | |
| 1277 | + | ctx.insert( | |
| 1278 | + | "_folder_name".into(), | |
| 1279 | + | JsonValue::String(folder_name_for(dst_path)), | |
| 1280 | + | ); | |
| 1281 | + | if !settings.external_data.is_empty() { | |
| 1282 | + | let ext_data = load_external_data(resolved, dst_path, renderer, &ctx, is_trusted)?; | |
| 1283 | + | ctx.insert("_external_data".into(), ext_data); | |
| 1284 | + | } | |
| 1285 | + | if !extensions.is_empty() { | |
| 1286 | + | extensions.run_context_hooks("render", &mut ctx)?; | |
| 1287 | + | } | |
| 1288 | + | ||
| 1289 | + | let mj_ctx = TemplateRenderer::compile_context(&ctx); | |
| 1290 | + | ||
| 1291 | + | let mut all_excludes = Vec::with_capacity(settings.exclude.len() + options.exclude.len()); | |
| 1292 | + | for pat in &settings.exclude { | |
| 1293 | + | let expanded = renderer.render_str_value(pat, &mj_ctx, "_exclude")?; | |
| 1294 | + | // Copier v9.18.0 (#2804): allow multiple newline-separated patterns in a single `_exclude` entry. | |
| 1295 | + | for line in expanded.lines() { | |
| 1296 | + | let trimmed = line.trim(); | |
| 1297 | + | if !trimmed.is_empty() { | |
| 1298 | + | all_excludes.push(trimmed.to_string()); | |
| 1299 | + | } | |
| 1300 | + | } | |
| 1301 | + | } | |
| 1302 | + | all_excludes.extend(options.exclude.iter().cloned()); | |
| 1303 | + | ||
| 1304 | + | let mut all_skip = | |
| 1305 | + | Vec::with_capacity(settings.skip_if_exists.len() + options.skip_if_exists.len()); | |
| 1306 | + | for pat in &settings.skip_if_exists { | |
| 1307 | + | let expanded = renderer.render_str_value(pat, &mj_ctx, "_skip_if_exists")?; | |
| 1308 | + | for line in expanded.lines() { | |
| 1309 | + | let trimmed = line.trim(); | |
| 1310 | + | if !trimmed.is_empty() { | |
| 1311 | + | all_skip.push(trimmed.to_string()); | |
| 1312 | + | } | |
| 1313 | + | } | |
| 1314 | + | } | |
| 1315 | + | all_skip.extend(options.skip_if_exists.iter().cloned()); | |
| 1316 | + | ||
| 1317 | + | let filter_root = Path::new(""); | |
| 1318 | + | let filter = PathFilter::new( | |
| 1319 | + | filter_root, | |
| 1320 | + | &all_excludes, | |
| 1321 | + | &all_skip, | |
| 1322 | + | options.use_default_excludes, | |
| 1323 | + | )?; | |
| 1324 | + | ||
| 1325 | + | if !options.pretend { | |
| 1326 | + | fs::create_dir_all(dst_path).map_err(|e| RoneoError::io(dst_path, e))?; | |
| 1327 | + | } | |
| 1328 | + | ||
| 1329 | + | // Phase 1: Walk source tree (either in-memory `gix` tree or disk) and plan ONLY non-excluded files. | |
| 1330 | + | // On GitTree, excluded directories (e.g. `tests/`, `docs/`, disabled `values/*`) are pruned BEFORE | |
| 1331 | + | // reading any subtrees or decompressing any blobs! | |
| 1332 | + | let mut planned_files: Vec<PlannedFile> = Vec::new(); | |
| 1333 | + | let mut planned_dirs: HashSet<PathBuf> = HashSet::new(); | |
| 1334 | + | ||
| 1335 | + | match &resolved.backing { | |
| 1336 | + | TemplateBacking::GitTree(tree) => { | |
| 1337 | + | let tree_files = tree.walk_files( | |
| 1338 | + | rendered_subdir.as_deref(), | |
| 1339 | + | |rel_dir, rendered_parent, dir_name, extra_vars| { | |
| 1340 | + | if filter.is_excluded(rel_dir, true) { | |
| 1341 | + | return Ok(Vec::new()); | |
| 1342 | + | } | |
| 1343 | + | let expanded = renderer.render_segment_expanded_value( | |
| 1344 | + | dir_name, | |
| 1345 | + | true, | |
| 1346 | + | &settings.templates_suffix, | |
| 1347 | + | &ctx, | |
| 1348 | + | extra_vars, | |
| 1349 | + | &mj_ctx, | |
| 1350 | + | &format!("path:{}", rel_dir.display()), | |
| 1351 | + | )?; | |
| 1352 | + | let mut branches = Vec::with_capacity(expanded.len()); | |
| 1353 | + | for seg in expanded { | |
| 1354 | + | let rendered_dir = if rendered_parent.as_os_str().is_empty() { | |
| 1355 | + | PathBuf::from(seg.name) | |
| 1356 | + | } else { | |
| 1357 | + | rendered_parent.join(seg.name) | |
| 1358 | + | }; | |
| 1359 | + | if filter.is_excluded(&rendered_dir, true) { | |
| 1360 | + | continue; | |
| 1361 | + | } | |
| 1362 | + | let mut next_vars = extra_vars.to_vec(); | |
| 1363 | + | if let Some(binding) = seg.yield_binding { | |
| 1364 | + | next_vars.push(binding); | |
| 1365 | + | } | |
| 1366 | + | branches.push((rendered_dir, next_vars)); | |
| 1367 | + | } | |
| 1368 | + | Ok(branches) | |
| 1369 | + | }, | |
| 1370 | + | )?; | |
| 1371 | + | ||
| 1372 | + | for entry in tree_files { | |
| 1373 | + | if filter.is_excluded(&entry.rel_path, false) { | |
| 1374 | + | continue; | |
| 1375 | + | } | |
| 1376 | + | let expanded = renderer.render_segment_expanded_value( | |
| 1377 | + | &entry.file_name, | |
| 1378 | + | false, | |
| 1379 | + | &settings.templates_suffix, | |
| 1380 | + | &ctx, | |
| 1381 | + | &entry.extra_vars, | |
| 1382 | + | &mj_ctx, | |
| 1383 | + | &format!("path:{}", entry.rel_path.display()), | |
| 1384 | + | )?; | |
| 1385 | + | for seg in expanded { | |
| 1386 | + | let rendered_rel = if entry.rendered_parent.as_os_str().is_empty() { | |
| 1387 | + | PathBuf::from(seg.name) | |
| 1388 | + | } else { | |
| 1389 | + | entry.rendered_parent.join(seg.name) | |
| 1390 | + | }; | |
| 1391 | + | if filter.is_excluded(&rendered_rel, false) { | |
| 1392 | + | continue; | |
| 1393 | + | } | |
| 1394 | + | if let Some(parent) = rendered_rel.parent() | |
| 1395 | + | && !parent.as_os_str().is_empty() | |
| 1396 | + | { | |
| 1397 | + | planned_dirs.insert(parent.to_path_buf()); | |
| 1398 | + | } | |
| 1399 | + | let mut file_vars = entry.extra_vars.clone(); | |
| 1400 | + | if let Some(binding) = seg.yield_binding { | |
| 1401 | + | file_vars.push(binding); | |
| 1402 | + | } | |
| 1403 | + | planned_files.push(PlannedFile { | |
| 1404 | + | rel_src: entry.rel_path.clone(), | |
| 1405 | + | rendered_rel, | |
| 1406 | + | is_template_file: seg.is_template_file, | |
| 1407 | + | extra_vars: file_vars, | |
| 1408 | + | source: RenderItemSource::GitBlob { | |
| 1409 | + | tree: Arc::clone(tree), | |
| 1410 | + | oid: entry.oid, | |
| 1411 | + | is_executable: entry.is_executable, | |
| 1412 | + | is_symlink: entry.is_symlink, | |
| 1413 | + | }, | |
| 1414 | + | }); | |
| 1415 | + | } | |
| 1416 | + | } | |
| 1417 | + | } | |
| 1418 | + | TemplateBacking::Disk(_) => { | |
| 1419 | + | let content_root = resolved.disk_content_root(rendered_subdir.as_deref())?; | |
| 1420 | + | let plan_ctx = PlanCtx { | |
| 1421 | + | root: &content_root, | |
| 1422 | + | follow_symlinks: !settings.preserve_symlinks, | |
| 1423 | + | templates_suffix: &settings.templates_suffix, | |
| 1424 | + | renderer, | |
| 1425 | + | base_ctx: &ctx, | |
| 1426 | + | mj_ctx: &mj_ctx, | |
| 1427 | + | filter: &filter, | |
| 1428 | + | }; | |
| 1429 | + | plan_disk_dir( | |
| 1430 | + | &plan_ctx, | |
| 1431 | + | &content_root, | |
| 1432 | + | Path::new(""), | |
| 1433 | + | &[], | |
| 1434 | + | &mut planned_dirs, | |
| 1435 | + | &mut planned_files, | |
| 1436 | + | )?; | |
| 1437 | + | } | |
| 1438 | + | } | |
| 1439 | + | ||
| 1440 | + | // Create all unique target directories upfront once (avoids redundant create_dir_all races in parallel). | |
| 1441 | + | if !options.pretend { | |
| 1442 | + | for dir in &planned_dirs { | |
| 1443 | + | let full_dir = dst_path.join(dir); | |
| 1444 | + | if !full_dir.exists() { | |
| 1445 | + | fs::create_dir_all(&full_dir).map_err(|e| RoneoError::io(&full_dir, e))?; | |
| 1446 | + | } | |
| 1447 | + | } | |
| 1448 | + | } | |
| 1449 | + | ||
| 1450 | + | let answers_file_written = planned_files.iter().any(|f| f.rendered_rel == answers_rel); | |
| 1451 | + | ||
| 1452 | + | let overwrite_policy = if options.overwrite { | |
| 1453 | + | OverwritePolicy::Force | |
| 1454 | + | } else if prompter.is_some() && !options.defaults && !options.pretend { | |
| 1455 | + | OverwritePolicy::Prompt | |
| 1456 | + | } else { | |
| 1457 | + | OverwritePolicy::Skip | |
| 1458 | + | }; | |
| 1459 | + | ||
| 1460 | + | // Phase 2: Render & write files in parallel using `rayon`, reusing ONE thread-local | |
| 1461 | + | // `gix::Repository` per worker thread (hot pack delta cache across all blobs!). | |
| 1462 | + | let git_tree_opt = match &resolved.backing { | |
| 1463 | + | TemplateBacking::GitTree(tree) => Some(Arc::clone(tree)), | |
| 1464 | + | TemplateBacking::Disk(_) => None, | |
| 1465 | + | }; | |
| 1466 | + | let file_ctx = FileRenderCtx { | |
| 1467 | + | dst_path, | |
| 1468 | + | renderer, | |
| 1469 | + | base_ctx: &ctx, | |
| 1470 | + | shared_mj_ctx: &mj_ctx, | |
| 1471 | + | filter: &filter, | |
| 1472 | + | preserve_symlinks: settings.preserve_symlinks, | |
| 1473 | + | overwrite_policy, | |
| 1474 | + | pretend: options.pretend, | |
| 1475 | + | }; | |
| 1476 | + | let outcomes: Vec<FileOutcome> = planned_files | |
| 1477 | + | .par_iter() | |
| 1478 | + | .map_init( | |
| 1479 | + | || git_tree_opt.as_ref().map(|t| t.thread_local_repo()), | |
| 1480 | + | |thread_repo, item| process_planned_file(&file_ctx, item, thread_repo.as_ref()), | |
| 1481 | + | ) | |
| 1482 | + | .collect::<Result<Vec<_>>>()?; | |
| 1483 | + | ||
| 1484 | + | let mut created = 0usize; | |
| 1485 | + | let mut updated = 0usize; | |
| 1486 | + | let mut skipped = 0usize; | |
| 1487 | + | let mut overwrite_all = false; | |
| 1488 | + | ||
| 1489 | + | for outcome in outcomes { | |
| 1490 | + | match outcome { | |
| 1491 | + | FileOutcome::Created(rel) => { | |
| 1492 | + | created += 1; | |
| 1493 | + | reporter.emit(ActionEvent::Create(rel)); | |
| 1494 | + | } | |
| 1495 | + | FileOutcome::Overwritten(rel) => { | |
| 1496 | + | updated += 1; | |
| 1497 | + | reporter.emit(ActionEvent::Overwrite(rel)); | |
| 1498 | + | } | |
| 1499 | + | FileOutcome::Identical(rel) => { | |
| 1500 | + | reporter.emit(ActionEvent::Identical(rel)); | |
| 1501 | + | } | |
| 1502 | + | FileOutcome::Skipped(rel) => { | |
| 1503 | + | skipped += 1; | |
| 1504 | + | reporter.emit(ActionEvent::Skip(rel)); | |
| 1505 | + | } | |
| 1506 | + | FileOutcome::NeedsOverwriteConfirm(pending) => { | |
| 1507 | + | let should_write = if overwrite_all { | |
| 1508 | + | true | |
| 1509 | + | } else if let Some(p) = prompter { | |
| 1510 | + | match p.confirm_overwrite(&pending.rel)? { | |
| 1511 | + | OverwriteChoice::Yes => true, | |
| 1512 | + | OverwriteChoice::All => { | |
| 1513 | + | overwrite_all = true; | |
| 1514 | + | true | |
| 1515 | + | } | |
| 1516 | + | OverwriteChoice::No => false, | |
| 1517 | + | OverwriteChoice::Quit => return Err(RoneoError::UserAborted), | |
| 1518 | + | } | |
| 1519 | + | } else { | |
| 1520 | + | false | |
| 1521 | + | }; | |
| 1522 | + | if should_write { | |
| 1523 | + | apply_pending_overwrite(&pending)?; | |
| 1524 | + | updated += 1; | |
| 1525 | + | reporter.emit(ActionEvent::Overwrite(pending.rel)); | |
| 1526 | + | } else { | |
| 1527 | + | skipped += 1; | |
| 1528 | + | reporter.emit(ActionEvent::Skip(pending.rel)); | |
| 1529 | + | } | |
| 1530 | + | } | |
| 1531 | + | } | |
| 1532 | + | } | |
| 1533 | + | ||
| 1534 | + | let answers_dst = dst_path.join(&answers_rel); | |
| 1535 | + | if !answers_file_written { | |
| 1536 | + | let existed = answers_dst.exists(); | |
| 1537 | + | if !options.pretend { | |
| 1538 | + | answers.save(&answers_dst)?; | |
| 1539 | + | } | |
| 1540 | + | if existed { | |
| 1541 | + | updated += 1; | |
| 1542 | + | reporter.emit(ActionEvent::Overwrite(answers_rel)); | |
| 1543 | + | } else { | |
| 1544 | + | created += 1; | |
| 1545 | + | reporter.emit(ActionEvent::Create(answers_rel)); | |
| 1546 | + | } | |
| 1547 | + | } | |
| 1548 | + | ||
| 1549 | + | Ok(( | |
| 1550 | + | OperationReport { | |
| 1551 | + | src_path: resolved.original_src.clone(), | |
| 1552 | + | dst_path: dst_path.to_path_buf(), | |
| 1553 | + | commit: resolved.commit.clone(), | |
| 1554 | + | answers_file: answers_dst, | |
| 1555 | + | created, | |
| 1556 | + | updated, | |
| 1557 | + | skipped, | |
| 1558 | + | conflicts: Vec::new(), | |
| 1559 | + | }, | |
| 1560 | + | ctx, | |
| 1561 | + | )) | |
| 1562 | + | } | |
| 1563 | + | ||
| 1564 | + | fn apply_pending_overwrite(pending: &PendingOverwrite) -> Result<()> { | |
| 1565 | + | if let Some(parent) = pending.dst_entry_path.parent() | |
| 1566 | + | && !parent.exists() | |
| 1567 | + | { | |
| 1568 | + | fs::create_dir_all(parent).map_err(|e| RoneoError::io(parent, e))?; | |
| 1569 | + | } | |
| 1570 | + | match &pending.content { | |
| 1571 | + | PendingContent::Symlink { target } => { | |
| 1572 | + | let _ = fs::remove_file(&pending.dst_entry_path); | |
| 1573 | + | create_symlink(Path::new(target), &pending.dst_entry_path) | |
| 1574 | + | } | |
| 1575 | + | PendingContent::File { | |
| 1576 | + | bytes, | |
| 1577 | + | src_for_perms, | |
| 1578 | + | is_executable, | |
| 1579 | + | } => { | |
| 1580 | + | // Copier v9.18.2: unlink an existing destination symlink before writing a regular file. | |
| 1581 | + | if pending | |
| 1582 | + | .dst_entry_path | |
| 1583 | + | .symlink_metadata() | |
| 1584 | + | .is_ok_and(|m| m.file_type().is_symlink()) | |
| 1585 | + | { | |
| 1586 | + | let _ = fs::remove_file(&pending.dst_entry_path); | |
| 1587 | + | } | |
| 1588 | + | fs::write(&pending.dst_entry_path, bytes) | |
| 1589 | + | .map_err(|e| RoneoError::io(&pending.dst_entry_path, e))?; | |
| 1590 | + | if let Some(src) = src_for_perms { | |
| 1591 | + | copy_permissions(src, &pending.dst_entry_path)?; | |
| 1592 | + | } else if *is_executable { | |
| 1593 | + | set_executable(&pending.dst_entry_path)?; | |
| 1594 | + | } | |
| 1595 | + | Ok(()) | |
| 1596 | + | } | |
| 1597 | + | } | |
| 1598 | + | } | |
| 1599 | + | ||
| 1600 | + | struct PlanCtx<'a> { | |
| 1601 | + | root: &'a Path, | |
| 1602 | + | follow_symlinks: bool, | |
| 1603 | + | templates_suffix: &'a str, | |
| 1604 | + | renderer: &'a TemplateRenderer, | |
| 1605 | + | base_ctx: &'a IndexMap<String, JsonValue>, | |
| 1606 | + | mj_ctx: &'a minijinja::Value, | |
| 1607 | + | filter: &'a PathFilter, | |
| 1608 | + | } | |
| 1609 | + | ||
| 1610 | + | fn plan_disk_dir( | |
| 1611 | + | pctx: &PlanCtx<'_>, | |
| 1612 | + | current: &Path, | |
| 1613 | + | rendered_parent: &Path, | |
| 1614 | + | extra_vars: &[(String, JsonValue)], | |
| 1615 | + | planned_dirs: &mut HashSet<PathBuf>, | |
| 1616 | + | planned_files: &mut Vec<PlannedFile>, | |
| 1617 | + | ) -> Result<()> { | |
| 1618 | + | let mut entries: Vec<_> = fs::read_dir(current) | |
| 1619 | + | .map_err(|e| RoneoError::io(current, e))? | |
| 1620 | + | .collect::<std::result::Result<Vec<_>, _>>() | |
| 1621 | + | .map_err(|e| RoneoError::io(current, e))?; | |
| 1622 | + | entries.sort_by_key(fs::DirEntry::file_name); | |
| 1623 | + | ||
| 1624 | + | for entry in entries { | |
| 1625 | + | let abs_path = entry.path(); | |
| 1626 | + | let rel_path = abs_path | |
| 1627 | + | .strip_prefix(pctx.root) | |
| 1628 | + | .map_or_else(|_| PathBuf::from(entry.file_name()), Path::to_path_buf); | |
| 1629 | + | ||
| 1630 | + | let sym_meta = fs::symlink_metadata(&abs_path).map_err(|e| RoneoError::io(&abs_path, e))?; | |
| 1631 | + | let is_symlink = sym_meta.file_type().is_symlink(); | |
| 1632 | + | let is_dir = if is_symlink && pctx.follow_symlinks { | |
| 1633 | + | fs::metadata(&abs_path).is_ok_and(|m| m.is_dir()) | |
| 1634 | + | } else { | |
| 1635 | + | sym_meta.is_dir() | |
| 1636 | + | }; | |
| 1637 | + | ||
| 1638 | + | if pctx.filter.is_excluded(&rel_path, is_dir) { | |
| 1639 | + | continue; | |
| 1640 | + | } | |
| 1641 | + | ||
| 1642 | + | let name = entry.file_name().to_string_lossy().into_owned(); | |
| 1643 | + | let expanded = pctx.renderer.render_segment_expanded_value( | |
| 1644 | + | &name, | |
| 1645 | + | is_dir, | |
| 1646 | + | pctx.templates_suffix, | |
| 1647 | + | pctx.base_ctx, | |
| 1648 | + | extra_vars, | |
| 1649 | + | pctx.mj_ctx, | |
| 1650 | + | &format!("path:{}", rel_path.display()), | |
| 1651 | + | )?; | |
| 1652 | + | ||
| 1653 | + | for seg in expanded { | |
| 1654 | + | let rendered_rel = if rendered_parent.as_os_str().is_empty() { | |
| 1655 | + | PathBuf::from(seg.name) | |
| 1656 | + | } else { | |
| 1657 | + | rendered_parent.join(seg.name) | |
| 1658 | + | }; | |
| 1659 | + | if pctx.filter.is_excluded(&rendered_rel, is_dir) { | |
| 1660 | + | continue; | |
| 1661 | + | } | |
| 1662 | + | let mut next_vars = extra_vars.to_vec(); | |
| 1663 | + | if let Some(binding) = seg.yield_binding { | |
| 1664 | + | next_vars.push(binding); | |
| 1665 | + | } | |
| 1666 | + | ||
| 1667 | + | if is_dir { | |
| 1668 | + | planned_dirs.insert(rendered_rel.clone()); | |
| 1669 | + | plan_disk_dir( | |
| 1670 | + | pctx, | |
| 1671 | + | &abs_path, | |
| 1672 | + | &rendered_rel, | |
| 1673 | + | &next_vars, | |
| 1674 | + | planned_dirs, | |
| 1675 | + | planned_files, | |
| 1676 | + | )?; | |
| 1677 | + | } else { | |
| 1678 | + | if let Some(parent) = rendered_rel.parent() | |
| 1679 | + | && !parent.as_os_str().is_empty() | |
| 1680 | + | { | |
| 1681 | + | planned_dirs.insert(parent.to_path_buf()); | |
| 1682 | + | } | |
| 1683 | + | let file_mode = if is_symlink { | |
| 1684 | + | None | |
| 1685 | + | } else { | |
| 1686 | + | file_mode_from_metadata(&sym_meta) | |
| 1687 | + | }; | |
| 1688 | + | planned_files.push(PlannedFile { | |
| 1689 | + | rel_src: rel_path.clone(), | |
| 1690 | + | rendered_rel, | |
| 1691 | + | is_template_file: seg.is_template_file, | |
| 1692 | + | extra_vars: next_vars, | |
| 1693 | + | source: RenderItemSource::Disk { | |
| 1694 | + | src_path: abs_path.clone(), | |
| 1695 | + | is_symlink, | |
| 1696 | + | file_mode, | |
| 1697 | + | }, | |
| 1698 | + | }); | |
| 1699 | + | } | |
| 1700 | + | } | |
| 1701 | + | } | |
| 1702 | + | Ok(()) | |
| 1703 | + | } | |
| 1704 | + | ||
| 1705 | + | struct FileRenderCtx<'a> { | |
| 1706 | + | dst_path: &'a Path, | |
| 1707 | + | renderer: &'a TemplateRenderer, | |
| 1708 | + | base_ctx: &'a IndexMap<String, JsonValue>, | |
| 1709 | + | shared_mj_ctx: &'a minijinja::Value, | |
| 1710 | + | filter: &'a PathFilter, | |
| 1711 | + | preserve_symlinks: bool, | |
| 1712 | + | overwrite_policy: OverwritePolicy, | |
| 1713 | + | pretend: bool, | |
| 1714 | + | } | |
| 1715 | + | ||
| 1716 | + | fn process_planned_file( | |
| 1717 | + | fctx: &FileRenderCtx<'_>, | |
| 1718 | + | item: &PlannedFile, | |
| 1719 | + | thread_repo: Option<&gix::Repository>, | |
| 1720 | + | ) -> Result<FileOutcome> { | |
| 1721 | + | let overlay_ctx = if item.extra_vars.is_empty() { | |
| 1722 | + | None | |
| 1723 | + | } else { | |
| 1724 | + | Some(TemplateRenderer::compile_context_with_extra( | |
| 1725 | + | fctx.base_ctx, | |
| 1726 | + | &item.extra_vars, | |
| 1727 | + | )) | |
| 1728 | + | }; | |
| 1729 | + | let ctx = overlay_ctx.as_ref().unwrap_or(fctx.shared_mj_ctx); | |
| 1730 | + | let dst_entry_path = fctx.dst_path.join(&item.rendered_rel); | |
| 1731 | + | ||
| 1732 | + | // Handle symlinks when `_preserve_symlinks` is enabled. | |
| 1733 | + | let is_symlink = match &item.source { | |
| 1734 | + | RenderItemSource::Disk { is_symlink, .. } | |
| 1735 | + | | RenderItemSource::GitBlob { is_symlink, .. } => *is_symlink, | |
| 1736 | + | }; | |
| 1737 | + | if fctx.preserve_symlinks && is_symlink { | |
| 1738 | + | let raw_target = match &item.source { | |
| 1739 | + | RenderItemSource::Disk { src_path, .. } => fs::read_link(src_path) | |
| 1740 | + | .map_err(|e| RoneoError::io(src_path, e))? | |
| 1741 | + | .to_string_lossy() | |
| 1742 | + | .into_owned(), | |
| 1743 | + | RenderItemSource::GitBlob { tree, oid, .. } => { | |
| 1744 | + | let bytes = match thread_repo { | |
| 1745 | + | Some(repo) => InMemoryGitTree::read_blob_with_repo(repo, *oid)?, | |
| 1746 | + | None => tree.read_blob_oid(*oid)?, | |
| 1747 | + | }; | |
| 1748 | + | String::from_utf8_lossy(&bytes).into_owned() | |
| 1749 | + | } | |
| 1750 | + | }; | |
| 1751 | + | let rendered_target = fctx.renderer.render_str_value( | |
| 1752 | + | &raw_target, | |
| 1753 | + | ctx, | |
| 1754 | + | &format!("symlink:{}", item.rel_src.display()), | |
| 1755 | + | )?; | |
| 1756 | + | let exists = dst_entry_path.symlink_metadata().is_ok(); | |
| 1757 | + | if exists { | |
| 1758 | + | match fctx.overwrite_policy { | |
| 1759 | + | OverwritePolicy::Force => {} | |
| 1760 | + | OverwritePolicy::Prompt => { | |
| 1761 | + | return Ok(FileOutcome::NeedsOverwriteConfirm(PendingOverwrite { | |
| 1762 | + | rel: item.rendered_rel.clone(), | |
| 1763 | + | dst_entry_path, | |
| 1764 | + | content: PendingContent::Symlink { | |
| 1765 | + | target: rendered_target, | |
| 1766 | + | }, | |
| 1767 | + | })); | |
| 1768 | + | } | |
| 1769 | + | OverwritePolicy::Skip => { | |
| 1770 | + | return Ok(FileOutcome::Skipped(item.rendered_rel.clone())); | |
| 1771 | + | } | |
| 1772 | + | } | |
| 1773 | + | } | |
| 1774 | + | if !fctx.pretend { | |
| 1775 | + | verify_no_symlink_in_ancestors(fctx.dst_path, &item.rendered_rel)?; | |
| 1776 | + | if let Some(parent) = dst_entry_path.parent() | |
| 1777 | + | && !parent.exists() | |
| 1778 | + | { | |
| 1779 | + | fs::create_dir_all(parent).map_err(|e| RoneoError::io(parent, e))?; | |
| 1780 | + | } | |
| 1781 | + | if exists { | |
| 1782 | + | let _ = fs::remove_file(&dst_entry_path); | |
| 1783 | + | } | |
| 1784 | + | create_symlink(Path::new(&rendered_target), &dst_entry_path)?; | |
| 1785 | + | } | |
| 1786 | + | return Ok(if exists { | |
| 1787 | + | FileOutcome::Overwritten(item.rendered_rel.clone()) | |
| 1788 | + | } else { | |
| 1789 | + | FileOutcome::Created(item.rendered_rel.clone()) | |
| 1790 | + | }); | |
| 1791 | + | } | |
| 1792 | + | ||
| 1793 | + | // Fast path: check `_skip_if_exists` before reading/rendering if destination already exists | |
| 1794 | + | // (use `symlink_metadata` so broken destination symlinks are also detected, Copier v9.18.2). | |
| 1795 | + | let dst_meta = dst_entry_path.symlink_metadata().ok(); | |
| 1796 | + | let exists = dst_meta.is_some(); | |
| 1797 | + | let dst_is_symlink = dst_meta.is_some_and(|m| m.file_type().is_symlink()); | |
| 1798 | + | if exists && fctx.filter.should_skip_if_exists(&item.rendered_rel, false) { | |
| 1799 | + | return Ok(FileOutcome::Skipped(item.rendered_rel.clone())); | |
| 1800 | + | } | |
| 1801 | + | ||
| 1802 | + | // Read raw source bytes (reusing thread-local `gix::Repository` pack cache or disk). | |
| 1803 | + | let raw_bytes = match &item.source { | |
| 1804 | + | RenderItemSource::Disk { src_path, .. } => { | |
| 1805 | + | fs::read(src_path).map_err(|e| RoneoError::io(src_path, e))? | |
| 1806 | + | } | |
| 1807 | + | RenderItemSource::GitBlob { tree, oid, .. } => match thread_repo { | |
| 1808 | + | Some(repo) => InMemoryGitTree::read_blob_with_repo(repo, *oid)?, | |
| 1809 | + | None => tree.read_blob_oid(*oid)?, | |
| 1810 | + | }, | |
| 1811 | + | }; | |
| 1812 | + | ||
| 1813 | + | let new_bytes = if item.is_template_file { | |
| 1814 | + | let raw_text = String::from_utf8(raw_bytes).map_err(|e| { | |
| 1815 | + | RoneoError::TemplateSource(format!( | |
| 1816 | + | "Template file '{}' is not valid UTF-8: {e}", | |
| 1817 | + | item.rel_src.display() | |
| 1818 | + | )) | |
| 1819 | + | })?; | |
| 1820 | + | let rendered_text = | |
| 1821 | + | fctx.renderer | |
| 1822 | + | .render_str_value(&raw_text, ctx, &item.rel_src.to_string_lossy())?; | |
| 1823 | + | rendered_text.into_bytes() | |
| 1824 | + | } else { | |
| 1825 | + | raw_bytes | |
| 1826 | + | }; | |
| 1827 | + | ||
| 1828 | + | if exists { | |
| 1829 | + | if !dst_is_symlink | |
| 1830 | + | && let Ok(existing_bytes) = fs::read(&dst_entry_path) | |
| 1831 | + | && existing_bytes == new_bytes | |
| 1832 | + | { | |
| 1833 | + | return Ok(FileOutcome::Identical(item.rendered_rel.clone())); | |
| 1834 | + | } | |
| 1835 | + | match fctx.overwrite_policy { | |
| 1836 | + | OverwritePolicy::Force => {} | |
| 1837 | + | OverwritePolicy::Prompt => { | |
| 1838 | + | let (src_for_perms, is_executable) = match &item.source { | |
| 1839 | + | RenderItemSource::Disk { src_path, .. } => (Some(src_path.clone()), false), | |
| 1840 | + | RenderItemSource::GitBlob { is_executable, .. } => (None, *is_executable), | |
| 1841 | + | }; | |
| 1842 | + | return Ok(FileOutcome::NeedsOverwriteConfirm(PendingOverwrite { | |
| 1843 | + | rel: item.rendered_rel.clone(), | |
| 1844 | + | dst_entry_path, | |
| 1845 | + | content: PendingContent::File { | |
| 1846 | + | bytes: new_bytes, | |
| 1847 | + | src_for_perms, | |
| 1848 | + | is_executable, | |
| 1849 | + | }, | |
| 1850 | + | })); | |
| 1851 | + | } | |
| 1852 | + | OverwritePolicy::Skip => { | |
| 1853 | + | return Ok(FileOutcome::Skipped(item.rendered_rel.clone())); | |
| 1854 | + | } | |
| 1855 | + | } | |
| 1856 | + | } | |
| 1857 | + | ||
| 1858 | + | if !fctx.pretend { | |
| 1859 | + | verify_no_symlink_in_ancestors(fctx.dst_path, &item.rendered_rel)?; | |
| 1860 | + | if let Some(parent) = dst_entry_path.parent() | |
| 1861 | + | && !parent.exists() | |
| 1862 | + | { | |
| 1863 | + | fs::create_dir_all(parent).map_err(|e| RoneoError::io(parent, e))?; | |
| 1864 | + | } | |
| 1865 | + | // Copier v9.18.2: replace an existing symlink instead of writing through it. | |
| 1866 | + | if dst_is_symlink { | |
| 1867 | + | let _ = fs::remove_file(&dst_entry_path); | |
| 1868 | + | } | |
| 1869 | + | fs::write(&dst_entry_path, &new_bytes).map_err(|e| RoneoError::io(&dst_entry_path, e))?; | |
| 1870 | + | ||
| 1871 | + | match &item.source { | |
| 1872 | + | RenderItemSource::Disk { | |
| 1873 | + | src_path, | |
| 1874 | + | file_mode, | |
| 1875 | + | .. | |
| 1876 | + | } => { | |
| 1877 | + | if let Some(mode) = file_mode { | |
| 1878 | + | set_file_mode(&dst_entry_path, *mode)?; | |
| 1879 | + | } else { | |
| 1880 | + | copy_permissions(src_path, &dst_entry_path)?; | |
| 1881 | + | } | |
| 1882 | + | } | |
| 1883 | + | RenderItemSource::GitBlob { is_executable, .. } => { | |
| 1884 | + | if *is_executable { | |
| 1885 | + | set_executable(&dst_entry_path)?; | |
| 1886 | + | } | |
| 1887 | + | } | |
| 1888 | + | } | |
| 1889 | + | } | |
| 1890 | + | ||
| 1891 | + | Ok(if exists { | |
| 1892 | + | FileOutcome::Overwritten(item.rendered_rel.clone()) | |
| 1893 | + | } else { | |
| 1894 | + | FileOutcome::Created(item.rendered_rel.clone()) | |
| 1895 | + | }) | |
| 1896 | + | } | |
| 1897 | + | ||
| 1898 | + | /// Reject writing through any pre-existing symlink directory under `dst_root` so a template | |
| 1899 | + | /// or malicious destination symlink cannot redirect output outside `dst_root`. | |
| 1900 | + | fn verify_no_symlink_in_ancestors(dst_root: &Path, rel: &Path) -> Result<()> { | |
| 1901 | + | let Some(parent_rel) = rel.parent() else { | |
| 1902 | + | return Ok(()); | |
| 1903 | + | }; | |
| 1904 | + | let mut cur = dst_root.to_path_buf(); | |
| 1905 | + | for comp in parent_rel.components() { | |
| 1906 | + | cur.push(comp); | |
| 1907 | + | if let Ok(meta) = cur.symlink_metadata() | |
| 1908 | + | && meta.file_type().is_symlink() | |
| 1909 | + | { | |
| 1910 | + | return Err(RoneoError::InvalidConfig(format!( | |
| 1911 | + | "Refusing to write through symlink directory '{}'", | |
| 1912 | + | cur.display() | |
| 1913 | + | ))); | |
| 1914 | + | } | |
| 1915 | + | } | |
| 1916 | + | Ok(()) | |
| 1917 | + | } | |
| 1918 | + | ||
| 1919 | + | #[derive(Default)] | |
| 1920 | + | struct PatchSummary { | |
| 1921 | + | created: Vec<String>, | |
| 1922 | + | modified: Vec<String>, | |
| 1923 | + | deleted: Vec<String>, | |
| 1924 | + | } | |
| 1925 | + | ||
| 1926 | + | fn summarize_patch(patch: &[u8]) -> PatchSummary { | |
| 1927 | + | let text = String::from_utf8_lossy(patch); | |
| 1928 | + | let mut summary = PatchSummary::default(); | |
| 1929 | + | let mut current_path: Option<String> = None; | |
| 1930 | + | let mut is_new = false; | |
| 1931 | + | let mut is_deleted = false; | |
| 1932 | + | ||
| 1933 | + | let flush = |path: &mut Option<String>, | |
| 1934 | + | is_new: &mut bool, | |
| 1935 | + | is_deleted: &mut bool, | |
| 1936 | + | summary: &mut PatchSummary| { | |
| 1937 | + | if let Some(p) = path.take() { | |
| 1938 | + | if *is_new { | |
| 1939 | + | summary.created.push(p); | |
| 1940 | + | } else if *is_deleted { | |
| 1941 | + | summary.deleted.push(p); | |
| 1942 | + | } else { | |
| 1943 | + | summary.modified.push(p); | |
| 1944 | + | } | |
| 1945 | + | } | |
| 1946 | + | *is_new = false; | |
| 1947 | + | *is_deleted = false; | |
| 1948 | + | }; | |
| 1949 | + | ||
| 1950 | + | for line in text.lines() { | |
| 1951 | + | if let Some(rest) = line.strip_prefix("diff --git ") { | |
| 1952 | + | flush( | |
| 1953 | + | &mut current_path, | |
| 1954 | + | &mut is_new, | |
| 1955 | + | &mut is_deleted, | |
| 1956 | + | &mut summary, | |
| 1957 | + | ); | |
| 1958 | + | // Handles standard `a/foo b/foo` as well as `--no-index --no-prefix` `b/foo b/foo` (new) | |
| 1959 | + | // and `a/foo a/foo` (deleted). | |
| 1960 | + | if let Some((_, b_part)) = rest.split_once(" b/") { | |
| 1961 | + | current_path = Some(b_part.to_string()); | |
| 1962 | + | } else if let Some((_, a_part)) = rest.split_once(" a/") { | |
| 1963 | + | current_path = Some(a_part.to_string()); | |
| 1964 | + | } | |
| 1965 | + | } else if line.starts_with("new file mode") { | |
| 1966 | + | is_new = true; | |
| 1967 | + | } else if line.starts_with("deleted file mode") { | |
| 1968 | + | is_deleted = true; | |
| 1969 | + | } | |
| 1970 | + | } | |
| 1971 | + | flush( | |
| 1972 | + | &mut current_path, | |
| 1973 | + | &mut is_new, | |
| 1974 | + | &mut is_deleted, | |
| 1975 | + | &mut summary, | |
| 1976 | + | ); | |
| 1977 | + | ||
| 1978 | + | summary | |
| 1979 | + | } |
| @@ -0,0 +1,2085 @@ | |||
| 1 | + | use std::fs; | |
| 2 | + | use std::path::Path; | |
| 3 | + | use std::process::Command; | |
| 4 | + | ||
| 5 | + | use indexmap::IndexMap; | |
| 6 | + | use roneo_core::fs_util::TempDir; | |
| 7 | + | use roneo_core::vcs::ConflictMode; | |
| 8 | + | use roneo_core::{ | |
| 9 | + | AnswersMap, CopyOptions, NonInteractivePrompter, NoopReporter, OverwriteChoice, PromptRequest, | |
| 10 | + | Prompter, RoneoError, UserSettings, check_update, copy, diff_update, recopy, update, | |
| 11 | + | }; | |
| 12 | + | use serde_json::json; | |
| 13 | + | ||
| 14 | + | fn git(dir: &Path, args: &[&str]) { | |
| 15 | + | let out = Command::new("git") | |
| 16 | + | .current_dir(dir) | |
| 17 | + | .args(args) | |
| 18 | + | .output() | |
| 19 | + | .expect("git command should run"); | |
| 20 | + | assert!( | |
| 21 | + | out.status.success(), | |
| 22 | + | "git {:?} failed: {}", | |
| 23 | + | args, | |
| 24 | + | String::from_utf8_lossy(&out.stderr) | |
| 25 | + | ); | |
| 26 | + | } | |
| 27 | + | ||
| 28 | + | fn init_git_repo(dir: &Path) { | |
| 29 | + | git(dir, &["init", "-b", "main"]); | |
| 30 | + | git(dir, &["config", "user.name", "Test"]); | |
| 31 | + | git(dir, &["config", "user.email", "test@example.com"]); | |
| 32 | + | git(dir, &["config", "commit.gpgsign", "false"]); | |
| 33 | + | } | |
| 34 | + | ||
| 35 | + | fn commit_all(dir: &Path, msg: &str) { | |
| 36 | + | git(dir, &["add", "-A"]); | |
| 37 | + | git(dir, &["commit", "-m", msg]); | |
| 38 | + | } | |
| 39 | + | ||
| 40 | + | #[test] | |
| 41 | + | fn copy_renders_copier_template_with_pycompat_paths_secrets_and_conditions() { | |
| 42 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 43 | + | let dst_dir = TempDir::new().unwrap(); | |
| 44 | + | ||
| 45 | + | fs::write( | |
| 46 | + | tpl_dir.path().join("copier.yml"), | |
| 47 | + | r#" | |
| 48 | + | _subdirectory: template | |
| 49 | + | _exclude: | |
| 50 | + | - "ignored.txt" | |
| 51 | + | project_name: | |
| 52 | + | type: str | |
| 53 | + | default: my-cool-app | |
| 54 | + | module_name: | |
| 55 | + | type: str | |
| 56 | + | default: "{{ project_name.lower().replace('-', '_') }}" | |
| 57 | + | include_extras: | |
| 58 | + | type: bool | |
| 59 | + | default: false | |
| 60 | + | api_token: | |
| 61 | + | type: str | |
| 62 | + | secret: true | |
| 63 | + | default: super-secret-value | |
| 64 | + | "#, | |
| 65 | + | ) | |
| 66 | + | .unwrap(); | |
| 67 | + | ||
| 68 | + | let tpl_sub = tpl_dir.path().join("template"); | |
| 69 | + | fs::create_dir_all(tpl_sub.join("src")).unwrap(); | |
| 70 | + | fs::write( | |
| 71 | + | tpl_sub.join("README.md.jinja"), | |
| 72 | + | "# {{ project_name }}\nmodule={{ module_name }}\ntoken={{ api_token }}\n", | |
| 73 | + | ) | |
| 74 | + | .unwrap(); | |
| 75 | + | fs::write( | |
| 76 | + | tpl_sub.join("src/{{ module_name }}.txt.jinja"), | |
| 77 | + | "hello {{ module_name }}", | |
| 78 | + | ) | |
| 79 | + | .unwrap(); | |
| 80 | + | fs::write( | |
| 81 | + | tpl_sub.join("{% if include_extras %}extras.txt{% endif %}.jinja"), | |
| 82 | + | "extra content", | |
| 83 | + | ) | |
| 84 | + | .unwrap(); | |
| 85 | + | fs::write(tpl_sub.join("ignored.txt"), "should not be copied").unwrap(); | |
| 86 | + | ||
| 87 | + | let mut data = IndexMap::new(); | |
| 88 | + | data.insert("project_name".into(), json!("Roneo-Demo")); | |
| 89 | + | ||
| 90 | + | let opts = CopyOptions { | |
| 91 | + | data, | |
| 92 | + | defaults: true, | |
| 93 | + | ..CopyOptions::default() | |
| 94 | + | }; | |
| 95 | + | ||
| 96 | + | let report = copy( | |
| 97 | + | tpl_dir.path().to_str().unwrap(), | |
| 98 | + | dst_dir.path(), | |
| 99 | + | &opts, | |
| 100 | + | &NonInteractivePrompter, | |
| 101 | + | &NoopReporter, | |
| 102 | + | ) | |
| 103 | + | .unwrap(); | |
| 104 | + | ||
| 105 | + | assert!(report.created >= 3); | |
| 106 | + | let readme = fs::read_to_string(dst_dir.path().join("README.md")).unwrap(); | |
| 107 | + | assert!(readme.contains("# Roneo-Demo")); | |
| 108 | + | assert!(readme.contains("module=roneo_demo")); | |
| 109 | + | assert!(readme.contains("token=super-secret-value")); | |
| 110 | + | ||
| 111 | + | let mod_file = fs::read_to_string(dst_dir.path().join("src/roneo_demo.txt")).unwrap(); | |
| 112 | + | assert_eq!(mod_file, "hello roneo_demo"); | |
| 113 | + | ||
| 114 | + | // Conditional file skipped when false | |
| 115 | + | assert!(!dst_dir.path().join("extras.txt").exists()); | |
| 116 | + | // Excluded file skipped | |
| 117 | + | assert!(!dst_dir.path().join("ignored.txt").exists()); | |
| 118 | + | ||
| 119 | + | // Secret answer must NOT be written into .copier-answers.yml | |
| 120 | + | let answers = AnswersMap::load(&dst_dir.path().join(".copier-answers.yml")).unwrap(); | |
| 121 | + | assert_eq!(answers.user.get("project_name"), Some(&json!("Roneo-Demo"))); | |
| 122 | + | assert_eq!(answers.user.get("module_name"), Some(&json!("roneo_demo"))); | |
| 123 | + | assert!(!answers.user.contains_key("api_token")); | |
| 124 | + | } | |
| 125 | + | ||
| 126 | + | #[test] | |
| 127 | + | fn pretend_mode_writes_nothing() { | |
| 128 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 129 | + | let dst_dir = TempDir::new().unwrap(); | |
| 130 | + | ||
| 131 | + | fs::write(tpl_dir.path().join("copier.yml"), "name: demo\n").unwrap(); | |
| 132 | + | fs::write(tpl_dir.path().join("hello.txt.jinja"), "Hi {{ name }}").unwrap(); | |
| 133 | + | ||
| 134 | + | let opts = CopyOptions { | |
| 135 | + | defaults: true, | |
| 136 | + | pretend: true, | |
| 137 | + | ..CopyOptions::default() | |
| 138 | + | }; | |
| 139 | + | ||
| 140 | + | let report = copy( | |
| 141 | + | tpl_dir.path().to_str().unwrap(), | |
| 142 | + | dst_dir.path(), | |
| 143 | + | &opts, | |
| 144 | + | &NonInteractivePrompter, | |
| 145 | + | &NoopReporter, | |
| 146 | + | ) | |
| 147 | + | .unwrap(); | |
| 148 | + | ||
| 149 | + | assert!(report.created >= 1); | |
| 150 | + | assert!(!dst_dir.path().join("hello.txt").exists()); | |
| 151 | + | assert!(!dst_dir.path().join(".copier-answers.yml").exists()); | |
| 152 | + | } | |
| 153 | + | ||
| 154 | + | #[test] | |
| 155 | + | fn recopy_reuses_previous_answers_and_updates_files() { | |
| 156 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 157 | + | let dst_dir = TempDir::new().unwrap(); | |
| 158 | + | ||
| 159 | + | fs::write( | |
| 160 | + | tpl_dir.path().join("copier.yml"), | |
| 161 | + | "project_name: alpha\ngreeting: hello\n", | |
| 162 | + | ) | |
| 163 | + | .unwrap(); | |
| 164 | + | fs::write( | |
| 165 | + | tpl_dir.path().join("info.txt.jinja"), | |
| 166 | + | "{{ greeting }}, {{ project_name }}!\n", | |
| 167 | + | ) | |
| 168 | + | .unwrap(); | |
| 169 | + | ||
| 170 | + | let mut data = IndexMap::new(); | |
| 171 | + | data.insert("project_name".into(), json!("beta")); | |
| 172 | + | copy( | |
| 173 | + | tpl_dir.path().to_str().unwrap(), | |
| 174 | + | dst_dir.path(), | |
| 175 | + | &CopyOptions { | |
| 176 | + | data, | |
| 177 | + | defaults: true, | |
| 178 | + | ..CopyOptions::default() | |
| 179 | + | }, | |
| 180 | + | &NonInteractivePrompter, | |
| 181 | + | &NoopReporter, | |
| 182 | + | ) | |
| 183 | + | .unwrap(); | |
| 184 | + | assert_eq!( | |
| 185 | + | fs::read_to_string(dst_dir.path().join("info.txt")).unwrap(), | |
| 186 | + | "hello, beta!\n" | |
| 187 | + | ); | |
| 188 | + | ||
| 189 | + | let mut override_data = IndexMap::new(); | |
| 190 | + | override_data.insert("greeting".into(), json!("bonjour")); | |
| 191 | + | recopy( | |
| 192 | + | dst_dir.path(), | |
| 193 | + | None, | |
| 194 | + | &CopyOptions { | |
| 195 | + | data: override_data, | |
| 196 | + | defaults: true, | |
| 197 | + | ..CopyOptions::default() | |
| 198 | + | }, | |
| 199 | + | &NonInteractivePrompter, | |
| 200 | + | &NoopReporter, | |
| 201 | + | ) | |
| 202 | + | .unwrap(); | |
| 203 | + | ||
| 204 | + | // `project_name` preserved from `.copier-answers.yml`, `greeting` updated! | |
| 205 | + | assert_eq!( | |
| 206 | + | fs::read_to_string(dst_dir.path().join("info.txt")).unwrap(), | |
| 207 | + | "bonjour, beta!\n" | |
| 208 | + | ); | |
| 209 | + | } | |
| 210 | + | ||
| 211 | + | #[test] | |
| 212 | + | fn smart_update_preserves_local_edits_and_applies_upstream_changes() { | |
| 213 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 214 | + | let dst_dir = TempDir::new().unwrap(); | |
| 215 | + | ||
| 216 | + | // Create git-backed template v1.0.0 | |
| 217 | + | init_git_repo(tpl_dir.path()); | |
| 218 | + | fs::write(tpl_dir.path().join("copier.yml"), "project_name: demo\n").unwrap(); | |
| 219 | + | fs::write( | |
| 220 | + | tpl_dir.path().join("README.md.jinja"), | |
| 221 | + | "# {{ project_name }}\n\nTemplate header v1\n\n## Custom Notes\nWrite notes here.\n", | |
| 222 | + | ) | |
| 223 | + | .unwrap(); | |
| 224 | + | fs::write(tpl_dir.path().join("legacy.txt"), "old file\n").unwrap(); | |
| 225 | + | commit_all(tpl_dir.path(), "v1.0.0"); | |
| 226 | + | git(tpl_dir.path(), &["tag", "v1.0.0"]); | |
| 227 | + | ||
| 228 | + | // Copy v1.0.0 into destination and commit as a git repo | |
| 229 | + | copy( | |
| 230 | + | tpl_dir.path().to_str().unwrap(), | |
| 231 | + | dst_dir.path(), | |
| 232 | + | &CopyOptions { | |
| 233 | + | defaults: true, | |
| 234 | + | ..CopyOptions::default() | |
| 235 | + | }, | |
| 236 | + | &NonInteractivePrompter, | |
| 237 | + | &NoopReporter, | |
| 238 | + | ) | |
| 239 | + | .unwrap(); | |
| 240 | + | init_git_repo(dst_dir.path()); | |
| 241 | + | commit_all(dst_dir.path(), "Initial scaffold"); | |
| 242 | + | ||
| 243 | + | // User customizes README.md and adds a custom file | |
| 244 | + | fs::write( | |
| 245 | + | dst_dir.path().join("README.md"), | |
| 246 | + | "# demo\n\nTemplate header v1\n\n## Custom Notes\nMy precious user edits!\n", | |
| 247 | + | ) | |
| 248 | + | .unwrap(); | |
| 249 | + | fs::write(dst_dir.path().join("user_code.rs"), "fn main() {}\n").unwrap(); | |
| 250 | + | commit_all(dst_dir.path(), "User edits"); | |
| 251 | + | ||
| 252 | + | // Template releases v2.0.0: updates header, removes legacy.txt, adds CHANGELOG.md | |
| 253 | + | fs::write( | |
| 254 | + | tpl_dir.path().join("README.md.jinja"), | |
| 255 | + | "# {{ project_name }}\n\nTemplate header v2 (improved!)\n\n## Custom Notes\nWrite notes here.\n", | |
| 256 | + | ) | |
| 257 | + | .unwrap(); | |
| 258 | + | fs::remove_file(tpl_dir.path().join("legacy.txt")).unwrap(); | |
| 259 | + | fs::write( | |
| 260 | + | tpl_dir.path().join("CHANGELOG.md.jinja"), | |
| 261 | + | "# Changelog for {{ project_name }}\n- v2.0.0\n", | |
| 262 | + | ) | |
| 263 | + | .unwrap(); | |
| 264 | + | commit_all(tpl_dir.path(), "v2.0.0"); | |
| 265 | + | git(tpl_dir.path(), &["tag", "v2.0.0"]); | |
| 266 | + | ||
| 267 | + | // Run smart update! | |
| 268 | + | let report = update( | |
| 269 | + | dst_dir.path(), | |
| 270 | + | &CopyOptions { | |
| 271 | + | defaults: true, | |
| 272 | + | ..CopyOptions::default() | |
| 273 | + | }, | |
| 274 | + | &NonInteractivePrompter, | |
| 275 | + | &NoopReporter, | |
| 276 | + | ) | |
| 277 | + | .unwrap(); | |
| 278 | + | ||
| 279 | + | assert!( | |
| 280 | + | report.conflicts.is_empty(), | |
| 281 | + | "Unexpected conflicts: {:?}", | |
| 282 | + | report.conflicts | |
| 283 | + | ); | |
| 284 | + | assert_eq!(report.commit.as_deref(), Some("v2.0.0")); | |
| 285 | + | ||
| 286 | + | // README has BOTH v2 template update AND preserved user edits! | |
| 287 | + | let readme = fs::read_to_string(dst_dir.path().join("README.md")).unwrap(); | |
| 288 | + | assert!(readme.contains("Template header v2 (improved!)")); | |
| 289 | + | assert!(readme.contains("My precious user edits!")); | |
| 290 | + | ||
| 291 | + | // New file added, legacy file removed, user custom file untouched | |
| 292 | + | assert!(dst_dir.path().join("CHANGELOG.md").exists()); | |
| 293 | + | assert!(!dst_dir.path().join("legacy.txt").exists()); | |
| 294 | + | assert!(dst_dir.path().join("user_code.rs").exists()); | |
| 295 | + | ||
| 296 | + | // Answers file updated to v2.0.0 | |
| 297 | + | let answers = AnswersMap::load(&dst_dir.path().join(".copier-answers.yml")).unwrap(); | |
| 298 | + | assert_eq!(answers.commit(), Some("v2.0.0")); | |
| 299 | + | } | |
| 300 | + | ||
| 301 | + | #[test] | |
| 302 | + | fn smart_update_reports_three_way_conflicts_inline() { | |
| 303 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 304 | + | let dst_dir = TempDir::new().unwrap(); | |
| 305 | + | ||
| 306 | + | init_git_repo(tpl_dir.path()); | |
| 307 | + | fs::write(tpl_dir.path().join("copier.yml"), "name: app\n").unwrap(); | |
| 308 | + | fs::write(tpl_dir.path().join("config.txt.jinja"), "port=8080\n").unwrap(); | |
| 309 | + | commit_all(tpl_dir.path(), "v1"); | |
| 310 | + | git(tpl_dir.path(), &["tag", "v1.0.0"]); | |
| 311 | + | ||
| 312 | + | copy( | |
| 313 | + | tpl_dir.path().to_str().unwrap(), | |
| 314 | + | dst_dir.path(), | |
| 315 | + | &CopyOptions { | |
| 316 | + | defaults: true, | |
| 317 | + | ..CopyOptions::default() | |
| 318 | + | }, | |
| 319 | + | &NonInteractivePrompter, | |
| 320 | + | &NoopReporter, | |
| 321 | + | ) | |
| 322 | + | .unwrap(); | |
| 323 | + | init_git_repo(dst_dir.path()); | |
| 324 | + | commit_all(dst_dir.path(), "scaffold"); | |
| 325 | + | ||
| 326 | + | // User edits same line | |
| 327 | + | fs::write(dst_dir.path().join("config.txt"), "port=9090\n").unwrap(); | |
| 328 | + | commit_all(dst_dir.path(), "change port"); | |
| 329 | + | ||
| 330 | + | // Upstream edits same line differently | |
| 331 | + | fs::write(tpl_dir.path().join("config.txt.jinja"), "port=3000\n").unwrap(); | |
| 332 | + | commit_all(tpl_dir.path(), "v2"); | |
| 333 | + | git(tpl_dir.path(), &["tag", "v2.0.0"]); | |
| 334 | + | ||
| 335 | + | let report = update( | |
| 336 | + | dst_dir.path(), | |
| 337 | + | &CopyOptions { | |
| 338 | + | defaults: true, | |
| 339 | + | conflict_mode: ConflictMode::Inline, | |
| 340 | + | ..CopyOptions::default() | |
| 341 | + | }, | |
| 342 | + | &NonInteractivePrompter, | |
| 343 | + | &NoopReporter, | |
| 344 | + | ) | |
| 345 | + | .unwrap(); | |
| 346 | + | ||
| 347 | + | assert_eq!(report.conflicts, vec!["config.txt"]); | |
| 348 | + | let content = fs::read_to_string(dst_dir.path().join("config.txt")).unwrap(); | |
| 349 | + | assert!(content.contains("<<<<<<<")); | |
| 350 | + | assert!(content.contains("port=9090")); | |
| 351 | + | assert!(content.contains("port=3000")); | |
| 352 | + | } | |
| 353 | + | ||
| 354 | + | #[test] | |
| 355 | + | fn tasks_require_trust_flag() { | |
| 356 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 357 | + | let dst_dir = TempDir::new().unwrap(); | |
| 358 | + | ||
| 359 | + | fs::write( | |
| 360 | + | tpl_dir.path().join("copier.yml"), | |
| 361 | + | r#" | |
| 362 | + | _tasks: | |
| 363 | + | - "echo 'ran {{ name }}' > task_ran.txt" | |
| 364 | + | name: ok | |
| 365 | + | "#, | |
| 366 | + | ) | |
| 367 | + | .unwrap(); | |
| 368 | + | fs::write(tpl_dir.path().join("a.txt"), "hello").unwrap(); | |
| 369 | + | ||
| 370 | + | // Without --trust -> rejected | |
| 371 | + | let err = copy( | |
| 372 | + | tpl_dir.path().to_str().unwrap(), | |
| 373 | + | dst_dir.path(), | |
| 374 | + | &CopyOptions { | |
| 375 | + | defaults: true, | |
| 376 | + | trust: false, | |
| 377 | + | ..CopyOptions::default() | |
| 378 | + | }, | |
| 379 | + | &NonInteractivePrompter, | |
| 380 | + | &NoopReporter, | |
| 381 | + | ) | |
| 382 | + | .unwrap_err(); | |
| 383 | + | assert!(matches!(err, RoneoError::UnsafeTemplate(_))); | |
| 384 | + | ||
| 385 | + | // With --trust -> succeeds and executes task | |
| 386 | + | copy( | |
| 387 | + | tpl_dir.path().to_str().unwrap(), | |
| 388 | + | dst_dir.path(), | |
| 389 | + | &CopyOptions { | |
| 390 | + | defaults: true, | |
| 391 | + | trust: true, | |
| 392 | + | ..CopyOptions::default() | |
| 393 | + | }, | |
| 394 | + | &NonInteractivePrompter, | |
| 395 | + | &NoopReporter, | |
| 396 | + | ) | |
| 397 | + | .unwrap(); | |
| 398 | + | let marker = fs::read_to_string(dst_dir.path().join("task_ran.txt")).unwrap(); | |
| 399 | + | assert_eq!(marker.trim(), "ran ok"); | |
| 400 | + | } | |
| 401 | + | ||
| 402 | + | #[test] | |
| 403 | + | fn external_data_and_extra_filters_render_cleanly() { | |
| 404 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 405 | + | let dst_dir = TempDir::new().unwrap(); | |
| 406 | + | ||
| 407 | + | fs::write( | |
| 408 | + | tpl_dir.path().join("meta.yml"), | |
| 409 | + | "org: Acme\nports:\n - 80\n - 443\n", | |
| 410 | + | ) | |
| 411 | + | .unwrap(); | |
| 412 | + | fs::write( | |
| 413 | + | tpl_dir.path().join("copier.yml"), | |
| 414 | + | r#" | |
| 415 | + | _external_data: | |
| 416 | + | meta: meta.yml | |
| 417 | + | _exclude: | |
| 418 | + | - "meta.yml" | |
| 419 | + | title: | |
| 420 | + | type: str | |
| 421 | + | default: "Hello World 2026!" | |
| 422 | + | "#, | |
| 423 | + | ) | |
| 424 | + | .unwrap(); | |
| 425 | + | fs::write( | |
| 426 | + | tpl_dir.path().join("out.yml.jinja"), | |
| 427 | + | r#"org: {{ _external_data.meta.org }} | |
| 428 | + | slug: {{ title | slugify }} | |
| 429 | + | joined: {{ pathjoin("a", "b", "c.yml") }} | |
| 430 | + | parsed: {{ '{"k": 42}' | from_json | to_json }} | |
| 431 | + | bool_ok: {{ "yes" | to_bool }} | |
| 432 | + | "#, | |
| 433 | + | ) | |
| 434 | + | .unwrap(); | |
| 435 | + | ||
| 436 | + | copy( | |
| 437 | + | tpl_dir.path().to_str().unwrap(), | |
| 438 | + | dst_dir.path(), | |
| 439 | + | &CopyOptions { | |
| 440 | + | defaults: true, | |
| 441 | + | ..CopyOptions::default() | |
| 442 | + | }, | |
| 443 | + | &NonInteractivePrompter, | |
| 444 | + | &NoopReporter, | |
| 445 | + | ) | |
| 446 | + | .unwrap(); | |
| 447 | + | ||
| 448 | + | let rendered = fs::read_to_string(dst_dir.path().join("out.yml")).unwrap(); | |
| 449 | + | // AutoEscape::None means `.yml` strings are NOT wrapped in extra JSON quotes! | |
| 450 | + | assert!(rendered.contains("org: Acme\n"), "got:\n{rendered}"); | |
| 451 | + | assert!( | |
| 452 | + | rendered.contains("slug: hello-world-2026\n"), | |
| 453 | + | "got:\n{rendered}" | |
| 454 | + | ); | |
| 455 | + | assert!(rendered.contains("joined: a/b/c.yml\n"), "got:\n{rendered}"); | |
| 456 | + | assert!( | |
| 457 | + | rendered.contains("parsed: {\"k\":42}\n"), | |
| 458 | + | "got:\n{rendered}" | |
| 459 | + | ); | |
| 460 | + | assert!(rendered.contains("bool_ok: True\n"), "got:\n{rendered}"); | |
| 461 | + | } | |
| 462 | + | ||
| 463 | + | #[test] | |
| 464 | + | fn pep440_prerelease_tags_and_in_memory_gix_includes() { | |
| 465 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 466 | + | let dst_stable = TempDir::new().unwrap(); | |
| 467 | + | let dst_pre = TempDir::new().unwrap(); | |
| 468 | + | ||
| 469 | + | init_git_repo(tpl_dir.path()); | |
| 470 | + | fs::create_dir_all(tpl_dir.path().join("template/includes")).unwrap(); | |
| 471 | + | fs::write( | |
| 472 | + | tpl_dir.path().join("copier.yml"), | |
| 473 | + | "_subdirectory: template\n---\n!include template/questions.yml\n", | |
| 474 | + | ) | |
| 475 | + | .unwrap(); | |
| 476 | + | fs::write( | |
| 477 | + | tpl_dir.path().join("template/questions.yml"), | |
| 478 | + | "_exclude:\n - questions.yml\n - includes\n - includes/**\nver_label: v1\n", | |
| 479 | + | ) | |
| 480 | + | .unwrap(); | |
| 481 | + | fs::write( | |
| 482 | + | tpl_dir.path().join("template/includes/part.jinja"), | |
| 483 | + | "included-v1-{{ ver_label }}", | |
| 484 | + | ) | |
| 485 | + | .unwrap(); | |
| 486 | + | fs::write( | |
| 487 | + | tpl_dir.path().join("template/out.txt.jinja"), | |
| 488 | + | "{% include 'template/includes/part.jinja' %}\n", | |
| 489 | + | ) | |
| 490 | + | .unwrap(); | |
| 491 | + | commit_all(tpl_dir.path(), "v1.0.0"); | |
| 492 | + | git(tpl_dir.path(), &["tag", "v1.0.0"]); | |
| 493 | + | ||
| 494 | + | // Add a PEP 440 pre-release tag v2.0.0rc1 | |
| 495 | + | fs::write( | |
| 496 | + | tpl_dir.path().join("template/includes/part.jinja"), | |
| 497 | + | "included-rc-{{ ver_label }}", | |
| 498 | + | ) | |
| 499 | + | .unwrap(); | |
| 500 | + | commit_all(tpl_dir.path(), "v2.0.0rc1"); | |
| 501 | + | git(tpl_dir.path(), &["tag", "v2.0.0rc1"]); | |
| 502 | + | ||
| 503 | + | // Default (`use_prereleases = false`) selects stable `v1.0.0`! | |
| 504 | + | let rep_stable = copy( | |
| 505 | + | tpl_dir.path().to_str().unwrap(), | |
| 506 | + | dst_stable.path(), | |
| 507 | + | &CopyOptions { | |
| 508 | + | defaults: true, | |
| 509 | + | ..CopyOptions::default() | |
| 510 | + | }, | |
| 511 | + | &NonInteractivePrompter, | |
| 512 | + | &NoopReporter, | |
| 513 | + | ) | |
| 514 | + | .unwrap(); | |
| 515 | + | assert_eq!(rep_stable.commit.as_deref(), Some("v1.0.0")); | |
| 516 | + | assert_eq!( | |
| 517 | + | fs::read_to_string(dst_stable.path().join("out.txt")).unwrap(), | |
| 518 | + | "included-v1-v1\n" | |
| 519 | + | ); | |
| 520 | + | ||
| 521 | + | // With `use_prereleases = true` selects `v2.0.0rc1`! | |
| 522 | + | let rep_pre = copy( | |
| 523 | + | tpl_dir.path().to_str().unwrap(), | |
| 524 | + | dst_pre.path(), | |
| 525 | + | &CopyOptions { | |
| 526 | + | defaults: true, | |
| 527 | + | use_prereleases: true, | |
| 528 | + | ..CopyOptions::default() | |
| 529 | + | }, | |
| 530 | + | &NonInteractivePrompter, | |
| 531 | + | &NoopReporter, | |
| 532 | + | ) | |
| 533 | + | .unwrap(); | |
| 534 | + | assert_eq!(rep_pre.commit.as_deref(), Some("v2.0.0rc1")); | |
| 535 | + | assert_eq!( | |
| 536 | + | fs::read_to_string(dst_pre.path().join("out.txt")).unwrap(), | |
| 537 | + | "included-rc-v1\n" | |
| 538 | + | ); | |
| 539 | + | } | |
| 540 | + | ||
| 541 | + | #[test] | |
| 542 | + | fn skipped_when_questions_not_persisted_and_unset_supported() { | |
| 543 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 544 | + | let dst_dir = TempDir::new().unwrap(); | |
| 545 | + | ||
| 546 | + | fs::write( | |
| 547 | + | tpl_dir.path().join("copier.yml"), | |
| 548 | + | r#" | |
| 549 | + | enable_feature: | |
| 550 | + | type: bool | |
| 551 | + | default: false | |
| 552 | + | hidden_opt: | |
| 553 | + | type: str | |
| 554 | + | default: "fallback" | |
| 555 | + | when: "{{ enable_feature }}" | |
| 556 | + | unset_opt: | |
| 557 | + | type: str | |
| 558 | + | default: "{% if enable_feature %}set{% else %}{{ UNSET }}{% endif %}" | |
| 559 | + | when: "{{ enable_feature }}" | |
| 560 | + | "#, | |
| 561 | + | ) | |
| 562 | + | .unwrap(); | |
| 563 | + | fs::write( | |
| 564 | + | tpl_dir.path().join("f.txt.jinja"), | |
| 565 | + | "hidden={{ hidden_opt }}\n", | |
| 566 | + | ) | |
| 567 | + | .unwrap(); | |
| 568 | + | ||
| 569 | + | copy( | |
| 570 | + | tpl_dir.path().to_str().unwrap(), | |
| 571 | + | dst_dir.path(), | |
| 572 | + | &CopyOptions { | |
| 573 | + | defaults: true, | |
| 574 | + | ..CopyOptions::default() | |
| 575 | + | }, | |
| 576 | + | &NonInteractivePrompter, | |
| 577 | + | &NoopReporter, | |
| 578 | + | ) | |
| 579 | + | .unwrap(); | |
| 580 | + | ||
| 581 | + | assert_eq!( | |
| 582 | + | fs::read_to_string(dst_dir.path().join("f.txt")).unwrap(), | |
| 583 | + | "hidden=fallback\n" | |
| 584 | + | ); | |
| 585 | + | let answers = AnswersMap::load(&dst_dir.path().join(".copier-answers.yml")).unwrap(); | |
| 586 | + | assert_eq!(answers.user.get("enable_feature"), Some(&json!(false))); | |
| 587 | + | assert!(!answers.user.contains_key("hidden_opt")); | |
| 588 | + | assert!(!answers.user.contains_key("unset_opt")); | |
| 589 | + | } | |
| 590 | + | ||
| 591 | + | #[test] | |
| 592 | + | fn diff_update_previews_patch_without_mutating_destination() { | |
| 593 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 594 | + | let dst_dir = TempDir::new().unwrap(); | |
| 595 | + | ||
| 596 | + | init_git_repo(tpl_dir.path()); | |
| 597 | + | fs::write(tpl_dir.path().join("copier.yml"), "name: demo\n").unwrap(); | |
| 598 | + | fs::write(tpl_dir.path().join("app.txt.jinja"), "version=1\n").unwrap(); | |
| 599 | + | commit_all(tpl_dir.path(), "v1.0.0"); | |
| 600 | + | git(tpl_dir.path(), &["tag", "v1.0.0"]); | |
| 601 | + | ||
| 602 | + | copy( | |
| 603 | + | tpl_dir.path().to_str().unwrap(), | |
| 604 | + | dst_dir.path(), | |
| 605 | + | &CopyOptions { | |
| 606 | + | defaults: true, | |
| 607 | + | ..CopyOptions::default() | |
| 608 | + | }, | |
| 609 | + | &NonInteractivePrompter, | |
| 610 | + | &NoopReporter, | |
| 611 | + | ) | |
| 612 | + | .unwrap(); | |
| 613 | + | ||
| 614 | + | fs::write(tpl_dir.path().join("app.txt.jinja"), "version=2\n").unwrap(); | |
| 615 | + | commit_all(tpl_dir.path(), "v2.0.0"); | |
| 616 | + | git(tpl_dir.path(), &["tag", "v2.0.0"]); | |
| 617 | + | ||
| 618 | + | let diff = diff_update( | |
| 619 | + | dst_dir.path(), | |
| 620 | + | &CopyOptions { | |
| 621 | + | defaults: true, | |
| 622 | + | ..CopyOptions::default() | |
| 623 | + | }, | |
| 624 | + | &NonInteractivePrompter, | |
| 625 | + | ) | |
| 626 | + | .unwrap(); | |
| 627 | + | ||
| 628 | + | assert_eq!(diff.from_commit, "v1.0.0"); | |
| 629 | + | assert_eq!(diff.to_commit.as_deref(), Some("v2.0.0")); | |
| 630 | + | assert!(diff.patch.contains("-version=1")); | |
| 631 | + | assert!(diff.patch.contains("+version=2")); | |
| 632 | + | // Destination file remains untouched! | |
| 633 | + | assert_eq!( | |
| 634 | + | fs::read_to_string(dst_dir.path().join("app.txt")).unwrap(), | |
| 635 | + | "version=1\n" | |
| 636 | + | ); | |
| 637 | + | } | |
| 638 | + | ||
| 639 | + | #[test] | |
| 640 | + | fn min_copier_version_and_user_settings_defaults_and_trust() { | |
| 641 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 642 | + | let dst_dir = TempDir::new().unwrap(); | |
| 643 | + | ||
| 644 | + | // 1. Template requiring Copier 99.0.0 must be rejected. | |
| 645 | + | fs::write( | |
| 646 | + | tpl_dir.path().join("copier.yml"), | |
| 647 | + | "_min_copier_version: '99.0.0'\nname: demo\n", | |
| 648 | + | ) | |
| 649 | + | .unwrap(); | |
| 650 | + | let err = copy( | |
| 651 | + | tpl_dir.path().to_str().unwrap(), | |
| 652 | + | dst_dir.path(), | |
| 653 | + | &CopyOptions { | |
| 654 | + | defaults: true, | |
| 655 | + | ..CopyOptions::default() | |
| 656 | + | }, | |
| 657 | + | &NonInteractivePrompter, | |
| 658 | + | &NoopReporter, | |
| 659 | + | ) | |
| 660 | + | .unwrap_err(); | |
| 661 | + | assert!(matches!(err, RoneoError::IncompatibleCopierVersion { .. })); | |
| 662 | + | ||
| 663 | + | // 2. Compatible `_min_copier_version` + `UserSettings` (`defaults` + `trust` prefix). | |
| 664 | + | fs::write( | |
| 665 | + | tpl_dir.path().join("copier.yml"), | |
| 666 | + | r#" | |
| 667 | + | _min_copier_version: "9.0.0" | |
| 668 | + | _tasks: | |
| 669 | + | - "echo 'trusted {{ author }}' > ran.txt" | |
| 670 | + | author: | |
| 671 | + | type: str | |
| 672 | + | default: anonymous | |
| 673 | + | "#, | |
| 674 | + | ) | |
| 675 | + | .unwrap(); | |
| 676 | + | fs::write( | |
| 677 | + | tpl_dir.path().join("info.txt.jinja"), | |
| 678 | + | "author={{ author }}\nfolder={{ _folder_name }}\nop={{ _copier_operation }}\nunsafe={{ _copier_conf.unsafe }}\n", | |
| 679 | + | ) | |
| 680 | + | .unwrap(); | |
| 681 | + | ||
| 682 | + | let mut user_settings = UserSettings::default(); | |
| 683 | + | user_settings | |
| 684 | + | .defaults | |
| 685 | + | .insert("author".into(), json!("Jean")); | |
| 686 | + | user_settings | |
| 687 | + | .trust | |
| 688 | + | .push(format!("{}/", tpl_dir.path().parent().unwrap().display())); | |
| 689 | + | ||
| 690 | + | copy( | |
| 691 | + | tpl_dir.path().to_str().unwrap(), | |
| 692 | + | dst_dir.path(), | |
| 693 | + | &CopyOptions { | |
| 694 | + | defaults: true, | |
| 695 | + | trust: false, // Trusted via `user_settings.trust`! | |
| 696 | + | user_settings: Some(user_settings), | |
| 697 | + | ..CopyOptions::default() | |
| 698 | + | }, | |
| 699 | + | &NonInteractivePrompter, | |
| 700 | + | &NoopReporter, | |
| 701 | + | ) | |
| 702 | + | .unwrap(); | |
| 703 | + | ||
| 704 | + | let info = fs::read_to_string(dst_dir.path().join("info.txt")).unwrap(); | |
| 705 | + | let expected_folder = dst_dir.path().file_name().unwrap().to_str().unwrap(); | |
| 706 | + | assert!(info.contains("author=Jean\n"), "got:\n{info}"); | |
| 707 | + | assert!( | |
| 708 | + | info.contains(&format!("folder={expected_folder}\n")), | |
| 709 | + | "got:\n{info}" | |
| 710 | + | ); | |
| 711 | + | assert!(info.contains("op=copy\n"), "got:\n{info}"); | |
| 712 | + | assert!(info.contains("unsafe=True\n"), "got:\n{info}"); | |
| 713 | + | assert_eq!( | |
| 714 | + | fs::read_to_string(dst_dir.path().join("ran.txt")) | |
| 715 | + | .unwrap() | |
| 716 | + | .trim(), | |
| 717 | + | "trusted Jean" | |
| 718 | + | ); | |
| 719 | + | } | |
| 720 | + | ||
| 721 | + | #[test] | |
| 722 | + | fn update_with_current_vcs_ref_and_migration_stage() { | |
| 723 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 724 | + | let dst_dir = TempDir::new().unwrap(); | |
| 725 | + | ||
| 726 | + | init_git_repo(tpl_dir.path()); | |
| 727 | + | fs::write( | |
| 728 | + | tpl_dir.path().join("copier.yml"), | |
| 729 | + | r#" | |
| 730 | + | _migrations: | |
| 731 | + | - version: "2.0.0" | |
| 732 | + | when: "{{ _stage == 'before' }}" | |
| 733 | + | before: | |
| 734 | + | - "echo before >> migration.log" | |
| 735 | + | after: | |
| 736 | + | - "echo after >> migration.log" | |
| 737 | + | greeting: | |
| 738 | + | type: str | |
| 739 | + | default: hello | |
| 740 | + | "#, | |
| 741 | + | ) | |
| 742 | + | .unwrap(); | |
| 743 | + | fs::write(tpl_dir.path().join("msg.txt.jinja"), "{{ greeting }} v1\n").unwrap(); | |
| 744 | + | commit_all(tpl_dir.path(), "v1.0.0"); | |
| 745 | + | git(tpl_dir.path(), &["tag", "v1.0.0"]); | |
| 746 | + | ||
| 747 | + | copy( | |
| 748 | + | tpl_dir.path().to_str().unwrap(), | |
| 749 | + | dst_dir.path(), | |
| 750 | + | &CopyOptions { | |
| 751 | + | defaults: true, | |
| 752 | + | trust: true, | |
| 753 | + | ..CopyOptions::default() | |
| 754 | + | }, | |
| 755 | + | &NonInteractivePrompter, | |
| 756 | + | &NoopReporter, | |
| 757 | + | ) | |
| 758 | + | .unwrap(); | |
| 759 | + | init_git_repo(dst_dir.path()); | |
| 760 | + | commit_all(dst_dir.path(), "scaffold"); | |
| 761 | + | ||
| 762 | + | // Release v2.0.0 on the template, then update with `--vcs-ref :current:` to stay on v1.0.0 | |
| 763 | + | // while changing an answer. | |
| 764 | + | fs::write(tpl_dir.path().join("msg.txt.jinja"), "{{ greeting }} v2\n").unwrap(); | |
| 765 | + | commit_all(tpl_dir.path(), "v2.0.0"); | |
| 766 | + | git(tpl_dir.path(), &["tag", "v2.0.0"]); | |
| 767 | + | ||
| 768 | + | let mut data = IndexMap::new(); | |
| 769 | + | data.insert("greeting".into(), json!("bonjour")); | |
| 770 | + | let rep_current = update( | |
| 771 | + | dst_dir.path(), | |
| 772 | + | &CopyOptions { | |
| 773 | + | vcs_ref: Some(":current:".into()), | |
| 774 | + | data, | |
| 775 | + | defaults: true, | |
| 776 | + | trust: true, | |
| 777 | + | ..CopyOptions::default() | |
| 778 | + | }, | |
| 779 | + | &NonInteractivePrompter, | |
| 780 | + | &NoopReporter, | |
| 781 | + | ) | |
| 782 | + | .unwrap(); | |
| 783 | + | assert_eq!(rep_current.commit.as_deref(), Some("v1.0.0")); | |
| 784 | + | assert_eq!( | |
| 785 | + | fs::read_to_string(dst_dir.path().join("msg.txt")).unwrap(), | |
| 786 | + | "bonjour v1\n" | |
| 787 | + | ); | |
| 788 | + | commit_all(dst_dir.path(), "re-answered at current"); | |
| 789 | + | ||
| 790 | + | // Now upgrade to v2.0.0 and verify `_stage == 'before'` only ran the `before` stage! | |
| 791 | + | let rep_v2 = update( | |
| 792 | + | dst_dir.path(), | |
| 793 | + | &CopyOptions { | |
| 794 | + | defaults: true, | |
| 795 | + | trust: true, | |
| 796 | + | ..CopyOptions::default() | |
| 797 | + | }, | |
| 798 | + | &NonInteractivePrompter, | |
| 799 | + | &NoopReporter, | |
| 800 | + | ) | |
| 801 | + | .unwrap(); | |
| 802 | + | assert_eq!(rep_v2.commit.as_deref(), Some("v2.0.0")); | |
| 803 | + | assert_eq!( | |
| 804 | + | fs::read_to_string(dst_dir.path().join("msg.txt")).unwrap(), | |
| 805 | + | "bonjour v2\n" | |
| 806 | + | ); | |
| 807 | + | assert_eq!( | |
| 808 | + | fs::read_to_string(dst_dir.path().join("migration.log")) | |
| 809 | + | .unwrap() | |
| 810 | + | .trim(), | |
| 811 | + | "before" | |
| 812 | + | ); | |
| 813 | + | } | |
| 814 | + | ||
| 815 | + | #[test] | |
| 816 | + | fn interactive_overwrite_confirmation_respects_user_choice() { | |
| 817 | + | struct AlwaysYesPrompter; | |
| 818 | + | impl Prompter for AlwaysYesPrompter { | |
| 819 | + | fn prompt_string(&self, req: &PromptRequest) -> roneo_core::Result<String> { | |
| 820 | + | Ok(req.default_display.clone().unwrap_or_default()) | |
| 821 | + | } | |
| 822 | + | fn prompt_bool(&self, _req: &PromptRequest, default: bool) -> roneo_core::Result<bool> { | |
| 823 | + | Ok(default) | |
| 824 | + | } | |
| 825 | + | fn prompt_select( | |
| 826 | + | &self, | |
| 827 | + | _req: &PromptRequest, | |
| 828 | + | choices: &[roneo_core::config::ChoiceSpec], | |
| 829 | + | default_idx: Option<usize>, | |
| 830 | + | ) -> roneo_core::Result<serde_json::Value> { | |
| 831 | + | Ok(choices[default_idx.unwrap_or(0)].value.clone()) | |
| 832 | + | } | |
| 833 | + | fn prompt_multiselect( | |
| 834 | + | &self, | |
| 835 | + | _req: &PromptRequest, | |
| 836 | + | _choices: &[roneo_core::config::ChoiceSpec], | |
| 837 | + | _defaults: &[usize], | |
| 838 | + | ) -> roneo_core::Result<Vec<serde_json::Value>> { | |
| 839 | + | Ok(Vec::new()) | |
| 840 | + | } | |
| 841 | + | fn show_validation_error(&self, _question: &str, _error: &str) {} | |
| 842 | + | fn confirm_overwrite(&self, _path: &Path) -> roneo_core::Result<OverwriteChoice> { | |
| 843 | + | Ok(OverwriteChoice::Yes) | |
| 844 | + | } | |
| 845 | + | } | |
| 846 | + | ||
| 847 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 848 | + | let dst_dir = TempDir::new().unwrap(); | |
| 849 | + | ||
| 850 | + | fs::write(tpl_dir.path().join("copier.yml"), "name: new\n").unwrap(); | |
| 851 | + | fs::write( | |
| 852 | + | tpl_dir.path().join("file.txt.jinja"), | |
| 853 | + | "content={{ name }}\n", | |
| 854 | + | ) | |
| 855 | + | .unwrap(); | |
| 856 | + | fs::write(dst_dir.path().join("file.txt"), "old content\n").unwrap(); | |
| 857 | + | ||
| 858 | + | let mut data = IndexMap::new(); | |
| 859 | + | data.insert("name".into(), json!("updated")); | |
| 860 | + | ||
| 861 | + | let rep = copy( | |
| 862 | + | tpl_dir.path().to_str().unwrap(), | |
| 863 | + | dst_dir.path(), | |
| 864 | + | &CopyOptions { | |
| 865 | + | data, | |
| 866 | + | defaults: false, | |
| 867 | + | overwrite: false, | |
| 868 | + | ..CopyOptions::default() | |
| 869 | + | }, | |
| 870 | + | &AlwaysYesPrompter, | |
| 871 | + | &NoopReporter, | |
| 872 | + | ) | |
| 873 | + | .unwrap(); | |
| 874 | + | ||
| 875 | + | assert_eq!(rep.updated, 1); | |
| 876 | + | assert_eq!( | |
| 877 | + | fs::read_to_string(dst_dir.path().join("file.txt")).unwrap(), | |
| 878 | + | "content=updated\n" | |
| 879 | + | ); | |
| 880 | + | } | |
| 881 | + | ||
| 882 | + | #[test] | |
| 883 | + | fn include_glob_merges_list_settings_and_supports_templated_question_fields() { | |
| 884 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 885 | + | let dst_dir = TempDir::new().unwrap(); | |
| 886 | + | ||
| 887 | + | init_git_repo(tpl_dir.path()); | |
| 888 | + | fs::create_dir_all(tpl_dir.path().join("parts")).unwrap(); | |
| 889 | + | fs::write( | |
| 890 | + | tpl_dir.path().join("copier.yml"), | |
| 891 | + | r#" | |
| 892 | + | _exclude: | |
| 893 | + | - "parts" | |
| 894 | + | - "parts/**" | |
| 895 | + | - "drop1.txt" | |
| 896 | + | --- | |
| 897 | + | !include parts/*.yml | |
| 898 | + | "#, | |
| 899 | + | ) | |
| 900 | + | .unwrap(); | |
| 901 | + | fs::write( | |
| 902 | + | tpl_dir.path().join("parts/01_base.yml"), | |
| 903 | + | r#" | |
| 904 | + | _exclude: | |
| 905 | + | - "drop2.txt" | |
| 906 | + | use_int: | |
| 907 | + | type: bool | |
| 908 | + | default: true | |
| 909 | + | "#, | |
| 910 | + | ) | |
| 911 | + | .unwrap(); | |
| 912 | + | fs::write( | |
| 913 | + | tpl_dir.path().join("parts/02_dynamic.yml"), | |
| 914 | + | r#" | |
| 915 | + | dynamic_val: | |
| 916 | + | type: "{% if use_int %}int{% else %}str{% endif %}" | |
| 917 | + | default: "42" | |
| 918 | + | env_choice: | |
| 919 | + | type: str | |
| 920 | + | choices: "['dev', 'prod']" | |
| 921 | + | default: prod | |
| 922 | + | "#, | |
| 923 | + | ) | |
| 924 | + | .unwrap(); | |
| 925 | + | fs::write(tpl_dir.path().join("drop1.txt"), "excluded 1").unwrap(); | |
| 926 | + | fs::write(tpl_dir.path().join("drop2.txt"), "excluded 2").unwrap(); | |
| 927 | + | fs::write( | |
| 928 | + | tpl_dir.path().join("out.txt.jinja"), | |
| 929 | + | "val={{ dynamic_val + 1 }} env={{ env_choice }}\n", | |
| 930 | + | ) | |
| 931 | + | .unwrap(); | |
| 932 | + | commit_all(tpl_dir.path(), "v1.0.0"); | |
| 933 | + | git(tpl_dir.path(), &["tag", "v1.0.0"]); | |
| 934 | + | ||
| 935 | + | copy( | |
| 936 | + | tpl_dir.path().to_str().unwrap(), | |
| 937 | + | dst_dir.path(), | |
| 938 | + | &CopyOptions { | |
| 939 | + | defaults: true, | |
| 940 | + | ..CopyOptions::default() | |
| 941 | + | }, | |
| 942 | + | &NonInteractivePrompter, | |
| 943 | + | &NoopReporter, | |
| 944 | + | ) | |
| 945 | + | .unwrap(); | |
| 946 | + | ||
| 947 | + | // Both `_exclude` lists (root + `!include parts/01_base.yml`) were merged! | |
| 948 | + | assert!(!dst_dir.path().join("drop1.txt").exists()); | |
| 949 | + | assert!(!dst_dir.path().join("drop2.txt").exists()); | |
| 950 | + | // Dynamic `type: int` coerced "42" -> 42 so `dynamic_val + 1 == 43`! | |
| 951 | + | assert_eq!( | |
| 952 | + | fs::read_to_string(dst_dir.path().join("out.txt")).unwrap(), | |
| 953 | + | "val=43 env=prod\n" | |
| 954 | + | ); | |
| 955 | + | } | |
| 956 | + | ||
| 957 | + | #[test] | |
| 958 | + | fn copy_cleanup_on_error_respects_no_cleanup_flag() { | |
| 959 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 960 | + | let parent = TempDir::new().unwrap(); | |
| 961 | + | ||
| 962 | + | fs::write( | |
| 963 | + | tpl_dir.path().join("copier.yml"), | |
| 964 | + | r#" | |
| 965 | + | _tasks: | |
| 966 | + | - "exit 1" | |
| 967 | + | name: demo | |
| 968 | + | "#, | |
| 969 | + | ) | |
| 970 | + | .unwrap(); | |
| 971 | + | fs::write(tpl_dir.path().join("hello.txt.jinja"), "hi {{ name }}").unwrap(); | |
| 972 | + | ||
| 973 | + | // Default (`cleanup_on_error: true`): newly created destination is deleted on task failure. | |
| 974 | + | let dst_cleaned = parent.path().join("cleaned"); | |
| 975 | + | let err = copy( | |
| 976 | + | tpl_dir.path().to_str().unwrap(), | |
| 977 | + | &dst_cleaned, | |
| 978 | + | &CopyOptions { | |
| 979 | + | defaults: true, | |
| 980 | + | trust: true, | |
| 981 | + | cleanup_on_error: true, | |
| 982 | + | ..CopyOptions::default() | |
| 983 | + | }, | |
| 984 | + | &NonInteractivePrompter, | |
| 985 | + | &NoopReporter, | |
| 986 | + | ) | |
| 987 | + | .unwrap_err(); | |
| 988 | + | assert!(matches!(err, RoneoError::TaskFailed { .. })); | |
| 989 | + | assert!( | |
| 990 | + | !dst_cleaned.exists(), | |
| 991 | + | "destination should be cleaned up on error" | |
| 992 | + | ); | |
| 993 | + | ||
| 994 | + | // `--no-cleanup` (`cleanup_on_error: false`): destination is kept on failure. | |
| 995 | + | let dst_kept = parent.path().join("kept"); | |
| 996 | + | let err2 = copy( | |
| 997 | + | tpl_dir.path().to_str().unwrap(), | |
| 998 | + | &dst_kept, | |
| 999 | + | &CopyOptions { | |
| 1000 | + | defaults: true, | |
| 1001 | + | trust: true, | |
| 1002 | + | cleanup_on_error: false, | |
| 1003 | + | ..CopyOptions::default() | |
| 1004 | + | }, | |
| 1005 | + | &NonInteractivePrompter, | |
| 1006 | + | &NoopReporter, | |
| 1007 | + | ) | |
| 1008 | + | .unwrap_err(); | |
| 1009 | + | assert!(matches!(err2, RoneoError::TaskFailed { .. })); | |
| 1010 | + | assert!(dst_kept.join("hello.txt").exists()); | |
| 1011 | + | } | |
| 1012 | + | ||
| 1013 | + | #[test] | |
| 1014 | + | fn update_in_monorepo_subdir_honors_skip_if_exists_new_excludes_and_operation_env() { | |
| 1015 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 1016 | + | let monorepo = TempDir::new().unwrap(); | |
| 1017 | + | ||
| 1018 | + | // Template v1.0.0 | |
| 1019 | + | init_git_repo(tpl_dir.path()); | |
| 1020 | + | fs::write( | |
| 1021 | + | tpl_dir.path().join("copier.yml"), | |
| 1022 | + | r#" | |
| 1023 | + | _skip_if_exists: | |
| 1024 | + | - "local.env" | |
| 1025 | + | _tasks: | |
| 1026 | + | - "echo $COPIER_OPERATION > op.log" | |
| 1027 | + | name: svc | |
| 1028 | + | "#, | |
| 1029 | + | ) | |
| 1030 | + | .unwrap(); | |
| 1031 | + | fs::write(tpl_dir.path().join("app.txt.jinja"), "v1 {{ name }}\n").unwrap(); | |
| 1032 | + | fs::write(tpl_dir.path().join("local.env.jinja"), "SECRET=v1\n").unwrap(); | |
| 1033 | + | fs::write(tpl_dir.path().join("keep_me.txt"), "v1 keep\n").unwrap(); | |
| 1034 | + | commit_all(tpl_dir.path(), "v1.0.0"); | |
| 1035 | + | git(tpl_dir.path(), &["tag", "v1.0.0"]); | |
| 1036 | + | ||
| 1037 | + | // Scaffold into `services/my-svc` inside a Git monorepo | |
| 1038 | + | init_git_repo(monorepo.path()); | |
| 1039 | + | let subproject = monorepo.path().join("services/my-svc"); | |
| 1040 | + | copy( | |
| 1041 | + | tpl_dir.path().to_str().unwrap(), | |
| 1042 | + | &subproject, | |
| 1043 | + | &CopyOptions { | |
| 1044 | + | defaults: true, | |
| 1045 | + | trust: true, | |
| 1046 | + | ..CopyOptions::default() | |
| 1047 | + | }, | |
| 1048 | + | &NonInteractivePrompter, | |
| 1049 | + | &NoopReporter, | |
| 1050 | + | ) | |
| 1051 | + | .unwrap(); | |
| 1052 | + | assert_eq!( | |
| 1053 | + | fs::read_to_string(subproject.join("op.log")) | |
| 1054 | + | .unwrap() | |
| 1055 | + | .trim(), | |
| 1056 | + | "copy" | |
| 1057 | + | ); | |
| 1058 | + | // User customizes local.env | |
| 1059 | + | fs::write(subproject.join("local.env"), "SECRET=my-local-secret\n").unwrap(); | |
| 1060 | + | commit_all(monorepo.path(), "Initial monorepo commit"); | |
| 1061 | + | ||
| 1062 | + | // Template v2.0.0 updates app.txt & local.env, and adds keep_me.txt to `_exclude` | |
| 1063 | + | fs::write( | |
| 1064 | + | tpl_dir.path().join("copier.yml"), | |
| 1065 | + | r#" | |
| 1066 | + | _exclude: | |
| 1067 | + | - "keep_me.txt" | |
| 1068 | + | _skip_if_exists: | |
| 1069 | + | - "local.env" | |
| 1070 | + | _tasks: | |
| 1071 | + | - "echo $COPIER_OPERATION > op.log" | |
| 1072 | + | name: svc | |
| 1073 | + | "#, | |
| 1074 | + | ) | |
| 1075 | + | .unwrap(); | |
| 1076 | + | fs::write(tpl_dir.path().join("app.txt.jinja"), "v2 {{ name }}\n").unwrap(); | |
| 1077 | + | fs::write(tpl_dir.path().join("local.env.jinja"), "SECRET=v2\n").unwrap(); | |
| 1078 | + | commit_all(tpl_dir.path(), "v2.0.0"); | |
| 1079 | + | git(tpl_dir.path(), &["tag", "v2.0.0"]); | |
| 1080 | + | ||
| 1081 | + | let report = update( | |
| 1082 | + | &subproject, | |
| 1083 | + | &CopyOptions { | |
| 1084 | + | defaults: true, | |
| 1085 | + | trust: true, | |
| 1086 | + | context_lines: 2, | |
| 1087 | + | ..CopyOptions::default() | |
| 1088 | + | }, | |
| 1089 | + | &NonInteractivePrompter, | |
| 1090 | + | &NoopReporter, | |
| 1091 | + | ) | |
| 1092 | + | .unwrap(); | |
| 1093 | + | ||
| 1094 | + | assert!( | |
| 1095 | + | report.conflicts.is_empty(), | |
| 1096 | + | "Unexpected conflicts: {:?}", | |
| 1097 | + | report.conflicts | |
| 1098 | + | ); | |
| 1099 | + | assert_eq!(report.commit.as_deref(), Some("v2.0.0")); | |
| 1100 | + | assert_eq!( | |
| 1101 | + | fs::read_to_string(subproject.join("app.txt")).unwrap(), | |
| 1102 | + | "v2 svc\n" | |
| 1103 | + | ); | |
| 1104 | + | // `_skip_if_exists` prevented `local.env` from being overwritten on update! | |
| 1105 | + | assert_eq!( | |
| 1106 | + | fs::read_to_string(subproject.join("local.env")).unwrap(), | |
| 1107 | + | "SECRET=my-local-secret\n" | |
| 1108 | + | ); | |
| 1109 | + | // Newly excluded `keep_me.txt` was NOT deleted from the user's subproject! | |
| 1110 | + | assert!(subproject.join("keep_me.txt").exists()); | |
| 1111 | + | // Task received `COPIER_OPERATION=update`! | |
| 1112 | + | assert_eq!( | |
| 1113 | + | fs::read_to_string(subproject.join("op.log")) | |
| 1114 | + | .unwrap() | |
| 1115 | + | .trim(), | |
| 1116 | + | "update" | |
| 1117 | + | ); | |
| 1118 | + | } | |
| 1119 | + | ||
| 1120 | + | #[test] | |
| 1121 | + | fn yield_tag_expands_nested_dirs_and_files_on_disk_and_git_tree() { | |
| 1122 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 1123 | + | let dst_disk = TempDir::new().unwrap(); | |
| 1124 | + | let dst_git = TempDir::new().unwrap(); | |
| 1125 | + | ||
| 1126 | + | fs::write( | |
| 1127 | + | tpl_dir.path().join("copier.yml"), | |
| 1128 | + | r" | |
| 1129 | + | services: | |
| 1130 | + | type: yaml | |
| 1131 | + | default: | |
| 1132 | + | - auth | |
| 1133 | + | - billing | |
| 1134 | + | envs: | |
| 1135 | + | type: yaml | |
| 1136 | + | default: | |
| 1137 | + | - dev | |
| 1138 | + | - prod | |
| 1139 | + | ", | |
| 1140 | + | ) | |
| 1141 | + | .unwrap(); | |
| 1142 | + | ||
| 1143 | + | let nested_dir = tpl_dir | |
| 1144 | + | .path() | |
| 1145 | + | .join("{% yield svc from services %}{{ svc }}{% endyield %}"); | |
| 1146 | + | fs::create_dir_all(&nested_dir).unwrap(); | |
| 1147 | + | fs::write( | |
| 1148 | + | nested_dir.join("{% yield env from envs %}{{ env }}.yml{% endyield %}.jinja"), | |
| 1149 | + | "service: {{ svc }}\nenv: {{ env }}\n", | |
| 1150 | + | ) | |
| 1151 | + | .unwrap(); | |
| 1152 | + | ||
| 1153 | + | // 1. Disk-backed template | |
| 1154 | + | copy( | |
| 1155 | + | tpl_dir.path().to_str().unwrap(), | |
| 1156 | + | dst_disk.path(), | |
| 1157 | + | &CopyOptions { | |
| 1158 | + | defaults: true, | |
| 1159 | + | ..CopyOptions::default() | |
| 1160 | + | }, | |
| 1161 | + | &NonInteractivePrompter, | |
| 1162 | + | &NoopReporter, | |
| 1163 | + | ) | |
| 1164 | + | .unwrap(); | |
| 1165 | + | ||
| 1166 | + | for svc in ["auth", "billing"] { | |
| 1167 | + | for env in ["dev", "prod"] { | |
| 1168 | + | let content = | |
| 1169 | + | fs::read_to_string(dst_disk.path().join(format!("{svc}/{env}.yml"))).unwrap(); | |
| 1170 | + | assert_eq!(content, format!("service: {svc}\nenv: {env}\n")); | |
| 1171 | + | } | |
| 1172 | + | } | |
| 1173 | + | ||
| 1174 | + | // 2. GitTree-backed (in-memory gix) template | |
| 1175 | + | init_git_repo(tpl_dir.path()); | |
| 1176 | + | commit_all(tpl_dir.path(), "v1.0.0"); | |
| 1177 | + | git(tpl_dir.path(), &["tag", "v1.0.0"]); | |
| 1178 | + | ||
| 1179 | + | copy( | |
| 1180 | + | tpl_dir.path().to_str().unwrap(), | |
| 1181 | + | dst_git.path(), | |
| 1182 | + | &CopyOptions { | |
| 1183 | + | defaults: true, | |
| 1184 | + | ..CopyOptions::default() | |
| 1185 | + | }, | |
| 1186 | + | &NonInteractivePrompter, | |
| 1187 | + | &NoopReporter, | |
| 1188 | + | ) | |
| 1189 | + | .unwrap(); | |
| 1190 | + | ||
| 1191 | + | for svc in ["auth", "billing"] { | |
| 1192 | + | for env in ["dev", "prod"] { | |
| 1193 | + | let content = | |
| 1194 | + | fs::read_to_string(dst_git.path().join(format!("{svc}/{env}.yml"))).unwrap(); | |
| 1195 | + | assert_eq!(content, format!("service: {svc}\nenv: {env}\n")); | |
| 1196 | + | } | |
| 1197 | + | } | |
| 1198 | + | } | |
| 1199 | + | ||
| 1200 | + | #[test] | |
| 1201 | + | fn extra_jinja_filters_task_extra_env_old_template_warning_and_git_bundle() { | |
| 1202 | + | use std::sync::Mutex; | |
| 1203 | + | struct CaptureReporter(Mutex<Vec<String>>); | |
| 1204 | + | impl roneo_core::Reporter for CaptureReporter { | |
| 1205 | + | fn emit(&self, event: roneo_core::ActionEvent) { | |
| 1206 | + | if let roneo_core::ActionEvent::Warning(w) = event { | |
| 1207 | + | self.0.lock().unwrap().push(w); | |
| 1208 | + | } | |
| 1209 | + | } | |
| 1210 | + | } | |
| 1211 | + | ||
| 1212 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 1213 | + | let bundle_dir = TempDir::new().unwrap(); | |
| 1214 | + | let dst_dir = TempDir::new().unwrap(); | |
| 1215 | + | ||
| 1216 | + | init_git_repo(tpl_dir.path()); | |
| 1217 | + | fs::write( | |
| 1218 | + | tpl_dir.path().join("copier.yml"), | |
| 1219 | + | r#" | |
| 1220 | + | _min_copier_version: "8.0.0" | |
| 1221 | + | _tasks: | |
| 1222 | + | - command: "echo $CUSTOM_TAG > env.txt" | |
| 1223 | + | extra_env: | |
| 1224 | + | CUSTOM_TAG: "hello-{{ label | to_snake }}" | |
| 1225 | + | label: | |
| 1226 | + | type: str | |
| 1227 | + | default: "MySuperService" | |
| 1228 | + | qmark: "🚀" | |
| 1229 | + | "#, | |
| 1230 | + | ) | |
| 1231 | + | .unwrap(); | |
| 1232 | + | fs::write( | |
| 1233 | + | tpl_dir.path().join("filters.txt.jinja"), | |
| 1234 | + | r#"snake={{ label | to_snake }} | |
| 1235 | + | kebab={{ label | to_kebab }} | |
| 1236 | + | camel={{ label | to_camel }} | |
| 1237 | + | pascal={{ "my_super_service" | to_pascal }} | |
| 1238 | + | b64={{ "roneo!" | b64encode }} | |
| 1239 | + | dec={{ "cm9uZW8h" | b64decode }} | |
| 1240 | + | year_len={{ now("%Y") | length }} | |
| 1241 | + | "#, | |
| 1242 | + | ) | |
| 1243 | + | .unwrap(); | |
| 1244 | + | commit_all(tpl_dir.path(), "v1.0.0"); | |
| 1245 | + | git(tpl_dir.path(), &["tag", "v1.0.0"]); | |
| 1246 | + | ||
| 1247 | + | // Export as a `.bundle` file and copy directly from the git bundle! | |
| 1248 | + | let bundle_path = bundle_dir.path().join("tpl.bundle"); | |
| 1249 | + | git( | |
| 1250 | + | tpl_dir.path(), | |
| 1251 | + | &["bundle", "create", bundle_path.to_str().unwrap(), "--all"], | |
| 1252 | + | ); | |
| 1253 | + | ||
| 1254 | + | let reporter = CaptureReporter(Mutex::new(Vec::new())); | |
| 1255 | + | copy( | |
| 1256 | + | bundle_path.to_str().unwrap(), | |
| 1257 | + | dst_dir.path(), | |
| 1258 | + | &CopyOptions { | |
| 1259 | + | defaults: true, | |
| 1260 | + | trust: true, | |
| 1261 | + | ..CopyOptions::default() | |
| 1262 | + | }, | |
| 1263 | + | &NonInteractivePrompter, | |
| 1264 | + | &reporter, | |
| 1265 | + | ) | |
| 1266 | + | .unwrap(); | |
| 1267 | + | ||
| 1268 | + | let rendered = fs::read_to_string(dst_dir.path().join("filters.txt")).unwrap(); | |
| 1269 | + | assert!( | |
| 1270 | + | rendered.contains("snake=my_super_service\n"), | |
| 1271 | + | "got:\n{rendered}" | |
| 1272 | + | ); | |
| 1273 | + | assert!( | |
| 1274 | + | rendered.contains("kebab=my-super-service\n"), | |
| 1275 | + | "got:\n{rendered}" | |
| 1276 | + | ); | |
| 1277 | + | assert!( | |
| 1278 | + | rendered.contains("camel=mySuperService\n"), | |
| 1279 | + | "got:\n{rendered}" | |
| 1280 | + | ); | |
| 1281 | + | assert!( | |
| 1282 | + | rendered.contains("pascal=MySuperService\n"), | |
| 1283 | + | "got:\n{rendered}" | |
| 1284 | + | ); | |
| 1285 | + | assert!(rendered.contains("b64=cm9uZW8h\n"), "got:\n{rendered}"); | |
| 1286 | + | assert!(rendered.contains("dec=roneo!\n"), "got:\n{rendered}"); | |
| 1287 | + | assert!(rendered.contains("year_len=4\n"), "got:\n{rendered}"); | |
| 1288 | + | ||
| 1289 | + | assert_eq!( | |
| 1290 | + | fs::read_to_string(dst_dir.path().join("env.txt")) | |
| 1291 | + | .unwrap() | |
| 1292 | + | .trim(), | |
| 1293 | + | "hello-my_super_service" | |
| 1294 | + | ); | |
| 1295 | + | ||
| 1296 | + | let warnings = reporter.0.lock().unwrap(); | |
| 1297 | + | assert!( | |
| 1298 | + | warnings.iter().any(|w| w.contains("older Copier 8.0.0")), | |
| 1299 | + | "expected OldTemplateWarning, got: {warnings:?}" | |
| 1300 | + | ); | |
| 1301 | + | } | |
| 1302 | + | ||
| 1303 | + | #[test] | |
| 1304 | + | fn update_never_conflicts_on_answers_file_when_user_edits_header() { | |
| 1305 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 1306 | + | let dst_dir = TempDir::new().unwrap(); | |
| 1307 | + | ||
| 1308 | + | init_git_repo(tpl_dir.path()); | |
| 1309 | + | fs::write(tpl_dir.path().join("copier.yml"), "name: demo\n").unwrap(); | |
| 1310 | + | fs::write(tpl_dir.path().join("f.txt.jinja"), "v1 {{ name }}\n").unwrap(); | |
| 1311 | + | commit_all(tpl_dir.path(), "v1.0.0"); | |
| 1312 | + | git(tpl_dir.path(), &["tag", "v1.0.0"]); | |
| 1313 | + | ||
| 1314 | + | copy( | |
| 1315 | + | tpl_dir.path().to_str().unwrap(), | |
| 1316 | + | dst_dir.path(), | |
| 1317 | + | &CopyOptions { | |
| 1318 | + | defaults: true, | |
| 1319 | + | ..CopyOptions::default() | |
| 1320 | + | }, | |
| 1321 | + | &NonInteractivePrompter, | |
| 1322 | + | &NoopReporter, | |
| 1323 | + | ) | |
| 1324 | + | .unwrap(); | |
| 1325 | + | init_git_repo(dst_dir.path()); | |
| 1326 | + | commit_all(dst_dir.path(), "init"); | |
| 1327 | + | ||
| 1328 | + | // User modifies the comment line in `.copier-answers.yml` (classic cause of false conflict if patched). | |
| 1329 | + | let answers_path = dst_dir.path().join(".copier-answers.yml"); | |
| 1330 | + | let raw = fs::read_to_string(&answers_path).unwrap(); | |
| 1331 | + | fs::write(&answers_path, format!("# custom user comment\n{raw}")).unwrap(); | |
| 1332 | + | commit_all(dst_dir.path(), "user edited answers comment"); | |
| 1333 | + | ||
| 1334 | + | fs::write(tpl_dir.path().join("f.txt.jinja"), "v2 {{ name }}\n").unwrap(); | |
| 1335 | + | commit_all(tpl_dir.path(), "v2.0.0"); | |
| 1336 | + | git(tpl_dir.path(), &["tag", "v2.0.0"]); | |
| 1337 | + | ||
| 1338 | + | let rep = update( | |
| 1339 | + | dst_dir.path(), | |
| 1340 | + | &CopyOptions { | |
| 1341 | + | defaults: true, | |
| 1342 | + | ..CopyOptions::default() | |
| 1343 | + | }, | |
| 1344 | + | &NonInteractivePrompter, | |
| 1345 | + | &NoopReporter, | |
| 1346 | + | ) | |
| 1347 | + | .unwrap(); | |
| 1348 | + | assert!( | |
| 1349 | + | rep.conflicts.is_empty(), | |
| 1350 | + | "Answers file must not conflict during update, got: {:?}", | |
| 1351 | + | rep.conflicts | |
| 1352 | + | ); | |
| 1353 | + | let updated_answers = AnswersMap::load(&answers_path).unwrap(); | |
| 1354 | + | assert_eq!(updated_answers.commit(), Some("v2.0.0")); | |
| 1355 | + | } | |
| 1356 | + | ||
| 1357 | + | #[test] | |
| 1358 | + | fn update_inline_conflict_works_after_git_history_squash() { | |
| 1359 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 1360 | + | let dst_dir = TempDir::new().unwrap(); | |
| 1361 | + | ||
| 1362 | + | init_git_repo(tpl_dir.path()); | |
| 1363 | + | fs::write(tpl_dir.path().join("copier.yml"), "name: app\n").unwrap(); | |
| 1364 | + | fs::write(tpl_dir.path().join("config.txt.jinja"), "port=8080\n").unwrap(); | |
| 1365 | + | commit_all(tpl_dir.path(), "v1.0.0"); | |
| 1366 | + | git(tpl_dir.path(), &["tag", "v1.0.0"]); | |
| 1367 | + | ||
| 1368 | + | copy( | |
| 1369 | + | tpl_dir.path().to_str().unwrap(), | |
| 1370 | + | dst_dir.path(), | |
| 1371 | + | &CopyOptions { | |
| 1372 | + | defaults: true, | |
| 1373 | + | ..CopyOptions::default() | |
| 1374 | + | }, | |
| 1375 | + | &NonInteractivePrompter, | |
| 1376 | + | &NoopReporter, | |
| 1377 | + | ) | |
| 1378 | + | .unwrap(); | |
| 1379 | + | ||
| 1380 | + | // User edits config.txt BEFORE initializing git (simulating a squashed history where | |
| 1381 | + | // the original v1.0.0 blob OID does NOT exist in destination `.git/objects`!). | |
| 1382 | + | fs::write(dst_dir.path().join("config.txt"), "port=9090\n").unwrap(); | |
| 1383 | + | init_git_repo(dst_dir.path()); | |
| 1384 | + | commit_all(dst_dir.path(), "squashed initial commit"); | |
| 1385 | + | ||
| 1386 | + | // Upstream v2.0.0 changes same line differently | |
| 1387 | + | fs::write(tpl_dir.path().join("config.txt.jinja"), "port=3000\n").unwrap(); | |
| 1388 | + | commit_all(tpl_dir.path(), "v2.0.0"); | |
| 1389 | + | git(tpl_dir.path(), &["tag", "v2.0.0"]); | |
| 1390 | + | ||
| 1391 | + | let report = update( | |
| 1392 | + | dst_dir.path(), | |
| 1393 | + | &CopyOptions { | |
| 1394 | + | defaults: true, | |
| 1395 | + | conflict_mode: ConflictMode::Inline, | |
| 1396 | + | ..CopyOptions::default() | |
| 1397 | + | }, | |
| 1398 | + | &NonInteractivePrompter, | |
| 1399 | + | &NoopReporter, | |
| 1400 | + | ) | |
| 1401 | + | .unwrap(); | |
| 1402 | + | ||
| 1403 | + | assert_eq!(report.conflicts, vec!["config.txt"]); | |
| 1404 | + | assert!(!dst_dir.path().join("config.txt.rej").exists()); | |
| 1405 | + | let content = fs::read_to_string(dst_dir.path().join("config.txt")).unwrap(); | |
| 1406 | + | assert!( | |
| 1407 | + | content.contains("<<<<<<< before updating"), | |
| 1408 | + | "got:\n{content}" | |
| 1409 | + | ); | |
| 1410 | + | assert!(content.contains("port=9090"), "got:\n{content}"); | |
| 1411 | + | assert!(content.contains("port=3000"), "got:\n{content}"); | |
| 1412 | + | assert!( | |
| 1413 | + | content.contains(">>>>>>> after updating"), | |
| 1414 | + | "got:\n{content}" | |
| 1415 | + | ); | |
| 1416 | + | } | |
| 1417 | + | ||
| 1418 | + | #[test] | |
| 1419 | + | fn update_protects_gitignored_files_blocks_downgrades_and_cleans_renamed_answers_file() { | |
| 1420 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 1421 | + | let dst_dir = TempDir::new().unwrap(); | |
| 1422 | + | ||
| 1423 | + | init_git_repo(tpl_dir.path()); | |
| 1424 | + | fs::write(tpl_dir.path().join("copier.yml"), "name: demo\n").unwrap(); | |
| 1425 | + | fs::write(tpl_dir.path().join("app.txt.jinja"), "v1 {{ name }}\n").unwrap(); | |
| 1426 | + | fs::write(tpl_dir.path().join("local.secret.jinja"), "SECRET=v1\n").unwrap(); | |
| 1427 | + | commit_all(tpl_dir.path(), "v1.0.0"); | |
| 1428 | + | git(tpl_dir.path(), &["tag", "v1.0.0"]); | |
| 1429 | + | ||
| 1430 | + | copy( | |
| 1431 | + | tpl_dir.path().to_str().unwrap(), | |
| 1432 | + | dst_dir.path(), | |
| 1433 | + | &CopyOptions { | |
| 1434 | + | defaults: true, | |
| 1435 | + | ..CopyOptions::default() | |
| 1436 | + | }, | |
| 1437 | + | &NonInteractivePrompter, | |
| 1438 | + | &NoopReporter, | |
| 1439 | + | ) | |
| 1440 | + | .unwrap(); | |
| 1441 | + | // User gitignores `local.secret` and puts a private value in it. | |
| 1442 | + | fs::write(dst_dir.path().join(".gitignore"), "local.secret\n").unwrap(); | |
| 1443 | + | init_git_repo(dst_dir.path()); | |
| 1444 | + | commit_all(dst_dir.path(), "init"); | |
| 1445 | + | fs::write(dst_dir.path().join("local.secret"), "SECRET=user-ignored\n").unwrap(); | |
| 1446 | + | ||
| 1447 | + | // Template v2.0.0 renames `_answers_file` and modifies both `app.txt` and `local.secret`. | |
| 1448 | + | fs::write( | |
| 1449 | + | tpl_dir.path().join("copier.yml"), | |
| 1450 | + | "_answers_file: .config/answers.yml\nname: demo\n", | |
| 1451 | + | ) | |
| 1452 | + | .unwrap(); | |
| 1453 | + | fs::write(tpl_dir.path().join("app.txt.jinja"), "v2 {{ name }}\n").unwrap(); | |
| 1454 | + | fs::write(tpl_dir.path().join("local.secret.jinja"), "SECRET=v2\n").unwrap(); | |
| 1455 | + | commit_all(tpl_dir.path(), "v2.0.0"); | |
| 1456 | + | git(tpl_dir.path(), &["tag", "v2.0.0"]); | |
| 1457 | + | ||
| 1458 | + | let rep = update( | |
| 1459 | + | dst_dir.path(), | |
| 1460 | + | &CopyOptions { | |
| 1461 | + | defaults: true, | |
| 1462 | + | ..CopyOptions::default() | |
| 1463 | + | }, | |
| 1464 | + | &NonInteractivePrompter, | |
| 1465 | + | &NoopReporter, | |
| 1466 | + | ) | |
| 1467 | + | .unwrap(); | |
| 1468 | + | assert!( | |
| 1469 | + | rep.conflicts.is_empty(), | |
| 1470 | + | "Unexpected conflicts: {:?}", | |
| 1471 | + | rep.conflicts | |
| 1472 | + | ); | |
| 1473 | + | assert_eq!( | |
| 1474 | + | fs::read_to_string(dst_dir.path().join("app.txt")).unwrap(), | |
| 1475 | + | "v2 demo\n" | |
| 1476 | + | ); | |
| 1477 | + | // `.gitignore`-d `local.secret` was untouched! | |
| 1478 | + | assert_eq!( | |
| 1479 | + | fs::read_to_string(dst_dir.path().join("local.secret")).unwrap(), | |
| 1480 | + | "SECRET=user-ignored\n" | |
| 1481 | + | ); | |
| 1482 | + | // Old `.copier-answers.yml` cleaned up and replaced by `.config/answers.yml`! | |
| 1483 | + | assert!(!dst_dir.path().join(".copier-answers.yml").exists()); | |
| 1484 | + | assert!(dst_dir.path().join(".config/answers.yml").is_file()); | |
| 1485 | + | ||
| 1486 | + | commit_all(dst_dir.path(), "upgraded to v2.0.0"); | |
| 1487 | + | ||
| 1488 | + | // Attempting to downgrade from v2.0.0 -> v1.0.0 must be rejected! | |
| 1489 | + | let err = update( | |
| 1490 | + | dst_dir.path(), | |
| 1491 | + | &CopyOptions { | |
| 1492 | + | answers_file: Some(".config/answers.yml".into()), | |
| 1493 | + | vcs_ref: Some("v1.0.0".into()), | |
| 1494 | + | defaults: true, | |
| 1495 | + | ..CopyOptions::default() | |
| 1496 | + | }, | |
| 1497 | + | &NonInteractivePrompter, | |
| 1498 | + | &NoopReporter, | |
| 1499 | + | ) | |
| 1500 | + | .unwrap_err(); | |
| 1501 | + | assert!(matches!(err, RoneoError::DowngradeNotSupported { .. })); | |
| 1502 | + | } | |
| 1503 | + | ||
| 1504 | + | #[test] | |
| 1505 | + | fn task_stage_context_and_nullable_typed_defaults() { | |
| 1506 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 1507 | + | let dst_dir = TempDir::new().unwrap(); | |
| 1508 | + | ||
| 1509 | + | fs::write( | |
| 1510 | + | tpl_dir.path().join("copier.yml"), | |
| 1511 | + | r#" | |
| 1512 | + | _tasks: | |
| 1513 | + | - command: "echo {{ _stage }}:$STAGE > stage.txt" | |
| 1514 | + | when: "{{ _stage == 'task' }}" | |
| 1515 | + | opt_int: | |
| 1516 | + | type: int | |
| 1517 | + | default: null | |
| 1518 | + | opt_float: | |
| 1519 | + | type: float | |
| 1520 | + | default: null | |
| 1521 | + | opt_bool: | |
| 1522 | + | type: bool | |
| 1523 | + | default: null | |
| 1524 | + | "#, | |
| 1525 | + | ) | |
| 1526 | + | .unwrap(); | |
| 1527 | + | fs::write( | |
| 1528 | + | tpl_dir.path().join("vals.txt.jinja"), | |
| 1529 | + | "int={{ opt_int is none }} float={{ opt_float is none }} bool={{ opt_bool is none }}\n", | |
| 1530 | + | ) | |
| 1531 | + | .unwrap(); | |
| 1532 | + | ||
| 1533 | + | copy( | |
| 1534 | + | tpl_dir.path().to_str().unwrap(), | |
| 1535 | + | dst_dir.path(), | |
| 1536 | + | &CopyOptions { | |
| 1537 | + | defaults: true, | |
| 1538 | + | trust: true, | |
| 1539 | + | ..CopyOptions::default() | |
| 1540 | + | }, | |
| 1541 | + | &NonInteractivePrompter, | |
| 1542 | + | &NoopReporter, | |
| 1543 | + | ) | |
| 1544 | + | .unwrap(); | |
| 1545 | + | ||
| 1546 | + | assert_eq!( | |
| 1547 | + | fs::read_to_string(dst_dir.path().join("stage.txt")) | |
| 1548 | + | .unwrap() | |
| 1549 | + | .trim(), | |
| 1550 | + | "task:task" | |
| 1551 | + | ); | |
| 1552 | + | assert_eq!( | |
| 1553 | + | fs::read_to_string(dst_dir.path().join("vals.txt")).unwrap(), | |
| 1554 | + | "int=True float=True bool=True\n" | |
| 1555 | + | ); | |
| 1556 | + | let answers = AnswersMap::load(&dst_dir.path().join(".copier-answers.yml")).unwrap(); | |
| 1557 | + | assert_eq!(answers.user.get("opt_int"), Some(&json!(null))); | |
| 1558 | + | assert_eq!(answers.user.get("opt_float"), Some(&json!(null))); | |
| 1559 | + | assert_eq!(answers.user.get("opt_bool"), Some(&json!(null))); | |
| 1560 | + | } | |
| 1561 | + | ||
| 1562 | + | #[test] | |
| 1563 | + | fn check_update_reports_available_updates_and_respects_prereleases() { | |
| 1564 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 1565 | + | let dst_dir = TempDir::new().unwrap(); | |
| 1566 | + | ||
| 1567 | + | init_git_repo(tpl_dir.path()); | |
| 1568 | + | fs::write(tpl_dir.path().join("copier.yml"), "name: demo\n").unwrap(); | |
| 1569 | + | fs::write(tpl_dir.path().join("app.txt.jinja"), "v1 {{ name }}\n").unwrap(); | |
| 1570 | + | commit_all(tpl_dir.path(), "v1.0.0"); | |
| 1571 | + | git(tpl_dir.path(), &["tag", "v1.0.0"]); | |
| 1572 | + | ||
| 1573 | + | copy( | |
| 1574 | + | tpl_dir.path().to_str().unwrap(), | |
| 1575 | + | dst_dir.path(), | |
| 1576 | + | &CopyOptions { | |
| 1577 | + | defaults: true, | |
| 1578 | + | ..CopyOptions::default() | |
| 1579 | + | }, | |
| 1580 | + | &NonInteractivePrompter, | |
| 1581 | + | &NoopReporter, | |
| 1582 | + | ) | |
| 1583 | + | .unwrap(); | |
| 1584 | + | ||
| 1585 | + | // Up-to-date on v1.0.0 | |
| 1586 | + | let rep = check_update(dst_dir.path(), &CopyOptions::default()).unwrap(); | |
| 1587 | + | assert!(!rep.update_available); | |
| 1588 | + | assert_eq!(rep.current_version, "v1.0.0"); | |
| 1589 | + | assert_eq!(rep.latest_version, "v1.0.0"); | |
| 1590 | + | ||
| 1591 | + | // Tag a prerelease v2.0.0rc1 | |
| 1592 | + | fs::write(tpl_dir.path().join("app.txt.jinja"), "v2rc1 {{ name }}\n").unwrap(); | |
| 1593 | + | commit_all(tpl_dir.path(), "v2.0.0rc1"); | |
| 1594 | + | git(tpl_dir.path(), &["tag", "v2.0.0rc1"]); | |
| 1595 | + | ||
| 1596 | + | let rep_stable = check_update(dst_dir.path(), &CopyOptions::default()).unwrap(); | |
| 1597 | + | assert!(!rep_stable.update_available); | |
| 1598 | + | assert_eq!(rep_stable.latest_version, "v1.0.0"); | |
| 1599 | + | ||
| 1600 | + | let rep_pre = check_update( | |
| 1601 | + | dst_dir.path(), | |
| 1602 | + | &CopyOptions { | |
| 1603 | + | use_prereleases: true, | |
| 1604 | + | ..CopyOptions::default() | |
| 1605 | + | }, | |
| 1606 | + | ) | |
| 1607 | + | .unwrap(); | |
| 1608 | + | assert!(rep_pre.update_available); | |
| 1609 | + | assert_eq!(rep_pre.current_version, "v1.0.0"); | |
| 1610 | + | assert_eq!(rep_pre.latest_version, "v2.0.0rc1"); | |
| 1611 | + | ||
| 1612 | + | // Tag stable v2.0.0 | |
| 1613 | + | fs::write(tpl_dir.path().join("app.txt.jinja"), "v2 {{ name }}\n").unwrap(); | |
| 1614 | + | commit_all(tpl_dir.path(), "v2.0.0"); | |
| 1615 | + | git(tpl_dir.path(), &["tag", "v2.0.0"]); | |
| 1616 | + | ||
| 1617 | + | let rep_v2 = check_update(dst_dir.path(), &CopyOptions::default()).unwrap(); | |
| 1618 | + | assert!(rep_v2.update_available); | |
| 1619 | + | assert_eq!(rep_v2.current_version, "v1.0.0"); | |
| 1620 | + | assert_eq!(rep_v2.latest_version, "v2.0.0"); | |
| 1621 | + | } | |
| 1622 | + | ||
| 1623 | + | #[test] | |
| 1624 | + | fn question_ask_attribute_and_cli_ask_flag_override() { | |
| 1625 | + | use std::sync::Mutex; | |
| 1626 | + | ||
| 1627 | + | struct RecordingPrompter { | |
| 1628 | + | asked: Mutex<Vec<String>>, | |
| 1629 | + | } | |
| 1630 | + | impl Prompter for RecordingPrompter { | |
| 1631 | + | fn prompt_string(&self, req: &PromptRequest) -> roneo_core::Result<String> { | |
| 1632 | + | self.asked.lock().unwrap().push(req.name.clone()); | |
| 1633 | + | Ok(format!("prompted-{}", req.name)) | |
| 1634 | + | } | |
| 1635 | + | ||
| 1636 | + | fn prompt_bool(&self, req: &PromptRequest, default: bool) -> roneo_core::Result<bool> { | |
| 1637 | + | self.asked.lock().unwrap().push(req.name.clone()); | |
| 1638 | + | Ok(default) | |
| 1639 | + | } | |
| 1640 | + | ||
| 1641 | + | fn prompt_select( | |
| 1642 | + | &self, | |
| 1643 | + | req: &PromptRequest, | |
| 1644 | + | choices: &[roneo_core::config::ChoiceSpec], | |
| 1645 | + | default_idx: Option<usize>, | |
| 1646 | + | ) -> roneo_core::Result<serde_json::Value> { | |
| 1647 | + | self.asked.lock().unwrap().push(req.name.clone()); | |
| 1648 | + | Ok(choices[default_idx.unwrap_or(0)].value.clone()) | |
| 1649 | + | } | |
| 1650 | + | ||
| 1651 | + | fn prompt_multiselect( | |
| 1652 | + | &self, | |
| 1653 | + | req: &PromptRequest, | |
| 1654 | + | _choices: &[roneo_core::config::ChoiceSpec], | |
| 1655 | + | _defaults: &[usize], | |
| 1656 | + | ) -> roneo_core::Result<Vec<serde_json::Value>> { | |
| 1657 | + | self.asked.lock().unwrap().push(req.name.clone()); | |
| 1658 | + | Ok(Vec::new()) | |
| 1659 | + | } | |
| 1660 | + | ||
| 1661 | + | fn show_validation_error(&self, _name: &str, _message: &str) {} | |
| 1662 | + | } | |
| 1663 | + | ||
| 1664 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 1665 | + | let dst_dir = TempDir::new().unwrap(); | |
| 1666 | + | ||
| 1667 | + | fs::write( | |
| 1668 | + | tpl_dir.path().join("copier.yml"), | |
| 1669 | + | r#" | |
| 1670 | + | project: | |
| 1671 | + | type: str | |
| 1672 | + | default: default-proj | |
| 1673 | + | silent_token: | |
| 1674 | + | type: str | |
| 1675 | + | default: auto-token | |
| 1676 | + | ask: false | |
| 1677 | + | conditional_field: | |
| 1678 | + | type: str | |
| 1679 | + | default: auto-cond | |
| 1680 | + | ask: "{{ project == 'custom' }}" | |
| 1681 | + | "#, | |
| 1682 | + | ) | |
| 1683 | + | .unwrap(); | |
| 1684 | + | fs::write( | |
| 1685 | + | tpl_dir.path().join("out.txt.jinja"), | |
| 1686 | + | "{{ project }}|{{ silent_token }}|{{ conditional_field }}\n", | |
| 1687 | + | ) | |
| 1688 | + | .unwrap(); | |
| 1689 | + | ||
| 1690 | + | // 1. Interactive without `--defaults`: `silent_token` (`ask: false`) and `conditional_field` | |
| 1691 | + | // (`ask` evaluates false) must NOT be prompted; only `project` is asked. | |
| 1692 | + | let prompter = RecordingPrompter { | |
| 1693 | + | asked: Mutex::new(Vec::new()), | |
| 1694 | + | }; | |
| 1695 | + | copy( | |
| 1696 | + | tpl_dir.path().to_str().unwrap(), | |
| 1697 | + | dst_dir.path(), | |
| 1698 | + | &CopyOptions::default(), | |
| 1699 | + | &prompter, | |
| 1700 | + | &NoopReporter, | |
| 1701 | + | ) | |
| 1702 | + | .unwrap(); | |
| 1703 | + | assert_eq!(*prompter.asked.lock().unwrap(), vec!["project"]); | |
| 1704 | + | assert_eq!( | |
| 1705 | + | fs::read_to_string(dst_dir.path().join("out.txt")).unwrap(), | |
| 1706 | + | "prompted-project|auto-token|auto-cond\n" | |
| 1707 | + | ); | |
| 1708 | + | ||
| 1709 | + | // 2. With `--defaults` AND `--ask silent_*` (fnmatch glob): ONLY `silent_token` is forced interactive! | |
| 1710 | + | let dst_dir2 = TempDir::new().unwrap(); | |
| 1711 | + | let prompter2 = RecordingPrompter { | |
| 1712 | + | asked: Mutex::new(Vec::new()), | |
| 1713 | + | }; | |
| 1714 | + | copy( | |
| 1715 | + | tpl_dir.path().to_str().unwrap(), | |
| 1716 | + | dst_dir2.path(), | |
| 1717 | + | &CopyOptions { | |
| 1718 | + | defaults: true, | |
| 1719 | + | ask_questions: vec!["silent_*".into()], | |
| 1720 | + | ..CopyOptions::default() | |
| 1721 | + | }, | |
| 1722 | + | &prompter2, | |
| 1723 | + | &NoopReporter, | |
| 1724 | + | ) | |
| 1725 | + | .unwrap(); | |
| 1726 | + | assert_eq!(*prompter2.asked.lock().unwrap(), vec!["silent_token"]); | |
| 1727 | + | assert_eq!( | |
| 1728 | + | fs::read_to_string(dst_dir2.path().join("out.txt")).unwrap(), | |
| 1729 | + | "default-proj|prompted-silent_token|auto-cond\n" | |
| 1730 | + | ); | |
| 1731 | + | } | |
| 1732 | + | ||
| 1733 | + | #[test] | |
| 1734 | + | fn multiline_exclude_and_symlink_overwrite_without_following() { | |
| 1735 | + | let tpl_dir = TempDir::new().unwrap(); | |
| 1736 | + | let dst_dir = TempDir::new().unwrap(); | |
| 1737 | + | let outside_dir = TempDir::new().unwrap(); | |
| 1738 | + | ||
| 1739 | + | fs::write( | |
| 1740 | + | tpl_dir.path().join("copier.yml"), | |
| 1741 | + | r" | |
| 1742 | + | _exclude: | |
| 1743 | + | - | | |
| 1744 | + | {% if true %} | |
| 1745 | + | drop_a.txt | |
| 1746 | + | drop_b.txt | |
| 1747 | + | {% endif %} | |
| 1748 | + | name: demo | |
| 1749 | + | ", | |
| 1750 | + | ) | |
| 1751 | + | .unwrap(); | |
| 1752 | + | fs::write(tpl_dir.path().join("keep.txt.jinja"), "kept {{ name }}\n").unwrap(); | |
| 1753 | + | fs::write(tpl_dir.path().join("drop_a.txt"), "a").unwrap(); | |
| 1754 | + | fs::write(tpl_dir.path().join("drop_b.txt"), "b").unwrap(); | |
| 1755 | + | fs::write(tpl_dir.path().join("broken_target.txt"), "fresh\n").unwrap(); | |
| 1756 | + | ||
| 1757 | + | // Pre-populate destination with: | |
| 1758 | + | // 1) a live symlink `keep.txt -> outside/secret.txt` | |
| 1759 | + | // 2) a broken symlink `broken_target.txt -> /nonexistent/path` | |
| 1760 | + | let outside_secret = outside_dir.path().join("secret.txt"); | |
| 1761 | + | fs::write(&outside_secret, "DO NOT TOUCH\n").unwrap(); | |
| 1762 | + | #[cfg(unix)] | |
| 1763 | + | { | |
| 1764 | + | std::os::unix::fs::symlink(&outside_secret, dst_dir.path().join("keep.txt")).unwrap(); | |
| 1765 | + | std::os::unix::fs::symlink( | |
| 1766 | + | outside_dir.path().join("missing.txt"), | |
| 1767 | + | dst_dir.path().join("broken_target.txt"), | |
| 1768 | + | ) | |
| 1769 | + | .unwrap(); | |
| 1770 | + | } | |
| 1771 | + | ||
| 1772 | + | copy( | |
| 1773 | + | tpl_dir.path().to_str().unwrap(), | |
| 1774 | + | dst_dir.path(), | |
| 1775 | + | &CopyOptions { | |
| 1776 | + | defaults: true, | |
| 1777 | + | overwrite: true, | |
| 1778 | + | ..CopyOptions::default() | |
| 1779 | + | }, | |
| 1780 | + | &NonInteractivePrompter, | |
| 1781 | + | &NoopReporter, | |
| 1782 | + | ) | |
| 1783 | + | .unwrap(); | |
| 1784 | + | ||
| 1785 | + | // Multi-line `_exclude` dropped both files. | |
| 1786 | + | assert!(!dst_dir.path().join("drop_a.txt").exists()); | |
| 1787 | + | assert!(!dst_dir.path().join("drop_b.txt").exists()); | |
| 1788 | + | ||
| 1789 | + | // Destination symlinks were unlinked and replaced with regular files; external target untouched! | |
| 1790 | + | assert_eq!( | |
| 1791 | + | fs::read_to_string(dst_dir.path().join("keep.txt")).unwrap(), | |
| 1792 | + | "kept demo\n" | |
| 1793 | + | ); | |
| 1794 | + | assert_eq!( | |
| 1795 | + | fs::read_to_string(dst_dir.path().join("broken_target.txt")).unwrap(), | |
| 1796 | + | "fresh\n" | |
| 1797 | + | ); | |
| 1798 | + | assert_eq!( | |
| 1799 | + | fs::read_to_string(&outside_secret).unwrap(), | |
| 1800 | + | "DO NOT TOUCH\n" | |
| 1801 | + | ); | |
| 1802 | + | #[cfg(unix)] | |
| 1803 | + | { | |
| 1804 | + | assert!( | |
| 1805 | + | !fs::symlink_metadata(dst_dir.path().join("keep.txt")) | |
| 1806 | + | .unwrap() | |
| 1807 | + | .file_type() | |
| 1808 | + | .is_symlink() | |
| 1809 | + | ); | |
| 1810 | + | assert!( | |
| 1811 | + | !fs::symlink_metadata(dst_dir.path().join("broken_target.txt")) | |
| 1812 | + | .unwrap() | |
| 1813 | + | .file_type() | |
| 1814 | + | .is_symlink() | |
| 1815 | + | ); | |
| 1816 | + | } | |
| 1817 | + | } | |
| 1818 | + | ||
| 1819 | + | #[test] | |
| 1820 | + | fn security_path_containment_and_git_ref_injection_guard() { | |
| 1821 | + | // 1. `!include ../escape.yml` must be rejected. | |
| 1822 | + | let parent_dir = TempDir::new().unwrap(); | |
| 1823 | + | let tpl_dir = parent_dir.path().join("tpl"); | |
| 1824 | + | fs::create_dir_all(&tpl_dir).unwrap(); | |
| 1825 | + | fs::write(parent_dir.path().join("escape.yml"), "secret: leaked\n").unwrap(); | |
| 1826 | + | fs::write(tpl_dir.join("copier.yml"), "!include ../escape.yml\n").unwrap(); | |
| 1827 | + | ||
| 1828 | + | let dst_dir = TempDir::new().unwrap(); | |
| 1829 | + | let err = copy( | |
| 1830 | + | tpl_dir.to_str().unwrap(), | |
| 1831 | + | dst_dir.path(), | |
| 1832 | + | &CopyOptions { | |
| 1833 | + | defaults: true, | |
| 1834 | + | ..CopyOptions::default() | |
| 1835 | + | }, | |
| 1836 | + | &NonInteractivePrompter, | |
| 1837 | + | &NoopReporter, | |
| 1838 | + | ) | |
| 1839 | + | .unwrap_err(); | |
| 1840 | + | assert!( | |
| 1841 | + | err.to_string().contains("escapes template root") || err.to_string().contains("Invalid"), | |
| 1842 | + | "expected path containment error, got: {err}" | |
| 1843 | + | ); | |
| 1844 | + | ||
| 1845 | + | // 2. Jinja `{% include '../secret.txt' %}` and symlink escaping template root must be blocked. | |
| 1846 | + | let tpl_dir2 = parent_dir.path().join("tpl2"); | |
| 1847 | + | fs::create_dir_all(&tpl_dir2).unwrap(); | |
| 1848 | + | fs::write(parent_dir.path().join("secret.txt"), "TOP-SECRET").unwrap(); | |
| 1849 | + | fs::write(tpl_dir2.join("copier.yml"), "name: ok\n").unwrap(); | |
| 1850 | + | fs::write( | |
| 1851 | + | tpl_dir2.join("leak.txt.jinja"), | |
| 1852 | + | "{% include '../secret.txt' %}\n", | |
| 1853 | + | ) | |
| 1854 | + | .unwrap(); | |
| 1855 | + | ||
| 1856 | + | let dst_dir2 = TempDir::new().unwrap(); | |
| 1857 | + | let err2 = copy( | |
| 1858 | + | tpl_dir2.to_str().unwrap(), | |
| 1859 | + | dst_dir2.path(), | |
| 1860 | + | &CopyOptions { | |
| 1861 | + | defaults: true, | |
| 1862 | + | ..CopyOptions::default() | |
| 1863 | + | }, | |
| 1864 | + | &NonInteractivePrompter, | |
| 1865 | + | &NoopReporter, | |
| 1866 | + | ) | |
| 1867 | + | .unwrap_err(); | |
| 1868 | + | assert!( | |
| 1869 | + | err2.to_string().contains("not found") || err2.to_string().contains("template"), | |
| 1870 | + | "expected Jinja include containment failure, got: {err2}" | |
| 1871 | + | ); | |
| 1872 | + | ||
| 1873 | + | // 3. Git refs starting with `-` must be rejected (argument injection defense). | |
| 1874 | + | let git_tpl = TempDir::new().unwrap(); | |
| 1875 | + | init_git_repo(git_tpl.path()); | |
| 1876 | + | fs::write(git_tpl.path().join("copier.yml"), "name: ok\n").unwrap(); | |
| 1877 | + | fs::write(git_tpl.path().join("a.txt"), "hi\n").unwrap(); | |
| 1878 | + | commit_all(git_tpl.path(), "init"); | |
| 1879 | + | ||
| 1880 | + | let dst_dir3 = TempDir::new().unwrap(); | |
| 1881 | + | let err3 = copy( | |
| 1882 | + | git_tpl.path().to_str().unwrap(), | |
| 1883 | + | dst_dir3.path(), | |
| 1884 | + | &CopyOptions { | |
| 1885 | + | vcs_ref: Some("--upload-pack=evil".into()), | |
| 1886 | + | defaults: true, | |
| 1887 | + | ..CopyOptions::default() | |
| 1888 | + | }, | |
| 1889 | + | &NonInteractivePrompter, | |
| 1890 | + | &NoopReporter, | |
| 1891 | + | ) | |
| 1892 | + | .unwrap_err(); | |
| 1893 | + | assert!( | |
| 1894 | + | err3.to_string().contains("may not start with '-'"), | |
| 1895 | + | "expected git ref injection error, got: {err3}" | |
| 1896 | + | ); | |
| 1897 | + | } | |
| 1898 | + | ||
| 1899 | + | #[test] | |
| 1900 | + | fn security_blocks_rendered_path_answers_subdir_and_external_data_traversal() { | |
| 1901 | + | let sandbox = TempDir::new().unwrap(); | |
| 1902 | + | let victim_secret = sandbox.path().join("outside_secret.yml"); | |
| 1903 | + | fs::write(&victim_secret, "token: topsecret\n").unwrap(); | |
| 1904 | + | ||
| 1905 | + | // 0. TempDir must be 0700 on Unix. | |
| 1906 | + | #[cfg(unix)] | |
| 1907 | + | { | |
| 1908 | + | use std::os::unix::fs::PermissionsExt; | |
| 1909 | + | let mode = fs::metadata(sandbox.path()).unwrap().permissions().mode() & 0o777; | |
| 1910 | + | assert_eq!(mode, 0o700, "TempDir must be private (0700)"); | |
| 1911 | + | } | |
| 1912 | + | ||
| 1913 | + | // 1. Rendered filename attempting `../pwned.txt` must be rejected. | |
| 1914 | + | let tpl1 = sandbox.path().join("tpl_path"); | |
| 1915 | + | let dst1 = sandbox.path().join("dst1"); | |
| 1916 | + | fs::create_dir_all(&tpl1).unwrap(); | |
| 1917 | + | fs::write(tpl1.join("copier.yml"), "target: '../pwned.txt'\n").unwrap(); | |
| 1918 | + | fs::write(tpl1.join("{{ target }}.jinja"), "pwned").unwrap(); | |
| 1919 | + | let err = copy( | |
| 1920 | + | tpl1.to_str().unwrap(), | |
| 1921 | + | &dst1, | |
| 1922 | + | &CopyOptions { | |
| 1923 | + | defaults: true, | |
| 1924 | + | ..CopyOptions::default() | |
| 1925 | + | }, | |
| 1926 | + | &NonInteractivePrompter, | |
| 1927 | + | &NoopReporter, | |
| 1928 | + | ) | |
| 1929 | + | .unwrap_err(); | |
| 1930 | + | assert!( | |
| 1931 | + | err.to_string().contains("escapes destination"), | |
| 1932 | + | "expected rendered path escape error, got: {err}" | |
| 1933 | + | ); | |
| 1934 | + | assert!(!sandbox.path().join("pwned.txt").exists()); | |
| 1935 | + | ||
| 1936 | + | // 2. `_answers_file: ../pwned-answers.yml` must be rejected. | |
| 1937 | + | let tpl2 = sandbox.path().join("tpl_ans"); | |
| 1938 | + | let dst2 = sandbox.path().join("dst2"); | |
| 1939 | + | fs::create_dir_all(&tpl2).unwrap(); | |
| 1940 | + | fs::write( | |
| 1941 | + | tpl2.join("copier.yml"), | |
| 1942 | + | "_answers_file: ../pwned-answers.yml\nname: x\n", | |
| 1943 | + | ) | |
| 1944 | + | .unwrap(); | |
| 1945 | + | fs::write(tpl2.join("ok.txt"), "hi").unwrap(); | |
| 1946 | + | let err = copy( | |
| 1947 | + | tpl2.to_str().unwrap(), | |
| 1948 | + | &dst2, | |
| 1949 | + | &CopyOptions { | |
| 1950 | + | defaults: true, | |
| 1951 | + | ..CopyOptions::default() | |
| 1952 | + | }, | |
| 1953 | + | &NonInteractivePrompter, | |
| 1954 | + | &NoopReporter, | |
| 1955 | + | ) | |
| 1956 | + | .unwrap_err(); | |
| 1957 | + | assert!( | |
| 1958 | + | err.to_string().contains("escapes destination"), | |
| 1959 | + | "expected answers_file escape error, got: {err}" | |
| 1960 | + | ); | |
| 1961 | + | assert!(!sandbox.path().join("pwned-answers.yml").exists()); | |
| 1962 | + | ||
| 1963 | + | // 3. `_subdirectory: ../` must be rejected. | |
| 1964 | + | let tpl3 = sandbox.path().join("tpl_sub"); | |
| 1965 | + | let dst3 = sandbox.path().join("dst3"); | |
| 1966 | + | fs::create_dir_all(&tpl3).unwrap(); | |
| 1967 | + | fs::write(tpl3.join("copier.yml"), "_subdirectory: ..\nname: x\n").unwrap(); | |
| 1968 | + | let err = copy( | |
| 1969 | + | tpl3.to_str().unwrap(), | |
| 1970 | + | &dst3, | |
| 1971 | + | &CopyOptions { | |
| 1972 | + | defaults: true, | |
| 1973 | + | ..CopyOptions::default() | |
| 1974 | + | }, | |
| 1975 | + | &NonInteractivePrompter, | |
| 1976 | + | &NoopReporter, | |
| 1977 | + | ) | |
| 1978 | + | .unwrap_err(); | |
| 1979 | + | assert!( | |
| 1980 | + | err.to_string().contains("escapes template root"), | |
| 1981 | + | "expected subdirectory escape error, got: {err}" | |
| 1982 | + | ); | |
| 1983 | + | ||
| 1984 | + | // 4. `_external_data` pointing outside template/dst without `--trust` must be rejected. | |
| 1985 | + | let tpl4 = sandbox.path().join("tpl_ext"); | |
| 1986 | + | let dst4 = sandbox.path().join("dst4"); | |
| 1987 | + | fs::create_dir_all(&tpl4).unwrap(); | |
| 1988 | + | fs::write( | |
| 1989 | + | tpl4.join("copier.yml"), | |
| 1990 | + | format!( | |
| 1991 | + | "_external_data:\n leak: {}\nname: x\n", | |
| 1992 | + | victim_secret.display() | |
| 1993 | + | ), | |
| 1994 | + | ) | |
| 1995 | + | .unwrap(); | |
| 1996 | + | let err = copy( | |
| 1997 | + | tpl4.to_str().unwrap(), | |
| 1998 | + | &dst4, | |
| 1999 | + | &CopyOptions { | |
| 2000 | + | defaults: true, | |
| 2001 | + | trust: false, | |
| 2002 | + | ..CopyOptions::default() | |
| 2003 | + | }, | |
| 2004 | + | &NonInteractivePrompter, | |
| 2005 | + | &NoopReporter, | |
| 2006 | + | ) | |
| 2007 | + | .unwrap_err(); | |
| 2008 | + | assert!( | |
| 2009 | + | err.to_string() | |
| 2010 | + | .contains("Failed to load `_external_data.leak`"), | |
| 2011 | + | "expected external_data containment error, got: {err}" | |
| 2012 | + | ); | |
| 2013 | + | ||
| 2014 | + | // 5. `_roneo_plugins` requires `--trust` and rejects absolute paths. | |
| 2015 | + | let tpl5 = sandbox.path().join("tpl_plug"); | |
| 2016 | + | let dst5 = sandbox.path().join("dst5"); | |
| 2017 | + | fs::create_dir_all(&tpl5).unwrap(); | |
| 2018 | + | fs::write( | |
| 2019 | + | tpl5.join("copier.yml"), | |
| 2020 | + | "_roneo_plugins:\n - /tmp/evil.wasm\nname: x\n", | |
| 2021 | + | ) | |
| 2022 | + | .unwrap(); | |
| 2023 | + | let err_untrusted = copy( | |
| 2024 | + | tpl5.to_str().unwrap(), | |
| 2025 | + | &dst5, | |
| 2026 | + | &CopyOptions { | |
| 2027 | + | defaults: true, | |
| 2028 | + | trust: false, | |
| 2029 | + | ..CopyOptions::default() | |
| 2030 | + | }, | |
| 2031 | + | &NonInteractivePrompter, | |
| 2032 | + | &NoopReporter, | |
| 2033 | + | ) | |
| 2034 | + | .unwrap_err(); | |
| 2035 | + | assert!(matches!(err_untrusted, RoneoError::UnsafeTemplate(_))); | |
| 2036 | + | ||
| 2037 | + | let err_abs = copy( | |
| 2038 | + | tpl5.to_str().unwrap(), | |
| 2039 | + | &dst5, | |
| 2040 | + | &CopyOptions { | |
| 2041 | + | defaults: true, | |
| 2042 | + | trust: true, | |
| 2043 | + | ..CopyOptions::default() | |
| 2044 | + | }, | |
| 2045 | + | &NonInteractivePrompter, | |
| 2046 | + | &NoopReporter, | |
| 2047 | + | ) | |
| 2048 | + | .unwrap_err(); | |
| 2049 | + | assert!( | |
| 2050 | + | err_abs.to_string().contains("must be a relative path"), | |
| 2051 | + | "expected relative path plugin error, got: {err_abs}" | |
| 2052 | + | ); | |
| 2053 | + | ||
| 2054 | + | // 6. Writing through a pre-existing symlink directory inside `dst` must be refused. | |
| 2055 | + | #[cfg(unix)] | |
| 2056 | + | { | |
| 2057 | + | let tpl6 = sandbox.path().join("tpl_symdir"); | |
| 2058 | + | let dst6 = sandbox.path().join("dst6"); | |
| 2059 | + | let outside = sandbox.path().join("outside_dir"); | |
| 2060 | + | fs::create_dir_all(tpl6.join("sub")).unwrap(); | |
| 2061 | + | fs::create_dir_all(&dst6).unwrap(); | |
| 2062 | + | fs::create_dir_all(&outside).unwrap(); | |
| 2063 | + | fs::write(tpl6.join("copier.yml"), "name: x\n").unwrap(); | |
| 2064 | + | fs::write(tpl6.join("sub/pwn.txt"), "pwned").unwrap(); | |
| 2065 | + | std::os::unix::fs::symlink(&outside, dst6.join("sub")).unwrap(); | |
| 2066 | + | ||
| 2067 | + | let err_sym = copy( | |
| 2068 | + | tpl6.to_str().unwrap(), | |
| 2069 | + | &dst6, | |
| 2070 | + | &CopyOptions { | |
| 2071 | + | defaults: true, | |
| 2072 | + | overwrite: true, | |
| 2073 | + | ..CopyOptions::default() | |
| 2074 | + | }, | |
| 2075 | + | &NonInteractivePrompter, | |
| 2076 | + | &NoopReporter, | |
| 2077 | + | ) | |
| 2078 | + | .unwrap_err(); | |
| 2079 | + | assert!( | |
| 2080 | + | err_sym.to_string().contains("symlink directory"), | |
| 2081 | + | "expected symlink directory error, got: {err_sym}" | |
| 2082 | + | ); | |
| 2083 | + | assert!(!outside.join("pwn.txt").exists()); | |
| 2084 | + | } | |
| 2085 | + | } |
| @@ -0,0 +1,18 @@ | |||
| 1 | + | [package] | |
| 2 | + | name = "roneo-plugin-sdk" | |
| 3 | + | version.workspace = true | |
| 4 | + | edition.workspace = true | |
| 5 | + | rust-version.workspace = true | |
| 6 | + | license.workspace = true | |
| 7 | + | repository.workspace = true | |
| 8 | + | keywords.workspace = true | |
| 9 | + | categories.workspace = true | |
| 10 | + | description = "Lightweight SDK for authoring standalone sandboxed WebAssembly (.wasm) plugins for Roneo" | |
| 11 | + | ||
| 12 | + | [lints] | |
| 13 | + | workspace = true | |
| 14 | + | ||
| 15 | + | [dependencies] | |
| 16 | + | indexmap.workspace = true | |
| 17 | + | serde.workspace = true | |
| 18 | + | serde_json.workspace = true |
| @@ -0,0 +1,192 @@ | |||
| 1 | + | //! Lightweight SDK for writing standalone WebAssembly (`.wasm`) plugins for Roneo. | |
| 2 | + | //! | |
| 3 | + | //! Compile any plugin crate with: | |
| 4 | + | //! ```sh | |
| 5 | + | //! cargo build --release --target wasm32-unknown-unknown | |
| 6 | + | //! ``` | |
| 7 | + | //! and load the resulting `.wasm` file via `roneo copy --plugin my_plugin.wasm ...` | |
| 8 | + | //! or `_roneo_plugins: [path/to/my_plugin.wasm]` in `copier.yml` / `roneo.yml`. | |
| 9 | + | ||
| 10 | + | use indexmap::IndexMap; | |
| 11 | + | use serde::{Deserialize, Serialize}; | |
| 12 | + | use serde_json::{Map as JsonMap, Value as JsonValue}; | |
| 13 | + | ||
| 14 | + | /// Manifest describing the capabilities a WASM plugin exports to Roneo. | |
| 15 | + | #[derive(Debug, Clone, Default, Serialize, Deserialize)] | |
| 16 | + | pub struct PluginManifest { | |
| 17 | + | pub name: String, | |
| 18 | + | #[serde(default)] | |
| 19 | + | pub strict_undefined: bool, | |
| 20 | + | #[serde(default)] | |
| 21 | + | pub globals: IndexMap<String, JsonValue>, | |
| 22 | + | #[serde(default)] | |
| 23 | + | pub filters: Vec<String>, | |
| 24 | + | #[serde(default)] | |
| 25 | + | pub functions: Vec<String>, | |
| 26 | + | #[serde(default)] | |
| 27 | + | pub tests: Vec<String>, | |
| 28 | + | #[serde(default)] | |
| 29 | + | pub has_context_hook: bool, | |
| 30 | + | /// Optional context keys forwarded on filter/function/test calls. | |
| 31 | + | #[serde(default)] | |
| 32 | + | pub context_keys: Vec<String>, | |
| 33 | + | /// Optional template files read by the host and passed to `init()` (zero FS access in WASM). | |
| 34 | + | #[serde(default)] | |
| 35 | + | pub template_files: Vec<String>, | |
| 36 | + | } | |
| 37 | + | ||
| 38 | + | /// Host initialization payload delivered to `RoneoPlugin::init`. | |
| 39 | + | #[derive(Debug, Clone, Default, Deserialize)] | |
| 40 | + | pub struct InitPayload { | |
| 41 | + | #[serde(default)] | |
| 42 | + | pub template_files: IndexMap<String, String>, | |
| 43 | + | #[serde(default)] | |
| 44 | + | pub recorded_answers: JsonValue, | |
| 45 | + | #[serde(default)] | |
| 46 | + | pub dst_path: String, | |
| 47 | + | #[serde(default)] | |
| 48 | + | pub template_root: String, | |
| 49 | + | } | |
| 50 | + | ||
| 51 | + | /// Request delivered to `RoneoPlugin::call`. | |
| 52 | + | #[derive(Debug, Clone, Deserialize)] | |
| 53 | + | pub struct CallRequest { | |
| 54 | + | pub kind: String, | |
| 55 | + | pub name: String, | |
| 56 | + | #[serde(default)] | |
| 57 | + | pub args: Vec<JsonValue>, | |
| 58 | + | #[serde(default)] | |
| 59 | + | pub kwargs: JsonMap<String, JsonValue>, | |
| 60 | + | #[serde(default)] | |
| 61 | + | pub context: JsonMap<String, JsonValue>, | |
| 62 | + | #[serde(default)] | |
| 63 | + | pub phase: String, | |
| 64 | + | } | |
| 65 | + | ||
| 66 | + | #[derive(Debug, Serialize)] | |
| 67 | + | #[serde(rename_all = "lowercase")] | |
| 68 | + | pub enum CallResponse { | |
| 69 | + | Ok(JsonValue), | |
| 70 | + | Err(String), | |
| 71 | + | } | |
| 72 | + | ||
| 73 | + | /// Trait implemented by external WASM plugins. | |
| 74 | + | pub trait RoneoPlugin: Default + Send + 'static { | |
| 75 | + | fn manifest(&self) -> PluginManifest; | |
| 76 | + | ||
| 77 | + | fn init(&mut self, _payload: InitPayload) -> Result<(), String> { | |
| 78 | + | Ok(()) | |
| 79 | + | } | |
| 80 | + | ||
| 81 | + | fn call(&self, req: CallRequest) -> Result<JsonValue, String>; | |
| 82 | + | } | |
| 83 | + | ||
| 84 | + | #[doc(hidden)] | |
| 85 | + | pub mod abi { | |
| 86 | + | use super::{CallRequest, CallResponse, InitPayload, RoneoPlugin}; | |
| 87 | + | use serde_json::Value as JsonValue; | |
| 88 | + | ||
| 89 | + | pub fn pack_bytes(bytes: Vec<u8>) -> u64 { | |
| 90 | + | let boxed = bytes.into_boxed_slice(); | |
| 91 | + | let len = boxed.len() as u64; | |
| 92 | + | let ptr = Box::into_raw(boxed).cast::<u8>() as usize as u64; | |
| 93 | + | (ptr << 32) | len | |
| 94 | + | } | |
| 95 | + | ||
| 96 | + | /// # Safety | |
| 97 | + | /// Caller (the WASM host) must pass a valid pointer/length pair allocated via `roneo_alloc`. | |
| 98 | + | pub unsafe fn read_slice(ptr: u32, len: u32) -> &'static [u8] { | |
| 99 | + | unsafe { std::slice::from_raw_parts(ptr as usize as *const u8, len as usize) } | |
| 100 | + | } | |
| 101 | + | ||
| 102 | + | #[allow(clippy::cast_possible_truncation)] | |
| 103 | + | pub fn alloc(size: u32) -> u32 { | |
| 104 | + | let mut buf = Vec::<u8>::with_capacity(size as usize); | |
| 105 | + | let ptr = buf.as_mut_ptr() as usize as u32; | |
| 106 | + | std::mem::forget(buf); | |
| 107 | + | ptr | |
| 108 | + | } | |
| 109 | + | ||
| 110 | + | #[allow(clippy::same_length_and_capacity)] | |
| 111 | + | pub fn dealloc(ptr: u32, size: u32) { | |
| 112 | + | if ptr == 0 || size == 0 { | |
| 113 | + | return; | |
| 114 | + | } | |
| 115 | + | unsafe { | |
| 116 | + | let _ = Vec::from_raw_parts(ptr as usize as *mut u8, size as usize, size as usize); | |
| 117 | + | } | |
| 118 | + | } | |
| 119 | + | ||
| 120 | + | pub fn dispatch_manifest<P: RoneoPlugin>(plugin: &P) -> u64 { | |
| 121 | + | let bytes = serde_json::to_vec(&plugin.manifest()).unwrap_or_default(); | |
| 122 | + | pack_bytes(bytes) | |
| 123 | + | } | |
| 124 | + | ||
| 125 | + | /// # Safety | |
| 126 | + | /// `ptr` and `len` must reference valid guest memory. | |
| 127 | + | pub unsafe fn dispatch_init<P: RoneoPlugin>(plugin: &mut P, ptr: u32, len: u32) -> u64 { | |
| 128 | + | let slice = unsafe { read_slice(ptr, len) }; | |
| 129 | + | let resp = match serde_json::from_slice::<InitPayload>(slice) { | |
| 130 | + | Ok(payload) => match plugin.init(payload) { | |
| 131 | + | Ok(()) => CallResponse::Ok(JsonValue::Null), | |
| 132 | + | Err(msg) => CallResponse::Err(msg), | |
| 133 | + | }, | |
| 134 | + | Err(e) => CallResponse::Err(format!("Invalid init payload: {e}")), | |
| 135 | + | }; | |
| 136 | + | pack_bytes(serde_json::to_vec(&resp).unwrap_or_default()) | |
| 137 | + | } | |
| 138 | + | ||
| 139 | + | /// # Safety | |
| 140 | + | /// `ptr` and `len` must reference valid guest memory. | |
| 141 | + | pub unsafe fn dispatch_call<P: RoneoPlugin>(plugin: &P, ptr: u32, len: u32) -> u64 { | |
| 142 | + | let slice = unsafe { read_slice(ptr, len) }; | |
| 143 | + | let resp = match serde_json::from_slice::<CallRequest>(slice) { | |
| 144 | + | Ok(req) => match plugin.call(req) { | |
| 145 | + | Ok(val) => CallResponse::Ok(val), | |
| 146 | + | Err(msg) => CallResponse::Err(msg), | |
| 147 | + | }, | |
| 148 | + | Err(e) => CallResponse::Err(format!("Invalid call payload: {e}")), | |
| 149 | + | }; | |
| 150 | + | pack_bytes(serde_json::to_vec(&resp).unwrap_or_default()) | |
| 151 | + | } | |
| 152 | + | } | |
| 153 | + | ||
| 154 | + | /// Export all required Roneo WASM ABI entry points for a `RoneoPlugin` implementation. | |
| 155 | + | #[macro_export] | |
| 156 | + | macro_rules! export_plugin { | |
| 157 | + | ($plugin_ty:ty) => { | |
| 158 | + | fn __roneo_plugin_cell() -> &'static ::std::sync::Mutex<$plugin_ty> { | |
| 159 | + | static CELL: ::std::sync::OnceLock<::std::sync::Mutex<$plugin_ty>> = | |
| 160 | + | ::std::sync::OnceLock::new(); | |
| 161 | + | CELL.get_or_init(|| ::std::sync::Mutex::new(<$plugin_ty as Default>::default())) | |
| 162 | + | } | |
| 163 | + | ||
| 164 | + | #[unsafe(no_mangle)] | |
| 165 | + | pub extern "C" fn roneo_alloc(size: u32) -> u32 { | |
| 166 | + | $crate::abi::alloc(size) | |
| 167 | + | } | |
| 168 | + | ||
| 169 | + | #[unsafe(no_mangle)] | |
| 170 | + | pub extern "C" fn roneo_dealloc(ptr: u32, size: u32) { | |
| 171 | + | $crate::abi::dealloc(ptr, size); | |
| 172 | + | } | |
| 173 | + | ||
| 174 | + | #[unsafe(no_mangle)] | |
| 175 | + | pub extern "C" fn roneo_manifest() -> u64 { | |
| 176 | + | let guard = __roneo_plugin_cell().lock().expect("plugin lock"); | |
| 177 | + | $crate::abi::dispatch_manifest(&*guard) | |
| 178 | + | } | |
| 179 | + | ||
| 180 | + | #[unsafe(no_mangle)] | |
| 181 | + | pub extern "C" fn roneo_init(ptr: u32, len: u32) -> u64 { | |
| 182 | + | let mut guard = __roneo_plugin_cell().lock().expect("plugin lock"); | |
| 183 | + | unsafe { $crate::abi::dispatch_init(&mut *guard, ptr, len) } | |
| 184 | + | } | |
| 185 | + | ||
| 186 | + | #[unsafe(no_mangle)] | |
| 187 | + | pub extern "C" fn roneo_call(ptr: u32, len: u32) -> u64 { | |
| 188 | + | let guard = __roneo_plugin_cell().lock().expect("plugin lock"); | |
| 189 | + | unsafe { $crate::abi::dispatch_call(&*guard, ptr, len) } | |
| 190 | + | } | |
| 191 | + | }; | |
| 192 | + | } |
deny.toml+37−0
| @@ -0,0 +1,37 @@ | |||
| 1 | + | # cargo-deny configuration for Ronéo | |
| 2 | + | ||
| 3 | + | [graph] | |
| 4 | + | all-features = false | |
| 5 | + | ||
| 6 | + | [advisories] | |
| 7 | + | version = 2 | |
| 8 | + | ignore = [ | |
| 9 | + | # Transitive via `serde_yaml_ng` (YAML parser); no known CVE, unmaintained warning only. | |
| 10 | + | # Tracked for future migration to a pure-safe Rust YAML parser (`serde-saphyr`). | |
| 11 | + | { id = "RUSTSEC-2024-0449", reason = "No CVE; serde_yaml_ng transitive dependency until pure-Rust YAML migration" }, | |
| 12 | + | ] | |
| 13 | + | ||
| 14 | + | [licenses] | |
| 15 | + | version = 2 | |
| 16 | + | allow = [ | |
| 17 | + | "MIT", | |
| 18 | + | "Apache-2.0", | |
| 19 | + | "Apache-2.0 WITH LLVM-exception", | |
| 20 | + | "BSL-1.0", | |
| 21 | + | "CC0-1.0", | |
| 22 | + | "MIT-0", | |
| 23 | + | "MPL-2.0", | |
| 24 | + | "Unicode-3.0", | |
| 25 | + | "Unlicense", | |
| 26 | + | "Zlib", | |
| 27 | + | ] | |
| 28 | + | ||
| 29 | + | [bans] | |
| 30 | + | multiple-versions = "allow" | |
| 31 | + | wildcards = "deny" | |
| 32 | + | allow-wildcard-paths = true | |
| 33 | + | ||
| 34 | + | [sources] | |
| 35 | + | unknown-registry = "deny" | |
| 36 | + | unknown-git = "deny" | |
| 37 | + | allow-registry = ["https://github.com/rust-lang/crates.io-index"] |
| @@ -0,0 +1,37 @@ | |||
| 1 | + | _subdirectory: template | |
| 2 | + | _answers_file: .copier-answers.yml | |
| 3 | + | _templates_suffix: .jinja | |
| 4 | + | _exclude: | |
| 5 | + | - "*.bak" | |
| 6 | + | _message_after_copy: | | |
| 7 | + | Project "{{ project_name }}" scaffolded with Roneo! | |
| 8 | + | ||
| 9 | + | project_name: | |
| 10 | + | type: str | |
| 11 | + | help: What is the name of your project? | |
| 12 | + | default: my-service | |
| 13 | + | validator: "{% if not project_name %}Project name cannot be empty{% endif %}" | |
| 14 | + | ||
| 15 | + | module_name: | |
| 16 | + | type: str | |
| 17 | + | help: Module identifier (snake_case) | |
| 18 | + | default: "{{ project_name.lower().replace('-', '_').replace(' ', '_') }}" | |
| 19 | + | ||
| 20 | + | author: | |
| 21 | + | type: str | |
| 22 | + | help: Author name | |
| 23 | + | default: Jane Doe | |
| 24 | + | ||
| 25 | + | license: | |
| 26 | + | type: str | |
| 27 | + | help: Choose a license | |
| 28 | + | choices: | |
| 29 | + | MIT License: MIT | |
| 30 | + | Apache 2.0: Apache-2.0 | |
| 31 | + | Proprietary: Proprietary | |
| 32 | + | default: MIT | |
| 33 | + | ||
| 34 | + | include_ci: | |
| 35 | + | type: bool | |
| 36 | + | help: Include GitHub Actions CI workflow? | |
| 37 | + | default: true |
| @@ -0,0 +1,5 @@ | |||
| 1 | + | # {{ project_name }} | |
| 2 | + | ||
| 3 | + | Author: {{ author }} | |
| 4 | + | License: {{ license }} | |
| 5 | + | Module: `{{ module_name }}` |
| @@ -0,0 +1,4 @@ | |||
| 1 | + | // Generated by Roneo for {{ project_name }} | |
| 2 | + | pub fn greeting() -> &'static str { | |
| 3 | + | "Hello from {{ module_name }}!" | |
| 4 | + | } |
| @@ -0,0 +1,8 @@ | |||
| 1 | + | name: CI ({{ project_name }}) | |
| 2 | + | on: [push, pull_request] | |
| 3 | + | jobs: | |
| 4 | + | check: | |
| 5 | + | runs-on: ubuntu-latest | |
| 6 | + | steps: | |
| 7 | + | - uses: actions/checkout@v4 | |
| 8 | + | - run: echo "Testing {{ module_name }}" |
| @@ -0,0 +1,2 @@ | |||
| 1 | + | # Changes here will be overwritten by Copier/Roneo; NEVER EDIT MANUALLY | |
| 2 | + | {{ _copier_answers|to_nice_yaml }} |
forge.toml+7−0
| @@ -0,0 +1,7 @@ | |||
| 1 | + | # Forge repository profile (PUBLIC-FORGE.md) | |
| 2 | + | schema = 1 | |
| 3 | + | ||
| 4 | + | [repository] | |
| 5 | + | default_branch = "main" | |
| 6 | + | description = "Fast, standalone Rust port of Copier for scaffolding and updating Jinja2 project templates." | |
| 7 | + | release_tag = "v" |
install.sh+162−0
| @@ -0,0 +1,162 @@ | |||
| 1 | + | #!/bin/sh | |
| 2 | + | # Install Ronéo from https://code.cleyrop.tech/roneo releases with SHA-256 verification. | |
| 3 | + | # | |
| 4 | + | # Usage: | |
| 5 | + | # curl -fsSL https://code.cleyrop.tech/roneo/raw/main/install.sh | sh | |
| 6 | + | # RONEO_VERSION=v0.1.0 sh install.sh | |
| 7 | + | # RONEO_INSTALL_DIR=/usr/local/bin sh install.sh | |
| 8 | + | set -eu | |
| 9 | + | ||
| 10 | + | FORGE_URL="${RONEO_FORGE_URL:-https://code.cleyrop.tech}" | |
| 11 | + | REPO="${RONEO_REPO:-roneo}" | |
| 12 | + | VERSION="${RONEO_VERSION:-latest}" | |
| 13 | + | INSTALL_DIR="${RONEO_INSTALL_DIR:-${HOME}/.local/bin}" | |
| 14 | + | ||
| 15 | + | need_cmd() { | |
| 16 | + | if ! command -v "$1" >/dev/null 2>&1; then | |
| 17 | + | printf 'error: required command not found: %s\n' "$1" >&2 | |
| 18 | + | exit 1 | |
| 19 | + | fi | |
| 20 | + | } | |
| 21 | + | ||
| 22 | + | detect_os() { | |
| 23 | + | case "$(uname -s)" in | |
| 24 | + | Linux*) printf 'linux' ;; | |
| 25 | + | Darwin*) printf 'darwin' ;; | |
| 26 | + | *) | |
| 27 | + | printf 'error: unsupported OS: %s\n' "$(uname -s)" >&2 | |
| 28 | + | exit 1 | |
| 29 | + | ;; | |
| 30 | + | esac | |
| 31 | + | } | |
| 32 | + | ||
| 33 | + | detect_arch() { | |
| 34 | + | case "$(uname -m)" in | |
| 35 | + | x86_64 | amd64) printf 'amd64' ;; | |
| 36 | + | aarch64 | arm64) printf 'arm64' ;; | |
| 37 | + | *) | |
| 38 | + | printf 'error: unsupported architecture: %s\n' "$(uname -m)" >&2 | |
| 39 | + | exit 1 | |
| 40 | + | ;; | |
| 41 | + | esac | |
| 42 | + | } | |
| 43 | + | ||
| 44 | + | sha256_file() { | |
| 45 | + | if command -v sha256sum >/dev/null 2>&1; then | |
| 46 | + | sha256sum "$1" | awk '{print $1}' | |
| 47 | + | elif command -v shasum >/dev/null 2>&1; then | |
| 48 | + | shasum -a 256 "$1" | awk '{print $1}' | |
| 49 | + | else | |
| 50 | + | printf 'error: neither sha256sum nor shasum found\n' >&2 | |
| 51 | + | exit 1 | |
| 52 | + | fi | |
| 53 | + | } | |
| 54 | + | ||
| 55 | + | main() { | |
| 56 | + | need_cmd curl | |
| 57 | + | need_cmd uname | |
| 58 | + | ||
| 59 | + | os="$(detect_os)" | |
| 60 | + | arch="$(detect_arch)" | |
| 61 | + | api_url="${FORGE_URL}/api/v1/repos/${REPO}/releases/${VERSION}" | |
| 62 | + | ||
| 63 | + | tmpdir="$(mktemp -d)" | |
| 64 | + | trap 'rm -rf "$tmpdir"' EXIT INT TERM | |
| 65 | + | ||
| 66 | + | meta_file="${tmpdir}/release.json" | |
| 67 | + | printf 'Fetching %s release metadata (%s/%s)...\n' "$REPO" "$os" "$arch" | |
| 68 | + | curl -fsSL -H 'Accept: application/json' "$api_url" -o "$meta_file" | |
| 69 | + | ||
| 70 | + | # Resolve asset url, sha256, and tag from the forge-public JSON schema (lot 7). | |
| 71 | + | # Uses python3 if available, otherwise jq (no `eval`). | |
| 72 | + | parsed_file="${tmpdir}/parsed.txt" | |
| 73 | + | if command -v python3 >/dev/null 2>&1; then | |
| 74 | + | python3 -c ' | |
| 75 | + | import json, sys | |
| 76 | + | data = json.load(open(sys.argv[1])) | |
| 77 | + | os_name, arch_name = sys.argv[2], sys.argv[3] | |
| 78 | + | tag = data.get("tag") or data.get("version") or "" | |
| 79 | + | match = None | |
| 80 | + | for a in data.get("assets", []): | |
| 81 | + | if a.get("bin", "roneo") == "roneo" and a.get("os") == os_name and a.get("arch") == arch_name: | |
| 82 | + | match = a | |
| 83 | + | break | |
| 84 | + | if not match: | |
| 85 | + | sys.stderr.write(f"error: no roneo release asset found for {os_name}/{arch_name} in {tag}\n") | |
| 86 | + | sys.exit(1) | |
| 87 | + | print(tag) | |
| 88 | + | print(match["url"]) | |
| 89 | + | print(match.get("sha256", "")) | |
| 90 | + | ' "$meta_file" "$os" "$arch" > "$parsed_file" | |
| 91 | + | elif command -v jq >/dev/null 2>&1; then | |
| 92 | + | jq -r --arg os "$os" --arg arch "$arch" ' | |
| 93 | + | (.tag // .version // ""), | |
| 94 | + | ([.assets[] | select((.bin // "roneo") == "roneo" and .os == $os and .arch == $arch)][0] | (.url // ""), (.sha256 // "")) | |
| 95 | + | ' "$meta_file" > "$parsed_file" | |
| 96 | + | else | |
| 97 | + | printf 'error: python3 or jq is required to parse release metadata\n' >&2 | |
| 98 | + | exit 1 | |
| 99 | + | fi | |
| 100 | + | ||
| 101 | + | { | |
| 102 | + | IFS= read -r TAG || true | |
| 103 | + | IFS= read -r ASSET_URL || true | |
| 104 | + | IFS= read -r ASSET_SHA256 || true | |
| 105 | + | } < "$parsed_file" | |
| 106 | + | if [ -z "$ASSET_URL" ]; then | |
| 107 | + | printf 'error: no roneo release asset found for %s/%s\n' "$os" "$arch" >&2 | |
| 108 | + | exit 1 | |
| 109 | + | fi | |
| 110 | + | ||
| 111 | + | case "$ASSET_URL" in | |
| 112 | + | http://*|https://*) download_url="$ASSET_URL" ;; | |
| 113 | + | /*) download_url="${FORGE_URL}${ASSET_URL}" ;; | |
| 114 | + | *) download_url="${FORGE_URL}/${ASSET_URL}" ;; | |
| 115 | + | esac | |
| 116 | + | ||
| 117 | + | dl_path="${tmpdir}/asset" | |
| 118 | + | printf 'Downloading roneo %s (%s/%s)...\n' "$TAG" "$os" "$arch" | |
| 119 | + | curl -fsSL "$download_url" -o "$dl_path" | |
| 120 | + | ||
| 121 | + | if [ -n "$ASSET_SHA256" ]; then | |
| 122 | + | actual="$(sha256_file "$dl_path")" | |
| 123 | + | if [ "$actual" != "$ASSET_SHA256" ]; then | |
| 124 | + | printf 'error: SHA-256 mismatch!\n expected: %s\n actual: %s\n' "$ASSET_SHA256" "$actual" >&2 | |
| 125 | + | exit 1 | |
| 126 | + | fi | |
| 127 | + | printf 'Verified SHA-256: %s\n' "$actual" | |
| 128 | + | fi | |
| 129 | + | ||
| 130 | + | bin_src="$dl_path" | |
| 131 | + | case "$download_url" in | |
| 132 | + | *.tar.gz|*.tgz) | |
| 133 | + | need_cmd tar | |
| 134 | + | mkdir -p "${tmpdir}/extract" | |
| 135 | + | tar -xzf "$dl_path" -C "${tmpdir}/extract" | |
| 136 | + | bin_src="$(find "${tmpdir}/extract" -type f -name roneo | head -n 1)" | |
| 137 | + | ;; | |
| 138 | + | *.zip) | |
| 139 | + | need_cmd unzip | |
| 140 | + | mkdir -p "${tmpdir}/extract" | |
| 141 | + | unzip -q "$dl_path" -d "${tmpdir}/extract" | |
| 142 | + | bin_src="$(find "${tmpdir}/extract" -type f -name roneo | head -n 1)" | |
| 143 | + | ;; | |
| 144 | + | esac | |
| 145 | + | ||
| 146 | + | if [ -z "$bin_src" ] || [ ! -f "$bin_src" ]; then | |
| 147 | + | printf 'error: downloaded asset did not contain a roneo binary\n' >&2 | |
| 148 | + | exit 1 | |
| 149 | + | fi | |
| 150 | + | ||
| 151 | + | mkdir -p "$INSTALL_DIR" | |
| 152 | + | chmod 0755 "$bin_src" | |
| 153 | + | mv -f "$bin_src" "${INSTALL_DIR}/roneo" | |
| 154 | + | ||
| 155 | + | printf 'Installed roneo %s -> %s/roneo\n' "$TAG" "$INSTALL_DIR" | |
| 156 | + | case ":${PATH}:" in | |
| 157 | + | *":${INSTALL_DIR}:"*) ;; | |
| 158 | + | *) printf 'Note: add %s to your PATH to run roneo directly.\n' "$INSTALL_DIR" ;; | |
| 159 | + | esac | |
| 160 | + | } | |
| 161 | + | ||
| 162 | + | main "$@" |
| @@ -0,0 +1,3 @@ | |||
| 1 | + | [toolchain] | |
| 2 | + | channel = "1.100.0" | |
| 3 | + | components = ["rustfmt", "clippy"] |