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;
12use spinners::{Spinner, Spinners};
13
14use crate::utils::github_metadata::{self, RepoMetadata};
15use lux_lib::{
16    config::Config,
17    package::PackageReq,
18    project::{Project, PROJECT_TOML},
19};
20
21// TODO:
22// - Automatically detect build type to insert into rockspec by inspecting the current repo.
23//   E.g. if there is a `Cargo.toml` in the project root we can infer the user wants to use the
24//   Rust build backend.
25
26/// The type of directory to create when making the project.
27#[derive(Debug, Clone, clap::ValueEnum)]
28enum SourceDirType {
29    Src,
30    Lua,
31}
32
33impl Display for SourceDirType {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        match self {
36            Self::Src => write!(f, "src"),
37            Self::Lua => write!(f, "lua"),
38        }
39    }
40}
41
42#[derive(Args)]
43pub struct NewProject {
44    /// The directory of the project.
45    target: PathBuf,
46
47    /// The project's name.
48    #[arg(long)]
49    name: Option<String>,
50
51    /// The description of the project.
52    #[arg(long)]
53    description: Option<String>,
54
55    /// The license of the project. Generic license names will be inferred.
56    #[arg(long, value_parser = clap_parse_license)]
57    license: Option<LicenseId>,
58
59    /// The maintainer of this project. Does not have to be the code author.
60    #[arg(long)]
61    maintainer: Option<String>,
62
63    /// A comma-separated list of labels to apply to this project.
64    #[arg(long, value_parser = clap_parse_list)]
65    labels: Option<std::vec::Vec<String>>, // Note: full qualified name required, see https://github.com/clap-rs/clap/issues/4626
66
67    /// A version constraint on the required Lua version for this project.
68    /// Examples: ">=5.1", "5.1"
69    #[arg(long, value_parser = clap_parse_version)]
70    lua_versions: Option<PackageReq>,
71
72    #[arg(long)]
73    main: Option<SourceDirType>,
74}
75
76struct NewProjectValidated {
77    target: PathBuf,
78    name: String,
79    description: String,
80    maintainer: String,
81    labels: Vec<String>,
82    lua_versions: PackageReq,
83    main: SourceDirType,
84    license: Option<LicenseId>,
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()
156        || project.is_some()
157            && !Confirm::new("Target directory already has a project, write anyway?")
158                .with_default(false)
159                .with_help_message(&format!("This may overwrite your existing {PROJECT_TOML}",))
160                .with_render_config(render_config)
161                .prompt()
162                .into_diagnostic()?
163    {
164        return Err(miette!("cancelled creation of project (already exists)"));
165    };
166
167    let validated = match cli_flags {
168        // If all parameters are provided then don't bother prompting the user
169        NewProject {
170            description: Some(description),
171            main: Some(main),
172            labels: Some(labels),
173            lua_versions: Some(lua_versions),
174            maintainer: Some(maintainer),
175            name: Some(name),
176            license,
177            target,
178        } => Ok::<_, miette::Report>(NewProjectValidated {
179            description,
180            labels,
181            license,
182            lua_versions,
183            main,
184            maintainer,
185            name,
186            target,
187        }),
188
189        NewProject {
190            description,
191            labels,
192            license,
193            lua_versions,
194            main,
195            maintainer,
196            name,
197            target,
198        } => {
199            let mut spinner = Spinner::new(
200                Spinners::Dots,
201                "Fetching remote repository metadata... ".into(),
202            );
203
204            let repo_metadata = match github_metadata::get_metadata_for(Some(&target)).await {
205                Ok(value) => value.map_or_else(|| RepoMetadata::default(&target), Ok),
206                Err(_) => {
207                    println!("Could not fetch remote repo metadata, defaulting to empty values.");
208
209                    RepoMetadata::default(&target)
210                }
211            }
212            .into_diagnostic()?;
213
214            spinner.stop_and_persist("✔", "Fetched remote repository metadata.".into());
215
216            let package_name = name
217                .map_or_else(
218                    || {
219                        Text::new("Package name:")
220                            .with_default(&repo_metadata.name)
221                            .with_help_message(
222                                "A folder with the same name will be created for you.",
223                            )
224                            .with_render_config(render_config)
225                            .prompt()
226                    },
227                    Ok,
228                )
229                .into_diagnostic()?;
230
231            let description = description
232                .map_or_else(
233                    || {
234                        Text::new("Description:")
235                            .with_default(&repo_metadata.description.unwrap_or_default())
236                            .with_render_config(render_config)
237                            .prompt()
238                    },
239                    Ok,
240                )
241                .into_diagnostic()?;
242
243            let license = license.map_or_else(
244                || {
245                    Ok::<_, miette::Report>(
246                        match Text::new("License:")
247                            .with_default(&repo_metadata.license.unwrap_or("none".into()))
248                            .with_help_message("Type 'none' for no license")
249                            .with_validator(validate_license)
250                            .with_render_config(render_config)
251                            .prompt()
252                            .into_diagnostic()?
253                            .as_str()
254                        {
255                            "none" => None,
256                            license => unsafe { Some(parse_license_unchecked(license)) },
257                        },
258                    )
259                },
260                |license| Ok(Some(license)),
261            )?;
262
263            let labels = labels.or(repo_metadata.labels).map_or_else(
264                || {
265                    Ok::<_, miette::Report>(
266                        Text::new("Labels:")
267                            .with_placeholder("web,filesystem")
268                            .with_help_message("Labels are comma separated")
269                            .prompt()
270                            .into_diagnostic()?
271                            .split(',')
272                            .map(|label| label.trim().to_string())
273                            .collect_vec(),
274                    )
275                },
276                Ok,
277            )?;
278
279            let maintainer = maintainer
280                .map_or_else(
281                    || {
282                        let prompt = Text::new("Maintainer:");
283                        if let Some(default_maintainer) = repo_metadata
284                            .contributors
285                            .first()
286                            .cloned()
287                            .or_else(|| whoami::realname().ok())
288                        {
289                            prompt.with_default(&default_maintainer).prompt()
290                        } else {
291                            prompt.prompt()
292                        }
293                    },
294                    Ok,
295                )
296                .into_diagnostic()?;
297
298            let lua_versions = lua_versions.map_or_else(
299                || {
300                    Ok::<_, miette::Report>(
301                        format!(
302                            "lua >= {}",
303                            Select::new(
304                                "What is the lowest Lua version you support?",
305                                vec!["5.1", "5.2", "5.3", "5.4", "5.5"]
306                            )
307                            .without_filtering()
308                            .with_vim_mode(true)
309                            .with_help_message(
310                                "This is equivalent to the 'lua >= {version}' constraint."
311                            )
312                            .prompt()
313                            .into_diagnostic()?
314                        )
315                        .parse()?,
316                    )
317                },
318                Ok,
319            )?;
320
321            Ok(NewProjectValidated {
322                target,
323                name: package_name,
324                description,
325                labels,
326                license,
327                lua_versions,
328                maintainer,
329                main: main.unwrap_or(SourceDirType::Src),
330            })
331        }
332    }?;
333
334    let _ = std::fs::create_dir_all(&validated.target).into_diagnostic();
335
336    let rocks_path = validated.target.join(PROJECT_TOML);
337
338    std::fs::write(
339        &rocks_path,
340        format!(
341            r#"
342package = "{package_name}"
343version = "0.1.0"
344lua = "{lua_version_req}"
345
346[description]
347summary = "{summary}"
348maintainer = "{maintainer}"
349labels = [ {labels} ]
350{license}
351
352[dependencies]
353# Add your dependencies here
354# `busted = ">=2.0"`
355
356[run]
357args = [ "{main}/main.lua" ]
358
359[build]
360type = "builtin"
361    "#,
362            package_name = validated.name,
363            summary = validated.description,
364            license = validated
365                .license
366                .map(|license| format!(r#"license = "{}""#, license.name))
367                .unwrap_or_default(),
368            maintainer = validated.maintainer,
369            labels = validated
370                .labels
371                .into_iter()
372                .map(|label| "\"".to_string() + &label + "\"")
373                .join(", "),
374            lua_version_req = validated.lua_versions.version_req(),
375            main = validated.main,
376        )
377        .trim(),
378    )
379    .into_diagnostic()?;
380
381    let main_dir = validated.target.join(validated.main.to_string());
382    if main_dir.exists() {
383        eprintln!(
384            "Directory `{}/` already exists - we won't make any changes to it.",
385            main_dir.display()
386        );
387    } else {
388        std::fs::create_dir(&main_dir).into_diagnostic()?;
389        std::fs::write(main_dir.join("main.lua"), r#"print("Hello world!")"#).into_diagnostic()?;
390    }
391
392    println!("All done!");
393
394    Ok(())
395}
396
397#[cfg(test)]
398mod test {
399    use super::*;
400
401    #[test]
402    fn test_parse_license() {
403        // non-regression for #1612
404        assert!(parse_license("EUPL-1.2").is_some());
405        assert!(parse_license("agplv3").is_some());
406    }
407}
408
409// TODO(vhyrro): Add more tests