openbim-ifc-cli 0.5.2

The openbim-ifc command: validate, convert, inspect, query and edit IFC files (STEP, ifcXML and ifcZIP), and exchange their values as CSV, TSV or XLSX tables, from a shell or CI.
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
//! `validate`: every file against the schema its own header declares.
//!
//! The verdict is the validator's: a file fails on an error or an
//! evaluation error (a rule that could not be decided is not a rule that
//! passed), on a truncated report (its counts are lower bounds), and with
//! `--deny-warnings` on a warning. Rules the validator does not evaluate
//! are counted, never a failure. A file that cannot be read or declares no
//! bundled schema is reported and makes the run exit 2, after every other
//! file has been checked.
//!
//! `--express FILE.exp` (#538) also evaluates every WHERE, type and global
//! rule of the file's release from the EXPRESS text the caller supplies.
//! The `.exp` files are read once, before any model; each model is checked
//! with the one that declares its release, and refused with
//! `express-mismatch` when none or several do. An `.exp` that cannot be read
//! ends the run; one that does not parse refuses every file with
//! `invalid-express`, whatever the order of the options. Rules that
//! evaluate to UNKNOWN are `indeterminate` findings: reported and counted,
//! never a failure.

use std::collections::HashMap;
use std::io::Write;
use std::path::PathBuf;

use ifc::validate::express::{ExpressError, ExpressRules};
use ifc::validate::{validate_with_options, Budget, Path, Report, Severity, ValidateOptions};
use ifc::Schema;

use crate::cli::{ReportFormat, ValidateArgs};
use crate::error::{CliError, CliResult, Outcome};
use crate::input::{self, Loaded};
use crate::json::Json;
use crate::sarif::{self, Level};

/// One finding, flattened for every output format.
struct Item {
    severity: Severity,
    rule: String,
    path: String,
    entity: Option<u64>,
    attribute_index: Option<usize>,
    attribute_name: Option<String>,
    line: Option<usize>,
    message: String,
}

/// One file's result.
struct Checked {
    schema: String,
    conformant: bool,
    truncated: bool,
    passed: bool,
    errors: usize,
    evaluation_errors: usize,
    warnings: usize,
    indeterminate: usize,
    unsupported: usize,
    items: Vec<Item>,
}

/// The `--express` files, read once, and their parses per release.
struct ExpressFiles {
    /// Each file's path as given, and its text.
    files: Vec<(PathBuf, String)>,
    /// The outcome of parsing file `.0` against the tables named `.1`.
    parsed: HashMap<(usize, String), Result<ExpressRules, ExpressError>>,
}

impl ExpressFiles {
    /// Read every file; the first that cannot be read ends the run.
    fn read(paths: &[PathBuf]) -> CliResult<Self> {
        let files = paths
            .iter()
            .map(|path| {
                let bytes = std::fs::read(path).map_err(|error| CliError::Io {
                    path: path.display().to_string(),
                    detail: error.to_string(),
                })?;
                // The normative files are ASCII, but some copies are
                // Latin-1: one character per byte then.
                let text = String::from_utf8(bytes).unwrap_or_else(|error| {
                    error.into_bytes().iter().map(|&b| char::from(b)).collect()
                });
                Ok((path.clone(), text))
            })
            .collect::<CliResult<_>>()?;
        Ok(Self {
            files,
            parsed: HashMap::new(),
        })
    }

    /// The rules for a model whose header declares `schema`.
    ///
    /// Every file is tried, so the verdict never depends on `--express`
    /// order: a file that does not parse refuses the model with
    /// `invalid-express` (even if another file would serve), a file that
    /// disagrees with the tables is `express-mismatch`, and exactly one file
    /// must declare the release -- none or several is `express-mismatch`.
    fn rules_for(&mut self, schema: &Schema) -> CliResult<ExpressRules> {
        let mut declaring: Vec<(usize, ExpressRules)> = Vec::new();
        let mut invalid = None;
        let mut disagreeing = None;
        for (index, (path, text)) in self.files.iter().enumerate() {
            let outcome = self
                .parsed
                .entry((index, schema.name().to_owned()))
                .or_insert_with(|| ExpressRules::parse(text, schema));
            match outcome {
                Ok(rules) => declaring.push((index, rules.clone())),
                Err(ExpressError::SchemaMismatch { .. }) => {}
                Err(error @ ExpressError::TableMismatch { .. }) => {
                    disagreeing.get_or_insert_with(|| format!("{}: {error}", path.display()));
                }
                Err(error) => {
                    invalid.get_or_insert_with(|| format!("{}: {error}", path.display()));
                }
            }
        }
        // Whatever the order: a file that does not parse outranks one that
        // disagrees with the tables.
        if let Some(detail) = invalid {
            return Err(CliError::InvalidExpress(detail));
        }
        if let Some(detail) = disagreeing {
            return Err(CliError::ExpressMismatch(detail));
        }
        let names = |indices: &mut dyn Iterator<Item = usize>| {
            indices
                .map(|index| self.files[index].0.display().to_string())
                .collect::<Vec<_>>()
                .join(", ")
        };
        match declaring.len() {
            1 => Ok(declaring.remove(0).1),
            0 => Err(CliError::ExpressMismatch(format!(
                "no --express file declares {} (given: {})",
                schema.name(),
                names(&mut (0..self.files.len()))
            ))),
            _ => Err(CliError::ExpressMismatch(format!(
                "more than one --express file declares {}: {}",
                schema.name(),
                names(&mut declaring.iter().map(|(index, _)| *index))
            ))),
        }
    }
}

