Skip to main content

luaur_cli_lib/functions/
get_module_path.rs

1use crate::functions::has_suffix::has_suffix;
2use crate::functions::is_absolute_path::is_absolute_path;
3use luaur_common::macros::luau_assert::LUAU_ASSERT;
4
5const K_INIT_SUFFIXES: &[&str] = &["/init.luau", "/init.lua"];
6const K_SUFFIXES: &[&str] = &[".luau", ".lua"];
7
8pub fn get_module_path(file_path: &str) -> alloc::string::String {
9    let file_path_normalized = file_path.replace('\\', "/");
10
11    let mut path_view: &str = &file_path_normalized;
12
13    if is_absolute_path(path_view) {
14        let first_slash = path_view.find('/');
15        LUAU_ASSERT!(first_slash.is_some());
16        if let Some(idx) = first_slash {
17            path_view = &path_view[idx..];
18        }
19    }
20
21    for &suffix in K_INIT_SUFFIXES {
22        if has_suffix(path_view, suffix) {
23            path_view = &path_view[..path_view.len() - suffix.len()];
24            return alloc::string::String::from(path_view);
25        }
26    }
27
28    for &suffix in K_SUFFIXES {
29        if has_suffix(path_view, suffix) {
30            path_view = &path_view[..path_view.len() - suffix.len()];
31            return alloc::string::String::from(path_view);
32        }
33    }
34
35    alloc::string::String::from(path_view)
36}