croft 0.1.1

Per-project dev-loop tool: Docker Compose, scripts, hooks, and agents in one config
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! `.pre-commit-config.yaml` schema.
//!
//! The schema croft reads is a strict subset of pre-commit's. Unknown keys
//! are tolerated (forward compat with the upstream format). The
//! [`HookLanguage`] tag is **advisory metadata** — croft does not gate
//! execution on it: every hook's `entry` is parsed with `shell_words` and
//! spawned directly, with the runtime (python, node, …) expected to be on
//! `PATH` after `croft install`. The one shape that can't be exec'd
//! verbatim is `repo: meta`; the runner rejects it at run-time.
//!
//! croft-specific extension keys (parsed but ignored by pre-commit):
//!
//! - `in: "<service>"` on a [`HookSpec`] routes the hook through the
//!   configured container [`Backend`](crate::container::Backend), the
//!   same way `[command.<name>] in = "..."` does for recipes. Absent →
//!   workspace target (host, or devcontainer when
//!   `[devcontainer] enabled = true`).

use crate::hooks::error::HookError;
use serde::Deserialize;
use std::path::Path;

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct PreCommitConfig {
    #[serde(default)]
    pub repos: Vec<Repo>,
    #[serde(default, rename = "default_stages")]
    pub default_stages: Vec<String>,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct Repo {
    pub repo: String,
    #[serde(default)]
    pub rev: Option<String>,
    #[serde(default)]
    pub hooks: Vec<HookSpec>,
}

impl Repo {
    /// True when the repo's hooks are defined inline in the user's
    /// `.pre-commit-config.yaml` (no clone needed). `repo: meta` was
    /// historically treated as local; it isn't — meta references
    /// pre-commit's built-in lint hooks, which croft does not
    /// implement. The runner errors when it encounters one.
    pub fn is_local(&self) -> bool {
        self.repo == "local"
    }

    /// True only for `repo: meta` — pre-commit's built-in hook bundle.
    pub fn is_meta(&self) -> bool {
        self.repo == "meta"
    }
}

/// Single hook entry as it appears inside an upstream repo's
/// `.pre-commit-hooks.yaml`. The shape matches [`HookSpec`] from the
/// user-side config — `id` is required, every other field is a
/// fallback that the user may override in their own
/// `.pre-commit-config.yaml`.
///
/// Kept as a separate struct (rather than reusing [`HookSpec`]) because
/// the merge direction matters: the user's `HookSpec` is the source of
/// truth for everything they explicitly set, falling back to this only
/// where they were silent.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct UpstreamHook {
    pub id: String,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub language: Option<HookLanguage>,
    #[serde(default)]
    pub entry: Option<String>,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default)]
    pub files: Option<String>,
    #[serde(default)]
    pub exclude: Option<String>,
    #[serde(default)]
    pub pass_filenames: Option<bool>,
    #[serde(default)]
    pub stages: Vec<String>,
    #[serde(default)]
    pub always_run: Option<bool>,
    /// croft extension: target service. Upstream repos rarely set this;
    /// it exists so a vendored `.pre-commit-hooks.yaml` can declare a
    /// sensible default that users can still override.
    #[serde(default, rename = "in")]
    pub service: Option<String>,
}

/// Read the `.pre-commit-hooks.yaml` from the root of a cached upstream
/// repo. Returns the full list as authored — callers index by `id`.
pub fn load_upstream_hooks(repo_dir: &Path) -> Result<Vec<UpstreamHook>, HookError> {
    let path = repo_dir.join(".pre-commit-hooks.yaml");
    let raw = std::fs::read_to_string(&path).map_err(|source| HookError::Io {
        path: path.clone(),
        source,
    })?;
    serde_yaml_ng::from_str(&raw).map_err(|source| HookError::Parse { path, source })
}

