bearout 0.2.0

A programmable contract engine for linked resources, documentation, and code
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
// SPDX-License-Identifier: Apache-2.0

//! Host values of the Starlark ABI. Repository code constructs findings and
//! outputs through `error()`, `warning()`, and `output()`; every field is
//! checked at construction, so a misspelled keyword or a wrong type fails
//! inside the script with a Starlark error that names the call site.

use std::fmt;

use starlark::environment::GlobalsBuilder;
use starlark::eval::Evaluator;
use starlark::starlark_module;
use starlark::values::Value;
use starlark::values::none::{NoneOr, NoneType};

use crate::identity;
use crate::paths::ProjectPath;

/// The host value types. `ProvidesStaticType` is an unsafe trait that
/// starlark's derive macro implements; this module exists so that the
/// `unsafe_code` allowance covers exactly these derive sites and nothing
/// handwritten. It holds type definitions and macro-generated impls only.
mod host_types {
    #![allow(unsafe_code)]
    // The `starlark_value` macro requires the named `'v` lifetime.
    #![allow(clippy::elidable_lifetime_names)]

    use std::cell::RefCell;

    use allocative::Allocative;
    use starlark::any::ProvidesStaticType;
    use starlark::starlark_simple_value;
    use starlark::values::{NoSerialize, StarlarkValue, starlark_value};

    use super::SchemaRegistration;

    /// A finding constructed by `error()` or `warning()`.
    #[derive(Debug, Clone, PartialEq, Eq, ProvidesStaticType, NoSerialize, Allocative)]
    pub struct Finding {
        /// `true` for `error()`, `false` for `warning()`.
        pub is_error: bool,
        pub message: String,
        /// Identifier of the resource the finding is about, when given.
        pub resource: Option<String>,
        /// Project-relative path of the schema-less document the finding is
        /// about, when given. Exclusive with `resource`.
        pub path: Option<String>,
        /// `true` when the target lives in the comparison baseline rather
        /// than the candidate.
        pub baseline: bool,
        /// One-based line in that resource, document, or commit message,
        /// when given.
        pub line: Option<u32>,
        /// Repository-owned rule identifier, when given.
        pub rule: Option<String>,
        /// The key of the commit a history finding is about, when given.
        /// Exclusive with `resource`, `path`, and the baseline side.
        pub commit: Option<String>,
    }

    starlark_simple_value!(Finding);

    #[starlark_value(type = "bearout.finding")]
    impl<'v> StarlarkValue<'v> for Finding {}

    /// A generation plan entry constructed by `output()`.
    #[derive(Debug, Clone, PartialEq, Eq, ProvidesStaticType, NoSerialize, Allocative)]
    pub struct Output {
        /// Template name relative to the templates root.
        pub template: String,
        /// Normalized output path relative to the project root.
        pub path: String,
        /// Rendering context as canonical JSON text.
        pub context: String,
    }

    starlark_simple_value!(Output);

    #[starlark_value(type = "bearout.output")]
    impl<'v> StarlarkValue<'v> for Output {}

    /// Registrations collected while the entry module runs. Callbacks are
    /// stored as synthetic module variables so they survive freezing.
    #[derive(Debug, Default, ProvidesStaticType)]
    pub struct Registry {
        pub schemas: RefCell<Vec<SchemaRegistration>>,
        /// `(name, module variable)`.
        pub checks: RefCell<Vec<(String, String)>>,
        /// `(name, module variable)`.
        pub generators: RefCell<Vec<(String, String)>>,
        /// `(name, module variable)`.
        pub history_checks: RefCell<Vec<(String, String)>>,
        counter: RefCell<u32>,
    }

    impl Registry {
        pub(super) fn next_slot(&self, prefix: &str) -> String {
            let mut counter = self.counter.borrow_mut();
            *counter += 1;
            format!("__bearout_{prefix}_{}", *counter)
        }
    }
}

pub use host_types::{Finding, Output, Registry};

impl fmt::Display for Finding {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let kind = if self.is_error { "error" } else { "warning" };
        write!(f, "{kind}({:?})", self.message)
    }
}

impl fmt::Display for Output {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "output({:?}, {:?})", self.template, self.path)
    }
}

/// One schema registration made by the entry module.
#[derive(Debug, Clone)]
pub struct SchemaRegistration {
    pub id: String,
    /// Shape file relative to the rules root.
    pub shape: Option<String>,
    /// Module variable holding the validate callback.
    pub validate: Option<String>,
}

fn fail(message: String) -> starlark::Error {
    starlark::Error::new_other(anyhow::anyhow!(message))
}

