ctb_formats_javascript/
ts_check.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//! TypeScript checker utility. While I usually try never to remove features, I can't
28//! promise that in this case. I'll probably find some way to keep it working,
29//! though.
30
31#[allow(
32    unused_imports,
33    clippy::wildcard_imports,
34    reason = "Standard workspace crate prelude"
35)]
36pub(crate) use ctb_utilities::*;
37
38use anyhow::{Result, bail};
39use std::path::{Path, PathBuf};
40use std::sync::Arc;
41
42use crate::deno_config;
43use crate::diagnostics;
44use crate::typescript;
45
46#[derive(clap::Args, Debug, Clone, Default)]
47pub struct TsCheckArgs {
48    /// Set the input file(s) or directories to use
49    #[arg(value_name = "FILES", num_args = 0..)]
50    pub files: Vec<String>,
51
52    /// Load config from file
53    #[arg(long = "config")]
54    pub config: Option<String>,
55
56    /// Configure output format
57    #[arg(long = "format", default_value = "pretty", value_parser = ["compact", "pretty"])]
58    pub format: String,
59
60    /// Dynamically patch tsconfig to add paths mapping for these types from the compiler's types folder
61    #[arg(long = "add-types", num_args = 1..)]
62    pub add_types: Vec<String>,
63}
64
65#[derive(clap::Parser, Debug, Clone)]
66#[command(name = "ts-check", version = env!("CARGO_PKG_VERSION"))]
67pub struct TsCheckBinaryCli {
68    #[command(flatten)]
69    pub args: TsCheckArgs,
70}
71
72fn load_maybe_config(
73    config_path: Option<&str>,
74) -> Result<Option<Arc<deno_config::Config>>> {
75    if let Some(config_path) = config_path {
76        let path = PathBuf::from(config_path);
77        if path
78            .file_name()
79            .and_then(|s| s.to_str())
80            .is_some_and(|s| s.contains("tsconfig"))
81        {
82            Ok(None)
83        } else {
84            let config = match path.extension().and_then(|s| s.to_str()) {
85                Some("json") => deno_config::load_from_json(&path)?,
86                ext => {
87                    bail!("Unknown extension: \"{ext:#?}\". Use .json instead.")
88                }
89            };
90            Ok(Some(Arc::new(config)))
91        }
92    } else if PathBuf::from("deno.json").exists()
93        && !PathBuf::from("tsconfig.json").exists()
94    {
95        Ok(Some(Arc::new(deno_config::load_from_json(Path::new(
96            "deno.json",
97        ))?)))
98    } else {
99        Ok(None)
100    }
101}
102
103pub fn run_typecheck_args(args: &TsCheckArgs) -> Result<i32> {
104    let cwd = std::env::current_dir()?;
105    let maybe_config = load_maybe_config(args.config.as_deref())?;
106    let mut all_diagnostics = Vec::new();
107
108    if args.files.is_empty() {
109        let config = maybe_config.map(|c| (*c).clone());
110        all_diagnostics.extend(typescript::ts_check_directory(
111            &cwd,
112            config,
113            &args.add_types,
114        )?);
115    } else {
116        let mut files_to_check = Vec::new();
117        for input_path in &args.files {
118            let path = cwd.join(input_path);
119            if path.is_dir() {
120                let config = maybe_config.clone().map(|c| (*c).clone());
121                all_diagnostics.extend(typescript::ts_check_directory(
122                    &path,
123                    config,
124                    &args.add_types,
125                )?);
126            } else {
127                files_to_check.push(path);
128            }
129        }
130        if !files_to_check.is_empty() {
131            all_diagnostics.extend(typescript::ts_check_files(
132                &files_to_check,
133                &args.add_types,
134            )?);
135        }
136    }
137
138    let error_count = all_diagnostics.len();
139    diagnostics::display_diagnostics(
140        &all_diagnostics,
141        Some(args.format.as_str()),
142    );
143
144    if error_count > 0 {
145        eprintln!(
146            "Found {} problem{}",
147            error_count,
148            if error_count == 1 { "" } else { "s" }
149        );
150        return Ok(1);
151    }
152
153    Ok(0)
154}
155
156/*
157Code from dlint is used under the following license:
158======
159
160MIT License
161
162Copyright (c) 2018-2024 the Deno authors
163
164Permission is hereby granted, free of charge, to any person obtaining a copy
165of this software and associated documentation files (the "Software"), to deal
166in the Software without restriction, including without limitation the rights
167to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
168copies of the Software, and to permit persons to whom the Software is
169furnished to do so, subject to the following conditions:
170
171The above copyright notice and this permission notice shall be included in all
172copies or substantial portions of the Software.
173
174THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
175IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
176FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
177AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
178LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
179OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
180SOFTWARE.
181*/