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, 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<lua::Version>,
84}
85
86impl FmtConfig {
87    fn resolve(root: &Path, lua_version: Option<lua::Version>) -> 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(
223    lua_version: &lua::Version,
224) -> Option<luafmt::LuaSyntaxLevel> {
225    match lua_version {
226        lua::Version::Lua51 => Some(luafmt::LuaSyntaxLevel::Lua51),
227        lua::Version::Lua52 => Some(luafmt::LuaSyntaxLevel::Lua52),
228        lua::Version::Lua53 => Some(luafmt::LuaSyntaxLevel::Lua53),
229        lua::Version::Lua54 => Some(luafmt::LuaSyntaxLevel::Lua54),
230        lua::Version::Lua55 => Some(luafmt::LuaSyntaxLevel::Lua55),
231        lua::Version::LuaJIT | lua::Version::LuaJIT52 => Some(luafmt::LuaSyntaxLevel::LuaJIT),
232        lua::Version::Luau => None,
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    use assert_fs::fixture::PathChild;
239    use assert_fs::{prelude::PathCopy, TempDir};
240    use lux_lib::config;
241    use serial_test::serial;
242
243    use super::*;
244    use std::path::PathBuf;
245
246    #[serial]
247    #[tokio::test]
248    async fn test_format_while_in_another_workspace() {
249        let unformatted_sample_project = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
250            .join("resources/test/sample-projects/unformatted/");
251        let unformatted_project_root = TempDir::new().unwrap();
252        unformatted_project_root
253            .copy_from(&unformatted_sample_project, &["**"])
254            .unwrap();
255
256        let cwd_sample_project =
257            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-projects/init/");
258        let cwd_project_root = TempDir::new().unwrap();
259        cwd_project_root
260            .copy_from(&cwd_sample_project, &["**"])
261            .unwrap();
262
263        let cwd = std::env::current_dir().unwrap();
264        std::env::set_current_dir(&cwd_project_root).unwrap();
265
266        let config = config::Builder::new().unwrap().build().unwrap();
267        let fmt = Fmt {
268            path: Some(unformatted_project_root.to_path_buf()),
269            backend: FmtBackend::Stylua,
270            package: None,
271        };
272
273        format(fmt, config).unwrap();
274
275        let unformatted_file_path = unformatted_project_root.child("src").child("main.lua");
276        let content = std::fs::read_to_string(&unformatted_file_path).unwrap();
277
278        // the unformatted variant contains too many spaces
279        assert!(content.contains("print(1 * 2)"));
280
281        std::env::set_current_dir(&cwd).unwrap();
282    }
283
284    fn loose_lua_temp_dir() -> TempDir {
285        let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/loose-lua/");
286        let dir = TempDir::new().unwrap();
287        dir.copy_from(&fixture, &["**"]).unwrap();
288        dir
289    }
290
291    fn fmt(path: Option<PathBuf>) -> Fmt {
292        Fmt {
293            path,
294            backend: FmtBackend::Stylua,
295            package: None,
296        }
297    }
298
299    #[test]
300    fn test_format_plain_directory_without_lux_toml() {
301        let dir = loose_lua_temp_dir();
302        let config = config::Builder::new().unwrap().build().unwrap();
303
304        format(fmt(Some(dir.to_path_buf())), config).unwrap();
305
306        let top = std::fs::read_to_string(dir.child("a.lua")).unwrap();
307        let nested = std::fs::read_to_string(dir.child("nested").child("b.lua")).unwrap();
308        let other = std::fs::read_to_string(dir.child("notes.txt")).unwrap();
309        assert!(top.contains("print(1 * 2)"));
310        assert!(nested.contains("print(3 + 4)"));
311        // non-Lua files are left untouched
312        assert!(other.contains("print( 5 *    6 )"));
313    }
314
315    #[test]
316    fn test_format_single_lua_file() {
317        let dir = loose_lua_temp_dir();
318        let config = config::Builder::new().unwrap().build().unwrap();
319
320        format(fmt(Some(dir.child("a.lua").to_path_buf())), config).unwrap();
321
322        let top = std::fs::read_to_string(dir.child("a.lua")).unwrap();
323        let nested = std::fs::read_to_string(dir.child("nested").child("b.lua")).unwrap();
324        assert!(top.contains("print(1 * 2)"));
325        // a sibling file is not touched when a single file is targeted
326        assert!(nested.contains("print( 3 +    4 )"));
327    }
328
329    #[test]
330    fn test_format_nonexistent_path_errors() {
331        let config = config::Builder::new().unwrap().build().unwrap();
332        let result = format(fmt(Some("/no/such/path".into())), config);
333        assert!(result.is_err());
334    }
335
336    #[test]
337    fn test_format_subdir_inherits_workspace_config() {
338        // must resolve workspace's stylua.toml (Spaces/2-width), not stylua default.
339        let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
340            .join("resources/test/sample-projects/stylua-config/");
341        let workspace = TempDir::new().unwrap();
342        workspace.copy_from(&fixture, &["**"]).unwrap();
343        let config = config::Builder::new().unwrap().build().unwrap();
344
345        format(fmt(Some(workspace.child("src").to_path_buf())), config).unwrap();
346
347        let content = std::fs::read_to_string(workspace.child("src").child("main.lua")).unwrap();
348        assert!(content.contains("\n  print(1 * 2)"));
349        assert!(!content.contains('\t'));
350    }
351}