ctb_formats_javascript/project_files_resolver.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 project file discovery and include/exclude path resolution.
28
29#[allow(
30 unused_imports,
31 clippy::wildcard_imports,
32 reason = "Standard workspace crate prelude"
33)]
34pub(crate) use ctb_utilities::*;
35
36use crate::deno_config::FilesConfig;
37
38/// Resolves and filters file paths within a base directory using the provided
39/// include and exclude pattern slices. Files are matched against allowed
40/// extensions (js, ts, jsx, tsx) and custom glob/prefix path matching.
41pub fn resolve_project_files(
42 base_dir: &std::path::Path,
43 include: &[String],
44 exclude: &[String],
45) -> Result<Vec<std::path::PathBuf>> {
46 let mut file_paths = Vec::new();
47 for entry in walkdir::WalkDir::new(base_dir)
48 .into_iter()
49 .filter_map(std::result::Result::ok)
50 .filter(|e| e.file_type().is_file())
51 {
52 let path = entry.path();
53 // Reason for fallback: strip_prefix returns Err if path is not under base_dir, falling back to original path.
54 let relative_path = path.strip_prefix(base_dir).unwrap_or(path);
55 let relative_path_str =
56 relative_path.to_string_lossy().replace('\\', "/");
57
58 let ext = path.extension().and_then(|s| s.to_str());
59 if ext != Some("js")
60 && ext != Some("ts")
61 && ext != Some("jsx")
62 && ext != Some("tsx")
63 {
64 continue;
65 }
66
67 let is_included = if include.is_empty() {
68 true
69 } else {
70 include.iter().any(|inc| {
71 // Reason for fallback: strip_prefix returns None if "./" prefix is absent, falling back to original pattern inc.
72 let inc_norm =
73 inc.strip_prefix("./").unwrap_or(inc).trim_end_matches('/');
74 relative_path_str.starts_with(inc_norm)
75 || glob::Pattern::new(inc_norm)
76 .map(|pat| pat.matches(&relative_path_str))
77 // Reason for fallback: if glob pattern fails to compile, false is returned to indicate no match.
78 .unwrap_or(false)
79 })
80 };
81
82 if is_included {
83 let is_excluded = exclude.iter().any(|exc| {
84 // Reason for fallback: strip_prefix returns None if "./" prefix is absent, falling back to original pattern exc.
85 let exc_norm =
86 exc.strip_prefix("./").unwrap_or(exc).trim_end_matches('/');
87 relative_path_str.starts_with(exc_norm)
88 || glob::Pattern::new(exc_norm)
89 .map(|pat| pat.matches(&relative_path_str))
90 // Reason for fallback: if glob pattern fails to compile, false is returned to indicate no match.
91 .unwrap_or(false)
92 });
93
94 if !is_excluded {
95 file_paths.push(path.to_path_buf());
96 }
97 }
98 }
99
100 Ok(file_paths)
101}
102
103/// Resolves file paths configured via Deno's `FilesConfig` in a directory.
104pub fn resolve_file_paths_in_dir(
105 base_dir: &std::path::Path,
106 files_config: &FilesConfig,
107) -> Result<Vec<std::path::PathBuf>> {
108 resolve_project_files(
109 base_dir,
110 &files_config.include,
111 &files_config.exclude,
112 )
113}
114
115#[cfg(test)]
116#[allow(
117 clippy::panic,
118 clippy::expect_used,
119 clippy::unwrap_used,
120 clippy::unwrap_in_result,
121 clippy::panic_in_result_fn,
122 clippy::indexing_slicing,
123 clippy::arithmetic_side_effects,
124 reason = "Standard repository test boilerplate"
125)]
126mod tests {
127 use super::*;
128
129 #[crate::ctb_test]
130 fn test_resolve_project_files() {
131 let temp_dir = tempfile::tempdir().unwrap();
132 let base_path = temp_dir.path();
133
134 // Create a hierarchy of test files
135 let file_js = base_path.join("a.js");
136 let file_ts = base_path.join("b.ts");
137 let file_jsx = base_path.join("c.jsx");
138 let file_tsx = base_path.join("d.tsx");
139 let file_txt = base_path.join("e.txt");
140 let sub_dir = base_path.join("subdir");
141 std::fs::create_dir(&sub_dir).unwrap();
142 let file_sub_js = sub_dir.join("f.js");
143 let file_sub_ignored_js = sub_dir.join("ignored.js");
144
145 std::fs::write(&file_js, "console.log('js');").unwrap();
146 std::fs::write(&file_ts, "console.log('ts');").unwrap();
147 std::fs::write(&file_jsx, "console.log('jsx');").unwrap();
148 std::fs::write(&file_tsx, "console.log('tsx');").unwrap();
149 std::fs::write(&file_txt, "hello text").unwrap();
150 std::fs::write(&file_sub_js, "console.log('sub js');").unwrap();
151 std::fs::write(&file_sub_ignored_js, "console.log('sub ignored js');")
152 .unwrap();
153
154 // 1. Resolve all files (no includes/excludes)
155 let files = resolve_project_files(base_path, &[], &[]).unwrap();
156 // Should contain js, ts, jsx, tsx and sub_dir files, but NOT txt
157 assert_eq!(files.len(), 6);
158 assert!(files.contains(&file_js));
159 assert!(files.contains(&file_ts));
160 assert!(files.contains(&file_jsx));
161 assert!(files.contains(&file_tsx));
162 assert!(files.contains(&file_sub_js));
163 assert!(files.contains(&file_sub_ignored_js));
164 assert!(!files.contains(&file_txt));
165
166 // 2. Resolve with include patterns
167 let files_inc = resolve_project_files(
168 base_path,
169 &["a.js".to_string(), "subdir/f.js".to_string()],
170 &[],
171 )
172 .unwrap();
173 assert_eq!(files_inc.len(), 2);
174 assert!(files_inc.contains(&file_js));
175 assert!(files_inc.contains(&file_sub_js));
176
177 // 3. Resolve with exclude patterns
178 let files_exc = resolve_project_files(
179 base_path,
180 &[],
181 &["subdir/ignored.js".to_string(), "b.ts".to_string()],
182 )
183 .unwrap();
184 assert_eq!(files_exc.len(), 4);
185 assert!(files_exc.contains(&file_js));
186 assert!(files_exc.contains(&file_jsx));
187 assert!(files_exc.contains(&file_tsx));
188 assert!(files_exc.contains(&file_sub_js));
189 assert!(!files_exc.contains(&file_sub_ignored_js));
190 assert!(!files_exc.contains(&file_ts));
191 }
192}
193
194/*
195Code from dlint is used under the following license:
196======
197
198MIT License
199
200Copyright (c) 2018-2024 the Deno authors
201
202Permission is hereby granted, free of charge, to any person obtaining a copy
203of this software and associated documentation files (the "Software"), to deal
204in the Software without restriction, including without limitation the rights
205to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
206copies of the Software, and to permit persons to whom the Software is
207furnished to do so, subject to the following conditions:
208
209The above copyright notice and this permission notice shall be included in all
210copies or substantial portions of the Software.
211
212THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
213IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
214FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
215AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
216LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
217OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
218SOFTWARE.
219*/