Skip to main content

luaur_cli_lib/functions/
get_source_files.rs

1use crate::functions::get_extension::get_extension;
2use crate::functions::is_directory::is_directory;
3use crate::functions::normalize_path::normalize_path;
4use crate::functions::traverse_directory_file_utils::traverse_directory_mut;
5use core::ffi::CStr;
6
7pub fn get_source_files(
8    argc: i32,
9    argv: *mut *mut core::ffi::c_char,
10) -> alloc::vec::Vec<alloc::string::String> {
11    let mut files = alloc::vec::Vec::new();
12
13    for i in 1..argc as usize {
14        let arg_ptr = unsafe { *argv.add(i) };
15        if arg_ptr.is_null() {
16            continue;
17        }
18
19        let arg = unsafe { CStr::from_ptr(arg_ptr).to_string_lossy() };
20
21        if arg == "--program-args" || arg == "-a" {
22            return files;
23        }
24
25        // Treat '-' as a special file whose source is read from stdin
26        // All other arguments that start with '-' are skipped
27        if arg.starts_with('-') && arg.len() > 1 {
28            continue;
29        }
30
31        let normalized = normalize_path(&arg);
32
33        if is_directory(&normalized) {
34            // Use a Cell or RefCell to allow mutation of the captured vector within the Fn closure,
35            // or use a raw pointer if we are sure about the safety context of traverse_directory_mut.
36            // Since traverse_directory_mut takes &dyn Fn, we use a RefCell for interior mutability.
37            let files_ref = std::cell::RefCell::new(&mut files);
38
39            traverse_directory_mut(&normalized, &|name: &str| {
40                let ext = get_extension(name);
41                if ext == ".lua" || ext == ".luau" {
42                    files_ref
43                        .borrow_mut()
44                        .push(alloc::string::String::from(name));
45                }
46            });
47        } else {
48            files.push(normalized);
49        }
50    }
51
52    files
53}