From 2299a02196d754b0ece072c3d9f2776ce63f721a Mon Sep 17 00:00:00 2001 From: Gal Schlezinger Date: Thu, 17 Nov 2022 17:52:40 +0200 Subject: [PATCH] infer version from current system state for shim --- src/current_version.rs | 41 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/src/current_version.rs b/src/current_version.rs index 8dbf846..eb122e6 100644 --- a/src/current_version.rs +++ b/src/current_version.rs @@ -1,12 +1,43 @@ +use std::path::Path; + use thiserror::Error; use crate::config::FnmConfig; -use crate::system_version; use crate::version::Version; +use crate::{default_version, installed_versions, system_version, version_files}; pub fn current_version(config: &FnmConfig) -> Result, Error> { - let multishell_path = config.multishell_path().ok_or(Error::EnvNotApplied)?; + match config.multishell_path() { + None => infer_current_version(config), + Some(multishell_path) => current_version_from_multishell(config, multishell_path), + } +} + +/// infer the current version from the system state, +/// by looking at the installed versions, the current working +/// directory and the default version +fn infer_current_version(config: &FnmConfig) -> Result, Error> { + let current_directory = + std::env::current_dir().map_err(|err| Error::CantAccessCurrentDirectory { source: err })?; + + if let Some(version) = version_files::get_user_version_for_directory(current_directory, config) + { + let all_versions = installed_versions::list(config.installations_dir()) + .map_err(|source| Error::VersionListingError { source })?; + return Ok(version.to_version(&all_versions, config).cloned()); + } + + if let Some(version) = default_version::find_default_version(config) { + return Ok(Some(version)); + } + + return Ok(None); +} +fn current_version_from_multishell( + _config: &FnmConfig, + multishell_path: &Path, +) -> Result, Error> { if multishell_path.read_link().ok() == Some(system_version::path()) { return Ok(Some(Version::Bypassed)); } @@ -32,11 +63,13 @@ pub fn current_version(config: &FnmConfig) -> Result, Error> { #[derive(Debug, Error)] pub enum Error { - #[error("`fnm env` was not applied in this context.\nCan't find fnm's environment variables")] - EnvNotApplied, #[error("Can't read the version as a valid semver")] VersionError { source: semver::Error, version: String, }, + #[error("Can't access current directory")] + CantAccessCurrentDirectory { source: std::io::Error }, + #[error("Can't list versions")] + VersionListingError { source: installed_versions::Error }, }