Skip to main content

greengate_runtime/hooks/
prettier.rs

1//! pre-commit-prettier — format check over staged files, scoped to repos that
2//! actually opt into prettier.
3
4use super::common::{
5    fail, first_existing, fixing_enabled, hl, ok, repo_root, resolve_js_tool, restage,
6    run as run_tool, run_quiet, staged_files, JsTool, Restaged,
7};
8use crate::check::Outcome;
9use std::path::Path;
10
11/// Everything prettier is asked to look at.
12///
13/// Exported, even though `registry.rs` deliberately declares
14/// `Scope::files(&[])` for this check (it is opt-in by CONFIG, not by file
15/// type): the drift guard needs to know what the check actually consumes, and
16/// an empty declared set is a subset of this one.
17pub const EXTS: &[&str] = &[
18    ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".json", ".jsonc", ".css", ".scss", ".less",
19    ".html", ".vue", ".md", ".mdx", ".yaml", ".yml",
20];
21
22/// A repo opts in via a prettier config file, or `prettier` named in its root
23/// package.json (a `"prettier"` key, or a direct dependency). Without that
24/// signal the hook does nothing — in a repo that does not use prettier, `npx
25/// prettier` would download it and flag every file against defaults.
26///
27/// A `node_modules/.bin/prettier` alone is NOT a signal (#307): a transitive
28/// dependency (an eslint preset, a storybook) hoists one into any workspace,
29/// and the check then judged a repository that never chose prettier.
30fn has_config(root: &str) -> bool {
31    if first_existing(
32        root,
33        &[
34            ".prettierrc",
35            "prettier.config.js",
36            "prettier.config.mjs",
37            "prettier.config.cjs",
38            ".prettierrc.json",
39            ".prettierrc.yml",
40            ".prettierrc.yaml",
41            ".prettierrc.js",
42            ".prettierrc.cjs",
43            ".prettierrc.mjs",
44            ".prettierrc.toml",
45        ],
46    )
47    .is_some()
48    {
49        return true;
50    }
51    std::fs::read_to_string(Path::new(root).join("package.json"))
52        .map(|p| p.contains("\"prettier\""))
53        .unwrap_or(false)
54}
55
56pub fn run(settings: &crate::config::Settings, _args: &[std::ffi::OsString]) -> Outcome {
57    let files = staged_files(EXTS);
58    if files.is_empty() {
59        return Outcome::Passed;
60    }
61    let root = repo_root();
62
63    // Without config the repo does not use prettier, whatever a dependency
64    // hoisted into node_modules/.bin (#307). Decided before resolving, which
65    // may probe a PATH copy's `--version`: a repo that does not use prettier
66    // must not pay for that.
67    if !has_config(&root) {
68        return Outcome::Passed;
69    }
70    let js = resolve_js_tool(&root, "prettier");
71    let argv = match &js.tool {
72        JsTool::Pinned(argv) => argv.clone(),
73        // Runs, and says it is not the repository's copy (ADR-0019).
74        JsTool::Ambient { argv, ambient } => {
75            js.warn_ambient(ambient);
76            argv.clone()
77        }
78        // NotInstalled: PATH's prettier is not the version package.json asked
79        // for. NpxHung, Missing: nothing to run.
80        JsTool::NotInstalled | JsTool::NpxHung | JsTool::Missing => {
81            js.warn_unavailable();
82            return Outcome::Unavailable;
83        }
84    };
85
86    // Ignore a GLOBAL ~/.editorconfig when this repo defines none of its own:
87    // prettier otherwise walks up past the repo and enforces machine-wide
88    // defaults (4-space, say) on a repo formatted differently — a false
89    // positive that also disagrees with CI, which has no ~/.editorconfig.
90    // A repo-level .editorconfig is still honoured, matching CI.
91    let mut flags: Vec<String> = Vec::new();
92    if !Path::new(&root).join(".editorconfig").is_file() {
93        flags.push("--no-editorconfig".into());
94    }
95
96    // `--` before the file list at each of these: a staged file named e.g.
97    // `-x.js` would otherwise be read as a flag by prettier's own parser —
98    // and prettier does not even error on that, it exits 0 having checked
99    // nothing, so the file would silently never be linted at all.
100    // ONE `--check` pass. It used to run twice on the clean path — once to
101    // decide whether to repair, once to decide the verdict — which is a whole
102    // extra prettier startup on every commit that had nothing wrong with it.
103    let mut check = flags.clone();
104    check.push("--check".into());
105    check.push("--".into());
106    check.extend(files.iter().cloned());
107    if run_quiet(settings, &root, &argv, &check) {
108        ok(settings, "Prettier passed");
109        return Outcome::Passed;
110    }
111
112    if fixing_enabled(settings) {
113        // Asked to repair, so repair rather than reporting an instruction the
114        // author would carry out identically by hand.
115        let mut write = flags.clone();
116        write.push("--write".into());
117        write.push("--".into());
118        write.extend(files.iter().cloned());
119        if run_quiet(settings, &root, &argv, &write) {
120            // Dropping the confirming re-`--check` after the write is safe:
121            // `prettier --write` exits NON-ZERO on a parse error, so a
122            // successful write means the files are formatted.
123            match restage(&files) {
124                Restaged::Staged => {
125                    ok(settings, "Prettier reformatted and re-staged");
126                    return Outcome::Fixed;
127                }
128                // The index still holds the content prettier has just replaced
129                // on disk. Reporting anything but a failure here is how
130                // unformatted code reached a commit the hook called clean.
131                Restaged::Failed(stuck) => {
132                    fail(&format!(
133                        "Prettier reformatted these files but {} failed — the index still \
134                         holds the UNFORMATTED content: {}",
135                        hl("git add"),
136                        stuck.join(", ")
137                    ));
138                    return Outcome::Failed;
139                }
140                // Nothing differed from the index, so the write changed
141                // nothing that was staged. Fall through and report.
142                Restaged::Nothing => {}
143            }
144        }
145    }
146
147    fail(&format!(
148        "Prettier found unformatted files. Run {} on:",
149        hl("prettier --write")
150    ));
151    let mut list = flags;
152    list.push("--list-different".into());
153    list.push("--".into());
154    list.extend(files);
155    let _ = run_tool(settings, &root, &argv, &list);
156    Outcome::Failed
157}