Skip to content

Commit

Permalink
refactor: dirs
Browse files Browse the repository at this point in the history
  • Loading branch information
Yakiyo committed Aug 4, 2023
1 parent eaa0cfe commit 9b22745
Show file tree
Hide file tree
Showing 9 changed files with 43 additions and 181 deletions.
1 change: 0 additions & 1 deletion src/commands/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ impl super::Command for Install {
}
UserVersion::Latest(c) => UserVersion::resolve_latest(&c)?,
};
let dir = &config.root_with_default();

config
.installation_dir()
Expand Down
7 changes: 4 additions & 3 deletions src/commands/list.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
use crate::alias;
use crate::config::Config;
use crate::user_version::list_versions;
use yansi::Paint;

#[derive(clap::Args, Debug, Default)]
pub struct List;

impl super::Command for List {
fn run(self, config: Config) -> anyhow::Result<()> {
let versions = config.base_dir.list_versions()?;
let versions = list_versions(config.installation_dir())?;
if versions.is_empty() {
println!("{}", Paint::yellow("No versions installed"));
return Ok(());
}
let current = config.base_dir.current_version().unwrap_or(None);
let alias_hash = alias::create_alias_hash(&config.base_dir.aliases)?;
let current = config.current_version().unwrap_or(None);
let alias_hash = alias::create_alias_hash(&config.aliases_dir())?;
for version in versions {
let aliases = match alias_hash.get(&version.to_str()) {
None => String::new(),
Expand Down
2 changes: 1 addition & 1 deletion src/commands/unalias.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub struct Unalias {

impl super::Command for Unalias {
fn run(self, config: Config) -> anyhow::Result<()> {
let alias_dir = &config.base_dir.aliases.join(&self.alias);
let alias_dir = &config.aliases_dir().join(&self.alias);
if !alias_dir.exists() {
return Err(anyhow::anyhow!(
"No alias with the name `{}` exists",
Expand Down
9 changes: 4 additions & 5 deletions src/commands/uninstall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,11 @@ impl super::Command for Uninstall {
UserVersion::Latest(_) => anyhow::bail!("Invalid version string. latest-channel is not valid for uninstallation. Provide an alias or full semver."),
_ => {}
}
let dir = &config.base_dir;
let version = self
.version
.to_version(Some(dir))
.to_version(Some(config.aliases_dir()))
.with_context(|| "Unable to resolve version")?;
let p = dir.find_version_dir(&version);
let p = config.installation_dir().join(version.to_string());
if !p.exists() {
return Err(anyhow::anyhow!(
"Version {} is not installed. Use the `ls` command to view all installed versions",
Expand All @@ -37,13 +36,13 @@ impl super::Command for Uninstall {
})?;

// Clean up aliases
let aliases = alias::create_alias_hash(&dir.aliases)
let aliases = alias::create_alias_hash(config.aliases_dir())
.with_context(|| "Failed to fetch aliases")?
.remove(&self.version.to_string())
.unwrap_or(Vec::new());

for alias in aliases {
let alias_dir = dir.find_alias_dir(alias);
let alias_dir = config.aliases_dir().join(alias);
if !alias_dir.exists() {
continue;
}
Expand Down
24 changes: 13 additions & 11 deletions src/commands/use.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use crate::config::Config;
use crate::dirs::DsmDir;
use crate::fs;
use crate::user_version::UserVersion;
use anyhow::Context;
use dart_semver::Version;
use std::path;
use yansi::Paint;

#[derive(clap::Args, Debug, Default)]
Expand All @@ -18,20 +17,23 @@ pub struct Use {

impl super::Command for Use {
fn run(self, config: Config) -> anyhow::Result<()> {
let dirs = &config.base_dir;
let version = self.version.to_version(Some(dirs))?;
let version_path = dirs.find_version_dir(&version);
// let dirs = config.root_with_default();
let version = self.version.to_version(Some(config.installation_dir()))?;
let version_path = config.installation_dir().join(version.to_str());
if !version_path.exists() {
return Err(anyhow::anyhow!("Version {} is not installed. Cannot use it. View all available versions with the `ls` command.", Paint::cyan(&self.version)));
}
let current = dirs.current_version().ok();
let current = config.current_version().ok();
if Some(Some(version)) == current {
if !self.silent_if_unchanged {
println!("{} is already in use", &version);
}
return Ok(());
}
replace_symlink(dirs, &version)?;
replace_symlink(
config.installation_dir().join(version.to_string()),
config.bin_dir(),
)?;
println!(
"Successfully set {} as current version",
Paint::cyan(&self.version)
Expand All @@ -42,12 +44,12 @@ impl super::Command for Use {
}

/// Remove prev symlink if it exists and symlink the target versions bin directory
fn replace_symlink(dirs: &DsmDir, version: &Version) -> anyhow::Result<()> {
let from = dirs.installations.join(version.to_str()).join("bin");
let to = &dirs.bin;
fn replace_symlink(version_dir: path::PathBuf, bin: path::PathBuf) -> anyhow::Result<()> {
let from = version_dir.join("bin");
let to = bin;
if to.exists() {
log::debug!("Removing previous link");
std::fs::remove_dir_all(to).with_context(|| "Failed to remove previous link")?;
std::fs::remove_dir_all(&to).with_context(|| "Failed to remove previous link")?;
}
fs::symlink_dir(from, to).with_context(|| "Failed to hard link executable.")?;
Ok(())
Expand Down
4 changes: 2 additions & 2 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ pub struct Config {
impl Config {
/// Get root dir, if provided, else use default
pub fn root_with_default(&self) -> path::PathBuf {
match self.base_dir {
match &self.base_dir {
Some(p) => p.to_path_buf(),
None => {
let h = home::home_dir();
Expand Down Expand Up @@ -105,7 +105,7 @@ pub trait EnsurePath {

impl EnsurePath for path::PathBuf {
fn ensure_path(&self) -> anyhow::Result<()> {
if !self.exists() && self.is_dir() {
if !self.exists() {
fs::create_dir_all(self)
.with_context(|| format!("Unable to create dir in path {}", self.display()))?;
}
Expand Down
154 changes: 0 additions & 154 deletions src/dirs.rs

This file was deleted.

1 change: 0 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ mod arch;
mod cli;
mod commands;
mod config;
mod dirs;
mod fs;
mod http;
mod platform;
Expand Down
22 changes: 19 additions & 3 deletions src/user_version.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::alias::Alias;
use crate::dirs::DsmDir;
use crate::http;
use anyhow::Context;
use dart_semver::{Channel, Version as DartVersion};
use std::path;

/// Represents a user version
#[derive(Debug, PartialEq)]
Expand Down Expand Up @@ -43,11 +43,11 @@ impl UserVersion {
}

/// Convert an alias to a version
pub fn to_version(&self, dirs: Option<&DsmDir>) -> anyhow::Result<DartVersion> {
pub fn to_version(&self, dirs: Option<path::PathBuf>) -> anyhow::Result<DartVersion> {
match self {
UserVersion::Version(a) => Ok(*a),
UserVersion::Alias(a) => {
let alias: Alias = dirs.unwrap().find_alias_dir(a).as_path().try_into()?;
let alias: Alias = dirs.unwrap().join(a).as_path().try_into()?;
Ok(alias.version)
}
UserVersion::Latest(c) => UserVersion::resolve_latest(c),
Expand Down Expand Up @@ -96,6 +96,22 @@ pub fn fetch_latest_version(channel: &Channel) -> anyhow::Result<String> {
)?))
}

pub fn list_versions<P: AsRef<path::Path>>(dir: P) -> anyhow::Result<Vec<DartVersion>> {
let dir = dir.as_ref();
if !dir.exists() {
return Ok(vec![]);
}
let vec: Vec<DartVersion> = dir
.read_dir()?
.filter_map(Result::ok)
.filter(|f| !f.file_name().to_str().map_or(false, |f| f.starts_with('.')))
.filter_map(|f| f.file_name().to_str().map(str::to_string))
.map(DartVersion::parse)
.filter_map(Result::ok)
.collect();
Ok(vec)
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down

0 comments on commit 9b22745

Please sign in to comment.