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    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}
85
86fn clap_parse_license(s: &str) -> std::result::Result<LicenseId, String> {
87    match validate_license(s) {
88        Ok(Validation::Valid) => Ok(parse_license_unchecked(s)),
89        Err(_) | Ok(Validation::Invalid(_)) => {
90            Err(format!("unable to identify license {s}, please try again!"))
91        }
92    }
93}
94
95fn clap_parse_version(input: &str) -> std::result::Result<PackageReq, String> {
96    PackageReq::from_str(format!("lua {}", input).as_str()).map_err(|err| err.to_string())
97}
98
99fn clap_parse_list(input: &str) -> std::result::Result<Vec<String>, String> {
100    if let Some((pos, char)) = input
101        .chars()
102        .find_position(|&c| c != '-' && c != '_' && c != ',' && c.is_ascii_punctuation())
103    {
104        Err(format!("Unexpected punctuation '{}' found at column {}. Lists are comma separated but names should not contain punctuation!", char, pos))
105    } else {
106        Ok(input.split(',').map(|str| str.trim().to_string()).collect())
107    }
108}
109
110/// Parses a license and panics upon failure.
111///
112/// # Security
113///
114/// This should only be invoked after validating the license with [`validate_license`].
115fn parse_license_unchecked(input: &str) -> LicenseId {
116    spdx::imprecise_license_id(input).unwrap().0
117}
118
119fn validate_license(input: &str) -> std::result::Result<Validation, Box<dyn Error + Send + Sync>> {
120    if input == "none" {
121        return Ok(Validation::Valid);
122    }
123
124    Ok(
125        match spdx::imprecise_license_id(input).ok_or(format!(
126            "Unable to identify license '{}', please try again!",
127            input
128        )) {
129            Ok(_) => Validation::Valid,
130            Err(err) => Validation::Invalid(err.into()),
131        },
132    )
133}
134
135pub async fn write_project_rockspec(cli_flags: NewProject) -> Result<()> {
136    let project = Project::from_exact(cli_flags.target.clone())?;
137    let render_config = RenderConfig::default_colored()
138        .with_prompt_prefix(Styled::new(">").with_fg(inquire::ui::Color::LightGreen));
139
140    // If the project already exists then ask for override confirmation
141    if project.is_some()
142        && !Confirm::new("Target directory already has a project, write anyway?")
143            .with_default(false)
144            .with_help_message(&format!(
145                "This may overwrite your existing {}",
146                PROJECT_TOML
147            ))
148            .with_render_config(render_config)
149            .prompt()?
150    {
151        return Err(eyre!("cancelled creation of project (already exists)"));
152    };
153
154    let validated = match cli_flags {
155        // If all parameters are provided then don't bother prompting the user
156        NewProject {
157            description: Some(description),
158            main: Some(main),
159            labels: Some(labels),
160            lua_versions: Some(lua_versions),
161            maintainer: Some(maintainer),
162            name: Some(name),
163            license,
164            target,
165        } => Ok::<_, eyre::Report>(NewProjectValidated {
166            description,
167            labels,
168            license,
169            lua_versions,
170            main,
171            maintainer,
172            name,
173            target,
174        }),
175
176        NewProject {
177            description,
178            labels,
179            license,
180            lua_versions,
181            main,
182            maintainer,
183            name,
184            target,
185        } => {
186            let mut spinner = Spinner::new(
187                Spinners::Dots,
188                "Fetching remote repository metadata... ".into(),
189            );
190
191            let repo_metadata = match github_metadata::get_metadata_for(Some(&target)).await {
192                Ok(value) => value.map_or_else(|| RepoMetadata::default(&target), Ok),
193                Err(_) => {
194                    println!("Could not fetch remote repo metadata, defaulting to empty values.");
195
196                    RepoMetadata::default(&target)
197                }
198            }?;
199
200            spinner.stop_and_persist("✔", "Fetched remote repository metadata.".into());
201
202            let package_name = name.map_or_else(
203                || {
204                    Text::new("Package name:")
205                        .with_default(&repo_metadata.name)
206                        .with_help_message("A folder with the same name will be created for you.")
207                        .with_render_config(render_config)
208                        .prompt()
209                },
210                Ok,
211            )?;
212
213            let description = description.map_or_else(
214                || {
215                    Text::new("Description:")
216                        .with_default(&repo_metadata.description.unwrap_or_default())
217                        .with_render_config(render_config)
218                        .prompt()
219                },
220                Ok,
221            )?;
222
223            let license = license.map_or_else(
224                || {
225                    Ok::<_, eyre::Error>(
226                        match Text::new("License:")
227                            .with_default(&repo_metadata.license.unwrap_or("none".into()))
228                            .with_help_message("Type 'none' for no license")
229                            .with_validator(validate_license)
230                            .with_render_config(render_config)
231                            .prompt()?
232                            .as_str()
233                        {
234                            "none" => None,
235                            license => Some(parse_license_unchecked(license)),
236                        },
237                    )
238                },
239                |license| Ok(Some(license)),
240            )?;
241
242            let labels = labels.or(repo_metadata.labels).map_or_else(
243                || {
244                    Ok::<_, eyre::Error>(
245                        Text::new("Labels:")
246                            .with_placeholder("web,filesystem")
247                            .with_help_message("Labels are comma separated")
248                            .prompt()?
249                            .split(',')
250                            .map(|label| label.trim().to_string())
251                            .collect_vec(),
252                    )
253                },
254                Ok,
255            )?;
256
257            let maintainer = maintainer.map_or_else(
258                || {
259                    let default_maintainer = repo_metadata
260                        .contributors
261                        .first()
262                        .cloned()
263                        .unwrap_or_else(whoami::realname);
264                    Text::new("Maintainer:")
265                        .with_default(&default_maintainer)
266                        .prompt()
267                },
268                Ok,
269            )?;
270
271            let lua_versions = lua_versions.map_or_else(
272                || {
273                    Ok::<_, eyre::Report>(
274                        format!(
275                            "lua >= {}",
276                            Select::new(
277                                "What is the lowest Lua version you support?",
278                                vec!["5.1", "5.2", "5.3", "5.4"]
279                            )
280                            .without_filtering()
281                            .with_vim_mode(true)
282                            .with_help_message(
283                                "This is equivalent to the 'lua >= {version}' constraint."
284                            )
285                            .prompt()?
286                        )
287                        .parse()?,
288                    )
289                },
290                Ok,
291            )?;
292
293            Ok(NewProjectValidated {
294                target,
295                name: package_name,
296                description,
297                labels,
298                license,
299                lua_versions,
300                maintainer,
301                main: main.unwrap_or(SourceDirType::Src),
302            })
303        }
304    }?;
305
306    let _ = std::fs::create_dir_all(&validated.target);
307
308    let rocks_path = validated.target.join(PROJECT_TOML);
309
310    std::fs::write(
311        &rocks_path,
312        format!(
313            r#"
314package = "{package_name}"
315version = "0.1.0"
316lua = "{lua_version_req}"
317
318[description]
319summary = "{summary}"
320maintainer = "{maintainer}"
321labels = [ {labels} ]
322{license}
323
324[dependencies]
325# Add your dependencies here
326# `busted = ">=2.0"`
327
328[run]
329args = [ "{main}/main.lua" ]
330
331[build]
332type = "builtin"
333    "#,
334            package_name = validated.name,
335            summary = validated.description,
336            license = validated
337                .license
338                .map(|license| format!(r#"license = "{}""#, license.name))
339                .unwrap_or_default(),
340            maintainer = validated.maintainer,
341            labels = validated
342                .labels
343                .into_iter()
344                .map(|label| "\"".to_string() + &label + "\"")
345                .join(", "),
346            lua_version_req = validated.lua_versions.version_req(),
347            main = validated.main,
348        )
349        .trim(),
350    )?;
351
352    let main_dir = validated.target.join(validated.main.to_string());
353    if main_dir.exists() {
354        eprintln!(
355            "Directory `{}/` already exists - we won't make any changes to it.",
356            main_dir.display()
357        );
358    } else {
359        std::fs::create_dir(&main_dir)?;
360        std::fs::write(main_dir.join("main.lua"), r#"print("Hello world!")"#)?;
361    }
362
363    println!("All done!");
364
365    Ok(())
366}
367
368// TODO(vhyrro): Add tests