Skip to main content

lux_cli/
check.rs

1use std::path::{Path, PathBuf};
2
3use clap::Args;
4use emmylua_check::OutputDestination;
5use itertools::Itertools;
6use lux_lib::{config::Config, workspace::Workspace};
7
8use miette::{miette, Result};
9
10use crate::{
11    args::OutputFormat,
12    utils::path::{classify_path, PathTarget},
13    workspace::sync_dependencies_if_locked,
14};
15
16#[derive(Args)]
17pub struct Check {
18    /// Path to a workspace, directory, or Lua file to check. Defaults to the current workspace.
19    #[arg(long)]
20    path: Option<PathBuf>,
21    /// Comma-separated list of ignore patterns.
22    /// Patterns must follow glob syntax.
23    /// Lux will automatically add top-level ignored project files.
24    #[arg(short, long, value_delimiter = ',')]
25    ignore: Option<Vec<String>>,
26
27    /// The output format.
28    #[arg(long, default_value = "text", value_enum, ignore_case = true)]
29    output_format: OutputFormat,
30
31    /// Output destination.{n}
32    /// (stdout or a file path, only used when the output format is json).
33    #[arg(long, default_value = "stdout")]
34    output: OutputDestination,
35
36    /// Treat warnings as errors.
37    #[arg(long)]
38    warnings_as_errors: bool,
39}
40
41impl From<OutputFormat> for emmylua_check::OutputFormat {
42    fn from(value: OutputFormat) -> Self {
43        match value {
44            OutputFormat::Json => emmylua_check::OutputFormat::Json,
45            OutputFormat::Text => emmylua_check::OutputFormat::Text,
46        }
47    }
48}
49
50pub async fn check(args: Check, config: Config) -> Result<()> {
51    let target = match args.path.as_deref() {
52        None => PathTarget::Workspace(Box::new(Workspace::current_or_err()?)),
53        Some(path) => classify_path(path)?,
54    };
55
56    let (workspace_dirs, rc_files) = match target {
57        PathTarget::Workspace(workspace) => {
58            sync_dependencies_if_locked(&workspace, &config).await?;
59
60            let dirs = workspace
61                .members()
62                .iter()
63                .map(|project| project.root())
64                .flat_map(|project_root| {
65                    vec![
66                        project_root.join("src"),
67                        project_root.join("lua"),
68                        // For now, we don't include tests
69                        // because they require LLS_Addons definitions for busted
70
71                        // project_root.join("test"),
72                        // project_root.join("tests"),
73                        // project_root.join("spec"),
74                    ]
75                })
76                .filter(|dir| dir.is_dir())
77                .collect_vec();
78
79            let luarc_path = workspace.luarc_path(&config);
80
81            let rc = if luarc_path.is_file() {
82                Some(vec![luarc_path])
83            } else {
84                None
85            };
86
87            (dirs, rc)
88        }
89        PathTarget::Directory(dir) => {
90            let rc = resolve_rc_files(&dir, &config)?;
91            (vec![dir], rc)
92        }
93        PathTarget::File(file) => {
94            let root = file
95                .parent()
96                .unwrap_or_else(|| Path::new("."))
97                .to_path_buf();
98
99            let rc = resolve_rc_files(&root, &config)?;
100            (vec![root], rc)
101        }
102    };
103
104    if workspace_dirs.is_empty() {
105        println!("Nothing to check!");
106        return Ok(());
107    }
108
109    let emmylua_check_args = emmylua_check::CmdArgs {
110        config: rc_files,
111        workspace: workspace_dirs,
112        ignore: args.ignore,
113        output_format: args.output_format.into(),
114        output: args.output,
115        warnings_as_errors: args.warnings_as_errors,
116        verbose: config.verbose(),
117    };
118
119    emmylua_check::run_check(emmylua_check_args)
120        .await
121        .map_err(|err| miette!("{err}"))?;
122    Ok(())
123}
124
125fn resolve_rc_files(root: &Path, config: &Config) -> Result<Option<Vec<PathBuf>>> {
126    let rc_path = match Workspace::from(root)? {
127        Some(workspace) => workspace.luarc_path(config),
128        None => root.join(".luarc.json"),
129    };
130
131    if rc_path.is_file() {
132        Ok(Some(vec![rc_path]))
133    } else {
134        Ok(None)
135    }
136}