rsconstruct 0.9.154

Rust based fast build system
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
//! iluacheck checker: luacheck's analysis, in-process.
//!
//! The engine is `crate::engines::luacheck`, a port of luacheck 1.2.0. This file is
//! the processor around it: luacheck's command-line options as TOML fields,
//! the `.luacheckrc` configuration, and findings printed as `luacheck
//! --formatter plain --codes` prints them. Any finding fails the build, as
//! `luacheck` exits non-zero on any warning.
//!
//! luacheck resolves implicitly defined globals (`allow_defined`,
//! `allow_defined_top`) across all files checked in one run, so a file's
//! findings depend on the other files. The processor therefore makes one
//! product of all its files, checked together on every change.

use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};

use crate::config::{StandardConfig, output_config_hash, resolve_extra_inputs};
use crate::engines::luacheck::{CliOptions, FileResult, Limit};
use crate::file_index::FileIndex;
use crate::graph::{BuildGraph, Product};

fn default_config_file() -> String {
    ".luacheckrc".to_string()
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct IluacheckConfig {
    /// The configuration file, looked up from the project root upwards, as
    /// `--config`. Empty: no configuration file, as `--no-config`.
    #[serde(default = "default_config_file")]
    pub config_file: String,
    /// Standard globals, as `--std` (`max`, `lua51`, `lua54+busted`, ...).
    /// Empty: unset.
    #[serde(default)]
    pub std: String,
    #[serde(default)]
    pub globals: Option<Vec<String>>,
    #[serde(default)]
    pub read_globals: Option<Vec<String>>,
    #[serde(default)]
    pub new_globals: Option<Vec<String>>,
    #[serde(default)]
    pub new_read_globals: Option<Vec<String>>,
    #[serde(default)]
    pub not_globals: Option<Vec<String>>,
    #[serde(default)]
    pub ignore: Option<Vec<String>>,
    #[serde(default)]
    pub enable: Option<Vec<String>>,
    #[serde(default)]
    pub only: Option<Vec<String>>,
    #[serde(default)]
    pub operators: Option<Vec<String>>,
    #[serde(default)]
    pub allow_defined: bool,
    #[serde(default)]
    pub allow_defined_top: bool,
    #[serde(default)]
    pub module: bool,
    #[serde(default)]
    pub no_global: bool,
    #[serde(default)]
    pub no_unused: bool,
    #[serde(default)]
    pub no_redefined: bool,
    #[serde(default)]
    pub no_unused_args: bool,
    #[serde(default)]
    pub no_unused_secondaries: bool,
    #[serde(default)]
    pub no_self: bool,
    #[serde(default)]
    pub max_line_length: Option<u64>,
    #[serde(default)]
    pub max_code_line_length: Option<u64>,
    #[serde(default)]
    pub max_string_line_length: Option<u64>,
    #[serde(default)]
    pub max_comment_line_length: Option<u64>,
    #[serde(default)]
    pub max_cyclomatic_complexity: Option<u64>,
    #[serde(flatten)]
    pub standard: StandardConfig,
}

impl Default for IluacheckConfig {
    fn default() -> Self {
        Self {
            config_file: default_config_file(),
            std: String::new(),
            globals: None,
            read_globals: None,
            new_globals: None,
            new_read_globals: None,
            not_globals: None,
            ignore: None,
            enable: None,
            only: None,
            operators: None,
            allow_defined: false,
            allow_defined_top: false,
            module: false,
            no_global: false,
            no_unused: false,
            no_redefined: false,
            no_unused_args: false,
            no_unused_secondaries: false,
            no_self: false,
            max_line_length: None,
            max_code_line_length: None,
            max_string_line_length: None,
            max_comment_line_length: None,
            max_cyclomatic_complexity: None,
            standard: StandardConfig::default(),
        }
    }
}

/// A limit field: a number, with 0 meaning no limit (`--no-max-...`).
const fn limit(n: u64) -> Limit {
    if n == 0 {
        Limit::Unlimited
    } else {
        Limit::Value(n as f64)
    }
}

impl IluacheckConfig {
    fn cli_options(&self) -> CliOptions {
        let mut disabled = Vec::new();
        for (set, name) in [
            (self.no_global, "global"),
            (self.no_unused, "unused"),
            (self.no_redefined, "redefined"),
            (self.no_unused_args, "unused_args"),
            (self.no_unused_secondaries, "unused_secondaries"),
            (self.no_self, "self"),
        ] {
            if set {
                disabled.push(name);
            }
        }
        CliOptions {
            config: if self.config_file.is_empty() {
                None
            } else {
                Some(self.config_file.clone())
            },
            std: if self.std.is_empty() {
                None
            } else {
                Some(self.std.clone())
            },
            globals: self.globals.clone(),
            read_globals: self.read_globals.clone(),
            new_globals: self.new_globals.clone(),
            new_read_globals: self.new_read_globals.clone(),
            not_globals: self.not_globals.clone(),
            ignore: self.ignore.clone(),
            enable: self.enable.clone(),
            only: self.only.clone(),
            operators: self.operators.clone(),
            allow_defined: self.allow_defined,
            allow_defined_top: self.allow_defined_top,
            module: self.module,
            disabled,
            max_line_length: self.max_line_length.map(limit),
            max_code_line_length: self.max_code_line_length.map(limit),
            max_string_line_length: self.max_string_line_length.map(limit),
            max_comment_line_length: self.max_comment_line_length.map(limit),
            max_cyclomatic_complexity: self.max_cyclomatic_complexity.map(limit),
        }
    }

    /// Where luacheck finds `config_file`: in the project root, else in the
    /// nearest ancestor directory, as `--config` looks a relative path up
    /// (`locate_config`), written the way luacheck then opens it
    /// (`../.luacheckrc`). The default `.luacheckrc` may be nowhere (then
    /// luacheck's fallback configuration applies); a file the user named
    /// must exist, as luacheck itself fails on "Couldn't find configuration
    /// file".
    fn locate_config_file(&self) -> Result<Option<String>> {
        let name = &self.config_file;
        if name.is_empty() {
            return Ok(None);
        }
        if Path::new(name).is_absolute() {
            return crate::processor::named_config_file("iluacheck", "config_file", name, "");
        }
        let root = std::env::current_dir().context("Failed to get the current directory")?;
        let mut prefix = String::new();
        for dir in root.ancestors() {
            if dir.join(name).is_file() {
                return Ok(Some(format!("{prefix}{name}")));
            }
            prefix.push_str("../");
        }
        if *name == default_config_file() {
            return Ok(None);
        }
        bail!("iluacheck config_file not found: {name}")
    }

    /// The inputs every product shares: `dep_inputs`, the `dep_auto` files
    /// that exist, and the configuration file luacheck reads (once, when it
    /// is also a `dep_auto` entry). An edit to the configuration re-checks
    /// every file.
    fn dep_inputs(&self) -> Result<Vec<PathBuf>> {
        let scan = &self.standard;
        let mut all_dep_inputs = scan.dep_inputs.clone();
        for ai in &scan.dep_auto {
            all_dep_inputs.extend(crate::processor::config_file_inputs(ai));
        }
        if let Some(config_file) = self.locate_config_file()?
            && !all_dep_inputs.contains(&config_file)
        {
            all_dep_inputs.push(config_file);
        }
        resolve_extra_inputs(&all_dep_inputs)
    }
}

pub struct IluacheckProcessor {
    config: IluacheckConfig,
}

impl IluacheckProcessor {
    pub const fn new(config: IluacheckConfig) -> Self {
        Self { config }
    }

    fn check_files(&self, files: &[&Path]) -> Result<()> {
        let names: Vec<String> = files.iter().map(|f| f.display().to_string()).collect();
        let results = crate::engines::luacheck::run(&names, &self.config.cli_options())?;
        let mut lines = Vec::new();
        for (_, result) in results {
            match result {
                FileResult::Checked(findings) => lines.extend(findings),
                FileResult::Fatal(message) => lines.push(message),
            }
        }
        if lines.is_empty() {
            Ok(())
        } else {
            bail!("{}", lines.join("\n"))
        }
    }
}

impl crate::processor::Processor for IluacheckProcessor {
    fn scan_config(&self) -> &crate::config::StandardConfig {
        &self.config.standard
    }

    // Serialize the FULL config (the trait default covers StandardConfig
    // only), so the extra fields reach config-change detection.
    fn config_json(&self) -> Option<String> {
        crate::processor::ProcessorBase::config_json(&self.config)
    }

    fn required_tools(&self) -> Vec<String> {
        Vec::new()
    }

    /// One product spanning every scanned file: luacheck's implicit globals
    /// are resolved across all files checked together.
    fn discover(
        &self,
        graph: &mut BuildGraph,
        file_index: &FileIndex,
        instance_name: &str,
    ) -> Result<()> {
        let mut inputs = file_index.scan(&self.config.standard, true);
        if inputs.is_empty() {
            return Ok(());
        }
        inputs.extend(self.config.dep_inputs()?);
        let hash = Some(output_config_hash(
            &self.config,
            &crate::config::checksum_fields_of(instance_name),
        ));
        graph.add_product(inputs, vec![], instance_name, hash)?;
        Ok(())
    }

    fn execute(&self, _ctx: &crate::build_context::BuildContext, product: &Product) -> Result<()> {
        let deps = self.config.dep_inputs()?;
        let files: Vec<&Path> = product
            .inputs
            .iter()
            .filter(|p| !deps.contains(p))
            .map(PathBuf::as_path)
            .collect();
        self.check_files(&files)
    }
}

fn plugin_create(toml: &toml::Value) -> anyhow::Result<Box<dyn crate::processor::Processor>> {
    crate::registries::deserialize_and_create(toml, |cfg| Box::new(IluacheckProcessor::new(cfg)))
}

inventory::submit! {
    crate::registries::RustAlternative { replaces: "processor.checker.luacheck", by: "processor.checker.iluacheck" }
}
inventory::submit! {
    crate::registries::ProcessorPlugin {
        version: 1,
        name: "iluacheck",
        processor_type: crate::processor::ProcessorType::Checker,
        create: plugin_create,
        defconfig_json: crate::registries::default_config_json::<IluacheckConfig>,
        fields: &[
            crate::config::FieldSpec { name: "config_file", ty: crate::config::FieldType::String,
                affects_output: true, required: false,
                doc: "The configuration file, looked up from the project root upwards, as --config (.luacheckrc); empty for --no-config" },
            crate::config::FieldSpec { name: "std", ty: crate::config::FieldType::String,
                affects_output: true, required: false,
                doc: "Standard globals, as --std (max, lua51, lua54+busted, ...); empty: unset" },
            crate::config::FieldSpec { name: "globals", ty: crate::config::FieldType::StringArray,
                affects_output: true, required: false,
                doc: "Custom globals or fields (foo, foo.bar), as --globals" },
            crate::config::FieldSpec { name: "read_globals", ty: crate::config::FieldType::StringArray,
                affects_output: true, required: false,
                doc: "Read-only globals or fields, as --read-globals" },
            crate::config::FieldSpec { name: "new_globals", ty: crate::config::FieldType::StringArray,
                affects_output: true, required: false,
                doc: "Custom globals replacing those set before, as --new-globals" },
            crate::config::FieldSpec { name: "new_read_globals", ty: crate::config::FieldType::StringArray,
                affects_output: true, required: false,
                doc: "Read-only globals replacing those set before, as --new-read-globals" },
            crate::config::FieldSpec { name: "not_globals", ty: crate::config::FieldType::StringArray,
                affects_output: true, required: false,
                doc: "Globals or fields to remove, as --not-globals" },
            crate::config::FieldSpec { name: "ignore", ty: crate::config::FieldType::StringArray,
                affects_output: true, required: false,
                doc: "Warning patterns to filter out (code, name, or code/name), as --ignore" },
            crate::config::FieldSpec { name: "enable", ty: crate::config::FieldType::StringArray,
                affects_output: true, required: false,
                doc: "Warning patterns not to filter out, as --enable" },
            crate::config::FieldSpec { name: "only", ty: crate::config::FieldType::StringArray,
                affects_output: true, required: false,
                doc: "Report only warnings matching these patterns, as --only" },
            crate::config::FieldSpec { name: "operators", ty: crate::config::FieldType::StringArray,
                affects_output: true, required: false,
                doc: "Compound operators to allow (+=, ...), as --operators" },
            crate::config::FieldSpec { name: "allow_defined", ty: crate::config::FieldType::Bool,
                affects_output: true, required: false,
                doc: "Allow defining globals implicitly by setting them, as --allow-defined" },
            crate::config::FieldSpec { name: "allow_defined_top", ty: crate::config::FieldType::Bool,
                affects_output: true, required: false,
                doc: "Allow defining globals implicitly by setting them in the main chunk, as --allow-defined-top" },
            crate::config::FieldSpec { name: "module", ty: crate::config::FieldType::Bool,
                affects_output: true, required: false,
                doc: "Limit implicitly defined globals to their files, as --module" },
            crate::config::FieldSpec { name: "no_global", ty: crate::config::FieldType::Bool,
                affects_output: true, required: false,
                doc: "Filter out warnings about globals, as --no-global" },
            crate::config::FieldSpec { name: "no_unused", ty: crate::config::FieldType::Bool,
                affects_output: true, required: false,
                doc: "Filter out warnings about unused variables and values, as --no-unused" },
            crate::config::FieldSpec { name: "no_redefined", ty: crate::config::FieldType::Bool,
                affects_output: true, required: false,
                doc: "Filter out warnings about redefined variables, as --no-redefined" },
            crate::config::FieldSpec { name: "no_unused_args", ty: crate::config::FieldType::Bool,
                affects_output: true, required: false,
                doc: "Filter out warnings about unused arguments and loop variables, as --no-unused-args" },
            crate::config::FieldSpec { name: "no_unused_secondaries", ty: crate::config::FieldType::Bool,
                affects_output: true, required: false,
                doc: "Filter out warnings about unused variables set together with used ones, as --no-unused-secondaries" },
            crate::config::FieldSpec { name: "no_self", ty: crate::config::FieldType::Bool,
                affects_output: true, required: false,
                doc: "Filter out warnings about the implicit self argument, as --no-self" },
            crate::config::FieldSpec { name: "max_line_length", ty: crate::config::FieldType::Integer,
                affects_output: true, required: false,
                doc: "Maximum line length, as --max-line-length; 0 for no limit (default 120, or the configuration's)" },
            crate::config::FieldSpec { name: "max_code_line_length", ty: crate::config::FieldType::Integer,
                affects_output: true, required: false,
                doc: "Maximum length of lines ending in code, as --max-code-line-length; 0 for no limit" },
            crate::config::FieldSpec { name: "max_string_line_length", ty: crate::config::FieldType::Integer,
                affects_output: true, required: false,
                doc: "Maximum length of lines inside a string, as --max-string-line-length; 0 for no limit" },
            crate::config::FieldSpec { name: "max_comment_line_length", ty: crate::config::FieldType::Integer,
                affects_output: true, required: false,
                doc: "Maximum length of comment lines, as --max-comment-line-length; 0 for no limit" },
            crate::config::FieldSpec { name: "max_cyclomatic_complexity", ty: crate::config::FieldType::Integer,
                affects_output: true, required: false,
                doc: "Maximum cyclomatic complexity of functions, as --max-cyclomatic-complexity; 0 for no limit (the default)" },
        ],
        omit_standard_fields: &[
        "command",
        "formats",
        "args",
        "output_dir",
        "required_tools",
        "batch",
    ],
        scan_defaults: Some(crate::config::ScanDefaultsData { src_dirs: &[], src_extensions: &[".lua"], src_exclude_dirs: &[] }),
        defaults: Some(crate::config::ProcessorDefaults { dep_auto: &[".luacheckrc"], output_depends_on_input_name: true, ..crate::config::ProcessorDefaults::EMPTY }),
        keywords: &["lua", "linter", "checker", "luacheck", "rust"],
        description: "Lint Lua files with luacheck's analysis (in-process)",
        is_builtin: true,
        is_rust: true,
        supports_batch: false,
        caches_outputs: true,
        max_jobs_cap: None,
    }
}