/// Merge an upstream hook definition into the user's reference. The
/// user wins on every explicitly-set field; upstream fills the gaps.
/// Errors only when the merged result lacks an `entry` — the
/// [`HookLanguage`] is treated as advisory metadata and never gates
/// the merge.
pub fn merge_with_upstream(
    user: &HookSpec,
    upstream: &UpstreamHook,
) -> Result<HookSpec, HookError> {
    // Upstream owns the language field — that's where the hook was
    // authored. We fall back to the user's value only when upstream
    // didn't declare one (rare, since `.pre-commit-hooks.yaml`
    // requires it).
    let language = upstream
        .language
        .clone()
        .unwrap_or_else(|| user.language.clone());
    let entry = user
        .entry
        .clone()
        .or_else(|| upstream.entry.clone())
        .ok_or_else(|| HookError::EntryMissing {
            hook: user.id.clone(),
        })?;
    Ok(HookSpec {
        id: user.id.clone(),
        name: user.name.clone().or_else(|| upstream.name.clone()),
        language,
        entry: Some(entry),
        args: if user.args.is_empty() {
            upstream.args.clone()
        } else {
            user.args.clone()
        },
        files: user.files.clone().or_else(|| upstream.files.clone()),
        exclude: user.exclude.clone().or_else(|| upstream.exclude.clone()),
        // `pass_filenames` defaults to true at deserialization, so we
        // can't tell whether the user said "yes" or omitted it. The
        // upstream value, when present, is taken as the more
        // authoritative default — but only when the user kept the
        // default true. Users who say `pass_filenames: false`
        // explicitly are honoured.
        pass_filenames: if !user.pass_filenames {
            false
        } else {
            upstream.pass_filenames.unwrap_or(true)
        },
        stages: if user.stages.is_empty() {
            upstream.stages.clone()
        } else {
            user.stages.clone()
        },
        always_run: user.always_run || upstream.always_run.unwrap_or(false),
        service: user.service.clone().or_else(|| upstream.service.clone()),
    })
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct HookSpec {
    pub id: String,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default = "default_language")]
    pub language: HookLanguage,
    #[serde(default)]
    pub entry: Option<String>,
    #[serde(default)]
    pub args: Vec<String>,
    /// Regex matched against staged file paths.
    #[serde(default)]
    pub files: Option<String>,
    /// Regex; matching files are excluded after `files` filtering.
    #[serde(default)]
    pub exclude: Option<String>,
    #[serde(default = "default_pass_filenames")]
    pub pass_filenames: bool,
    #[serde(default)]
    pub stages: Vec<String>,
    #[serde(default)]
    pub always_run: bool,
    /// croft extension: when set, the hook execs inside this container
    /// service (via the configured [`Backend`](crate::container::Backend))
    /// instead of running on the host or in the devcontainer. Matches
    /// recipe `in = "<service>"` semantics. Plain pre-commit ignores
    /// this key.
    #[serde(default, rename = "in")]
    pub service: Option<String>,
}

/// Hook language tag from `.pre-commit-config.yaml` / `.pre-commit-hooks.yaml`.
///
/// croft keeps this enum for parse fidelity and so future tooling
/// (`croft hooks list`, doctor) can reason about declared runtimes — but
/// it is **not** consulted by the runner. Every hook's `entry` is exec'd
/// verbatim regardless of language; the user is responsible for putting
/// the required runtime on `PATH` (typically through `croft install`).
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HookLanguage {
    System,
    Script,
    Python,
    Node,
    Ruby,
    Golang,
    Rust,
    Docker,
    DockerImage,
    Pygrep,
    Fail,
    #[serde(other)]
    Other,
}

fn default_language() -> HookLanguage {
    HookLanguage::System
}

const fn default_pass_filenames() -> bool {
    true
}

impl HookSpec {
    /// Whether this hook applies to `stage`.
    ///
    /// Pre-commit treats an empty `stages` list as "all stages", and
    /// project-level `default_stages` provides a fallback. We mirror that.
    pub fn applies_to_stage(&self, stage: &str, default_stages: &[String]) -> bool {
        if self.stages.is_empty() {
            return default_stages.is_empty() || default_stages.iter().any(|s| s == stage);
        }
        self.stages.iter().any(|s| s == stage)
    }
}

