use std::fs::{File, OpenOptions};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tuff_core::error::{Result, TuffError};
use tuff_core::lockfile;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Workspace {
root: PathBuf,
}
impl Workspace {
pub fn open(root: impl Into<PathBuf>) -> Result<Self> {
let root = root.into();
lockfile::require_lockfile(&root)?;
Ok(Self { root })
}
pub fn init(root: impl Into<PathBuf>) -> Result<Self> {
let root = root.into();
let path = root.join("tuff.lock");
if !path.exists() {
std::fs::create_dir_all(&root)?;
lockfile::write_lockfile_at(&path, &lockfile::Lockfile::empty())?;
}
Self::open(root)
}
pub fn root(&self) -> &Path {
&self.root
}
pub fn lock(&self) -> Result<WorkspaceLock> {
let canonical = self
.root
.canonicalize()
.unwrap_or_else(|_| self.root.clone());
let key = lockfile::hash_bytes(canonical.to_string_lossy().as_bytes());
let path = std::env::temp_dir().join(format!("tuff-workspace-{}.lock", &key[..32]));
let file = OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(&path)
.or_else(|_| File::open(&path))?;
match file.try_lock() {
Ok(()) => Ok(WorkspaceLock { _file: file }),
Err(std::fs::TryLockError::WouldBlock) => Err(TuffError::refused(format!(
"another Tuff operation is changing {}",
self.root.display()
))
.with_hint("wait for it to finish, then run this again")),
Err(std::fs::TryLockError::Error(error)) => Err(error.into()),
}
}
}
#[derive(Debug)]
pub struct WorkspaceLock {
_file: File,
}
pub trait BaselineStore: Send + Sync {
fn store(&self, hash: &str, tree: &Path) -> Result<()>;
}
#[derive(Clone, Default)]
pub enum Baselines {
Dir(PathBuf),
InWorkspace,
#[default]
None,
Store(Arc<dyn BaselineStore>),
}
impl std::fmt::Debug for Baselines {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Dir(path) => formatter.debug_tuple("Dir").field(path).finish(),
Self::InWorkspace => formatter.write_str("InWorkspace"),
Self::None => formatter.write_str("None"),
Self::Store(_) => formatter.write_str("Store(..)"),
}
}
}
pub const IN_WORKSPACE_BASELINES: &str = ".tuff-baselines";
impl Baselines {
pub fn dir(path: impl Into<PathBuf>) -> Self {
Self::Dir(path.into())
}
pub fn in_workspace() -> Self {
Self::InWorkspace
}
pub fn none() -> Self {
Self::None
}
pub fn custom(store: impl BaselineStore + 'static) -> Self {
Self::Store(Arc::new(store))
}
pub fn store(&self, root: &Path, hash: &str, tree: &Path) -> Result<()> {
match self {
Self::Dir(path) => {
tuff_core::cache::populate_in(path, hash, tree)?;
}
Self::InWorkspace => {
let folder = root.join(IN_WORKSPACE_BASELINES);
std::fs::create_dir_all(&folder)?;
let ignore = folder.join(".gitignore");
if !ignore.exists() {
std::fs::write(&ignore, "*\n")?;
}
tuff_core::cache::populate_in(&folder, hash, tree)?;
}
Self::None => {}
Self::Store(store) => store.store(hash, tree)?,
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct Environment {
pub home: Option<PathBuf>,
pub current_dir: PathBuf,
}
impl Environment {
pub fn from_process() -> Result<Self> {
Ok(Self {
home: std::env::var_os("HOME").map(PathBuf::from),
current_dir: std::env::current_dir()?,
})
}
pub fn require_home(&self) -> Result<&Path> {
self.home
.as_deref()
.ok_or_else(|| TuffError::usage("HOME environment variable not set"))
}
pub fn baselines(&self) -> Result<Baselines> {
Ok(Baselines::dir(tuff_core::cache::cache_root(
self.require_home()?,
)))
}
pub fn workspace(&self) -> Result<Workspace> {
Workspace::open(&self.current_dir)
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[serde(tag = "kind", content = "text", rename_all = "lowercase")]
pub enum Message {
Done(String),
Note(String),
Warning(String),
}
pub type Messages = Vec<Message>;