diff --git a/src/args.rs b/src/args.rs index 41980e8..687c23a 100644 --- a/src/args.rs +++ b/src/args.rs @@ -40,6 +40,10 @@ pub enum Command { /// Executes the given version specific node executable #[command()] Exec(ExecArgs), + + /// Initializes nenv directories and installs a default node version + #[command()] + Init, } #[derive(Clone, Debug, Parser)] diff --git a/src/main.rs b/src/main.rs index 2042d4c..634cd33 100644 --- a/src/main.rs +++ b/src/main.rs @@ -46,6 +46,7 @@ async fn main() -> Result<()> { } args::Command::Refresh => nenv.refresh().await, args::Command::ListVersions => nenv.list_versions().await, + args::Command::Init => nenv.init_nenv().await, _ => xkcd_unreachable!(), }?; diff --git a/src/nenv.rs b/src/nenv.rs index 77319cc..88092e8 100644 --- a/src/nenv.rs +++ b/src/nenv.rs @@ -1,8 +1,8 @@ -use std::ffi::OsString; +use std::{ffi::OsString, str::FromStr}; use crate::{ config::ConfigAccess, - consts::VERSION_FILE_PATH, + consts::{BIN_DIR, VERSION_FILE_PATH}, error::VersionError, mapper::Mapper, repository::{NodeVersion, Repository}, @@ -10,6 +10,7 @@ use crate::{ version_detection::{self, VersionDetector}, }; use crossterm::style::Stylize; +use dialoguer::{theme::ColorfulTheme, Input, Select}; use miette::{IntoDiagnostic, Result}; use tokio::fs; @@ -136,6 +137,39 @@ impl Nenv { Ok(()) } + /// Initializes nenv and prompts for a default version. + pub async fn init_nenv(&self) -> Result<()> { + let items = vec!["latest", "lts", "custom"]; + let selection = Select::with_theme(&ColorfulTheme::default()) + .with_prompt("Select a default node version") + .items(&items) + .default(0) + .interact() + .into_diagnostic()?; + + let version = if items[selection] == "custom" { + let version_string: String = Input::with_theme(&ColorfulTheme::default()) + .with_prompt("Enter a version number: ") + .interact_text() + .into_diagnostic()?; + NodeVersion::from_str(&version_string).unwrap() + } else { + NodeVersion::from_str(items[selection]).unwrap() + }; + + self.repo.install_version(&version).await?; + + println!("{}", "Initialized!".green()); + println!( + "{}\n {}\n{}", + "Make sure to add".bold(), + BIN_DIR.to_string_lossy().yellow(), + "to your PATH environment variables.".bold() + ); + + Ok(()) + } + /// Persits all changes made that aren't written to the disk yet #[tracing::instrument(level = "debug", skip(self))] pub async fn persist(&self) -> Result<()> {