ctb_formats_javascript/
deno_config.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later AND MIT
2// SPDX-License-Identifier for parts derived from dlint: MIT
3/*
4This file is part of Collective Toolbox, a database and document workspace and utilities.
5Copyright (C) 2026 Collective Toolbox Developers
6Contact: info@collectivetoolbox.com
7
8This program is free software: you can redistribute it and/or modify it under
9the terms of the GNU Affero General Public License as published by the Free
10Software Foundation, either version 3 of the License, or (at your option) any
11later version.
12
13This program is distributed in the hope that it will be useful, but WITHOUT ANY
14WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
16
17You should have received a copy of the GNU Affero General Public License along
18with this program.  If not, see <https://www.gnu.org/licenses/>.
19*/
20
21// Derived from Deno's dlint (https://github.com/denoland/deno_lint).
22// For parts derived from dlint:
23// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
24
25// See additional licensing details at end of file.
26
27//! Deno configuration file (`deno.json`) loader and parser.
28
29#[allow(
30    unused_imports,
31    clippy::wildcard_imports,
32    reason = "Standard workspace crate prelude"
33)]
34pub(crate) use ctb_utilities::*;
35
36use deno_lint::rules::{LintRule, filtered_rules, get_all_rules};
37use serde::Deserialize;
38
39#[derive(Deserialize)]
40#[serde(rename_all = "camelCase")]
41pub struct DenoJsonConfig {
42    pub lint: Option<Config>,
43    #[serde(flatten)]
44    pub direct: Config,
45}
46
47#[derive(Deserialize, Default, Clone)]
48#[serde(default)]
49pub struct Config {
50    pub rules: RulesConfig,
51    pub files: FilesConfig,
52    #[serde(flatten)]
53    pub direct_files: FilesConfig,
54}
55
56#[derive(Deserialize, Default, Clone)]
57#[serde(default)]
58pub struct RulesConfig {
59    pub tags: Vec<String>,
60    pub include: Vec<String>,
61    pub exclude: Vec<String>,
62}
63
64#[derive(Deserialize, Default, Clone)]
65#[serde(default)]
66pub struct FilesConfig {
67    pub include: Vec<String>,
68    pub exclude: Vec<String>,
69}
70
71impl Config {
72    pub fn get_rules(&self) -> Vec<Box<dyn LintRule>> {
73        filtered_rules(
74            get_all_rules(),
75            Some(self.rules.tags.clone()),
76            Some(self.rules.exclude.clone()),
77            Some(self.rules.include.clone()),
78        )
79    }
80
81    pub fn get_files(
82        &self,
83        base_dir: &std::path::Path,
84    ) -> Result<Vec<std::path::PathBuf>> {
85        crate::project_files_resolver::resolve_file_paths_in_dir(
86            base_dir,
87            &self.files,
88        )
89    }
90}
91
92pub fn parse_config(bytes: &[u8]) -> Result<Config> {
93    let config_str = std::str::from_utf8(bytes)?;
94    let parsed: DenoJsonConfig = serde_json::from_str(config_str)?;
95    // Reason for fallback: when optional lint subsection is absent in deno.json, direct root config serves as fallback.
96    let mut actual_config =
97        parsed.lint.clone().unwrap_or_else(|| parsed.direct.clone());
98    if actual_config.files.include.is_empty()
99        && !actual_config.direct_files.include.is_empty()
100    {
101        actual_config.files.include =
102            std::mem::take(&mut actual_config.direct_files.include);
103    }
104    if actual_config.files.exclude.is_empty()
105        && !actual_config.direct_files.exclude.is_empty()
106    {
107        actual_config.files.exclude =
108            std::mem::take(&mut actual_config.direct_files.exclude);
109    }
110
111    if parsed.lint.is_some() {
112        let mut top_level_exclude = Vec::new();
113        top_level_exclude.extend(parsed.direct.files.exclude.clone());
114        top_level_exclude.extend(parsed.direct.direct_files.exclude.clone());
115        for ext in top_level_exclude {
116            if !actual_config.files.exclude.contains(&ext) {
117                actual_config.files.exclude.push(ext);
118            }
119        }
120
121        if actual_config.files.include.is_empty() {
122            let mut top_level_include = Vec::new();
123            top_level_include.extend(parsed.direct.files.include.clone());
124            top_level_include
125                .extend(parsed.direct.direct_files.include.clone());
126            actual_config.files.include = top_level_include;
127        }
128    }
129
130    Ok(actual_config)
131}
132
133pub fn load_from_json(config_path: &std::path::Path) -> Result<Config> {
134    let json_str = std::fs::read_to_string(config_path)?;
135    let parsed = parse_config(json_str.as_bytes())?;
136    Ok(parsed)
137}
138
139pub fn get_rules_from_config(
140    config_bytes: &[u8],
141) -> Result<Vec<Box<dyn LintRule>>> {
142    let actual_config = parse_config(config_bytes)?;
143    let rules = filtered_rules(
144        get_all_rules(),
145        Some(actual_config.rules.tags),
146        Some(actual_config.rules.exclude),
147        Some(actual_config.rules.include),
148    );
149    Ok(rules)
150}
151
152#[cfg(test)]
153#[allow(
154    clippy::panic,
155    clippy::expect_used,
156    clippy::unwrap_used,
157    clippy::unwrap_in_result,
158    clippy::panic_in_result_fn,
159    clippy::indexing_slicing,
160    clippy::arithmetic_side_effects,
161    reason = "Standard repository test boilerplate"
162)]
163mod tests {
164    use super::*;
165    use deno_lint::rules::recommended_rules;
166    use std::collections::HashSet;
167
168    macro_rules! svec {
169    ($( $elem:literal ),* $(,)?) => {{
170      vec![$( $elem.to_string() ),*]
171    }}
172  }
173    macro_rules! set {
174    ($( $elem:literal ),* $(,)?) => {{
175      vec![$( $elem ),*].into_iter().collect::<HashSet<&'static str>>()
176    }}
177  }
178
179    fn into_codes(rules: Vec<Box<dyn LintRule>>) -> HashSet<&'static str> {
180        rules.iter().map(|rule| rule.code()).collect()
181    }
182
183    #[crate::ctb_test]
184    fn test_get_rules() {
185        let config = Config {
186            rules: RulesConfig {
187                tags: svec![],
188                include: svec![],
189                exclude: svec![],
190            },
191            ..Default::default()
192        };
193        assert!(config.get_rules().is_empty());
194
195        let config = Config {
196            rules: RulesConfig {
197                tags: svec!["recommended"],
198                include: svec![],
199                exclude: svec![],
200            },
201            ..Default::default()
202        };
203        let recommended_rules_codes =
204            into_codes(recommended_rules(get_all_rules()));
205        assert_eq!(into_codes(config.get_rules()), recommended_rules_codes);
206
207        // even if "recommended" is specified in `tags` and `include` contains a rule
208        // code that is in the "recommended" set, we have to make sure that each
209        // rule is run just once respectively.
210        let config = Config {
211            rules: RulesConfig {
212                tags: svec!["recommended"],
213                include: svec!["no-empty"], // "no-empty" belongs to "recommended"
214                exclude: svec![],
215            },
216            ..Default::default()
217        };
218        let recommended_rules_codes =
219            into_codes(recommended_rules(get_all_rules()));
220        assert_eq!(into_codes(config.get_rules()), recommended_rules_codes);
221
222        // `exclude` has higher precedence over `include`
223        let config = Config {
224            rules: RulesConfig {
225                tags: svec![],
226                include: svec!["eqeqeq"],
227                exclude: svec!["eqeqeq"],
228            },
229            ..Default::default()
230        };
231        assert_eq!(into_codes(config.get_rules()), set![]);
232
233        // if unknown rule is specified, just ignore it
234        let config = Config {
235            rules: RulesConfig {
236                tags: svec![],
237                include: svec!["this-is-a-totally-unknown-rule"],
238                exclude: svec!["this-is-also-another-unknown-rule"],
239            },
240            ..Default::default()
241        };
242        assert_eq!(into_codes(config.get_rules()), set![]);
243    }
244
245    #[crate::ctb_test]
246    fn test_parse_config_merges_top_level_excludes() {
247        let json_bytes = r#"{
248            "exclude": ["top-exclude"],
249            "lint": {
250                "include": ["lint-include"],
251                "exclude": ["lint-exclude"]
252            }
253        }"#
254        .as_bytes();
255        let config = parse_config(json_bytes).unwrap();
256        assert_eq!(config.files.include, vec!["lint-include"]);
257        assert!(config.files.exclude.contains(&"top-exclude".to_string()));
258        assert!(config.files.exclude.contains(&"lint-exclude".to_string()));
259    }
260}
261
262/*
263Code from dlint is used under the following license:
264======
265
266MIT License
267
268Copyright (c) 2018-2024 the Deno authors
269
270Permission is hereby granted, free of charge, to any person obtaining a copy
271of this software and associated documentation files (the "Software"), to deal
272in the Software without restriction, including without limitation the rights
273to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
274copies of the Software, and to permit persons to whom the Software is
275furnished to do so, subject to the following conditions:
276
277The above copyright notice and this permission notice shall be included in all
278copies or substantial portions of the Software.
279
280THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
281IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
282FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
283AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
284LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
285OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
286SOFTWARE.
287*/