Repository: seaofvoices/darklua (rust)

Issue:
Darklua assumes path require's extension as explicit extension set path while bundling
![Image](https://github.com/user-attachments/assets/42a199e6-a8f6-4626-a372-df64e56a9a1c)
If you look at the picture, Darklua sees the path require with the extension set as the path with the extension set explicitly and does not set the `.luau` extension. Also the path require with the extension set explicitly is not supported in the latest Luau(ex. `require("path/to/module.luau")`). So Darklua must watch for it by inserting the .luau extension, but the problem is, since the extension is already set, Darklua searches for the file itself(ex. Darklua tries `Error.global` instead of `Error.global.luau`)

A workaround is to bundle it by replacing the extension with something else (e.g. underscore) instead of using dot inside of the path require.

Pull request:
Support path requires with extensions
Closes #266 

Allow paths like `name.suffix` to match a file at 
- `name.suffix.luau`
- `name.suffix.lua`
- `name.suffix/init.luau`
- `name.suffix/init.lua`

- [x] add entry to the changelog


Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1002fab..75c0b88 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,6 @@
 # Changelog
 
+* add support for path requires ending with an extension different than `.luau` or `.lua` ([#280](https://github.com/seaofvoices/darklua/pull/280))
 * add rule to convert `math.sqrt()` calls into an exponent form (using the `^` operator) (`convert_square_root_call`) ([#278](https://github.com/seaofvoices/darklua/pull/278))
 * improve `inject_global_value` to support structured data. Add the `env_json` property to inject JSON encoded data and the `default_value` property to inject data when the provided environment variable is not defined ([#277](https://github.com/seaofvoices/darklua/pull/277))
 * add rule to remove method call syntax (`remove_method_call`) ([#276](https://github.com/seaofvoices/darklua/pull/276))
diff --git a/site/content/docs/path-require-mode/index.md b/site/content/docs/path-require-mode/index.md
index d46a42e..82ed271 100644
--- a/site/content/docs/path-require-mode/index.md
+++ b/site/content/docs/path-require-mode/index.md
@@ -36,17 +36,14 @@ The first step consist of figuring out the head of the path or where to start lo
 - **if the path starts with `/`:** the path is considered like a regular absolute path
 - **else:** the first component of the path is used to find a matching [source](#sources)
 
-The next step is to resolve the tail of the path:
-
-- **if the path has an extension:** the resource is expected exactly as is
-- **else:** darklua will find the first available file based on the given path:
-
-  1. the given path
-  1. the given path with a `luau` extension
-  1. the given path with a `lua` extension
-  1. the given path joined with the module folder name
-  1. (if the module folder name does not have an extension) the given path joined with the module folder name and a `luau` extension
-  1. (if the module folder name does not have an extension) the given path joined with the module folder name and a `lua` extension
+The next step is to resolve the tail of the path. Darklua will find the first available file based on the given path:
+
+1. the given path
+1. the given path with a `luau` extension
+1. the given path with a `lua` extension
+1. the given path joined with the module folder name
+1. (if the module folder name does not have an extension) the given path joined with the module folder name and a `luau` extension
+1. (if the module folder name does not have an extension) the given path joined with the module folder name and a `lua` extension
 
 Here is a concrete example of these steps with a require to `./example`. darklua will try the following paths and find the first file:
 
diff --git a/src/rules/require/path_iterator.rs b/src/rules/require/path_iterator.rs
index e8a0d44..8429e50 100644
--- a/src/rules/require/path_iterator.rs
+++ b/src/rules/require/path_iterator.rs
@@ -1,4 +1,7 @@
-use std::path::{Path, PathBuf};
+use std::{
+    ffi::OsStr,
+    path::{Path, PathBuf},
+};
 
 pub(crate) fn find_require_paths<'a, 'b, 'c>(
     path: &'a Path,
@@ -13,7 +16,8 @@ where
 
 struct PathIterator<'a, 'b> {
     path: &'a Path,
-    has_extension: bool,
+    extension: Option<&'a OsStr>,
+    file_name: Option<&'a OsStr>,
     module_folder_name: &'b str,
     index: u8,
 }
@@ -22,12 +26,14 @@ impl<'a, 'b> PathIterator<'a, 'b> {
     fn new(path: &'a Path, module_folder_name: &'b str) -> Self {
         Self {
             path,
-            has_extension: path.extension().is_some(),
+            extension: path.extension(),
+            file_name: path.file_name(),
             module_folder_name,
             index: 0,
         }
     }
 
+    #[inline]
     fn return_next(&mut self, path: PathBuf) -> Option<PathBuf> {
         self.index += 1;
         Some(path)
@@ -38,16 +44,23 @@ impl Iterator for PathIterator<'_, '_> {
     type Item = PathBuf;
 
     fn next(&mut self) -> Option<Self::Item> {
-        if self.has_extension {
-            match self.index {
-                0 => self.return_next(self.path.to_path_buf()),
-                _ => None,
-            }
-        } else {
-            match self.index {
-                0 => self.return_next(self.path.to_path_buf()),
-                1 => self.return_next(self.path.with_extension("luau")),
-                2 => self.return_next(self.path.with_extension("lua")),
+        if self.index == 0 {
+            return self.return_next(self.path.to_path_buf());
+        }
+
+        match (self.extension, self.file_name) {
+            (Some(extension), _) if matches!(extension.to_str(), Some("luau" | "lua")) => None,
+            (_, Some(name)) => match self.index {
+                1 => {
+                    let mut next_name = name.to_os_string();
+                    next_name.push(".luau");
+                    self.return_next(self.path.with_file_name(next_name))
+                }
+                2 => {
+                    let mut next_name = name.to_os_string();
+                    next_name.push(".lua");
+                    self.return_next(self.path.with_file_name(next_name))
+                }
                 3 => self.return_next(self.path.join(self.module_folder_name)),
                 4 | 5 => {
                     let mut next_path = self.path.join(self.module_folder_name);
@@ -59,7 +72,20 @@ impl Iterator for PathIterator<'_, '_> {
                     }
                 }
                 _ => None,
-            }
+            },
+            (_, None) => match self.index {
+                1 => self.return_next(self.path.join(self.module_folder_name)),
+                2 | 3 => {
+                    let mut next_path = self.path.join(self.module_folder_name);
+                    if next_path.extension().is_some() {
+                        None
+                    } else {
+                        next_path.set_extension(if self.index == 2 { "luau" } else { "lua" });
+                        self.return_next(next_path)
+                    }
+                }
+                _ => None,
+            },
         }
     }
 }
@@ -72,13 +98,39 @@ mod test {
     const ANY_FOLDER_NAME_WITH_EXTENSION: &str = "test.luau";
 
     #[test]
-    fn returns_exact_path_when_path_has_an_extension() {
+    fn returns_exact_path_when_path_has_a_lua_extension() {
         let source = Path::new("hello.lua");
         let iterator = PathIterator::new(source, ANY_FOLDER_NAME);
 
         pretty_assertions::assert_eq!(vec![source.to_path_buf()], iterator.collect::<Vec<_>>())
     }
 
+    #[test]
+    fn returns_exact_path_when_path_has_a_luau_extension() {
+        let source = Path::new("hello.luau");
+        let iterator = PathIterator::new(source, ANY_FOLDER_NAME);
+
+        pretty_assertions::assert_eq!(vec![source.to_path_buf()], iterator.collect::<Vec<_>>())
+    }
+
+    #[test]
+    fn returns_paths_when_a_random_extension() {
+        let source = Path::new("hello.global");
+        let iterator = PathIterator::new(source, ANY_FOLDER_NAME);
+
+        pretty_assertions::assert_eq!(
+            vec![
+                source.to_path_buf(),
+                PathBuf::from("hello.global.luau"),
+                PathBuf::from("hello.global.lua"),
+                source.join(ANY_FOLDER_NAME),
+                source.join(ANY_FOLDER_NAME).with_extension("luau"),
+                source.join(ANY_FOLDER_NAME).with_extension("lua"),
+            ],
+            iterator.collect::<Vec<_>>()
+        )
+    }
+
     #[test]
     fn returns_paths_when_path_has_no_extension() {
         let source = Path::new("hello");
@@ -97,6 +149,56 @@ mod test {
         )
     }
 
+    #[test]
+    fn returns_paths_when_path_is_dot_luau() {
+        let source = Path::new(".luau");
+        let iterator = PathIterator::new(source, ANY_FOLDER_NAME);
+
+        pretty_assertions::assert_eq!(
+            vec![
+                source.to_path_buf(),
+                source.with_extension("luau"),
+                source.with_extension("lua"),
+                source.join(ANY_FOLDER_NAME),
+                source.join(ANY_FOLDER_NAME).with_extension("luau"),
+                source.join(ANY_FOLDER_NAME).with_extension("lua"),
+            ],
+            iterator.collect::<Vec<_>>()
+        )
+    }
+
+    #[test]
+    fn returns_paths_when_path_is_parent() {
+        let source = Path::new("..");
+        let iterator = PathIterator::new(source, ANY_FOLDER_NAME);
+
+        pretty_assertions::assert_eq!(
+            vec![
+                source.to_path_buf(),
+                source.join(ANY_FOLDER_NAME),
+                source.join(ANY_FOLDER_NAME).with_extension("luau"),
+                source.join(ANY_FOLDER_NAME).with_extension("lua"),
+            ],
+            iterator.collect::<Vec<_>>()
+        )
+    }
+
+    #[test]
+    fn returns_paths_when_path_is_current_directory() {
+        let source = Path::new(".");
+        let iterator = PathIterator::new(source, ANY_FOLDER_NAME);
+
+        pretty_assertions::assert_eq!(
+            vec![
+                source.to_path_buf(),
+                source.join(ANY_FOLDER_NAME),
+                source.join(ANY_FOLDER_NAME).with_extension("luau"),
+                source.join(ANY_FOLDER_NAME).with_extension("lua"),
+            ],
+            iterator.collect::<Vec<_>>()
+        )
+    }
+
     #[test]
     fn returns_paths_when_path_has_no_extension_and_module_folder_name_has_an_extension() {
         let source = Path::new("hello");


Test patch:
diff --git a/tests/rule_tests/convert_require.rs b/tests/rule_tests/convert_require.rs
index 1ebce6b..e2cddc6 100644
--- a/tests/rule_tests/convert_require.rs
+++ b/tests/rule_tests/convert_require.rs
@@ -204,6 +204,20 @@ fn convert_parent_init_module_from_init_module() {
     );
 }
 
+#[test]
+fn convert_sibling_module_from_init_module_with_non_luau_extension() {
+    let resources = memory_resources!(
+        "src/init.lua" => "local value = require('./value.global')",
+        "src/value.global.lua" => "return nil",
+        ".darklua.json" => CONVERT_PATH_TO_ROBLOX_DEFAULT_CONFIG,
+    );
+    expect_file_process(
+        &resources,
+        "src/init.lua",
+        "local value = require(script:FindFirstChild('value.global'))",
+    );
+}
+
 mod luaurc {
     use super::*;