Skip to main content

lux_cli/project/
new.rs

1use std::{error::Error, fmt::Display, path::PathBuf, str::FromStr};
2
3use clap::Args;
4use eyre::{eyre, Result};
5use inquire::{
6    ui::{RenderConfig, Styled},
7    validator::Validation,
8    Confirm, Select, Text,
9};
10use itertools::Itertools;
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        || !Confirm::new("Target directory already has a project, write anyway?")
157            .with_default(false)
158            .with_help_message(&format!("This may overwrite your existing {PROJECT_TOML}",))
159            .with_render_config(render_config)
160            .prompt()?
161    {
162        return Err(eyre!("cancelled creation of project (already exists)"));
163    };
164
165    let validated = match cli_flags {
166        // If all parameters are provided then don't bother prompting the user
167        NewProject {
168            description: Some(description),
169            main: Some(main),
170            labels: Some(labels),
171            lua_versions: Some(lua_versions),
172            maintainer: Some(maintainer),
173            name: Some(name),
174            license,
175            target,
176        } => Ok::<_, eyre::Report>(NewProjectValidated {
177            description,
178            labels,
179            license,
180            lua_versions,
181            main,
182            maintainer,
183            name,
184            target,
185        }),
186
187        NewProject {
188            description,
189            labels,
190            license,
191            lua_versions,
192            main,
193            maintainer,
194            name,
195            target,
196        } => {
197            let mut spinner = Spinner::new(
198                Spinners::Dots,
199                "Fetching remote repository metadata... ".into(),
200            );
201
202            let repo_metadata = match github_metadata::get_metadata_for(Some(&target)).await {
203                Ok(value) => value.map_or_else(|| RepoMetadata::default(&target), Ok),
204                Err(_) => {
205                    println!("Could not fetch remote repo metadata, defaulting to empty values.");
206
207                    RepoMetadata::default(&target)
208                }
209            }?;
210
211            spinner.stop_and_persist("✔", "Fetched remote repository metadata.".into());
212
213            let package_name = name.map_or_else(
214                || {
215                    Text::new("Package name:")
216                        .with_default(&repo_metadata.name)
217                        .with_help_message("A folder with the same name will be created for you.")
218                        .with_render_config(render_config)
219                        .prompt()
220                },
221                Ok,
222            )?;
223
224            let description = description.map_or_else(
225                || {
226                    Text::new("Description:")
227                        .with_default(&repo_metadata.description.unwrap_or_default())
228                        .with_render_config(render_config)
229                        .prompt()
230                },
231                Ok,
232            )?;
233
234            let license = license.map_or_else(
235                || {
236                    Ok::<_, eyre::Error>(
237                        match Text::new("License:")
238                            .with_default(&repo_metadata.license.unwrap_or("none".into()))
239                            .with_help_message("Type 'none' for no license")
240                            .with_validator(validate_license)
241                            .with_render_config(render_config)
242                            .prompt()?
243                            .as_str()
244                        {
245                            "none" => None,
246                            license => unsafe { Some(parse_license_unchecked(license)) },
247                        },
248                    )
249                },
250                |license| Ok(Some(license)),
251            )?;
252
253            let labels = labels.or(repo_metadata.labels).map_or_else(
254                || {
255                    Ok::<_, eyre::Error>(
256                        Text::new("Labels:")
257                            .with_placeholder("web,filesystem")
258                            .with_help_message("Labels are comma separated")
259                            .prompt()?
260                            .split(',')
261                            .map(|label| label.trim().to_string())
262                            .collect_vec(),
263                    )
264                },
265                Ok,
266            )?;
267
268            let maintainer = maintainer.map_or_else(
269                || {
270                    let prompt = Text::new("Maintainer:");
271                    if let Some(default_maintainer) = repo_metadata
272                        .contributors
273                        .first()
274                        .cloned()
275                        .or_else(|| whoami::realname().ok())
276                    {
277                        prompt.with_default(&default_maintainer).prompt()
278                    } else {
279                        prompt.prompt()
280                    }
281                },
282                Ok,
283            )?;
284
285            let lua_versions = lua_versions.map_or_else(
286                || {
287                    Ok::<_, eyre::Report>(
288                        format!(
289                            "lua >= {}",
290                            Select::new(
291                                "What is the lowest Lua version you support?",
292                                vec!["5.1", "5.2", "5.3", "5.4", "5.5"]
293                            )
294                            .without_filtering()
295                            .with_vim_mode(true)
296                            .with_help_message(
297                                "This is equivalent to the 'lua >= {version}' constraint."
298                            )
299                            .prompt()?
300                        )
301                        .parse()?,
302                    )
303                },
304                Ok,
305            )?;
306
307            Ok(NewProjectValidated {
308                target,
309                name: package_name,
310                description,
311                labels,
312                license,
313                lua_versions,
314                maintainer,
315                main: main.unwrap_or(SourceDirType::Src),
316            })
317        }
318    }?;
319
320    let _ = std::fs::create_dir_all(&validated.target);
321
322    let rocks_path = validated.target.join(PROJECT_TOML);
323
324    std::fs::write(
325        &rocks_path,
326        format!(
327            r#"
328package = "{package_name}"
329version = "0.1.0"
330lua = "{lua_version_req}"
331
332[description]
333summary = "{summary}"
334maintainer = "{maintainer}"
335labels = [ {labels} ]
336{license}
337
338[dependencies]
339# Add your dependencies here
340# `busted = ">=2.0"`
341
342[run]
343args = [ "{main}/main.lua" ]
344
345[build]
346type = "builtin"
347    "#,
348            package_name = validated.name,
349            summary = validated.description,
350            license = validated
351                .license
352                .map(|license| format!(r#"license = "{}""#, license.name))
353                .unwrap_or_default(),
354            maintainer = validated.maintainer,
355            labels = validated
356                .labels
357                .into_iter()
358                .map(|label| "\"".to_string() + &label + "\"")
359                .join(", "),
360            lua_version_req = validated.lua_versions.version_req(),
361            main = validated.main,
362        )
363        .trim(),
364    )?;
365
366    let main_dir = validated.target.join(validated.main.to_string());
367    if main_dir.exists() {
368        eprintln!(
369            "Directory `{}/` already exists - we won't make any changes to it.",
370            main_dir.display()
371        );
372    } else {
373        std::fs::create_dir(&main_dir)?;
374        std::fs::write(main_dir.join("main.lua"), r#"print("Hello world!")"#)?;
375    }
376
377    println!("All done!");
378
379    Ok(())
380}
381
382#[cfg(test)]
383mod test {
384    use super::*;
385
386    #[test]
387    fn test_parse_license() {
388        // non-regression for #1612
389        assert!(parse_license("EUPL-1.2").is_some());
390        assert!(parse_license("agplv3").is_some());
391    }
392}
393
394// TODO(vhyrro): Add more tests