#![allow(clippy::missing_errors_doc)]
#![allow(clippy::must_use_candidate)]
use anyhow::{Context, Result};
use std::path::Path;
use std::process::Command;
pub trait ZoxideClient {
fn add(&self, path: &Path) -> Result<()>;
}
#[derive(Debug, Default)]
pub struct RealZoxideClient;
impl ZoxideClient for RealZoxideClient {
fn add(&self, path: &Path) -> Result<()> {
let output = Command::new("zoxide")
.arg("add")
.arg(path)
.output()
.context("Failed to execute zoxide add")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("zoxide add failed: {stderr}");
}
Ok(())
}
}
pub fn is_zoxide_available() -> bool {
Command::new("zoxide")
.arg("--version")
.output()
.is_ok_and(|output| output.status.success())
}
pub fn add_to_zoxide_if_enabled(path: &Path, enabled: bool) -> Result<()> {
if !enabled {
return Ok(());
}
if !is_zoxide_available() {
return Ok(());
}
let client = RealZoxideClient;
client.add(path)
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
struct MockZoxideClient {
should_fail: bool,
}
impl ZoxideClient for MockZoxideClient {
fn add(&self, _path: &Path) -> Result<()> {
if self.should_fail {
anyhow::bail!("Mock zoxide failure");
}
Ok(())
}
}
#[test]
fn test_mock_zoxide_client_success() {
let client = MockZoxideClient { should_fail: false };
let path = PathBuf::from("/test/path");
let result = client.add(&path);
assert!(result.is_ok());
}
#[test]
fn test_mock_zoxide_client_failure() {
let client = MockZoxideClient { should_fail: true };
let path = PathBuf::from("/test/path");
let result = client.add(&path);
assert!(result.is_err());
}
#[test]
fn test_is_zoxide_available() {
let _ = is_zoxide_available();
}
#[test]
fn test_add_to_zoxide_if_enabled_disabled() {
let path = PathBuf::from("/test/path");
let result = add_to_zoxide_if_enabled(&path, false);
assert!(result.is_ok());
}
#[test]
fn test_add_to_zoxide_if_enabled_enabled() {
let path = PathBuf::from("/tmp");
let result = add_to_zoxide_if_enabled(&path, true);
if is_zoxide_available() {
assert!(result.is_ok(), "Failed to add to zoxide: {result:?}");
} else {
assert!(result.is_ok());
}
}
}