joeira 0.1.9

joeira — the typed git-hook control plane: one closed predicate algebra, one registry, one default library
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
use std::io::Read;
use std::path::{Path, PathBuf};

use joeira_core::camadas::{
    Borda, Fontes, Lida, Resolucao, caminho_sistema, caminho_usuario, le_camada, resolve,
};
use joeira_core::journal::{Diario, Registro, TagVeredito};
use joeira_core::shell::{AmbienteShell, autoridade_de, raiz_de};
use joeira_core::{
    AmbienteGit, Nivel, Ponto, Regra, Severidade, Veredito, Verificador, avalia, le_envios,
};

pub const CHAVE_DESLIGA: &str = "JOEIRA_OFF";
pub const CHAVE_SEM_BORDA: &str = "JOEIRA_SEM_BORDA";
pub const ARQUIVOS_DE_BORDA: &[&str] = &["joeira.lisp", "caixa.lisp"];

pub fn le_borda(raiz: &Path) -> Lida<Borda> {
    for nome in ARQUIVOS_DE_BORDA {
        let caminho = raiz.join(nome);
        let fonte = caminho.display().to_string();
        let texto = match std::fs::read_to_string(&caminho) {
            Ok(t) => t,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
            Err(e) => return Some((fonte, Err(e.to_string()))),
        };
        match joeira_lisp::ler_borda(&texto) {
            Ok(Some(b)) => return Some((fonte, Ok(b))),
            Ok(None) => {}
            Err(e) => return Some((fonte, Err(e.to_string()))),
        }
    }
    None
}

pub fn em_camadas(regras: &[Regra], raiz: &Path) -> Resolucao {
    let sem_borda = std::env::var(CHAVE_SEM_BORDA).is_ok_and(|v| v == "1");
    let fontes = Fontes {
        sistema: le_camada(&caminho_sistema()),
        usuario: caminho_usuario().and_then(|p| le_camada(&p)),
        borda: if sem_borda { None } else { le_borda(raiz) },
        autoridade: autoridade_de(raiz).ok(),
    };
    if sem_borda {
        eprintln!("joeira: the repository edge layer is ignored ({CHAVE_SEM_BORDA}=1)");
    }
    resolve(regras.to_vec(), &fontes)
}

pub fn relata_recusas(onde: &str, r: &Resolucao) {
    for x in &r.recusas {
        eprintln!("joeira {onde}: REFUSED {x}");
    }
}

fn julga_em_camadas(ponto: Ponto, regras: &[Regra], amb: &AmbienteShell, repo: &Path) {
    let res = em_camadas(regras, repo);
    relata_recusas(ponto.arquivo(), &res);
    julga(ponto, &res.regras, amb, repo, Diario::padrao().as_ref());
}

#[derive(Debug, Default, PartialEq, Eq)]
pub struct Balanco {
    pub regras: usize,
    pub achados: usize,
    pub cegos: usize,
    pub fora: usize,
}

pub fn desligado() -> bool {
    std::env::var(CHAVE_DESLIGA).is_ok_and(|v| v == "1")
}

fn protegido(ponto: Ponto, corpo: impl FnOnce() -> anyhow::Result<()>) {
    if desligado() {
        eprintln!(
            "joeira {}: DISABLED by {CHAVE_DESLIGA}=1 — no rule was evaluated",
            ponto.arquivo()
        );
        return;
    }
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(corpo)) {
        Ok(Ok(())) => {}
        Ok(Err(e)) => eprintln!(
            "joeira {}: DEGRADED, nothing was judged: {e:#} (exit 0, advisory at P1)",
            ponto.arquivo()
        ),
        Err(_) => eprintln!(
            "joeira {}: DEGRADED, the engine panicked (exit 0, advisory at P1)",
            ponto.arquivo()
        ),
    }
}

fn raiz() -> anyhow::Result<PathBuf> {
    let aqui = std::env::current_dir()?;
    Ok(raiz_de(&aqui)?)
}

pub fn le_mensagem(bruta: &str) -> String {
    let mut linhas = Vec::new();
    for l in bruta.lines() {
        if l.starts_with("# ------------------------ >8 ------------------------") {
            break;
        }
        if !l.starts_with('#') {
            linhas.push(l);
        }
    }
    let mut m = linhas.join("\n");
    m.truncate(m.trim_end().len());
    m
}

