ctb_formats_javascript/
js_lint.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//! JavaScript and TypeScript code linter engine and execution pipeline.
28
29#[allow(
30    unused_imports,
31    clippy::wildcard_imports,
32    reason = "Standard workspace crate prelude"
33)]
34pub(crate) use ctb_utilities::*;
35
36use anyhow::{Result, anyhow, bail};
37use ctb_utilities::bail_if_err;
38use deno_ast::MediaType;
39use deno_ast::ModuleSpecifier;
40use deno_ast::diagnostics::Diagnostic;
41use deno_lint::linter::LintConfig;
42use deno_lint::linter::LintFileOptions;
43use deno_lint::linter::Linter;
44use deno_lint::linter::LinterOptions;
45use deno_lint::rules::get_all_rules;
46use deno_lint::rules::{filtered_rules, recommended_rules};
47use std::borrow::Cow;
48use std::collections::BTreeMap;
49use std::collections::HashSet;
50use std::path::{Path, PathBuf};
51use std::sync::atomic::{AtomicUsize, Ordering};
52use std::sync::{Arc, Mutex};
53
54use crate::deno_config;
55
56#[path = "js_lint_rules.rs"]
57mod js_lint_rules;
58
59#[derive(clap::Args, Debug, Clone, Default)]
60pub struct JsLintRunArgs {
61    /// Set the input file to use
62    #[arg(value_name = "FILES", num_args = 0..)]
63    pub files: Vec<String>,
64
65    /// Run a certain rule
66    #[arg(long = "rule")]
67    pub rule_code: Option<String>,
68
69    /// Load config from file
70    #[arg(long = "config")]
71    pub config: Option<String>,
72
73    /// Configure output format
74    #[arg(long = "format", default_value = "pretty", value_parser = ["compact", "pretty"])]
75    pub format: String,
76}
77
78#[derive(clap::Args, Debug, Clone, Default)]
79pub struct JsLintRulesArgs {
80    /// Show detailed information about rule. If omitted, show the list of all rules.
81    #[arg(value_name = "RULE_NAME")]
82    pub rule_name: Option<String>,
83
84    #[arg(long)]
85    pub json: bool,
86}
87
88#[derive(clap::Subcommand, Debug, Clone)]
89pub enum JsLintSubcommand {
90    Rules(JsLintRulesArgs),
91    Run(JsLintRunArgs),
92}
93
94#[derive(clap::Args, Debug, Clone, Default)]
95#[command(
96    args_conflicts_with_subcommands = true,
97    subcommand_precedence_over_arg = true
98)]
99pub struct JsLintCli {
100    #[command(subcommand)]
101    pub command: Option<JsLintSubcommand>,
102
103    #[command(flatten)]
104    pub run: JsLintRunArgs,
105}
106
107#[derive(clap::Parser, Debug, Clone)]
108#[command(name = "js-lint", version = env!("CARGO_PKG_VERSION"))]
109pub struct JsLintBinaryCli {
110    #[command(flatten)]
111    pub cli: JsLintCli,
112}
113
114fn load_maybe_config(
115    config_path: Option<&str>,
116) -> Result<Option<Arc<deno_config::Config>>> {
117    if let Some(config_path) = config_path {
118        let path = PathBuf::from(config_path);
119        let config = match path.extension().and_then(|s| s.to_str()) {
120            Some("json") => deno_config::load_from_json(&path)?,
121            ext => bail!("Unknown extension: \"{ext:#?}\". Use .json instead."),
122        };
123        Ok(Some(Arc::new(config)))
124    } else if PathBuf::from("deno.json").exists() {
125        Ok(Some(Arc::new(deno_config::load_from_json(Path::new(
126            "deno.json",
127        ))?)))
128    } else {
129        Ok(None)
130    }
131}
132
133fn run_linter(
134    paths: &[String],
135    filter_rule_name: Option<&str>,
136    maybe_config: Option<Arc<deno_config::Config>>,
137    format: Option<&str>,
138) -> Result<i32> {
139    let cwd = std::env::current_dir()?;
140    let mut paths: Vec<PathBuf> =
141        paths.iter().map(|path| cwd.join(path)).collect();
142
143    if let Some(config) = maybe_config.clone() {
144        paths.extend(config.get_files(&cwd)?);
145    }
146
147    let error_counts = Arc::new(AtomicUsize::new(0));
148
149    let all_rules = get_all_rules();
150    let mut all_rule_codes = all_rules
151        .iter()
152        .map(|rule| rule.code())
153        .map(Cow::from)
154        .collect::<HashSet<_>>();
155
156    all_rule_codes.insert("require-jsdoc".into());
157    all_rule_codes.insert("require-param".into());
158    all_rule_codes.insert("require-returns".into());
159
160    let mut jsdoc_rules = crate::jsdoc::JSDocRules::default();
161    if let Some(config) = &maybe_config {
162        jsdoc_rules.require_jsdoc =
163            config.rules.include.iter().any(|r| r == "require-jsdoc")
164                && !config.rules.exclude.iter().any(|r| r == "require-jsdoc");
165        jsdoc_rules.require_param =
166            config.rules.include.iter().any(|r| r == "require-param")
167                && !config.rules.exclude.iter().any(|r| r == "require-param");
168        jsdoc_rules.require_returns =
169            config.rules.include.iter().any(|r| r == "require-returns")
170                && !config.rules.exclude.iter().any(|r| r == "require-returns");
171    } else if let Some(rule_name) = filter_rule_name {
172        jsdoc_rules.require_jsdoc = rule_name == "require-jsdoc";
173        jsdoc_rules.require_param = rule_name == "require-param";
174        jsdoc_rules.require_returns = rule_name == "require-returns";
175    }
176    let jsdoc_enabled = jsdoc_rules.require_jsdoc
177        || jsdoc_rules.require_param
178        || jsdoc_rules.require_returns;
179
180    let rules = if let Some(config) = maybe_config.clone() {
181        config.get_rules()
182    } else if let Some(rule_name) = filter_rule_name {
183        let include = vec![rule_name.to_string()];
184        filtered_rules(get_all_rules(), Some(vec![]), None, Some(include))
185    } else {
186        recommended_rules(get_all_rules())
187    };
188    if rules.is_empty() && !jsdoc_enabled {
189        bail!("No lint rules configured");
190    }
191
192    let file_diagnostics = Arc::new(Mutex::new(BTreeMap::new()));
193    let linter = Linter::new(LinterOptions {
194        rules,
195        all_rule_codes,
196        custom_ignore_file_directive: None,
197        custom_ignore_diagnostic_directive: None,
198    });
199
200    use rayon::prelude::*;
201
202    paths.par_iter().try_for_each(|file_path| -> Result<()> {
203        let source_code = std::fs::read_to_string(file_path)?;
204
205        let external_linter = if jsdoc_enabled {
206            let cb: deno_lint::linter::ExternalLinterCb =
207                Arc::new(move |parsed_source| {
208                    let diags = crate::jsdoc::run_jsdoc_linter(
209                        &parsed_source,
210                        jsdoc_rules,
211                    );
212                    let mut rules = vec![];
213                    if jsdoc_rules.require_jsdoc {
214                        rules.push("require-jsdoc".into());
215                    }
216                    if jsdoc_rules.require_param {
217                        rules.push("require-param".into());
218                    }
219                    if jsdoc_rules.require_returns {
220                        rules.push("require-returns".into());
221                    }
222                    Some(deno_lint::linter::ExternalLinterResult {
223                        diagnostics: diags,
224                        rules,
225                    })
226                });
227            Some(cb)
228        } else {
229            None
230        };
231
232        let (parsed_source, diagnostics) =
233            linter.lint_file(LintFileOptions {
234                specifier: bail_if_err!(ModuleSpecifier::from_file_path(
235                    file_path
236                )),
237                source_code,
238                media_type: MediaType::from_path(file_path),
239                config: LintConfig {
240                    default_jsx_factory: Some(
241                        "React.createElement".to_string(),
242                    ),
243                    default_jsx_fragment_factory: Some(
244                        "React.Fragment".to_string(),
245                    ),
246                },
247                external_linter,
248            })?;
249
250        let parsing_diagnostics = parsed_source.diagnostics().clone();
251        let number_of_errors =
252            diagnostics.len().saturating_add(parsing_diagnostics.len());
253        for parsing_diagnostic in &parsing_diagnostics {
254            eprintln!("{}", parsing_diagnostic.display());
255        }
256
257        error_counts.fetch_add(number_of_errors, Ordering::Relaxed);
258
259        let mut lock = file_diagnostics
260            .lock()
261            .map_err(|_| anyhow!("js-lint diagnostics mutex poisoned"))?;
262        lock.insert(file_path.clone(), diagnostics);
263
264        Ok(())
265    })?;
266
267    let diagnostics_by_file = file_diagnostics
268        .lock()
269        .map_err(|_| anyhow!("js-lint diagnostics mutex poisoned"))?;
270    for diagnostics in diagnostics_by_file.values() {
271        crate::diagnostics::display_diagnostics(diagnostics, format);
272    }
273
274    let err_count = error_counts.load(Ordering::Relaxed);
275    if err_count > 0 {
276        eprintln!(
277            "Found {} problem{}",
278            err_count,
279            if err_count == 1 { "" } else { "s" }
280        );
281        return Ok(1);
282    }
283
284    Ok(0)
285}
286
287pub fn run_run_args(args: &JsLintRunArgs) -> Result<i32> {
288    let maybe_config = load_maybe_config(args.config.as_deref())?;
289    run_linter(
290        &args.files,
291        args.rule_code.as_deref(),
292        maybe_config,
293        Some(args.format.as_str()),
294    )
295}
296
297pub fn run_cli(cli: &JsLintCli) -> Result<i32> {
298    match &cli.command {
299        Some(JsLintSubcommand::Rules(args)) => {
300            let rules = if let Some(rule_name) = &args.rule_name {
301                js_lint_rules::get_specific_rule_metadata(rule_name)
302            } else {
303                js_lint_rules::get_all_rules_metadata()
304            };
305            if args.json {
306                js_lint_rules::print_rules::<js_lint_rules::JsonFormatter>(
307                    rules,
308                );
309            } else {
310                js_lint_rules::print_rules::<js_lint_rules::PrettyFormatter>(
311                    rules,
312                );
313            }
314            Ok(0)
315        }
316        Some(JsLintSubcommand::Run(args)) => run_run_args(args),
317        None => run_run_args(&cli.run),
318    }
319}
320
321/*
322Code from dlint is used under the following license:
323======
324
325MIT License
326
327Copyright (c) 2018-2024 the Deno authors
328
329Permission is hereby granted, free of charge, to any person obtaining a copy
330of this software and associated documentation files (the "Software"), to deal
331in the Software without restriction, including without limitation the rights
332to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
333copies of the Software, and to permit persons to whom the Software is
334furnished to do so, subject to the following conditions:
335
336The above copyright notice and this permission notice shall be included in all
337copies or substantial portions of the Software.
338
339THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
340IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
341FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
342AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
343LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
344OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
345SOFTWARE.
346*/