buildl-core 0.3.1

Domain data, ports, and pure pipeline logic for the buildl build system — no I/O, no Lua.
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
//! The wants of a plugin's targets that a plugin does not allow.
//!
//! Its own file because it reports rather than refuses: the plan stops at the first violation,
//! while a report of a workspace's plugins lists every one of them.
//!
//! Responsibilities: [`plugin_violations`].
//!
//! Non-responsibilities: refusing a build, which the plan's check does; collecting what a
//! target wants beyond its program, which is [`wanted`](super::wanted)'s; and holding a want to
//! the workspace's ceiling, which [`outside`](super::outside) and the plan's check do.

use std::collections::{BTreeMap, BTreeSet};

use crate::error::DeclarationSite;
use crate::grants::wanted::program_of;
use crate::placement::layout::Layout;
use crate::types::{
    EnvMark, NetworkAccess, NodeId, PluginCap, PluginNetwork, PluginViolation, SettingName,
    SettingValue, TargetGraph, Want, Workspace,
};

/// Every want of a plugin's target that one plugin holding it does not allow.
///
/// A target is held by each plugin in its `narrowing`: the chain that declared it, and the
/// chain of the rule it names. Its wants are the program its command runs, each environment
/// variable it reads, and the network when it declares it. A variable marked `key` is held to
/// the `env` lists and one marked `unkeyed` to the `unkeyed` lists. A program one of its
/// dependencies builds is no want, as in the ceiling check. A want is allowed by a plugin only
/// when the plugin's manifest lists it and the workspace's cap for that plugin lists it too; a
/// plugin with no cap in `workspace` allows nothing, and the network is allowed only by a cap
/// that allows it. A target with an empty `narrowing` is held by no plugin.
///
/// The violations come in label order, then chain order, then program, variables in written
/// order, and network. Each names the plugin that does not allow the want, and what that plugin
/// allows of the same kind.
pub(crate) fn plugin_violations(
    graph: &TargetGraph,
    settings: &BTreeMap<SettingName, SettingValue>,
    layout: &Layout,
    workspace: &Workspace,
) -> Vec<PluginViolation> {
    let no_cap = PluginCap::default();
    let mut found = Vec::new();
    for (node, id) in graph.nodes().iter().zip((0_u32..).map(NodeId::new)) {
        if node.narrowing.is_empty() {
            continue;
        }
        let program = program_of(graph, node, id, settings, layout);
        let site = DeclarationSite::from(node);
        for member in &node.narrowing {
            let cap = workspace.plugins.get(&member.name).unwrap_or(&no_cap);
            let mut violation = |want: Want, allowed: BTreeSet<String>| {
                found.push(PluginViolation {
                    want,
                    site: site.clone(),
                    plugin: member.clone(),
                    allowed,
                });
            };
            if let Some(program) = &program
                && !(member.run.contains(program) && cap.run.contains(program))
            {
                violation(Want::Program(program.clone()), both(&member.run, &cap.run));
            }
            for (name, mark) in &node.env {
                let (want, manifest_list, cap_list) = match mark {
                    EnvMark::Key => (Want::Env(name.clone()), &member.env, &cap.env),
                    EnvMark::Unkeyed => {
                        (Want::Unkeyed(name.clone()), &member.unkeyed, &cap.unkeyed)
                    }
                };
                if !(manifest_list.contains(name) && cap_list.contains(name)) {
                    violation(want, both(manifest_list, cap_list));
                }
            }
            if node.network == NetworkAccess::Declared && cap.network != PluginNetwork::Allowed {
                violation(Want::Network(node.label.clone()), BTreeSet::new());
            }
        }
    }
    found
}

/// The entries both `manifest` and `cap` list, as text.
fn both<T: Ord + ToString>(manifest: &BTreeSet<T>, cap: &BTreeSet<T>) -> BTreeSet<String> {
    manifest
        .intersection(cap)
        .map(ToString::to_string)
        .collect()
}

