Skip to content

Commit

Permalink
πŸ› Address review
Browse files Browse the repository at this point in the history
- Use ResultWithDefaultError where applicable
  • Loading branch information
shantanuraj committed Dec 12, 2023
1 parent ff44652 commit f39ae0a
Show file tree
Hide file tree
Showing 7 changed files with 49 additions and 40 deletions.
4 changes: 2 additions & 2 deletions src/commands/start.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,8 @@ impl StartCommand {
let workspace_id = (api_client.get_user().await?).default_workspace_id;
let entities = api_client.get_entities().await?;

let config_path = config::locate::locate_config_path().expect("failed to locate config");
let track_config = config::parser::get_config_from_file(config_path).expect("failed to parse config");
let config_path = config::locate::locate_config_path()?;
let track_config = config::parser::get_config_from_file(config_path)?;
let default_time_entry = track_config.get_default_entry(entities.clone())?;

let project = project_name
Expand Down
4 changes: 2 additions & 2 deletions src/config/active.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ pub struct ConfigActiveCommand;

impl ConfigActiveCommand {
pub async fn execute() -> ResultWithDefaultError<()> {
let config_path = super::locate::locate_config_path().expect("failed to locate config");
let track_config = super::parser::get_config_from_file(config_path).expect("failed to parse config");
let config_path = super::locate::locate_config_path()?;
let track_config = super::parser::get_config_from_file(config_path)?;
println!("{}", track_config.get_active_config()?);
Ok(())
}
Expand Down
16 changes: 8 additions & 8 deletions src/config/locate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ use std::path::{Path, PathBuf};
use base64::{engine::general_purpose, Engine as _};
use lazy_static::lazy_static;

use crate::error::ConfigError;
use crate::{error::ConfigError, models::ResultWithDefaultError};

lazy_static! {
pub static ref TRACKED_PATH: Option<PathBuf> = locate_tracked_path().ok();
}

pub fn locate_config_path() -> Result<PathBuf, Box<dyn std::error::Error>> {
pub fn locate_config_path() -> ResultWithDefaultError<PathBuf> {
let config_root = get_config_root();

let mut config_path = std::env::current_dir()?;
let mut config_path = std::env::current_dir().expect("failed to get current directory");
let mut config_filename = get_encoded_config_path(&config_root, &config_path);

while !config_filename.exists() {
Expand All @@ -24,24 +24,24 @@ pub fn locate_config_path() -> Result<PathBuf, Box<dyn std::error::Error>> {
Ok(config_filename)
}

fn locate_tracked_path() -> Result<PathBuf, Box<dyn std::error::Error>> {
fn locate_tracked_path() -> ResultWithDefaultError<PathBuf> {
let config_root = get_config_root();

let mut config_path = std::env::current_dir()?;
let mut config_path = std::env::current_dir().expect("failed to get current directory");
let mut config_filename = get_encoded_config_path(&config_root, &config_path);

while !config_filename.exists() {
if !config_path.pop() {
return Err("No config file found".into());
panic!("No config file found");
}
config_filename = get_encoded_config_path(&config_root, &config_path);
}
Ok(config_path)
}

pub fn get_config_path_for_current_dir() -> Result<PathBuf, Box<dyn std::error::Error>> {
pub fn get_config_path_for_current_dir() -> ResultWithDefaultError<PathBuf> {
let config_root = get_config_root();
let path = std::env::current_dir()?;
let path = std::env::current_dir().expect("failed to get current directory");
Ok(get_encoded_config_path(&config_root, &path))
}

Expand Down
2 changes: 1 addition & 1 deletion src/config/manage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub struct ConfigManageCommand;

impl ConfigManageCommand {
pub async fn execute(delete: bool, edit: bool, show_path: bool) -> ResultWithDefaultError<()> {
let path = super::locate::locate_config_path().expect("failed to locate config");
let path = super::locate::locate_config_path()?;
let display_path = utilities::simplify_config_path_for_display(path.as_path());

if delete {
Expand Down
49 changes: 29 additions & 20 deletions src/config/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,18 +293,19 @@ fn resolve_token_to_macro(token: &str) -> Option<Macro> {
}
}

fn resolve_macro(
base_dir: &Path,
instruction: Macro,
) -> Result<String, Box<dyn std::error::Error>> {
fn resolve_macro(base_dir: &Path, instruction: Macro) -> ResultWithDefaultError<String> {
match instruction {
Macro::Branch => {
let output = std::process::Command::new("git")
.arg("rev-parse")
.arg("--abbrev-ref")
.arg("HEAD")
.output()?;
Ok(String::from_utf8(output.stdout)?.trim().to_string())
.output()
.expect("Failed to resolve branch");
Ok(String::from_utf8(output.stdout)
.expect("Failed to convert branch name to string. This should never happen.")
.trim()
.to_string())
}
Macro::BaseDir => Ok(base_dir
.file_name()
Expand All @@ -325,11 +326,11 @@ fn resolve_macro(
Ok(parent_dir)
}
Macro::CurrentDir => {
let output = env::current_dir()?;
let output = env::current_dir().expect("Failed to get current directory");
Ok(output.file_name().unwrap().to_str().unwrap().to_string())
}
Macro::ParentDir => {
let current_dir = env::current_dir()?;
let current_dir = env::current_dir().expect("Failed to get current directory");
let parent_dir_path = current_dir.parent().unwrap().to_path_buf();
Ok(parent_dir_path
.file_name()
Expand All @@ -353,24 +354,24 @@ fn resolve_macro(
)));
}
let git_root = PathBuf::from(
String::from_utf8(output.stdout).map(|s| s.trim().to_string())?,
String::from_utf8(output.stdout)
.map(|s| s.trim().to_string())
.expect(
"Failed to convert git root to string. This should never happen.",
),
);

// Check if we are in a git worktree
// If so, we need to get the root of the main repository
let git_dir = git_root.join(".git");
if git_dir.is_file() {
let git_dir = std::fs::read_to_string(git_dir)?;
let git_dir = std::fs::read_to_string(git_dir)
.expect("Failed to read git directory. No git root maybe?");

let git_dir = git_dir
.split(':')
.nth(1)
.ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::Other,
"Failed to resolve git worktree root",
)
})?
.expect("Failed to resolve git worktree root")
.trim();
let git_root = PathBuf::from(git_dir);

Expand Down Expand Up @@ -417,7 +418,10 @@ fn resolve_macro(
"Failed to resolve git root",
)));
}
let git_root = PathBuf::from(String::from_utf8(output.stdout)?);
let git_root = PathBuf::from(
String::from_utf8(output.stdout)
.expect("Failed to convert git root to string. Not in a git root?"),
);
Ok(git_root
.parent()
.unwrap()
Expand All @@ -438,10 +442,15 @@ fn resolve_macro(
if !output.status.success() {
return Err(Box::new(ConfigError::ShellResolution(
command,
String::from_utf8(output.stderr)?,
String::from_utf8(output.stderr).unwrap(),
)));
}
Ok(String::from_utf8(output.stdout)?.trim().to_string())
Ok(String::from_utf8(output.stdout)
.expect(
"Failed to convert shell output to string. This should never happen.",
)
.trim()
.to_string())
}
Err(e) => Err(Box::new(ConfigError::ShellResolution(
command,
Expand All @@ -452,7 +461,7 @@ fn resolve_macro(
}
}

fn resolve_token(base_dir: &Path, token: &str) -> Result<String, Box<dyn std::error::Error>> {
fn resolve_token(base_dir: &Path, token: &str) -> ResultWithDefaultError<String> {
match resolve_token_to_macro(token) {
Some(macro_) => resolve_macro(base_dir, macro_),
None => Err(Box::new(ConfigError::UnrecognizedMarco(token.to_string()))),
Expand Down
10 changes: 5 additions & 5 deletions src/config/parser.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use std::path::Path;
use toml;

use crate::models::ResultWithDefaultError;

use super::model::TrackConfig;

pub fn get_config_from_file<P: AsRef<Path>>(
path: P,
) -> Result<TrackConfig, Box<dyn std::error::Error>> {
let contents = std::fs::read_to_string(path)?;
let config: TrackConfig = toml::from_str(&contents)?;
pub fn get_config_from_file<P: AsRef<Path>>(path: P) -> ResultWithDefaultError<TrackConfig> {
let contents = std::fs::read_to_string(path).expect("failed to read config file");
let config: TrackConfig = toml::from_str(&contents).expect("failed to parse config");

Ok(config)
}
4 changes: 2 additions & 2 deletions src/utilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::{
use colored::Colorize;
use directories::BaseDirs;

use crate::constants;
use crate::{constants, models::ResultWithDefaultError};

pub fn remove_trailing_newline(value: String) -> String {
value.trim_end().to_string()
Expand Down Expand Up @@ -50,7 +50,7 @@ pub fn read_from_stdin_with_constraints(text: &str, valid_values: &[String]) ->
}
}

pub fn open_path_in_editor<P>(path: P) -> Result<(), Box<dyn std::error::Error + Send>>
pub fn open_path_in_editor<P>(path: P) -> ResultWithDefaultError<()>
where
P: AsRef<Path> + std::convert::AsRef<std::ffi::OsStr>,
{
Expand Down

0 comments on commit f39ae0a

Please sign in to comment.