Skip to content

Commit

Permalink
Migrated to anyhow
Browse files Browse the repository at this point in the history
  • Loading branch information
Shtsh committed May 17, 2024
1 parent 1c4351e commit 61a342f
Show file tree
Hide file tree
Showing 21 changed files with 145 additions and 348 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
[package]
name = "rsvenv"
version = "0.4.0"
version = "0.4.1"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow = "1.0.82"
clap = { version = "4.5.3", features = ["derive"] }
config = { version = "0.14.0", features = ["yaml"] }
error-stack = "0.4.1"
glob = "0.3.1"
itertools = "0.12.1"
lazy_static = "1.4.0"
Expand Down
6 changes: 2 additions & 4 deletions src/arguments.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
use anyhow::Result;
use clap::{Parser, Subcommand};
use error_stack::Result;
use simplelog::debug;

use crate::errors::CommandExecutionError;

#[derive(Parser)]
#[command(version, about, long_about = None, arg_required_else_help(true))]
pub struct Cli {
Expand Down Expand Up @@ -43,7 +41,7 @@ pub enum Commands {
}

impl Commands {
pub fn execute(&self) -> Result<(), CommandExecutionError> {
pub fn execute(&self) -> Result<()> {
debug!("executing command");
match self {
Commands::Init(command) => command.execute(),
Expand Down
49 changes: 12 additions & 37 deletions src/commands/activate.rs
Original file line number Diff line number Diff line change
@@ -1,63 +1,38 @@
use anyhow::{bail, Result};
use clap::Parser;
use error_stack::{Report, Result, ResultExt};
use simplelog::{debug, error};
use simplelog::debug;

use crate::{
errors::{CommandExecutionError, VirtualEnvError},
virtualenv::{pyenv::Pyenv, rsenv::Rsenv, VirtualEnvironment},
};
use crate::virtualenv::{pyenv::Pyenv, rsenv::Rsenv, VirtualEnvironment};

#[derive(Debug, Parser)]
pub struct Command {
#[clap(help = "string matching a Python version known to pyenv-rs")]
virtualenv: String,
}

fn try_activate(v: VirtualEnvironment, venv: &String) -> Result<(), VirtualEnvError> {
fn try_activate(v: VirtualEnvironment, venv: &String) -> Result<()> {
if v.list().contains(venv) {
if let Err(e) = v.activate(Some(venv)) {
error!("{e}");
return Err(e);
debug!("Unable to activate venv: {e:?}");
bail!(e);
};
return Ok(());
}
Err(
Report::new(VirtualEnvError::NotVirtualEnv(venv.to_string()))
.attach_printable("{venv} is not a virtual environment"),
)
bail!("{venv} is not a virtual environment")
}

impl Command {
pub fn execute(&self) -> Result<(), CommandExecutionError> {
let context = CommandExecutionError {
command: "activate".into(),
};
if let Err(e) = VirtualEnvironment::deactivate(true) {
debug!("{e}");
};
if try_activate(
VirtualEnvironment::new(&Rsenv).change_context(context.clone())?,
&self.virtualenv,
)
.is_ok()
{
pub fn execute(&self) -> Result<()> {
VirtualEnvironment::deactivate(true)?;
if try_activate(VirtualEnvironment::new(&Rsenv)?, &self.virtualenv).is_ok() {
return Ok(());
}
if try_activate(
VirtualEnvironment::new(&Pyenv).change_context(context)?,
&self.virtualenv,
)
.is_ok()
{
if try_activate(VirtualEnvironment::new(&Pyenv)?, &self.virtualenv).is_ok() {
return Ok(());
}
error!(
bail!(
"Failed to find and activate virtual environment {}",
self.virtualenv
);
Err(Report::new(CommandExecutionError {
command: "activate".into(),
})
.attach_printable(format!("Unable to activate virtualenv {}", self.virtualenv)))
}
}
10 changes: 4 additions & 6 deletions src/commands/chdir_hook.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{errors::CommandExecutionError, virtualenv::VirtualEnvironment};
use crate::virtualenv::VirtualEnvironment;
use anyhow::Result;
use clap::Parser;
use error_stack::{Result, ResultExt};
use simplelog::{debug, error};
use std::path::Path;

Expand Down Expand Up @@ -44,7 +44,7 @@ impl Command {
}
}

pub fn execute(&self) -> Result<(), CommandExecutionError> {
pub fn execute(&self) -> Result<()> {
let deactivated = self.should_deactivate();
if deactivated {
if let Err(e) = VirtualEnvironment::deactivate(false) {
Expand All @@ -54,9 +54,7 @@ impl Command {
}
if self.should_activate(deactivated) {
if let Some(venv) = VirtualEnvironment::detect() {
venv.activate(None).change_context(CommandExecutionError {
command: "hook".into(),
})?;
venv.activate(None)?;
};
}
Ok(())
Expand Down
13 changes: 4 additions & 9 deletions src/commands/create.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use anyhow::Result;
use clap::Parser;
use error_stack::{Result, ResultExt};

use crate::{errors::CommandExecutionError, virtualenv::rsenv::Rsenv};
use crate::virtualenv::rsenv::Rsenv;

#[derive(Debug, Parser)]
pub struct CreateCommand {
Expand All @@ -12,12 +12,7 @@ pub struct CreateCommand {
}

impl CreateCommand {
pub fn execute(&self) -> Result<(), CommandExecutionError> {
Rsenv
.create(&self.name, &self.python)
.change_context(CommandExecutionError {
command: "create".into(),
})?;
Ok(())
pub fn execute(&self) -> Result<()> {
Rsenv.create(&self.name, &self.python)
}
}
10 changes: 4 additions & 6 deletions src/commands/deactivate.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{errors::CommandExecutionError, virtualenv::VirtualEnvironment};
use crate::virtualenv::VirtualEnvironment;
use anyhow::Result;
use clap::Parser;
use error_stack::{Result, ResultExt};

#[derive(Debug, Parser)]
pub struct Command {
Expand All @@ -9,9 +9,7 @@ pub struct Command {
}

impl Command {
pub fn execute(&self) -> Result<(), CommandExecutionError> {
VirtualEnvironment::deactivate(true).change_context(CommandExecutionError {
command: "deactivate".into(),
})
pub fn execute(&self) -> Result<()> {
VirtualEnvironment::deactivate(true)
}
}
12 changes: 4 additions & 8 deletions src/commands/delete.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{errors::CommandExecutionError, virtualenv::rsenv::Rsenv};
use crate::virtualenv::rsenv::Rsenv;
use anyhow::Result;
use clap::Parser;
use error_stack::{Result, ResultExt};

#[derive(Debug, Parser)]
pub struct DeleteCommand {
Expand All @@ -9,11 +9,7 @@ pub struct DeleteCommand {
}

impl DeleteCommand {
pub fn execute(&self) -> Result<(), CommandExecutionError> {
Rsenv
.delete(self.venv.clone())
.change_context(CommandExecutionError {
command: "delete".into(),
})
pub fn execute(&self) -> Result<()> {
Rsenv.delete(self.venv.clone())
}
}
15 changes: 4 additions & 11 deletions src/commands/init.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,21 @@
use crate::errors::CommandExecutionError;
use crate::shell::SupportedShell;
use anyhow::{Context, Result};
use clap::Parser;
use error_stack::{Result, ResultExt};
use std::io;
use std::io::Write;

#[derive(Debug, Parser)]
pub struct Command {}

impl Command {
pub fn execute(&self) -> Result<(), CommandExecutionError> {
let error_context = CommandExecutionError {
command: "init".into(),
};
let shell = SupportedShell::new()
.change_context(error_context.clone())
.attach("Unable to detect current shell")?;
pub fn execute(&self) -> Result<()> {
let shell = SupportedShell::new().context("Unable to detect current shell")?;

let hook = shell.get_hook();

io::stdout()
.write_all(hook.as_bytes())
.change_context(error_context)
.attach("Unable to write hook to STDOUT!")?;
.context("Unable to write hook to STDOUT!")?;
Ok(())
}
}
36 changes: 10 additions & 26 deletions src/commands/install.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,17 @@
use std::fs::{read_to_string, OpenOptions};
use std::io::Write;

use crate::errors::CommandExecutionError;
use crate::shell::SupportedShell;
use anyhow::{bail, Context, Result};
use clap::Parser;
use error_stack::{Report, Result, ResultExt};
use simplelog::{debug, error, info};
use simplelog::{debug, info};

#[derive(Debug, Parser)]
pub struct Command {}

fn find_occurence(filename: &str, substr: &str) -> Result<bool, CommandExecutionError> {
fn find_occurence(filename: &str, substr: &str) -> Result<bool> {
for line in read_to_string(filename)
.change_context(CommandExecutionError {
command: "install".into(),
})
.attach_printable("Unable to read config file")?
.context("Unable to read config file")?
.lines()
{
if line.contains(substr) {
Expand All @@ -26,37 +22,25 @@ fn find_occurence(filename: &str, substr: &str) -> Result<bool, CommandExecution
}

impl Command {
pub fn execute(&self) -> Result<(), CommandExecutionError> {
let error_context = CommandExecutionError {
command: "install".into(),
};
let shell = SupportedShell::new()
.change_context(error_context.clone())
.attach("Unable to detect current shell")?;
pub fn execute(&self) -> Result<()> {
let shell = SupportedShell::new()?;

let config_path = shell
.get_config_path()
.change_context(error_context.clone())?;
let config_path = shell.get_config_path()?;

debug!("Installing to {config_path}");

let init_line = shell.get_init_command();

if find_occurence(&config_path, init_line)? {
error!("RSVENV already installed to config");
return Err(Report::new(CommandExecutionError {
command: "install".into(),
}));
bail!("RSVENV already installed to config");
};
let mut file = OpenOptions::new()
.append(true)
.open(config_path)
.change_context(error_context.clone())
.attach("Unable to open config file for appending")?;
.context("Unable to open config file for appending")?;

file.write_all(init_line.as_bytes())
.change_context(error_context)
.attach_printable("Error when writing to the file")?;
.context("Error when writing to the file")?;

info!("Successfully modified shell config. Please restart you session");
Ok(())
Expand Down
5 changes: 2 additions & 3 deletions src/commands/list.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::errors::CommandExecutionError;
use crate::virtualenv::{pyenv::Pyenv, rsenv::Rsenv, traits::VirtualEnvCompatible};
use anyhow::Result;
use clap::Parser;
use error_stack::Result;
use std::collections::HashSet;
use std::io;
use std::io::Write;
Expand All @@ -18,7 +17,7 @@ fn print_venvs(rsenv_venvs: HashSet<String>) {
}

impl ListCommand {
pub fn execute(&self) -> Result<(), CommandExecutionError> {
pub fn execute(&self) -> Result<()> {
let rsenv_venvs = Rsenv.list();
if !rsenv_venvs.is_empty() {
io::stdout()
Expand Down
27 changes: 9 additions & 18 deletions src/commands/use_command.rs
Original file line number Diff line number Diff line change
@@ -1,42 +1,33 @@
use crate::{
errors::{CommandExecutionError, VirtualEnvError},
virtualenv::{pyenv::Pyenv, rsenv::Rsenv, traits::VirtualEnvCompatible},
};
use crate::virtualenv::{pyenv::Pyenv, rsenv::Rsenv, traits::VirtualEnvCompatible};
use anyhow::{bail, Result};
use clap::Parser;
use error_stack::{Report, Result};
use simplelog::error;
use simplelog::debug;

#[derive(Debug, Parser)]
pub struct UseCommand {
#[clap(help = "Virtual environment name")]
venv: String,
}

fn try_save(f: &dyn VirtualEnvCompatible, venv: String) -> Result<(), VirtualEnvError> {
fn try_save(f: &dyn VirtualEnvCompatible, venv: String) -> Result<()> {
if f.list().contains(&venv) {
f.save(&venv)?;
return Ok(());
}
Err(
Report::new(VirtualEnvError::NotVirtualEnv(venv.clone())).attach_printable(format!(
"{} not in the list of existing virtual environments",
venv
)),
)
bail!("{} not in the list of existing virtual environments", venv)
}

impl UseCommand {
pub fn execute(&self) -> Result<(), CommandExecutionError> {
pub fn execute(&self) -> Result<()> {
match try_save(&Rsenv, self.venv.clone()) {
Ok(()) => return Ok(()),
Err(e) => error!("{e}"),
Err(e) => debug!("Rsenv: {e}"),
}
match try_save(&Pyenv, self.venv.clone()) {
Ok(()) => return Ok(()),
Err(e) => error!("{e}"),
Err(e) => debug!("Pyenv: {e}"),
}

error!("Virtual environment {} doesn't exist", &self.venv);
Ok(())
bail!("Virtual environment {} doesn't exist", &self.venv);
}
}
Loading

0 comments on commit 61a342f

Please sign in to comment.