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
//! One instance of every port, held together.
//!
//! Its own file because it is the value beside the [`Ports`] trait: the trait names one
//! implementation of each port, and this struct holds one instance of each, so a pipeline is
//! built from one argument and a phase that needs several ports borrows one value.
//!
//! Responsibilities: [`PortSet`], and its `Debug` rendering, which asks only that every
//! port type the bundle names be `Debug`.
//!
//! Non-responsibilities: building the instances. A composition root does that.

use std::fmt;

use crate::ports::Ports;

/// One instance of each port a bundle names.
///
/// The fields are public: a set has no invariant of its own, and whoever built the adapters may
/// reach them again between two commands.
pub struct PortSet<P: Ports> {
    /// Evaluates build files.
    pub source: P::Source,
    /// Reads the workspace's manifest.
    pub manifest: P::Manifest,
    /// Answers for the machine actions run on.
    pub host: P::Host,
    /// Reads a file's metadata and content digest.
    pub digester: P::Digester,
    /// Keeps the digests of files already hashed.
    pub stat_cache: P::StatCache,
    /// Finds the programs commands name.
    pub tools: P::Tools,
    /// Holds each target's row: the previous build's, then this one's.
    pub cache: P::Cache,
    /// Stores what actions produce, by content.
    pub cas: P::Cas,
    /// Receives the record of how each target ended.
    pub log: P::Log,
    /// Runs one action.
    pub strategy: P::Strategy,
    /// Has several actions run at once.
    pub dispatcher: P::Dispatcher,
    /// Reads the wall clock.
    pub clock: P::Clock,
    /// Keeps the graph a build resolved.
    pub graph: P::Graph,
    /// Shows what a build is doing.
    pub reporter: P::Reporter,
    /// Says whether a build may do what it wants.
    pub approver: P::Approver,
    /// Says which workspace paths the ignore files cover.
    pub ignore: P::Ignore,
    /// Looks results up in, and stores them to, a cache shared between machines.
    pub remote: P::Remote,
}