/// Run `validate`.
pub(crate) fn run(args: &ValidateArgs, out: &mut impl Write) -> CliResult<Outcome> {
    let budget = args
        .max_findings
        .map_or(Budget::DEFAULT, |max_findings| Budget { max_findings });
    let files: Vec<String> = args
        .files
        .iter()
        .map(|file| file.display().to_string())
        .collect();
    let mut express = ExpressFiles::read(&args.express)?;
    let results: Vec<CliResult<Checked>> = args
        .files
        .iter()
        .map(|file| {
            let loaded = input::read(file, args.input.input_layout)?;
            check(&loaded, budget, args, &mut express)
        })
        .collect();

    match args.format {
        ReportFormat::Human => human(&files, &results, !args.express.is_empty(), out),
        ReportFormat::Json => json(&files, &results, out),
        ReportFormat::Sarif => sarif(&files, &results, out),
    }
    .map_err(|error| CliError::stdout(&error))?;

    Ok(verdict(&results))
}

/// The run's outcome: 2 if a file could not be checked, else 1 if one
/// failed, else 0.
fn verdict(results: &[CliResult<Checked>]) -> Outcome {
    if results.iter().any(Result::is_err) {
        Outcome::Incomplete
    } else if results.iter().flatten().any(|checked| !checked.passed) {
        Outcome::Findings
    } else {
        Outcome::Clean
    }
}

fn check(
    loaded: &Loaded,
    budget: Budget,
    args: &ValidateArgs,
    express: &mut ExpressFiles,
) -> CliResult<Checked> {
    let schema = input::declared_schema(&loaded.model)?;
    let rules = if express.files.is_empty() {
        None
    } else {
        Some(express.rules_for(schema)?)
    };
    let mut options = ValidateOptions::new().budget(budget);
    if let Some(rules) = &rules {
        options = options.express(rules);
    }
    let report: Report = validate_with_options(&loaded.model, schema, &options);
    let summary = report.summary();
    let line = |id: u64| loaded.lines.as_ref().and_then(|lines| lines.line(id));
    let items = report
        .sorted()
        .into_iter()
        .filter(|finding| args.include_unsupported || finding.severity != Severity::Unsupported)
        .map(|finding| {
            let (entity, attribute_index, attribute_name) = match &finding.path {
                Path::Entity(id) => (Some(id.0), None, None),
                Path::Attribute {
                    entity,
                    index,
                    name,
                } => (Some(entity.0), Some(*index), name.clone()),
                // The file, or a location kind added later: `path` still
                // says where.
                _ => (None, None, None),
            };
            Item {
                severity: finding.severity,
                rule: finding.rule.clone(),
                path: finding.path.to_string(),
                entity,
                attribute_index,
                attribute_name,
                line: entity.and_then(line),
                message: finding.message.clone(),
            }
        })
        .collect();
    let conformant = report.is_conformant();
    let truncated = report.is_truncated();
    Ok(Checked {
        schema: loaded
            .model
            .header()
            .schema_token()
            .unwrap_or_default()
            .to_owned(),
        conformant,
        truncated,
        passed: conformant && !truncated && !(args.deny_warnings && summary.warnings > 0),
        errors: summary.errors,
        evaluation_errors: summary.evaluation_errors,
        warnings: summary.warnings,
        indeterminate: summary.indeterminate,
        unsupported: summary.unsupported,
        items,
    })
}

fn plural(count: usize, one: &str, many: &str) -> String {
    format!("{count} {}", if count == 1 { one } else { many })
}