pub fn julga<E: AmbienteGit + ?Sized>(
    ponto: Ponto,
    regras: &[Regra],
    amb: &E,
    repo: &Path,
    diario: Option<&Diario>,
) -> Balanco {
    let mut b = Balanco::default();
    for r in regras.iter().filter(|r| r.ponto() == ponto) {
        b.regras += 1;
        let v = avalia(r, amb);
        match &v {
            Veredito::Achado {
                regra, mensagem, ..
            } => {
                b.achados += 1;
                eprintln!(
                    "joeira {}: WARN {regra} [{}]: {mensagem}",
                    ponto.arquivo(),
                    r.nivel().simbolo()
                );
            }
            Veredito::Cego { regra, porque } => {
                b.cegos += 1;
                eprintln!("joeira {}: NOT CHECKED {regra}: {porque}", ponto.arquivo());
            }
            Veredito::NaoSeAplica { .. } => b.fora += 1,
            Veredito::Limpo => {}
        }
        if let Some(d) = diario {
            let reg = Registro {
                regra: r.nome().to_owned(),
                veredito: TagVeredito::from(&v),
                repo: repo.display().to_string(),
                quando: joeira_core::journal::agora(),
                severidade: matches!(v, Veredito::Achado { .. }).then_some(Severidade::Avisa),
            };
            if let Err(e) = d.registrar(&reg) {
                eprintln!("joeira {}: journal not written: {e}", ponto.arquivo());
            }
        }
    }
    eprintln!(
        "joeira {}: {} rules, {} findings, {} not checked, {} not applicable — advisory (P1), exit 0",
        ponto.arquivo(),
        b.regras,
        b.achados,
        b.cegos,
        b.fora
    );
    b
}

pub fn pre_commit(regras: &[Regra]) {
    protegido(Ponto::PreCommit, || {
        let repo = raiz()?;
        let amb = AmbienteShell::novo(&repo);
        julga_em_camadas(Ponto::PreCommit, regras, &amb, &repo);
        Ok(())
    });
}

pub fn commit_msg(regras: &[Regra], arquivo: &Path) {
    protegido(Ponto::CommitMsg, || {
        let bruta = std::fs::read(arquivo)
            .map_err(|e| anyhow::anyhow!("cannot read message file {}: {e}", arquivo.display()))?;
        let msg = le_mensagem(&String::from_utf8_lossy(&bruta));
        if msg.is_empty() {
            eprintln!(
                "joeira commit-msg: the message in {} is EMPTY — judging it as empty",
                arquivo.display()
            );
        }
        let repo = raiz()?;
        let amb = AmbienteShell::novo(&repo).com_mensagem(&msg);
        julga_em_camadas(Ponto::CommitMsg, regras, &amb, &repo);
        Ok(())
    });
}

pub fn pre_push(regras: &[Regra], remoto: &str, url: &str) {
    protegido(Ponto::PrePush, || {
        let mut entrada = String::new();
        std::io::stdin()
            .read_to_string(&mut entrada)
            .map_err(|e| anyhow::anyhow!("cannot read pre-push stdin: {e}"))?;
        let envios = le_envios(&entrada)?;
        let vivos: Vec<_> = envios.into_iter().filter(|e| !e.eh_remocao()).collect();
        if vivos.is_empty() {
            eprintln!(
                "joeira pre-push: no ref-triples to judge on stdin for {remoto} ({url}) — nothing was checked"
            );
            return Ok(());
        }
        let repo = raiz()?;
        let amb = AmbienteShell::novo(&repo).com_envios(vivos);
        julga_em_camadas(Ponto::PrePush, regras, &amb, &repo);
        Ok(())
    });
}

pub fn explain(regras: &[Regra], staged: bool) -> anyhow::Result<()> {
    anyhow::ensure!(
        staged,
        "explain needs --staged; it judges the index as pre-commit would"
    );
    let repo = raiz()?;
    let amb = AmbienteShell::novo(&repo);
    let res = em_camadas(regras, &repo);
    println!("joeira explain --staged in {}", repo.display());
    println!(
        "source: joeira-lisp/catalogo/joeira.tlisp (compiled in), joeira {}",
        env!("CARGO_PKG_VERSION")
    );
    for x in &res.recusas {
        println!("  REFUSED {x}");
    }
    for (nome, o) in &res.subtraidas {
        println!("  -      {nome}\n         subtracted by {}", o.rotulo());
    }
    for r in &res.regras {
        let origem = res.origem(r.nome()).map_or_else(
            || "unknown".to_owned(),
            joeira_core::camadas::Origem::rotulo,
        );
        let isentos = if r.isencoes().is_empty() {
            String::new()
        } else {
            format!("; exempt under {}", r.isencoes().join(", "))
        };
        let cabeca = format!(
            "{} @{} layer={} trigger={}",
            r.nome(),
            r.ponto().arquivo(),
            r.nivel().simbolo(),
            r.gatilho().unwrap_or("-")
        );
        let porque = format!(
            "axes {} x {} => ceiling {}; effective floor {} set by {origem}{isentos}; P1 advisory: acts at most avisa, exit 0",
            r.reversibilidade().simbolo(),
            r.fp().simbolo(),
            r.tecto().simbolo(),
            r.severidade().simbolo()
        );
        if r.ponto() != Ponto::PreCommit {
            println!(
                "  -      {cabeca}\n         not evaluated: mounts at {}\n         {porque}",
                r.ponto().arquivo()
            );
            continue;
        }
        let (marca, detalhe) = match avalia(r, &amb) {
            Veredito::Achado { mensagem, .. } => ("WARN ", mensagem),
            Veredito::Limpo => ("clean", "predicate does not hold on the index".to_owned()),
            Veredito::NaoSeAplica { porque, .. } => ("n/a  ", porque),
            Veredito::Cego { porque, .. } => ("BLIND", porque),
        };
        println!("  {marca}  {cabeca}\n         {detalhe}\n         {porque}");
    }
    Ok(())
}