/// Read a `.pre-commit-config.yaml` from disk.
pub fn load_from_path(path: &Path) -> Result<PreCommitConfig, HookError> {
    let raw = std::fs::read_to_string(path).map_err(|source| HookError::Io {
        path: path.to_path_buf(),
        source,
    })?;
    serde_yaml_ng::from_str(&raw).map_err(|source| HookError::Parse {
        path: path.to_path_buf(),
        source,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;

    fn parse(yaml: &str) -> PreCommitConfig {
        serde_yaml_ng::from_str(yaml).unwrap()
    }

    #[test]
    fn parses_local_system_hook() {
        let cfg = parse(
            r#"
            repos:
              - repo: local
                hooks:
                  - id: rust-fmt
                    name: Rust fmt
                    language: system
                    entry: cargo fmt --check
                    files: \.rs$
                    pass_filenames: false
            "#,
        );
        assert_eq!(cfg.repos.len(), 1);
        let repo = &cfg.repos[0];
        assert!(repo.is_local());
        let hook = &repo.hooks[0];
        assert_eq!(hook.id, "rust-fmt");
        assert_eq!(hook.language, HookLanguage::System);
        assert_eq!(hook.entry.as_deref(), Some("cargo fmt --check"));
        assert!(!hook.pass_filenames);
    }

    #[test]
    fn parses_croft_service_extension() {
        let cfg = parse(
            r#"
            repos:
              - repo: local
                hooks:
                  - id: rustfmt
                    language: system
                    entry: cargo fmt --check
                    in: app
            "#,
        );
        assert_eq!(cfg.repos[0].hooks[0].service.as_deref(), Some("app"));
    }

    #[test]
    fn unknown_language_falls_back_to_other() {
        let cfg = parse(
            r#"
            repos:
              - repo: local
                hooks:
                  - id: weird
                    language: brainfuck
                    entry: noop
            "#,
        );
        assert_eq!(cfg.repos[0].hooks[0].language, HookLanguage::Other);
    }

    #[test]
    fn parses_external_repo_with_rev() {
        let cfg = parse(
            r#"
            repos:
              - repo: https://github.com/pre-commit/pre-commit-hooks
                rev: v4.5.0
                hooks:
                  - id: trailing-whitespace
            "#,
        );
        assert!(!cfg.repos[0].is_local());
        assert_eq!(cfg.repos[0].rev.as_deref(), Some("v4.5.0"));
    }

    #[test]
    fn pass_filenames_defaults_true() {
        let cfg = parse(
            r#"
            repos:
              - repo: local
                hooks:
                  - id: x
                    language: system
                    entry: echo
            "#,
        );
        assert!(cfg.repos[0].hooks[0].pass_filenames);
    }

    #[test]
    fn stage_filter_with_no_stages_uses_defaults() {
        let hook = HookSpec {
            id: "x".into(),
            name: None,
            language: HookLanguage::System,
            entry: None,
            args: vec![],
            files: None,
            exclude: None,
            pass_filenames: true,
            stages: vec![],
            always_run: false,
            service: None,
        };
        assert!(hook.applies_to_stage("pre-commit", &[]));
        assert!(hook.applies_to_stage("pre-commit", &["pre-commit".into()]));
        assert!(!hook.applies_to_stage("pre-push", &["pre-commit".into()]));
    }

    #[test]
    fn stage_filter_explicit() {
        let hook = HookSpec {
            id: "x".into(),
            name: None,
            language: HookLanguage::System,
            entry: None,
            args: vec![],
            files: None,
            exclude: None,
            pass_filenames: true,
            stages: vec!["pre-push".into()],
            always_run: false,
            service: None,
        };
        assert!(!hook.applies_to_stage("pre-commit", &[]));
        assert!(hook.applies_to_stage("pre-push", &[]));
    }

    #[test]
    fn merge_preserves_python_language_without_erroring() {
        let user = HookSpec {
            id: "ruff".into(),
            name: None,
            language: HookLanguage::System,
            entry: None,
            args: vec![],
            files: None,
            exclude: None,
            pass_filenames: true,
            stages: vec![],
            always_run: false,
            service: None,
        };
        let upstream = UpstreamHook {
            id: "ruff".into(),
            name: Some("Ruff".into()),
            language: Some(HookLanguage::Python),
            entry: Some("ruff".into()),
            args: vec![],
            files: None,
            exclude: None,
            pass_filenames: None,
            stages: vec![],
            always_run: None,
            service: None,
        };
        let merged = merge_with_upstream(&user, &upstream).unwrap();
        assert_eq!(merged.language, HookLanguage::Python);
        assert_eq!(merged.entry.as_deref(), Some("ruff"));
    }

    #[test]
    fn merge_inherits_service_from_upstream_when_user_silent() {
        let user = HookSpec {
            id: "lint".into(),
            name: None,
            language: HookLanguage::System,
            entry: None,
            args: vec![],
            files: None,
            exclude: None,
            pass_filenames: true,
            stages: vec![],
            always_run: false,
            service: None,
        };
        let upstream = UpstreamHook {
            id: "lint".into(),
            name: None,
            language: Some(HookLanguage::System),
            entry: Some("./lint.sh".into()),
            args: vec![],
            files: None,
            exclude: None,
            pass_filenames: None,
            stages: vec![],
            always_run: None,
            service: Some("app".into()),
        };
        let merged = merge_with_upstream(&user, &upstream).unwrap();
        assert_eq!(merged.service.as_deref(), Some("app"));
    }
}