#[allow(clippy::too_many_arguments)]
fn finding(
    is_error: bool,
    message: &str,
    resource: NoneOr<&str>,
    path: NoneOr<&str>,
    side: &str,
    line: NoneOr<i32>,
    code: NoneOr<&str>,
    commit: NoneOr<&str>,
) -> starlark::Result<Finding> {
    if message.trim().is_empty() {
        return Err(fail("finding message must not be empty".to_owned()));
    }
    let commit = match commit {
        NoneOr::None => None,
        NoneOr::Other(key) => {
            if key.is_empty() || key.chars().any(|c| c.is_control() || c.is_whitespace()) {
                return Err(fail(
                    "finding commit must be a commit key of the history view".to_owned(),
                ));
            }
            Some(key.to_owned())
        }
    };
    let baseline = match side {
        "candidate" => false,
        "baseline" => true,
        other => {
            return Err(fail(format!(
                "finding side must be \"candidate\" or \"baseline\", found {other:?}"
            )));
        }
    };
    let resource = match resource {
        NoneOr::None => None,
        NoneOr::Other(id) => {
            identity::check_id(id).map_err(|error| fail(format!("finding resource: {error}")))?;
            Some(id.to_owned())
        }
    };
    let path = match path {
        NoneOr::None => None,
        NoneOr::Other(text) => {
            let parsed =
                ProjectPath::parse(text).map_err(|error| fail(format!("finding path: {error}")))?;
            if parsed.as_str().is_empty() {
                return Err(fail("finding path must not be empty".to_owned()));
            }
            Some(parsed.as_str().to_owned())
        }
    };
    if resource.is_some() && path.is_some() {
        return Err(fail(
            "a finding names either a `resource` or a `path`, not both".to_owned(),
        ));
    }
    if commit.is_some() && (resource.is_some() || path.is_some() || baseline) {
        return Err(fail(
            "a finding that names a `commit` names neither a `resource`, a `path`, nor the baseline side"
                .to_owned(),
        ));
    }
    let line = match line {
        NoneOr::None => None,
        NoneOr::Other(line) => Some(
            u32::try_from(line)
                .ok()
                .filter(|line| *line > 0)
                .ok_or_else(|| {
                    fail(format!(
                        "finding line must be a positive integer, found {line}"
                    ))
                })?,
        ),
    };
    let rule = match code {
        NoneOr::None => None,
        NoneOr::Other(code) => {
            identity::check_kind(code).map_err(|error| fail(format!("finding code: {error}")))?;
            Some(code.to_owned())
        }
    };
    Ok(Finding {
        is_error,
        message: message.to_owned(),
        resource,
        path,
        baseline,
        line,
        rule,
        commit,
    })
}

/// Functions available to every module: the finding and output constructors.
#[starlark_module]
pub fn library(builder: &mut GlobalsBuilder) {
    /// Report an error about a resource, a schema-less document, or, from
    /// a history check, a commit. `resource` defaults to the resource
    /// being validated; project checks must name a `resource` or a
    /// document `path`; history checks may name a `commit` key or nothing
    /// for a range-wide finding.
    fn error(
        #[starlark(require = pos)] message: &str,
        #[starlark(require = named, default = NoneOr::None)] resource: NoneOr<&str>,
        #[starlark(require = named, default = NoneOr::None)] path: NoneOr<&str>,
        #[starlark(require = named, default = "candidate")] side: &str,
        #[starlark(require = named, default = NoneOr::None)] line: NoneOr<i32>,
        #[starlark(require = named, default = NoneOr::None)] code: NoneOr<&str>,
        #[starlark(require = named, default = NoneOr::None)] commit: NoneOr<&str>,
    ) -> starlark::Result<Finding> {
        finding(true, message, resource, path, side, line, code, commit)
    }

    /// Report a warning about a resource, a schema-less document, or,
    /// from a history check, a commit.
    fn warning(
        #[starlark(require = pos)] message: &str,
        #[starlark(require = named, default = NoneOr::None)] resource: NoneOr<&str>,
        #[starlark(require = named, default = NoneOr::None)] path: NoneOr<&str>,
        #[starlark(require = named, default = "candidate")] side: &str,
        #[starlark(require = named, default = NoneOr::None)] line: NoneOr<i32>,
        #[starlark(require = named, default = NoneOr::None)] code: NoneOr<&str>,
        #[starlark(require = named, default = NoneOr::None)] commit: NoneOr<&str>,
    ) -> starlark::Result<Finding> {
        finding(false, message, resource, path, side, line, code, commit)
    }

    /// Plan one generated file: render `template` to `path` with `context`.
    fn output<'v>(
        #[starlark(require = pos)] template: &str,
        #[starlark(require = pos)] path: &str,
        #[starlark(require = named, default = NoneOr::None)] context: NoneOr<Value<'v>>,
    ) -> starlark::Result<Output> {
        let template = ProjectPath::parse(template)
            .map_err(|error| fail(format!("output template: {error}")))?;
        if template.as_str().is_empty() {
            return Err(fail("output template must not be empty".to_owned()));
        }
        let path =
            ProjectPath::parse(path).map_err(|error| fail(format!("output path: {error}")))?;
        if path.as_str().is_empty() {
            return Err(fail("output path must not be empty".to_owned()));
        }
        let context = match context {
            NoneOr::None => serde_json::Value::Object(serde_json::Map::new()),
            NoneOr::Other(value) => {
                let json = value.to_json_value().map_err(|error| {
                    fail(format!("output context must be JSON-compatible: {error}"))
                })?;
                if !json.is_object() {
                    return Err(fail("output context must be a dict".to_owned()));
                }
                json
            }
        };
        Ok(Output {
            template: template.as_str().to_owned(),
            path: path.as_str().to_owned(),
            context: context.to_string(),
        })
    }
}