pub fn no_path(programa: &str) -> Option<PathBuf> {
    let path = std::env::var_os("PATH")?;
    std::env::split_paths(&path)
        .map(|d| d.join(programa))
        .find(|c| c.is_file())
}

pub fn status(regras: &[Regra]) {
    println!(
        "joeira {} — P1, every rule advises",
        env!("CARGO_PKG_VERSION")
    );
    println!(
        "kill switch: {CHAVE_DESLIGA}={}",
        if desligado() {
            "1 (hooks DISABLED)"
        } else {
            "unset (hooks armed)"
        }
    );
    println!("corpus: {} rules", regras.len());
    for p in Ponto::todos() {
        let n = regras.iter().filter(|r| r.ponto() == *p).count();
        println!("  {:<11} {n}", p.arquivo());
    }
    for nv in Nivel::todos() {
        let n = regras.iter().filter(|r| r.nivel() == *nv).count();
        println!("  layer {:<15} {n}", nv.simbolo());
    }
    println!("tools:");
    let mut vistos = Vec::new();
    for v in Verificador::todos() {
        let prog = v.programa();
        if vistos.contains(&prog) {
            continue;
        }
        vistos.push(prog);
        match no_path(prog) {
            Some(c) => println!("  {prog:<11} {}", c.display()),
            None => println!("  {prog:<11} ABSENT — its rows report `not checked`"),
        }
    }
    match Diario::padrao() {
        Some(d) => match d.registros() {
            Ok(r) => println!(
                "journal: {} ({} records)",
                d.caminho().as_path().display(),
                r.len()
            ),
            Err(e) => println!(
                "journal: {} (unreadable: {e})",
                d.caminho().as_path().display()
            ),
        },
        None => println!("journal: no state directory resolved"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use joeira_core::{AmbienteMock, ClasseFalsoPositivo, Predicado, Reversibilidade};

    #[test]
    fn the_message_file_drops_comments_and_the_scissors_tail() {
        let m = le_mensagem(
            "feat: x\n\nbody\n# Please enter\n# ------------------------ >8 ------------------------\ndiff\n",
        );
        assert_eq!(m, "feat: x\n\nbody");
    }

    #[test]
    fn an_empty_message_file_reads_empty() {
        assert_eq!(le_mensagem(""), "");
    }

    fn regra_externa() -> Regra {
        Regra::nova(
            "x",
            Ponto::PrePush,
            Predicado::Externo {
                verificador: Verificador::GoVet,
            },
            Reversibilidade::Recuperavel,
            ClasseFalsoPositivo::Limiar,
            "m",
            AmbienteMock::default(),
            AmbienteMock::default(),
        )
        .com_origem(Nivel::ClasseDeRepo, Some("go.mod".into()))
    }

    #[test]
    fn julga_counts_only_its_point_and_never_gates() {
        let r = regra_externa();
        let amb = AmbienteMock::default()
            .com_arvore("go.mod")
            .com_execucao(Verificador::GoVet, 2);
        let b = julga(
            Ponto::PrePush,
            std::slice::from_ref(&r),
            &amb,
            Path::new("/x"),
            None,
        );
        assert_eq!(
            b,
            Balanco {
                regras: 1,
                achados: 1,
                cegos: 0,
                fora: 0
            }
        );
        let b = julga(Ponto::PreCommit, &[r], &amb, Path::new("/x"), None);
        assert_eq!(b.regras, 0);
    }

    #[test]
    fn an_absent_tool_is_counted_not_checked() {
        let amb = AmbienteMock::default().com_arvore("go.mod");
        let b = julga(
            Ponto::PrePush,
            &[regra_externa()],
            &amb,
            Path::new("/x"),
            None,
        );
        assert_eq!(b.cegos, 1);
        assert_eq!(b.achados, 0);
    }

    #[test]
    fn an_absent_trigger_is_not_applicable() {
        let b = julga(
            Ponto::PrePush,
            &[regra_externa()],
            &AmbienteMock::default(),
            Path::new("/x"),
            None,
        );
        assert_eq!(b.fora, 1);
    }
}