Skip to main content

lux_cli/project/
new.rs

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