fn registry<'a>(eval: &Evaluator<'_, 'a, '_>) -> starlark::Result<&'a Registry> {
    eval.extra
        .and_then(|extra| extra.downcast_ref::<Registry>())
        .ok_or_else(|| {
            fail(
                "schema(), check(), generator(), and history_check() may only be called from the entry module"
                    .to_owned(),
            )
        })
}

fn require_callable(value: Value<'_>, label: &str) -> starlark::Result<()> {
    let kind = value.get_type();
    if kind == "function" {
        Ok(())
    } else {
        Err(fail(format!("{label} must be a function, found {kind}")))
    }
}

/// Functions available only to the entry module: registration.
#[starlark_module]
pub fn registration(builder: &mut GlobalsBuilder) {
    /// Register a schema identifier with an optional shape file and validator.
    fn schema<'v>(
        #[starlark(require = pos)] id: &str,
        #[starlark(require = named, default = NoneOr::None)] shape: NoneOr<&str>,
        #[starlark(require = named, default = NoneOr::None)] validate: NoneOr<Value<'v>>,
        eval: &mut Evaluator<'v, '_, '_>,
    ) -> starlark::Result<NoneType> {
        identity::check_schema_id(id).map_err(fail)?;
        let registry = registry(eval)?;
        if registry
            .schemas
            .borrow()
            .iter()
            .any(|existing| existing.id == id)
        {
            return Err(fail(format!("schema `{id}` is registered twice")));
        }
        let shape = match shape {
            NoneOr::None => None,
            NoneOr::Other(text) => {
                let path = ProjectPath::parse(text)
                    .map_err(|error| fail(format!("schema shape: {error}")))?;
                if path
                    .file_name()
                    .strip_suffix(".schema.toml")
                    .is_none_or(str::is_empty)
                {
                    return Err(fail(format!(
                        "schema shape `{text}` must be a `.schema.toml` file"
                    )));
                }
                Some(path.as_str().to_owned())
            }
        };
        let validate = match validate {
            NoneOr::None => None,
            NoneOr::Other(function) => {
                require_callable(function, "schema validate")?;
                let slot = registry.next_slot("validate");
                eval.module().set(&slot, function);
                Some(slot)
            }
        };
        registry.schemas.borrow_mut().push(SchemaRegistration {
            id: id.to_owned(),
            shape,
            validate,
        });
        Ok(NoneType)
    }

    /// Register a project-level check.
    fn check<'v>(
        #[starlark(require = pos)] name: &str,
        #[starlark(require = pos)] function: Value<'v>,
        eval: &mut Evaluator<'v, '_, '_>,
    ) -> starlark::Result<NoneType> {
        identity::check_kind(name).map_err(|error| fail(format!("check name: {error}")))?;
        require_callable(function, "check function")?;
        let registry = registry(eval)?;
        if registry
            .checks
            .borrow()
            .iter()
            .any(|(existing, _)| existing == name)
        {
            return Err(fail(format!("check `{name}` is registered twice")));
        }
        let slot = registry.next_slot("check");
        eval.module().set(&slot, function);
        registry.checks.borrow_mut().push((name.to_owned(), slot));
        Ok(NoneType)
    }

    /// Register a generator.
    fn generator<'v>(
        #[starlark(require = pos)] name: &str,
        #[starlark(require = pos)] function: Value<'v>,
        eval: &mut Evaluator<'v, '_, '_>,
    ) -> starlark::Result<NoneType> {
        identity::check_kind(name).map_err(|error| fail(format!("generator name: {error}")))?;
        require_callable(function, "generator function")?;
        let registry = registry(eval)?;
        if registry
            .generators
            .borrow()
            .iter()
            .any(|(existing, _)| existing == name)
        {
            return Err(fail(format!("generator `{name}` is registered twice")));
        }
        let slot = registry.next_slot("generator");
        eval.module().set(&slot, function);
        registry
            .generators
            .borrow_mut()
            .push((name.to_owned(), slot));
        Ok(NoneType)
    }

    /// Register a history check: a function of one history view, run only
    /// by `bearout history` and history fixture cases. **Experimental.**
    fn history_check<'v>(
        #[starlark(require = pos)] name: &str,
        #[starlark(require = pos)] function: Value<'v>,
        eval: &mut Evaluator<'v, '_, '_>,
    ) -> starlark::Result<NoneType> {
        identity::check_kind(name).map_err(|error| fail(format!("history check name: {error}")))?;
        require_callable(function, "history check function")?;
        let registry = registry(eval)?;
        if registry
            .history_checks
            .borrow()
            .iter()
            .any(|(existing, _)| existing == name)
        {
            return Err(fail(format!("history check `{name}` is registered twice")));
        }
        let slot = registry.next_slot("history");
        eval.module().set(&slot, function);
        registry
            .history_checks
            .borrow_mut()
            .push((name.to_owned(), slot));
        Ok(NoneType)
    }
}