Skip to main content

lux_cli/project/
new.rs

1use lux_lib::package;
2use std::{error::Error, path::PathBuf, str::FromStr};
3
4use clap::Args;
5use inquire::{
6    ui::{RenderConfig, Styled},
7    validator::Validation,
8    Confirm, Select, Text,
9};
10use itertools::Itertools;
11use miette::{miette, IntoDiagnostic, Result};
12use spdx::LicenseId;
13
14use crate::utils::github_metadata::{self, RepoMetadata};
15use lux_lib::{
16    config::Config,
17    project::{Project, PROJECT_TOML},
18};
19
20// TODO:
21// - Automatically detect build type to insert into rockspec by inspecting the current repo.
22//   E.g. if there is a `Cargo.toml` in the project root we can infer the user wants to use the
23//   Rust build backend.
24
25/// The type of directory to create when making the project.
26#[derive(Debug, Clone, clap::ValueEnum)]
27enum SourceDirType {
28    Src,
29    Lua,
30    None,
31}
32
33impl SourceDirType {
34    fn to_path_buf(&self) -> Option<PathBuf> {
35        match self {
36            Self::Src => Some("src".into()),
37            Self::Lua => Some("lua".into()),
38            Self::None => None,
39        }
40    }
41}
42
43#[derive(Args)]
44pub struct NewProject {
45    /// The directory of the project.
46    target: PathBuf,
47
48    /// The project's name.
49    #[arg(long)]
50    name: Option<String>,
51
52    /// The description of the project.
53    #[arg(long)]
54    description: Option<String>,
55
56    /// The license of the project. Generic license names will be inferred.
57    #[arg(long, value_parser = clap_parse_license)]
58    license: Option<LicenseId>,
59
60    /// The maintainer of this project. Does not have to be the code author.
61    #[arg(long)]
62    maintainer: Option<String>,
63
64    /// A comma-separated list of labels to apply to this project.
65    #[arg(long, value_parser = clap_parse_list)]
66    labels: Option<std::vec::Vec<String>>, // Note: full qualified name required, see https://github.com/clap-rs/clap/issues/4626
67
68    /// A version constraint on the required Lua version for this project.
69    /// Examples: ">=5.1", "5.1"
70    #[arg(long, value_parser = clap_parse_version)]
71    lua_versions: Option<package::Req>,
72
73    #[arg(long)]
74    main: Option<SourceDirType>,
75}
76
77struct NewProjectValidated {
78    target: PathBuf,
79    name: String,
80    description: String,
81    maintainer: String,
82    labels: Vec<String>,
83    lua_versions: package::Req,
84    main: SourceDirType,
85    license: Option<LicenseId>,
86    source_block: String,
87}
88
89fn clap_parse_license(s: &str) -> std::result::Result<LicenseId, String> {
90    match validate_license(s) {
91        Ok(Validation::Valid) => unsafe { Ok(parse_license_unchecked(s)) },
92        Err(_) | Ok(Validation::Invalid(_)) => {
93            Err(format!("unable to identify license {s}, please try again!"))
94        }
95    }
96}
97
98fn clap_parse_version(input: &str) -> std::result::Result<package::Req, String> {
99    package::Req::from_str(format!("lua {input}").as_str()).map_err(|err| err.to_string())
100}
101
102fn clap_parse_list(input: &str) -> std::result::Result<Vec<String>, String> {
103    if let Some((pos, char)) = input
104        .chars()
105        .find_position(|&c| c != '-' && c != '_' && c != ',' && c.is_ascii_punctuation())
106    {
107        Err(format!(
108            r#"Unexpected punctuation '{char}' found at column {pos}.
109    Lists are comma separated but names should not contain punctuation!"#
110        ))
111    } else {
112        Ok(input.split(',').map(|str| str.trim().to_string()).collect())
113    }
114}
115
116fn parse_license(input: &str) -> Option<LicenseId> {
117    spdx::license_id(input).or_else(|| spdx::imprecise_license_id(input).map(|li| li.0))
118}
119
120/// Parses a license.
121///
122/// # Security
123///
124/// WARNING: This should only be invoked after validating the license with [`validate_license`].
125unsafe fn parse_license_unchecked(input: &str) -> LicenseId {
126    parse_license(input).unwrap_unchecked()
127}
128
129fn validate_license(input: &str) -> std::result::Result<Validation, Box<dyn Error + Send + Sync>> {
130    if input == "none" {
131        return Ok(Validation::Valid);
132    }
133
134    Ok(
135        match parse_license(input).ok_or(format!(
136            r#"Unable to identify SPDX license '{input}', please try again!
137Supported SPDX license IDs are:
138{}
139            "#,
140            spdx::identifiers::LICENSES
141                .iter()
142                .map(|license| license.name)
143                .join(", ")
144        )) {
145            Ok(_) => Validation::Valid,
146            Err(err) => Validation::Invalid(err.into()),
147        },
148    )
149}
150
151pub async fn write_project_rockspec(cli_flags: NewProject, config: Config) -> Result<()> {
152    let project = Project::from_exact(cli_flags.target.clone())?;
153    let render_config = RenderConfig::default_colored()
154        .with_prompt_prefix(Styled::new(">").with_fg(inquire::ui::Color::LightGreen));
155
156    // If the project already exists then ask for override confirmation
157    if project.is_some() && (config.no_prompt() || !overwrite_prompt_confirmed(render_config)?) {
158        return Err(miette!("cancelled creation of project (already exists)"));
159    };
160
161    let validated = match cli_flags {
162        // If all parameters are provided then don't bother prompting the user
163        NewProject {
164            description: Some(description),
165            main: Some(main),
166            labels: Some(labels),
167            lua_versions: Some(lua_versions),
168            maintainer: Some(maintainer),
169            name: Some(name),
170            license,
171            target,
172        } => Ok::<_, miette::Report>(NewProjectValidated {
173            description,
174            labels,
175            license,
176            lua_versions,
177            main,
178            maintainer,
179            name,
180            target,
181            source_block: "# [source]\n# When publishing, configure the source URL here"
182                .to_string(),
183        }),
184
185        NewProject {
186            description,
187            labels,
188            license,
189            lua_versions,
190            main,
191            maintainer,
192            name,
193            target,
194        } => {
195            eprintln!("Fetching remote repository metadata...");
196            let (repo_metadata, is_github_repo) =
197                match github_metadata::get_metadata_for(Some(&target), &config).await {
198                    Ok(Some(value)) => Ok((value, true)),
199                    Ok(None) => RepoMetadata::default(&target).map(|m| (m, false)),
200                    Err(_) => {
201                        tracing::info!(
202                            "Could not fetch remote repo metadata, defaulting to empty values."
203                        );
204
205                        RepoMetadata::default(&target).map(|m| (m, false))
206                    }
207                }
208                .into_diagnostic()?;
209
210            eprintln!("✔ Fetched remote repository metadata.");
211
212            let package_name = name
213                .map_or_else(
214                    || {
215                        Text::new("Package name:")
216                            .with_default(&repo_metadata.name)
217                            .with_help_message(
218                                "A folder with the same name will be created for you.",
219                            )
220                            .with_render_config(render_config)
221                            .prompt()
222                    },
223                    Ok,
224                )
225                .into_diagnostic()?;
226
227            let description = description
228                .map_or_else(
229                    || {
230                        Text::new("Description:")
231                            .with_default(&repo_metadata.description.unwrap_or_default())
232                            .with_render_config(render_config)
233                            .prompt()
234                    },
235                    Ok,
236                )
237                .into_diagnostic()?;
238
239            let license = license.map_or_else(
240                || {
241                    Ok::<_, miette::Report>(
242                        match Text::new("License:")
243                            .with_default(&repo_metadata.license.unwrap_or("none".into()))
244                            .with_help_message("Type 'none' for no license")
245                            .with_validator(validate_license)
246                            .with_render_config(render_config)
247                            .prompt()
248                            .into_diagnostic()?
249                            .as_str()
250                        {
251                            "none" => None,
252                            license => unsafe { Some(parse_license_unchecked(license)) },
253                        },
254                    )
255                },
256                |license| Ok(Some(license)),
257            )?;
258
259            let labels = labels.or(repo_metadata.labels).map_or_else(
260                || {
261                    Ok::<_, miette::Report>(
262                        Text::new("Labels:")
263                            .with_placeholder("web,filesystem")
264                            .with_help_message("Labels are comma separated")
265                            .prompt()
266                            .into_diagnostic()?
267                            .split(',')
268                            .map(|label| label.trim().to_string())
269                            .collect_vec(),
270                    )
271                },
272                Ok,
273            )?;
274
275            let maintainer = maintainer
276                .map_or_else(
277                    || {
278                        let prompt = Text::new("Maintainer:");
279                        if let Some(default_maintainer) = repo_metadata
280                            .contributors
281                            .first()
282                            .cloned()
283                            .or_else(|| whoami::realname().ok())
284                        {
285                            prompt.with_default(&default_maintainer).prompt()
286                        } else {
287                            prompt.prompt()
288                        }
289                    },
290                    Ok,
291                )
292                .into_diagnostic()?;
293
294            let lua_versions = lua_versions.map_or_else(
295                || {
296                    Ok::<_, miette::Report>(
297                        format!(
298                            "lua >= {}",
299                            Select::new(
300                                "What is the lowest Lua version you support?",
301                                vec!["5.1", "5.2", "5.3", "5.4", "5.5"]
302                            )
303                            .without_filtering()
304                            .with_vim_mode(true)
305                            .with_help_message(
306                                "This is equivalent to the 'lua >= {version}' constraint."
307                            )
308                            .prompt()
309                            .into_diagnostic()?
310                        )
311                        .parse()?,
312                    )
313                },
314                Ok,
315            )?;
316
317            let mut source_block =
318                "# [source]\n# When publishing, configure the source URL here".to_string();
319
320            if is_github_repo {
321                let generated_url = format!(
322                    "https://github.com/{}/{}/archive/refs/tags/$(REF).zip",
323                    maintainer, package_name
324                );
325
326                if url::Url::parse(&generated_url).is_ok_and(|url| url.as_str() == generated_url) {
327                    source_block = format!("[source]\nurl = \"{generated_url}\"");
328                }
329            }
330
331            Ok(NewProjectValidated {
332                target,
333                name: package_name,
334                description,
335                labels,
336                license,
337                lua_versions,
338                maintainer,
339                main: main.unwrap_or(SourceDirType::Src),
340                source_block,
341            })
342        }
343    }?;
344
345    let _ = std::fs::create_dir_all(&validated.target).into_diagnostic();
346
347    let rocks_path = validated.target.join(PROJECT_TOML);
348
349    std::fs::write(
350        &rocks_path,
351        format!(
352            r#"
353package = "{package_name}"
354version = "0.1.0"
355lua = "{lua_version_req}"
356
357[description]
358summary = "{summary}"
359maintainer = "{maintainer}"
360labels = [ {labels} ]
361{license}
362
363{source}
364
365[dependencies]
366# Add your dependencies here
367# `busted = ">=2.0"`
368
369{run}
370
371[build]
372type = "builtin"
373    "#,
374            package_name = validated.name,
375            summary = validated.description,
376            license = validated
377                .license
378                .map(|license| format!(r#"license = "{}""#, license.name))
379                .unwrap_or_default(),
380            maintainer = validated.maintainer,
381            labels = validated
382                .labels
383                .into_iter()
384                .map(|label| "\"".to_string() + &label + "\"")
385                .join(", "),
386            lua_version_req = validated.lua_versions.version_req(),
387            run = validated
388                .main
389                .to_path_buf()
390                .map(|main| format!("[run]\nargs = [ \"{}/main.lua\" ]", main.display()))
391                .unwrap_or_default(),
392            source = validated.source_block,
393        )
394        .trim(),
395    )
396    .into_diagnostic()?;
397
398    if let Some(main_dir) = validated
399        .main
400        .to_path_buf()
401        .map(|path| validated.target.join(path))
402    {
403        if main_dir.exists() {
404            tracing::info!(
405                "Directory `{}/` already exists - we won't make any changes to it.",
406                main_dir.display()
407            );
408        } else {
409            std::fs::create_dir(&main_dir).into_diagnostic()?;
410            std::fs::write(main_dir.join("main.lua"), r#"print("Hello world!")"#)
411                .into_diagnostic()?;
412        }
413    }
414
415    println!("All done!");
416
417    Ok(())
418}
419
420fn overwrite_prompt_confirmed<'a>(render_config: RenderConfig<'a>) -> Result<bool> {
421    Confirm::new("Target directory already has a project, write anyway?")
422        .with_default(false)
423        .with_help_message(&format!("This may overwrite your existing {PROJECT_TOML}",))
424        .with_render_config(render_config)
425        .prompt()
426        .into_diagnostic()
427}
428
429#[cfg(test)]
430mod test {
431    use super::*;
432
433    #[test]
434    fn test_parse_license() {
435        // non-regression for #1612
436        assert!(parse_license("EUPL-1.2").is_some());
437        assert!(parse_license("agplv3").is_some());
438    }
439}
440
441// TODO(vhyrro): Add more tests