1use std::path::PathBuf;
2
3use eyre::{OptionExt, Result};
4use lux_lib::project::Project;
5use stylua_lib::Config;
6use walkdir::WalkDir;
7
8pub fn format() -> Result<()> {
10 let project = Project::current()?.ok_or_eyre(
11 "`lx fmt` can only be executed in a lux project! Run `lx new` to create one.",
12 )?;
13
14 let config: Config = std::fs::read_to_string("stylua.toml")
15 .or_else(|_| std::fs::read_to_string(".stylua.toml"))
16 .map(|config: String| toml::from_str(&config).unwrap_or_default())
17 .unwrap_or_default();
18
19 WalkDir::new(project.root().join("src"))
20 .into_iter()
21 .chain(WalkDir::new(project.root().join("lua")))
22 .chain(WalkDir::new(project.root().join("lib")))
23 .try_for_each(|file| {
24 if let Ok(file) = file {
25 if PathBuf::from(file.file_name())
26 .extension()
27 .is_some_and(|ext| ext == "lua")
28 {
29 let formatted_code = stylua_lib::format_code(
30 &std::fs::read_to_string(file.path())?,
31 config,
32 None,
33 stylua_lib::OutputVerification::Full,
34 )?;
35
36 std::fs::write(file.into_path(), formatted_code)?;
37 };
38 }
39 Ok::<_, eyre::Report>(())
40 })?;
41
42 let rockspec = project.root().join("extra.rockspec");
45
46 if rockspec.exists() {
47 let formatted_code = stylua_lib::format_code(
48 &std::fs::read_to_string(&rockspec)?,
49 config,
50 None,
51 stylua_lib::OutputVerification::Full,
52 )?;
53
54 std::fs::write(rockspec, formatted_code)?;
55 }
56
57 Ok(())
58}