Skip to main content

lux_cli/
format.rs

1use lux_lib::package;
2use std::path::{Path, PathBuf};
3
4use clap::Args;
5use emmylua_formatter as luafmt;
6use lux_lib::{config::Config, lua_version::LuaVersion, project::Project, workspace::Workspace};
7use miette::{bail, miette, Context, IntoDiagnostic, Result};
8use path_slash::PathExt;
9use walkdir::WalkDir;
10
11use crate::utils::path::{classify_path, PathTarget};
12
13#[derive(Args)]
14pub struct Fmt {
15    /// Path to a workspace, directory, or Lua file to format. Defaults to the current workspace.
16    #[arg(long)]
17    path: Option<PathBuf>,
18
19    #[clap(default_value = "stylua")]
20    #[arg(long)]
21    backend: FmtBackend,
22
23    /// Package to format.
24    #[arg(short, long, visible_short_alias = 'p')]
25    pub(crate) package: Option<package::Name>,
26}
27
28#[derive(clap::ValueEnum, Clone, Debug)]
29enum FmtBackend {
30    /// Mainly follows the [Roblox Lua style guide](https://roblox.github.io/lua-style-guide/).
31    Stylua,
32    /// The default formatter used by [emmylua-analyzer-rust](https://github.com/EmmyLuaLs/emmylua-analyzer-rust).
33    /// If invoked with `lx --lua-version=<version> fmt`, Lux will configure the luafmt syntax level
34    /// to match the specified Lua version.
35    Luafmt,
36    /// The default formatter used by [lua-language-server](https://luals.github.io/).
37    EmmyluaCodestyle,
38}
39
40pub fn format(args: Fmt, config: Config) -> Result<()> {
41    let target = match args.path.as_deref() {
42        None => PathTarget::Workspace(Box::new(Workspace::current_or_err()?)),
43        Some(path) => classify_path(path)?,
44    };
45    match target {
46        PathTarget::Workspace(workspace) => {
47            if let Some(package) = &args.package {
48                let project = workspace.select_member(package)?;
49                format_project(&args, &workspace, project, &config)?;
50            } else {
51                for project in workspace.members() {
52                    format_project(&args, &workspace, project, &config)?;
53                }
54            }
55        }
56        PathTarget::File(file) => {
57            ensure_no_package(&args)?;
58            let root = file
59                .parent()
60                .unwrap_or_else(|| Path::new("."))
61                .to_path_buf();
62            format_loose(std::iter::once(file), &root, &args.backend, &config)?;
63        }
64        PathTarget::Directory(dir) => {
65            ensure_no_package(&args)?;
66            let files = WalkDir::new(&dir)
67                .into_iter()
68                .filter_map(Result::ok)
69                .filter(|entry| entry.file_type().is_file())
70                .map(|entry| entry.into_path())
71                .filter(|path| is_lua_source(path));
72            format_loose(files, &dir, &args.backend, &config)?;
73        }
74    }
75    Ok(())
76}
77
78struct FmtConfig {
79    stylua: stylua_lib::Config,
80    luafmt: luafmt::LuaFormatConfig,
81    luafmt_syntax_level: Option<luafmt::LuaSyntaxLevel>,
82    editorconfig: PathBuf,
83    lua_version: Option<LuaVersion>,
84}
85
86impl FmtConfig {
87    fn resolve(root: &Path, lua_version: Option<LuaVersion>) -> Self {
88        let stylua: stylua_lib::Config = std::fs::read_to_string(root.join("stylua.toml"))
89            .or_else(|_| std::fs::read_to_string(root.join(".stylua.toml")))
90            .map(|config: String| toml::from_str(&config).unwrap_or_default())
91            .or_else(|_| {
92                stylua_lib::editorconfig::parse(stylua_lib::Config::new(), &root.join("*.lua"))
93            })
94            .unwrap_or_default();
95
96        let luafmt = luafmt::resolve_config_for_path(Some(root), None)
97            .map(|resolved| resolved.config)
98            .unwrap_or_default();
99        let luafmt_syntax_level = match &lua_version {
100            Some(version) => lua_version_to_luafmt_syntax_level(version),
101            None => Some(luafmt.syntax.level),
102        };
103
104        Self {
105            stylua,
106            luafmt,
107            luafmt_syntax_level,
108            editorconfig: root.join(".editorconfig"),
109            lua_version,
110        }
111    }
112
113    fn format(&self, backend: &FmtBackend, path: &Path, code: &str) -> Result<String> {
114        Ok(match backend {
115            FmtBackend::Stylua => stylua_lib::format_code(
116                code,
117                self.stylua,
118                None,
119                stylua_lib::OutputVerification::Full,
120            )
121            .into_diagnostic()
122            .context(format!("error formatting {} with stylua.", path.display()))?,
123            FmtBackend::Luafmt => {
124                let syntax_level = self.luafmt_syntax_level.ok_or_else(|| {
125                    miette!(
126                        "unsupported Lua version{} for luafmt",
127                        self.lua_version
128                            .as_ref()
129                            .map(|ver| format!(" '{}'", ver))
130                            .unwrap_or_default()
131                    )
132                })?;
133                luafmt::check_text(code, syntax_level.into(), &self.luafmt).formatted
134            }
135            FmtBackend::EmmyluaCodestyle => {
136                let uri = path.to_slash_lossy().to_string();
137                if self.editorconfig.is_file() {
138                    emmylua_codestyle::update_code_style(&uri, &self.editorconfig.to_slash_lossy());
139                }
140                emmylua_codestyle::reformat_code(
141                    code,
142                    &uri,
143                    emmylua_codestyle::FormattingOptions::default(),
144                )
145            }
146        })
147    }
148}
149
150fn format_files(
151    files: impl Iterator<Item = PathBuf>,
152    configs: &FmtConfig,
153    backend: &FmtBackend,
154) -> Result<()> {
155    files.into_iter().try_for_each(|file| {
156        let unformatted_code = std::fs::read_to_string(&file).into_diagnostic()?;
157        let formatted_code = configs.format(backend, &file, &unformatted_code)?;
158        std::fs::write(&file, formatted_code)
159            .into_diagnostic()
160            .context(format!("error writing formatted file {}.", file.display()))
161    })
162}
163
164fn format_project(
165    args: &Fmt,
166    workspace: &Workspace,
167    project: &Project,
168    config: &Config,
169) -> Result<()> {
170    let configs = FmtConfig::resolve(
171        workspace.root().as_ref(),
172        workspace.lua_version(config).ok(),
173    );
174
175    let lua_files = ["src", "lua", "lib", "spec", "test", "tests"]
176        .iter()
177        .flat_map(|dir| WalkDir::new(project.root().join(dir)))
178        .filter_map(Result::ok)
179        .map(walkdir::DirEntry::into_path)
180        .filter(|path| is_lua_source(path));
181
182    let rockspec = project.root().join("extra.rockspec");
183
184    format_files(
185        lua_files.chain(rockspec.exists().then_some(rockspec)),
186        &configs,
187        &args.backend,
188    )
189}
190
191fn is_lua_source(path: &Path) -> bool {
192    path.extension().is_some_and(|ext| {
193        let ext = ext.to_string_lossy();
194        ext == "lua" || ext == "luau" || ext == "rockspec"
195    })
196}
197
198fn ensure_no_package(args: &Fmt) -> Result<()> {
199    if args.package.is_some() {
200        bail!("--package is only valid within a workspace");
201    }
202    Ok(())
203}
204
205fn format_loose(
206    files: impl Iterator<Item = PathBuf>,
207    root: &Path,
208    backend: &FmtBackend,
209    config: &Config,
210) -> Result<()> {
211    let (config_root, lua_version) = match Workspace::from(root)? {
212        Some(workspace) => (
213            workspace.root().as_ref().to_path_buf(),
214            workspace.lua_version(config).ok(),
215        ),
216        None => (root.to_path_buf(), config.lua_version().cloned()),
217    };
218    let configs = FmtConfig::resolve(&config_root, lua_version);
219    format_files(files, &configs, backend)
220}
221
222fn lua_version_to_luafmt_syntax_level(lua_version: &LuaVersion) -> Option<luafmt::LuaSyntaxLevel> {
223    match lua_version {
224        LuaVersion::Lua51 => Some(luafmt::LuaSyntaxLevel::Lua51),
225        LuaVersion::Lua52 => Some(luafmt::LuaSyntaxLevel::Lua52),
226        LuaVersion::Lua53 => Some(luafmt::LuaSyntaxLevel::Lua53),
227        LuaVersion::Lua54 => Some(luafmt::LuaSyntaxLevel::Lua54),
228        LuaVersion::Lua55 => Some(luafmt::LuaSyntaxLevel::Lua55),
229        LuaVersion::LuaJIT | LuaVersion::LuaJIT52 => Some(luafmt::LuaSyntaxLevel::LuaJIT),
230        LuaVersion::Luau => None,
231    }
232}
233
234#[cfg(test)]
235mod tests {
236    use assert_fs::fixture::PathChild;
237    use assert_fs::{prelude::PathCopy, TempDir};
238    use lux_lib::config::ConfigBuilder;
239    use serial_test::serial;
240
241    use super::*;
242    use std::path::PathBuf;
243
244    #[serial]
245    #[tokio::test]
246    async fn test_format_while_in_another_workspace() {
247        let unformatted_sample_project = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
248            .join("resources/test/sample-projects/unformatted/");
249        let unformatted_project_root = TempDir::new().unwrap();
250        unformatted_project_root
251            .copy_from(&unformatted_sample_project, &["**"])
252            .unwrap();
253
254        let cwd_sample_project =
255            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-projects/init/");
256        let cwd_project_root = TempDir::new().unwrap();
257        cwd_project_root
258            .copy_from(&cwd_sample_project, &["**"])
259            .unwrap();
260
261        let cwd = std::env::current_dir().unwrap();
262        std::env::set_current_dir(&cwd_project_root).unwrap();
263
264        let config = ConfigBuilder::new().unwrap().build().unwrap();
265        let fmt = Fmt {
266            path: Some(unformatted_project_root.to_path_buf()),
267            backend: FmtBackend::Stylua,
268            package: None,
269        };
270
271        format(fmt, config).unwrap();
272
273        let unformatted_file_path = unformatted_project_root.child("src").child("main.lua");
274        let content = std::fs::read_to_string(&unformatted_file_path).unwrap();
275
276        // the unformatted variant contains too many spaces
277        assert!(content.contains("print(1 * 2)"));
278
279        std::env::set_current_dir(&cwd).unwrap();
280    }
281
282    fn loose_lua_temp_dir() -> TempDir {
283        let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/loose-lua/");
284        let dir = TempDir::new().unwrap();
285        dir.copy_from(&fixture, &["**"]).unwrap();
286        dir
287    }
288
289    fn fmt(path: Option<PathBuf>) -> Fmt {
290        Fmt {
291            path,
292            backend: FmtBackend::Stylua,
293            package: None,
294        }
295    }
296
297    #[test]
298    fn test_format_plain_directory_without_lux_toml() {
299        let dir = loose_lua_temp_dir();
300        let config = ConfigBuilder::new().unwrap().build().unwrap();
301
302        format(fmt(Some(dir.to_path_buf())), config).unwrap();
303
304        let top = std::fs::read_to_string(dir.child("a.lua")).unwrap();
305        let nested = std::fs::read_to_string(dir.child("nested").child("b.lua")).unwrap();
306        let other = std::fs::read_to_string(dir.child("notes.txt")).unwrap();
307        assert!(top.contains("print(1 * 2)"));
308        assert!(nested.contains("print(3 + 4)"));
309        // non-Lua files are left untouched
310        assert!(other.contains("print( 5 *    6 )"));
311    }
312
313    #[test]
314    fn test_format_single_lua_file() {
315        let dir = loose_lua_temp_dir();
316        let config = ConfigBuilder::new().unwrap().build().unwrap();
317
318        format(fmt(Some(dir.child("a.lua").to_path_buf())), config).unwrap();
319
320        let top = std::fs::read_to_string(dir.child("a.lua")).unwrap();
321        let nested = std::fs::read_to_string(dir.child("nested").child("b.lua")).unwrap();
322        assert!(top.contains("print(1 * 2)"));
323        // a sibling file is not touched when a single file is targeted
324        assert!(nested.contains("print( 3 +    4 )"));
325    }
326
327    #[test]
328    fn test_format_nonexistent_path_errors() {
329        let config = ConfigBuilder::new().unwrap().build().unwrap();
330        let result = format(fmt(Some("/no/such/path".into())), config);
331        assert!(result.is_err());
332    }
333
334    #[test]
335    fn test_format_subdir_inherits_workspace_config() {
336        // must resolve workspace's stylua.toml (Spaces/2-width), not stylua default.
337        let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
338            .join("resources/test/sample-projects/stylua-config/");
339        let workspace = TempDir::new().unwrap();
340        workspace.copy_from(&fixture, &["**"]).unwrap();
341        let config = ConfigBuilder::new().unwrap().build().unwrap();
342
343        format(fmt(Some(workspace.child("src").to_path_buf())), config).unwrap();
344
345        let content = std::fs::read_to_string(workspace.child("src").child("main.lua")).unwrap();
346        assert!(content.contains("\n  print(1 * 2)"));
347        assert!(!content.contains('\t'));
348    }
349}