1use std::path::{Path, PathBuf};
2
3use clap::Args;
4use emmylua_formatter as luafmt;
5use lux_lib::{
6 config::Config, lua_version::LuaVersion, package::PackageName, project::Project,
7 workspace::Workspace,
8};
9use miette::{bail, miette, Context, IntoDiagnostic, Result};
10use path_slash::PathExt;
11use walkdir::WalkDir;
12
13use crate::utils::path::{classify_path, PathTarget};
14
15#[derive(Args)]
16pub struct Fmt {
17 #[arg(long)]
19 path: Option<PathBuf>,
20
21 #[clap(default_value = "stylua")]
22 #[arg(long)]
23 backend: FmtBackend,
24
25 #[arg(short, long, visible_short_alias = 'p')]
27 pub(crate) package: Option<PackageName>,
28}
29
30#[derive(clap::ValueEnum, Clone, Debug)]
31enum FmtBackend {
32 Stylua,
34 Luafmt,
38 EmmyluaCodestyle,
40}
41
42pub fn format(args: Fmt, config: Config) -> Result<()> {
43 let target = match args.path.as_deref() {
44 None => PathTarget::Workspace(Box::new(Workspace::current_or_err()?)),
45 Some(path) => classify_path(path)?,
46 };
47 match target {
48 PathTarget::Workspace(workspace) => {
49 if let Some(package) = &args.package {
50 let project = workspace.select_member(package)?;
51 format_project(&args, &workspace, project, &config)?;
52 } else {
53 for project in workspace.members() {
54 format_project(&args, &workspace, project, &config)?;
55 }
56 }
57 }
58 PathTarget::File(file) => {
59 ensure_no_package(&args)?;
60 let root = file
61 .parent()
62 .unwrap_or_else(|| Path::new("."))
63 .to_path_buf();
64 format_loose(std::iter::once(file), &root, &args.backend, &config)?;
65 }
66 PathTarget::Directory(dir) => {
67 ensure_no_package(&args)?;
68 let files = WalkDir::new(&dir)
69 .into_iter()
70 .filter_map(Result::ok)
71 .filter(|entry| entry.file_type().is_file())
72 .map(|entry| entry.into_path())
73 .filter(|path| is_lua_source(path));
74 format_loose(files, &dir, &args.backend, &config)?;
75 }
76 }
77 Ok(())
78}
79
80struct FmtConfig {
81 stylua: stylua_lib::Config,
82 luafmt: luafmt::LuaFormatConfig,
83 luafmt_syntax_level: Option<luafmt::LuaSyntaxLevel>,
84 editorconfig: PathBuf,
85 lua_version: Option<LuaVersion>,
86}
87
88impl FmtConfig {
89 fn resolve(root: &Path, lua_version: Option<LuaVersion>) -> Self {
90 let stylua: stylua_lib::Config = std::fs::read_to_string(root.join("stylua.toml"))
91 .or_else(|_| std::fs::read_to_string(root.join(".stylua.toml")))
92 .map(|config: String| toml::from_str(&config).unwrap_or_default())
93 .or_else(|_| {
94 stylua_lib::editorconfig::parse(stylua_lib::Config::new(), &root.join("*.lua"))
95 })
96 .unwrap_or_default();
97
98 let luafmt = luafmt::resolve_config_for_path(Some(root), None)
99 .map(|resolved| resolved.config)
100 .unwrap_or_default();
101 let luafmt_syntax_level = match &lua_version {
102 Some(version) => lua_version_to_luafmt_syntax_level(version),
103 None => Some(luafmt.syntax.level),
104 };
105
106 Self {
107 stylua,
108 luafmt,
109 luafmt_syntax_level,
110 editorconfig: root.join(".editorconfig"),
111 lua_version,
112 }
113 }
114
115 fn format(&self, backend: &FmtBackend, path: &Path, code: &str) -> Result<String> {
116 Ok(match backend {
117 FmtBackend::Stylua => stylua_lib::format_code(
118 code,
119 self.stylua,
120 None,
121 stylua_lib::OutputVerification::Full,
122 )
123 .into_diagnostic()
124 .context(format!("error formatting {} with stylua.", path.display()))?,
125 FmtBackend::Luafmt => {
126 let syntax_level = self.luafmt_syntax_level.ok_or_else(|| {
127 miette!(
128 "unsupported Lua version{} for luafmt",
129 self.lua_version
130 .as_ref()
131 .map(|ver| format!(" '{}'", ver))
132 .unwrap_or_default()
133 )
134 })?;
135 luafmt::check_text(code, syntax_level.into(), &self.luafmt).formatted
136 }
137 FmtBackend::EmmyluaCodestyle => {
138 let uri = path.to_slash_lossy().to_string();
139 if self.editorconfig.is_file() {
140 emmylua_codestyle::update_code_style(&uri, &self.editorconfig.to_slash_lossy());
141 }
142 emmylua_codestyle::reformat_code(
143 code,
144 &uri,
145 emmylua_codestyle::FormattingOptions::default(),
146 )
147 }
148 })
149 }
150}
151
152fn format_files(
153 files: impl Iterator<Item = PathBuf>,
154 configs: &FmtConfig,
155 backend: &FmtBackend,
156) -> Result<()> {
157 files.into_iter().try_for_each(|file| {
158 let unformatted_code = std::fs::read_to_string(&file).into_diagnostic()?;
159 let formatted_code = configs.format(backend, &file, &unformatted_code)?;
160 std::fs::write(&file, formatted_code)
161 .into_diagnostic()
162 .context(format!("error writing formatted file {}.", file.display()))
163 })
164}
165
166fn format_project(
167 args: &Fmt,
168 workspace: &Workspace,
169 project: &Project,
170 config: &Config,
171) -> Result<()> {
172 let configs = FmtConfig::resolve(
173 workspace.root().as_ref(),
174 workspace.lua_version(config).ok(),
175 );
176
177 let lua_files = ["src", "lua", "lib", "spec", "test", "tests"]
178 .iter()
179 .flat_map(|dir| WalkDir::new(project.root().join(dir)))
180 .filter_map(Result::ok)
181 .map(walkdir::DirEntry::into_path)
182 .filter(|path| is_lua_source(path));
183
184 let rockspec = project.root().join("extra.rockspec");
185
186 format_files(
187 lua_files.chain(rockspec.exists().then_some(rockspec)),
188 &configs,
189 &args.backend,
190 )
191}
192
193fn is_lua_source(path: &Path) -> bool {
194 path.extension().is_some_and(|ext| {
195 let ext = ext.to_string_lossy();
196 ext == "lua" || ext == "luau" || ext == "rockspec"
197 })
198}
199
200fn ensure_no_package(args: &Fmt) -> Result<()> {
201 if args.package.is_some() {
202 bail!("--package is only valid within a workspace");
203 }
204 Ok(())
205}
206
207fn format_loose(
208 files: impl Iterator<Item = PathBuf>,
209 root: &Path,
210 backend: &FmtBackend,
211 config: &Config,
212) -> Result<()> {
213 let (config_root, lua_version) = match Workspace::from(root)? {
214 Some(workspace) => (
215 workspace.root().as_ref().to_path_buf(),
216 workspace.lua_version(config).ok(),
217 ),
218 None => (root.to_path_buf(), config.lua_version().cloned()),
219 };
220 let configs = FmtConfig::resolve(&config_root, lua_version);
221 format_files(files, &configs, backend)
222}
223
224fn lua_version_to_luafmt_syntax_level(lua_version: &LuaVersion) -> Option<luafmt::LuaSyntaxLevel> {
225 match lua_version {
226 LuaVersion::Lua51 => Some(luafmt::LuaSyntaxLevel::Lua51),
227 LuaVersion::Lua52 => Some(luafmt::LuaSyntaxLevel::Lua52),
228 LuaVersion::Lua53 => Some(luafmt::LuaSyntaxLevel::Lua53),
229 LuaVersion::Lua54 => Some(luafmt::LuaSyntaxLevel::Lua54),
230 LuaVersion::Lua55 => Some(luafmt::LuaSyntaxLevel::Lua55),
231 LuaVersion::LuaJIT | LuaVersion::LuaJIT52 => Some(luafmt::LuaSyntaxLevel::LuaJIT),
232 LuaVersion::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::ConfigBuilder;
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 = ConfigBuilder::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 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 = ConfigBuilder::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 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 = ConfigBuilder::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 assert!(nested.contains("print( 3 + 4 )"));
327 }
328
329 #[test]
330 fn test_format_nonexistent_path_errors() {
331 let config = ConfigBuilder::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 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 = ConfigBuilder::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}