#[cfg(test)]
mod tests {
    #![expect(
        clippy::unwrap_used,
        reason = "tests unwrap known-valid fixtures; a panic is the intended failure signal"
    )]

    use std::collections::{BTreeMap, BTreeSet};

    use super::plugin_violations;
    use crate::grants::fixtures::{command, dir, env_name, graph, keyed, marked, node, program};
    use crate::placement::layout::Layout;
    use crate::types::{
        ApproverMode, Ceiling, EnvMark, Execution, NetworkAccess, Node, Origin, PluginCap,
        PluginName, PluginNetwork, PluginRef, PluginVersion, PluginViolation, TargetGraph, Want,
        Workspace,
    };

    /// The plugin `name` at version 1.3.0, whose manifest lists `run` and `env`.
    fn plugin(name: &str, run: &[&str], env: &[&str]) -> PluginRef {
        PluginRef {
            unkeyed: BTreeSet::new(),
            name: PluginName::parse(name).unwrap(),
            version: PluginVersion::parse("1.3.0").unwrap(),
            run: run.iter().map(|text| program(text)).collect(),
            env: env.iter().map(|text| env_name(text)).collect(),
        }
    }

    /// The cap letting a plugin run `run` and read `env`, with the network as `network`.
    fn cap(run: &[&str], env: &[&str], network: PluginNetwork) -> PluginCap {
        PluginCap {
            unkeyed: BTreeSet::new(),
            run: run.iter().map(|text| program(text)).collect(),
            env: env.iter().map(|text| env_name(text)).collect(),
            network,
        }
    }

    /// A workspace holding `caps`, one per plugin name.
    fn workspace(caps: Vec<(&str, PluginCap)>) -> Workspace {
        Workspace {
            out: dir("out"),
            state: dir(".buildl"),
            ceiling: Ceiling {
                unkeyed: BTreeSet::new(),
                run: BTreeSet::new(),
                env: BTreeSet::new(),
                read: BTreeSet::new(),
                write: BTreeSet::new(),
            },
            execution: Execution::default(),
            approver: ApproverMode::Manifest,
            plugins: caps
                .into_iter()
                .map(|(name, cap)| (PluginName::parse(name).unwrap(), cap))
                .collect(),
            remote: None,
        }
    }

    /// A target `raw` running `run`, declared through the chain `chain`.
    fn by(raw: &str, run: &[&str], chain: &[PluginRef], change: impl FnOnce(&mut Node)) -> Node {
        node(raw, |node| {
            node.run = command(run);
            node.origin = Origin::plugins(chain.to_vec()).unwrap();
            node.narrowing = chain.to_vec();
            change(node);
        })
    }

    fn violations(graph: &TargetGraph, workspace: &Workspace) -> Vec<PluginViolation> {
        let layout = Layout::of(graph, &workspace.out).unwrap();
        plugin_violations(graph, &BTreeMap::new(), &layout, workspace)
    }

    fn texts(items: &[&str]) -> BTreeSet<String> {
        items.iter().map(|text| (*text).to_owned()).collect()
    }

    /// What a violation names: the want, the target, the plugin, and what the plugin allows.
    fn summary(violation: &PluginViolation) -> (Want, String, String, BTreeSet<String>) {
        (
            violation.want.clone(),
            violation.site.label.to_string(),
            violation.plugin.name.to_string(),
            violation.allowed.clone(),
        )
    }

    #[test]
    fn a_program_outside_the_manifest_is_refused() {
        let go = plugin("go", &["go"], &[]);
        let graph = graph(vec![by("//:app", &["curl"], &[go], |_| {})], &[&[]]);
        let workspace = workspace(vec![(
            "go",
            cap(&["go", "curl"], &[], PluginNetwork::Sealed),
        )]);
        let found = violations(&graph, &workspace);
        assert_eq!(
            found.iter().map(summary).collect::<Vec<_>>(),
            [(
                Want::Program(program("curl")),
                "//:app".to_owned(),
                "go".to_owned(),
                texts(&["go"])
            )]
        );
    }

    #[test]
    fn a_program_outside_the_workspace_cap_is_refused() {
        let go = plugin("go", &["go", "curl"], &[]);
        let graph = graph(vec![by("//:app", &["curl"], &[go], |_| {})], &[&[]]);
        let workspace = workspace(vec![("go", cap(&["go"], &[], PluginNetwork::Sealed))]);
        let found = violations(&graph, &workspace);
        assert_eq!(
            found.iter().map(summary).collect::<Vec<_>>(),
            [(
                Want::Program(program("curl")),
                "//:app".to_owned(),
                "go".to_owned(),
                texts(&["go"])
            )]
        );
    }

    #[test]
    fn a_plugin_with_no_cap_allows_nothing() {
        let go = plugin("go", &["go"], &[]);
        let graph = graph(vec![by("//:app", &["go"], &[go], |_| {})], &[&[]]);
        let found = violations(&graph, &workspace(Vec::new()));
        assert_eq!(
            found.iter().map(summary).collect::<Vec<_>>(),
            [(
                Want::Program(program("go")),
                "//:app".to_owned(),
                "go".to_owned(),
                BTreeSet::new()
            )]
        );
    }

    #[test]
    fn allowed_is_manifest_intersect_cap() {
        let go = plugin("go", &["go", "gofmt", "vet"], &[]);
        let graph = graph(vec![by("//:app", &["curl"], &[go], |_| {})], &[&[]]);
        let workspace = workspace(vec![(
            "go",
            cap(&["go", "vet", "curl"], &[], PluginNetwork::Sealed),
        )]);
        let found = violations(&graph, &workspace);
        assert_eq!(found[0].allowed, texts(&["go", "vet"]));
    }

    #[test]
    fn every_narrowing_member_is_checked() {
        let ourgo = plugin("ourgo", &["go"], &[]);
        let go = plugin("go", &["go", "gofmt"], &[]);
        let graph = graph(vec![by("//:app", &["gofmt"], &[ourgo, go], |_| {})], &[&[]]);
        let workspace = workspace(vec![
            ("ourgo", cap(&["go", "gofmt"], &[], PluginNetwork::Sealed)),
            ("go", cap(&["go", "gofmt"], &[], PluginNetwork::Sealed)),
        ]);
        let found = violations(&graph, &workspace);
        assert_eq!(
            found.iter().map(summary).collect::<Vec<_>>(),
            [(
                Want::Program(program("gofmt")),
                "//:app".to_owned(),
                "ourgo".to_owned(),
                texts(&["go"])
            )]
        );
    }

    #[test]
    fn the_innermost_member_is_checked_too() {
        let ourgo = plugin("ourgo", &["go", "gofmt"], &[]);
        let go = plugin("go", &["go"], &[]);
        let graph = graph(vec![by("//:app", &["gofmt"], &[ourgo, go], |_| {})], &[&[]]);
        let workspace = workspace(vec![
            ("ourgo", cap(&["go", "gofmt"], &[], PluginNetwork::Sealed)),
            ("go", cap(&["go", "gofmt"], &[], PluginNetwork::Sealed)),
        ]);
        let found = violations(&graph, &workspace);
        assert_eq!(
            found.iter().map(summary).collect::<Vec<_>>(),
            [(
                Want::Program(program("gofmt")),
                "//:app".to_owned(),
                "go".to_owned(),
                texts(&["go"])
            )]
        );
    }

    #[test]
    fn a_member_earlier_in_the_chain_is_listed_first() {
        let ourgo = plugin("ourgo", &["go"], &[]);
        let go = plugin("go", &["go"], &[]);
        let graph = graph(vec![by("//:app", &["cc"], &[ourgo, go], |_| {})], &[&[]]);
        let found = violations(&graph, &workspace(Vec::new()));
        let plugins: Vec<String> = found.iter().map(|v| v.plugin.name.to_string()).collect();
        assert_eq!(plugins, ["ourgo", "go"]);
    }

    #[test]
    fn a_plugin_rule_used_by_a_hand_written_target_is_checked() {
        let go = plugin("go", &["go"], &[]);
        let target = node("//:app", |node| {
            node.run = command(&["curl"]);
            node.narrowing = vec![go];
        });
        let graph = graph(vec![target], &[&[]]);
        let workspace = workspace(vec![(
            "go",
            cap(&["go", "curl"], &[], PluginNetwork::Sealed),
        )]);
        let found = violations(&graph, &workspace);
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].want, Want::Program(program("curl")));
        assert_eq!(found[0].site.origin, Origin::BuildFile);
    }

    #[test]
    fn a_variable_needs_the_manifest_and_the_cap() {
        let go = plugin("go", &["go"], &["GOPATH", "HOME"]);
        let graph = graph(
            vec![by("//:app", &["go"], &[go], |node| {
                node.env = keyed(&["GOPATH", "HOME", "PATH"]);
            })],
            &[&[]],
        );
        let workspace = workspace(vec![(
            "go",
            cap(&["go"], &["GOPATH", "PATH"], PluginNetwork::Sealed),
        )]);
        let found = violations(&graph, &workspace);
        assert_eq!(
            found.iter().map(summary).collect::<Vec<_>>(),
            [
                (
                    Want::Env(env_name("HOME")),
                    "//:app".to_owned(),
                    "go".to_owned(),
                    texts(&["GOPATH"])
                ),
                (
                    Want::Env(env_name("PATH")),
                    "//:app".to_owned(),
                    "go".to_owned(),
                    texts(&["GOPATH"])
                ),
            ]
        );
    }

    #[test]
    fn plugin_unkeyed_needs_table_and_manifest() {
        let violations_with = |manifest: &[&str], table: &[&str]| {
            let mut go = plugin("go", &["go"], &["HOME"]);
            go.unkeyed = manifest.iter().map(|text| env_name(text)).collect();
            let graph = graph(
                vec![by("//:app", &["go"], &[go], |node| {
                    node.env = marked(&[("HOME", EnvMark::Unkeyed)]);
                })],
                &[&[]],
            );
            let mut table_cap = cap(&["go"], &["HOME"], PluginNetwork::Sealed);
            table_cap.unkeyed = table.iter().map(|text| env_name(text)).collect();
            violations(&graph, &workspace(vec![("go", table_cap)]))
        };

        assert_eq!(violations_with(&["HOME"], &["HOME"]), Vec::new());
        for (manifest, table) in [(&[][..], &["HOME"][..]), (&["HOME"], &[]), (&[], &[])] {
            let found = violations_with(manifest, table);
            assert_eq!(
                found.iter().map(summary).collect::<Vec<_>>(),
                [(
                    Want::Unkeyed(env_name("HOME")),
                    "//:app".to_owned(),
                    "go".to_owned(),
                    texts(
                        &manifest
                            .iter()
                            .copied()
                            .filter(|name| table.contains(name))
                            .collect::<Vec<_>>()
                    )
                )]
            );
        }
    }

    #[test]
    fn a_key_mark_is_held_to_env_read_alone() {
        let go = plugin("go", &["go"], &["HOME"]);
        let graph = graph(
            vec![by("//:app", &["go"], &[go], |node| {
                node.env = keyed(&["HOME"]);
            })],
            &[&[]],
        );
        let workspace = workspace(vec![("go", cap(&["go"], &["HOME"], PluginNetwork::Sealed))]);
        assert_eq!(violations(&graph, &workspace), Vec::new());
    }

    #[test]
    fn network_needs_the_cap() {
        let go = plugin("go", &["go"], &[]);
        let fetch = |go: &PluginRef| {
            by("//:fetch", &["go"], std::slice::from_ref(go), |node| {
                node.network = NetworkAccess::Declared;
            })
        };

        let sealed = workspace(vec![("go", cap(&["go"], &[], PluginNetwork::Sealed))]);
        let found = violations(&graph(vec![fetch(&go)], &[&[]]), &sealed);
        assert_eq!(
            found.iter().map(summary).collect::<Vec<_>>(),
            [(
                Want::Network(crate::grants::fixtures::label("//:fetch")),
                "//:fetch".to_owned(),
                "go".to_owned(),
                BTreeSet::new()
            )]
        );

        let allowed = workspace(vec![("go", cap(&["go"], &[], PluginNetwork::Allowed))]);
        assert_eq!(
            violations(&graph(vec![fetch(&go)], &[&[]]), &allowed),
            Vec::new()
        );
    }

    #[test]
    fn a_built_program_is_not_held_to_a_plugin() {
        let go = plugin("go", &["go"], &[]);
        let generator = node("//:gen", |node| node.run = command(&["cc"]));
        let tool = by("//:use", &["out/gen/gen"], &[go], |_| {});
        let graph = graph(vec![generator, tool], &[&[], &[0]]);
        let workspace = workspace(vec![("go", cap(&["go"], &[], PluginNetwork::Sealed))]);
        assert_eq!(violations(&graph, &workspace), Vec::new());
    }

    #[test]
    fn build_file_targets_are_not_checked() {
        let graph = graph(
            vec![node("//:app", |node| {
                node.run = command(&["curl"]);
                node.env = keyed(&["HOME"]);
                node.network = NetworkAccess::Declared;
            })],
            &[&[]],
        );
        assert_eq!(violations(&graph, &workspace(Vec::new())), Vec::new());
    }

    #[test]
    fn violations_are_listed_in_label_order() {
        let go = plugin("go", &["go"], &[]);
        let graph = graph(
            vec![
                by("//:a", &["curl"], std::slice::from_ref(&go), |_| {}),
                by("//:b", &["curl"], std::slice::from_ref(&go), |_| {}),
                by("//lib:c", &["curl"], &[go], |_| {}),
            ],
            &[&[], &[], &[]],
        );
        let workspace = workspace(vec![("go", cap(&["go"], &[], PluginNetwork::Sealed))]);
        let labels: Vec<String> = violations(&graph, &workspace)
            .iter()
            .map(|violation| violation.site.label.to_string())
            .collect();
        assert_eq!(labels, ["//:a", "//:b", "//lib:c"]);
    }
}