fn human(
    files: &[String],
    results: &[CliResult<Checked>],
    express: bool,
    out: &mut impl Write,
) -> std::io::Result<()> {
    for (file, result) in files.iter().zip(results) {
        let checked = match result {
            Ok(checked) => checked,
            Err(error) => {
                eprintln!("openbim-ifc: {file}: not validated: {error}");
                continue;
            }
        };
        for item in &checked.items {
            let at = match item.line {
                Some(line) => format!("{file}:{line}"),
                None => file.clone(),
            };
            let target = if item.entity.is_some() {
                format!(" {}", item.path)
            } else {
                String::new()
            };
            writeln!(
                out,
                "{at}: {} [{}]{target}: {}",
                item.severity, item.rule, item.message
            )?;
        }
        let verdict = match (checked.passed, checked.conformant) {
            (true, _) => "conformant",
            (false, true) if checked.truncated => "verdict not final (report truncated)",
            (false, true) => "fails on warnings",
            (false, false) => "not conformant",
        };
        let truncated = if checked.truncated {
            " (truncated: counts are lower bounds)"
        } else {
            ""
        };
        // Only a run that evaluates EXPRESS rules can decide "indeterminate".
        let indeterminate = if express {
            format!(", {} indeterminate", checked.indeterminate)
        } else {
            String::new()
        };
        writeln!(
            out,
            "{file}: {}: {verdict}: {}, {}, {}{indeterminate}; {} not evaluated{truncated}",
            checked.schema,
            plural(checked.errors, "error", "errors"),
            plural(
                checked.evaluation_errors,
                "evaluation error",
                "evaluation errors"
            ),
            plural(checked.warnings, "warning", "warnings"),
            plural(checked.unsupported, "rule", "rules"),
        )?;
    }
    Ok(())
}

fn json(
    files: &[String],
    results: &[CliResult<Checked>],
    out: &mut impl Write,
) -> std::io::Result<()> {
    let reports = files
        .iter()
        .zip(results)
        .map(|(file, result)| match result {
            Ok(checked) => Json::object([
                ("file", Json::str(file.clone())),
                ("schema", Json::str(checked.schema.clone())),
                ("passed", Json::Bool(checked.passed)),
                ("conformant", Json::Bool(checked.conformant)),
                ("truncated", Json::Bool(checked.truncated)),
                (
                    "summary",
                    Json::object([
                        ("errors", Json::uint(checked.errors as u64)),
                        (
                            "evaluation_errors",
                            Json::uint(checked.evaluation_errors as u64),
                        ),
                        ("warnings", Json::uint(checked.warnings as u64)),
                        ("indeterminate", Json::uint(checked.indeterminate as u64)),
                        ("unsupported", Json::uint(checked.unsupported as u64)),
                    ]),
                ),
                (
                    "findings",
                    Json::Array(
                        checked
                            .items
                            .iter()
                            .map(|item| {
                                Json::object([
                                    ("severity", Json::str(item.severity.to_string())),
                                    ("rule", Json::str(item.rule.clone())),
                                    ("path", Json::str(item.path.clone())),
                                    ("entity", Json::opt_uint(item.entity)),
                                    (
                                        "attribute_index",
                                        Json::opt_uint(item.attribute_index.map(|i| i as u64)),
                                    ),
                                    ("attribute_name", Json::opt_str(item.attribute_name.clone())),
                                    ("line", Json::opt_uint(item.line.map(|l| l as u64))),
                                    ("message", Json::str(item.message.clone())),
                                ])
                            })
                            .collect(),
                    ),
                ),
            ]),
            Err(error) => Json::object([
                ("file", Json::str(file.clone())),
                (
                    "error",
                    Json::object([
                        ("kind", Json::str(error.kind())),
                        ("message", Json::str(error.to_string())),
                    ]),
                ),
            ]),
        })
        .collect();
    let document = Json::object([
        ("tool", Json::str("openbim-ifc")),
        ("version", Json::str(env!("CARGO_PKG_VERSION"))),
        ("passed", Json::Bool(verdict(results) == Outcome::Clean)),
        ("files", Json::Array(reports)),
    ]);
    out.write_all(document.pretty().as_bytes())
}

fn sarif(
    files: &[String],
    results: &[CliResult<Checked>],
    out: &mut impl Write,
) -> std::io::Result<()> {
    let mut run = sarif::Run {
        files: files.to_vec(),
        ..sarif::Run::default()
    };
    for (index, result) in results.iter().enumerate() {
        match result {
            Ok(checked) => {
                run.findings
                    .extend(checked.items.iter().map(|item| sarif::Finding {
                        rule: item.rule.clone(),
                        level: match item.severity {
                            Severity::Error | Severity::EvaluationError => Level::Error,
                            Severity::Warning => Level::Warning,
                            _ => Level::Note,
                        },
                        message: item.message.clone(),
                        file: index,
                        line: item.line,
                        entity: item.entity.map(|_| item.path.clone()),
                        is_attribute: item.attribute_index.is_some(),
                    }));
            }
            Err(error) => run.failures.push((index, error.to_string())),
        }
    }
    out.write_all(run.to_json().pretty().as_bytes())
}