/// Written by hand because a derive would require the bundle type itself to be `Debug`, and a
/// bundle is only a choice of port types. This asks only that each port type the bundle names be `Debug`.
impl<P: Ports> fmt::Debug for PortSet<P>
where
    P::Source: fmt::Debug,
    P::Manifest: fmt::Debug,
    P::Host: fmt::Debug,
    P::Digester: fmt::Debug,
    P::StatCache: fmt::Debug,
    P::Tools: fmt::Debug,
    P::Cache: fmt::Debug,
    P::Cas: fmt::Debug,
    P::Log: fmt::Debug,
    P::Strategy: fmt::Debug,
    P::Dispatcher: fmt::Debug,
    P::Clock: fmt::Debug,
    P::Graph: fmt::Debug,
    P::Reporter: fmt::Debug,
    P::Approver: fmt::Debug,
    P::Ignore: fmt::Debug,
    P::Remote: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PortSet")
            .field("source", &self.source)
            .field("manifest", &self.manifest)
            .field("host", &self.host)
            .field("digester", &self.digester)
            .field("stat_cache", &self.stat_cache)
            .field("tools", &self.tools)
            .field("cache", &self.cache)
            .field("cas", &self.cas)
            .field("log", &self.log)
            .field("strategy", &self.strategy)
            .field("dispatcher", &self.dispatcher)
            .field("clock", &self.clock)
            .field("graph", &self.graph)
            .field("reporter", &self.reporter)
            .field("approver", &self.approver)
            .field("ignore", &self.ignore)
            .field("remote", &self.remote)
            .finish()
    }
}

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

    use std::collections::BTreeSet;

    use super::PortSet;
    use crate::error::Result;
    use crate::ports::{
        ActionCache, Approver, Clock, ContentStore, DeclarationSource, Digester, Dispatcher,
        EventLog, ExecStrategy, GraphRecord, Host, Manifest, NoRemote, NothingIgnored, Ports,
        Reporter, RunHistory, StatCache, ToolResolver,
    };
    use crate::types::{
        Approval, Attribution, BuildFile, CacheRow, Captured, Ceiling, Channel, Digest, Directory,
        Discovered, EnvName, EnvValue, Evaluated, Exit, FileMode, Found, InputStat, Label,
        LiveSink, LogLine, OutcomeEvent, OutputPath, Platform, Program, RawOutcome, ReadyAction,
        RemoteNotice, SourcePath, StatEntry, Summary, TargetGraph, Timestamp, Turn, WantedSet,
        Workspace,
    };

    /// One port type answering that there is nothing, standing in for every port.
    #[derive(Debug)]
    struct Stub;

    impl DeclarationSource for Stub {
        fn evaluate(&self, _file: &BuildFile, _discovered: &Discovered) -> Result<Evaluated> {
            Ok(Evaluated::Absent)
        }
    }

    impl Manifest for Stub {
        fn workspace(&self) -> Result<Workspace> {
            Ok(Workspace {
                out: Directory::parse("out")?,
                state: Directory::parse(".buildl")?,
                ceiling: Ceiling {
                    unkeyed: BTreeSet::new(),
                    run: BTreeSet::new(),
                    env: BTreeSet::new(),
                    read: BTreeSet::new(),
                    write: BTreeSet::new(),
                },
                execution: crate::types::Execution::default(),
                approver: crate::types::ApproverMode::Manifest,
                plugins: std::collections::BTreeMap::new(),
                remote: None,
            })
        }
    }

    impl Host for Stub {
        fn platform(&self) -> Platform {
            Platform::parse("linux/x86_64").unwrap()
        }

        fn env(&self, _name: &EnvName) -> Result<Option<EnvValue>> {
            Ok(None)
        }

        fn machine_folders(&self) -> crate::types::MachineFolders {
            crate::types::MachineFolders::default()
        }
    }

    impl Digester for Stub {
        fn stat(&self, _path: &SourcePath) -> Result<InputStat> {
            Ok(InputStat::Missing)
        }

        fn digest(&self, _paths: &[SourcePath]) -> Result<Vec<Digest>> {
            Ok(Vec::new())
        }
    }

    impl StatCache for Stub {
        fn entry(&self, _path: &SourcePath) -> Option<StatEntry> {
            None
        }

        fn record(&mut self, _path: SourcePath, _entry: StatEntry) {}

        fn commit(&mut self) -> Result<()> {
            Ok(())
        }
    }

    impl ToolResolver for Stub {
        fn fingerprint(&self, _program: &Program) -> Result<Option<Digest>> {
            Ok(None)
        }
    }

    impl ActionCache for Stub {
        fn row(&self, _label: &Label) -> Option<&CacheRow> {
            None
        }

        fn labels(&self) -> Vec<Label> {
            Vec::new()
        }

        fn record(&mut self, _label: Label, _row: CacheRow) -> Result<()> {
            Ok(())
        }

        fn forget(&mut self, _label: &Label) -> Result<()> {
            Ok(())
        }
    }

    impl ContentStore for Stub {
        fn put(&self, bytes: &[u8]) -> Result<Digest> {
            Ok(Digest::of(bytes))
        }

        fn contains(&self, _digest: &Digest) -> bool {
            false
        }

        fn get(&self, _digest: &Digest) -> Result<Option<Vec<u8>>> {
            Ok(None)
        }

        fn clear(&self, _at: &OutputPath) -> Result<()> {
            Ok(())
        }

        fn place(&self, _digest: &Digest, _mode: FileMode, _at: &OutputPath) -> Result<()> {
            Ok(())
        }
    }

    impl EventLog for Stub {
        fn append(&mut self, _event: &OutcomeEvent) -> Result<()> {
            Ok(())
        }
    }

    impl RunHistory for Stub {
        fn lines(&self) -> Result<Vec<LogLine>> {
            Ok(Vec::new())
        }
    }

    impl ExecStrategy for Stub {
        type Dir = ();

        fn prepare(&self, _action: &ReadyAction) -> Result<()> {
            Ok(())
        }

        fn run(
            &self,
            _dir: &(),
            _action: &ReadyAction,
            _live: Option<LiveSink<'_>>,
        ) -> Result<RawOutcome> {
            Ok(RawOutcome {
                exit: Exit::Exited(0),
                stdout: Vec::new(),
                stderr: Vec::new(),
            })
        }

        fn collect<C: ContentStore>(
            &self,
            _dir: &(),
            _action: &ReadyAction,
            _cas: &C,
        ) -> Result<Vec<Found>> {
            Ok(Vec::new())
        }
    }

    impl Dispatcher for Stub {
        fn dispatch<T, M, R, W, S>(&mut self, _work: W, _step: S) -> Result<()>
        where
            T: Send,
            M: Send,
            R: Send,
            W: Fn(T, &(dyn Fn(M) + Sync)) -> R + Sync,
            S: FnMut(Turn<M, R>) -> Vec<T>,
        {
            Ok(())
        }
    }

    impl GraphRecord for Stub {
        fn record(&mut self, _graph: &TargetGraph) -> Result<()> {
            Ok(())
        }
    }

    impl Reporter for Stub {
        fn begun(&mut self, _targets: usize) {}

        fn started(&mut self, _action: &ReadyAction) {}

        fn printed(&mut self, _label: &Label, _channel: Channel, _bytes: &[u8]) {}

        fn finished(&mut self, _event: &OutcomeEvent, _printed: Captured<'_>) {}

        fn remote(&mut self, _notice: &RemoteNotice) {}

        fn summary(&mut self, _summary: Summary) {}
    }

    impl Approver for Stub {
        fn approve(&mut self, _wanted: &WantedSet, _attribution: &Attribution) -> Result<Approval> {
            Ok(Approval::Granted)
        }
    }

    impl Clock for Stub {
        fn now(&self) -> Timestamp {
            Timestamp::UNIX_EPOCH
        }
    }

    /// A bundle choosing [`Stub`] for every port. It deliberately does not implement `Debug`:
    /// a bundle is only a choice of port types, so rendering a set must not require it.
    struct UndebuggableBundle;

    impl Ports for UndebuggableBundle {
        type Source = Stub;
        type Manifest = Stub;
        type Host = Stub;
        type Digester = Stub;
        type StatCache = Stub;
        type Tools = Stub;
        type Cache = Stub;
        type Cas = Stub;
        type Log = Stub;
        type Strategy = Stub;
        type Dispatcher = Stub;
        type Clock = Stub;
        type Graph = Stub;
        type Reporter = Stub;
        type Approver = Stub;
        type Ignore = NothingIgnored;
        type Remote = NoRemote;
    }

    #[test]
    fn debug_renders_every_port_without_the_bundle_being_debug() {
        let set = PortSet::<UndebuggableBundle> {
            source: Stub,
            manifest: Stub,
            host: Stub,
            digester: Stub,
            stat_cache: Stub,
            tools: Stub,
            cache: Stub,
            cas: Stub,
            log: Stub,
            strategy: Stub,
            dispatcher: Stub,
            clock: Stub,
            graph: Stub,
            reporter: Stub,
            approver: Stub,
            ignore: NothingIgnored,
            remote: NoRemote,
        };

        let text = format!("{set:?}");

        assert!(text.starts_with("PortSet"), "unexpected rendering: {text}");
        for field in [
            "source",
            "manifest",
            "host",
            "digester",
            "stat_cache",
            "tools",
            "cache",
            "cas",
            "log",
            "strategy",
            "dispatcher",
            "clock",
            "graph",
            "reporter",
            "approver",
        ] {
            assert!(
                text.contains(&format!("{field}: Stub")),
                "field `{field}` missing from: {text}"
            );
        }
        assert!(
            text.contains("ignore: NothingIgnored"),
            "field `ignore` missing from: {text}"
        );
        assert!(
            text.contains("remote: NoRemote"),
            "field `remote` missing from: {text}"
        );
    }
}