#[cfg(test)]
use std::cell::Cell;
use std::collections::{BTreeMap, BTreeSet};
use std::env;
use std::ffi::OsString;
use std::fs;
use std::fs::OpenOptions;
use std::io::{Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use tempfile::NamedTempFile;
use crate::config::{CONFIG_VERSION, UserConfig};
use crate::error::{DaloError, DaloResult, shell_quote_path};
use crate::git;
use crate::lockfile::{USER_LOCK_SCHEMA_VERSION, UserLock};
pub const STORE_ENV_VAR: &str = "DALO_STORE";
pub const DEFAULT_STORE_DIR: &str = ".dalo";
#[cfg(test)]
thread_local! {
static CONFIG_READ_INVOCATIONS: Cell<usize> = const { Cell::new(0) };
static COMPARABLE_PATH_INVOCATIONS: Cell<usize> = const { Cell::new(0) };
}
#[cfg(test)]
pub(crate) fn reset_path_io_invocations() {
CONFIG_READ_INVOCATIONS.with(|count| count.set(0));
COMPARABLE_PATH_INVOCATIONS.with(|count| count.set(0));
}
#[cfg(test)]
pub(crate) fn path_io_invocations() -> (usize, usize) {
(
CONFIG_READ_INVOCATIONS.with(Cell::get),
COMPARABLE_PATH_INVOCATIONS.with(Cell::get),
)
}
pub const STATE_SCHEMA_VERSION: u32 = 1;
pub const APPROVALS_SCHEMA_VERSION: u32 = 1;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StorePaths {
pub root: PathBuf,
pub config_file: PathBuf,
pub lock_file: PathBuf,
pub state_file: PathBuf,
pub approvals_file: PathBuf,
pub lock_guard_file: PathBuf,
pub local_dir: PathBuf,
pub local_skills_dir: PathBuf,
pub local_instructions_dir: PathBuf,
pub local_agents_dir: PathBuf,
pub tools_dir: PathBuf,
pub binaries_dir: PathBuf,
pub bin_dir: PathBuf,
pub generated_dir: PathBuf,
pub hooks_dir: PathBuf,
pub hook_state_file: PathBuf,
pub plugins_dir: PathBuf,
pub plugin_state_file: PathBuf,
pub sources_dir: PathBuf,
pub source_lock_file: PathBuf,
pub catalog_advance_file: PathBuf,
pub catalog_lock_file: PathBuf,
pub audits_dir: PathBuf,
pub autosync_file: PathBuf,
pub autosync_run_file: PathBuf,
pub autosync_log_file: PathBuf,
pub autosync_error_log_file: PathBuf,
}
impl StorePaths {
#[must_use]
pub fn new(root: PathBuf) -> Self {
let local_dir = root.join("local");
Self {
config_file: root.join("config.toml"),
lock_file: root.join("lock.toml"),
state_file: root.join("state.toml"),
approvals_file: root.join("approvals.toml"),
lock_guard_file: root.join(".lock"),
local_skills_dir: local_dir.join("skills"),
local_instructions_dir: local_dir.join("instructions"),
local_agents_dir: local_dir.join("agents"),
tools_dir: root.join("tools"),
binaries_dir: root.join("binaries"),
bin_dir: root.join("bin"),
generated_dir: root.join("generated"),
hooks_dir: root.join("hooks"),
hook_state_file: root.join("hooks/state.json"),
plugins_dir: root.join("plugins"),
plugin_state_file: root.join("plugins/state.json"),
sources_dir: root.join("sources"),
source_lock_file: root.join("source-lock.toml"),
catalog_advance_file: root.join("catalog-advance.toml"),
catalog_lock_file: root.join(".catalog.lock"),
audits_dir: root.join("audits"),
autosync_file: root.join("autosync.toml"),
autosync_run_file: root.join("autosync-run.toml"),
autosync_log_file: root.join("autosync.log"),
autosync_error_log_file: root.join("autosync-error.log"),
local_dir,
root,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct StateFile {
pub schema_version: u32,
pub targets: Vec<TargetState>,
#[serde(default)]
pub materialization_dirs: Vec<MaterializationDirState>,
pub owned_skills: Vec<OwnedSkillState>,
#[serde(default)]
pub protected_skills: Vec<ProtectedSkillState>,
#[serde(flatten)]
pub extra: BTreeMap<String, toml::Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TargetState {
pub id: String,
pub path: PathBuf,
pub canonical_path: PathBuf,
pub enabled: bool,
#[serde(flatten)]
pub extra: BTreeMap<String, toml::Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MaterializationDirState {
pub path: PathBuf,
pub logical_targets: Vec<String>,
#[serde(flatten)]
pub extra: BTreeMap<String, toml::Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OwnedSkillState {
pub target_id: String,
pub slot_name: String,
pub link_path: PathBuf,
pub store_path: PathBuf,
#[serde(flatten)]
pub extra: BTreeMap<String, toml::Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProtectedSkillState {
#[serde(default)]
pub target_id: String,
pub slot_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<PathBuf>,
#[serde(flatten)]
pub extra: BTreeMap<String, toml::Value>,
}
impl StateFile {
#[must_use]
pub fn empty() -> Self {
Self {
schema_version: STATE_SCHEMA_VERSION,
targets: Vec::new(),
materialization_dirs: Vec::new(),
owned_skills: Vec::new(),
protected_skills: Vec::new(),
extra: BTreeMap::new(),
}
}
pub fn rebuild_materialization_dirs(&mut self) -> DaloResult<()> {
self.rebuild_materialization_dirs_with_conflict_policy(true)
}
pub(crate) fn rebuild_materialization_dirs_for_removal(&mut self) -> DaloResult<()> {
self.rebuild_materialization_dirs_with_conflict_policy(false)
}
fn rebuild_materialization_dirs_with_conflict_policy(
&mut self,
reject_conflicts: bool,
) -> DaloResult<()> {
let mut grouped: BTreeMap<PathBuf, Vec<String>> = BTreeMap::new();
for target in self.targets.iter().filter(|target| target.enabled) {
grouped
.entry(target.canonical_path.clone())
.or_default()
.push(target.id.clone());
}
let mut rebuilt = Vec::with_capacity(grouped.len());
for (path, mut logical_targets) in grouped {
logical_targets.sort();
let mut extra = BTreeMap::new();
let mut conflicting_fields = BTreeSet::new();
for previous in self.materialization_dirs.iter().filter(|previous| {
previous.path == path
|| previous
.logical_targets
.iter()
.any(|target| logical_targets.contains(target))
}) {
for (key, value) in &previous.extra {
if conflicting_fields.contains(key) {
continue;
}
if let Some(existing) = extra.get(key) {
if existing != value {
if reject_conflicts {
return Err(DaloError::StateMetadataConflict {
path,
field: key.clone(),
});
}
extra.remove(key);
conflicting_fields.insert(key.clone());
}
} else {
extra.insert(key.clone(), value.clone());
}
}
}
rebuilt.push(MaterializationDirState {
extra,
path,
logical_targets,
});
}
self.materialization_dirs = rebuilt;
Ok(())
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ApprovalsFile {
pub schema_version: u32,
pub approvals: Vec<ApprovalRecord>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ApprovalRecord {
pub scope: String,
pub value: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub granted_at_unix: Option<u64>,
}
impl ApprovalRecord {
#[must_use]
pub fn granted(scope: String, value: String) -> Self {
Self {
scope,
value,
granted_at_unix: Some(now_unix()),
}
}
#[must_use]
pub fn matches(&self, other: &Self) -> bool {
self.scope == other.scope && self.value == other.value
}
}
fn now_unix() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |duration| duration.as_secs())
}
impl ApprovalsFile {
#[must_use]
pub fn empty() -> Self {
Self {
schema_version: APPROVALS_SCHEMA_VERSION,
approvals: Vec::new(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum InitOperationStatus {
Planned,
Created,
Existing,
Repaired,
}
impl InitOperationStatus {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Planned => "planned",
Self::Created => "created",
Self::Existing => "existing",
Self::Repaired => "repaired",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum InitOperationAction {
CreateDir,
WriteFile,
GitInit,
}
impl InitOperationAction {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::CreateDir => "create_dir",
Self::WriteFile => "write_file",
Self::GitInit => "git_init",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InitOperation {
pub action: InitOperationAction,
pub path: PathBuf,
pub status: InitOperationStatus,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InitReport {
pub store: PathBuf,
pub dry_run: bool,
pub operations: Vec<InitOperation>,
pub validation_warnings: Vec<InitValidationWarning>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InitValidationWarning {
pub path: PathBuf,
pub message: String,
}
pub fn resolve_store_path(explicit: Option<&Path>) -> DaloResult<PathBuf> {
let candidate = if let Some(path) = explicit {
path.to_path_buf()
} else if let Some(path) = env::var_os(STORE_ENV_VAR) {
PathBuf::from(path)
} else {
home_dir()?.join(DEFAULT_STORE_DIR)
};
absolute_path(&expand_user_path(&candidate)?)
}
#[must_use]
pub fn dalo_command(store_root: &Path, arguments: &str) -> String {
if resolve_store_path(None)
.ok()
.is_some_and(|default_store| comparable_path(&default_store) == comparable_path(store_root))
&& (env::var_os(STORE_ENV_VAR).is_some()
|| env::current_dir()
.ok()
.and_then(|cwd| crate::project::discover(&cwd).ok())
.flatten()
.is_none())
{
format!("dalo {arguments}")
} else {
format!("dalo --store {} {arguments}", shell_quote_path(store_root))
}
}
#[must_use]
pub fn contextualize_dalo_commands(store_root: &Path, text: &str) -> String {
let prefix = dalo_command(store_root, "");
if prefix == "dalo " {
return text.to_owned();
}
let mut contextualized = String::with_capacity(text.len() + prefix.len());
let mut remaining = text;
while let Some(index) = remaining.find("dalo ") {
contextualized.push_str(&remaining[..index]);
let after_command = &remaining[index + "dalo ".len()..];
let command = after_command
.split(|character: char| character.is_whitespace() || character == '`')
.next()
.unwrap_or_default();
if (index == 0 || remaining[..index].ends_with('`'))
&& matches!(
command,
"init"
| "status"
| "sync"
| "approve"
| "target"
| "source"
| "resolve"
| "audit"
| "adopt"
| "instructions"
| "autosync"
| "doctor"
| "agent"
| "team"
| "--dry-run"
| "--json"
)
{
contextualized.push_str(&prefix);
} else {
contextualized.push_str("dalo ");
}
remaining = after_command;
}
contextualized.push_str(remaining);
contextualized
}
pub fn absolute_path(path: &Path) -> DaloResult<PathBuf> {
if let Ok(canonical) = path.canonicalize() {
return Ok(canonical);
}
if path.is_absolute() {
return Ok(path.to_path_buf());
}
Ok(env::current_dir()?.join(path))
}
#[must_use]
pub fn resolve_link_target(link_path: &Path, target: &Path) -> PathBuf {
if target.is_absolute() {
return target.to_path_buf();
}
link_path
.parent()
.map_or_else(|| target.to_path_buf(), |parent| parent.join(target))
}
#[must_use]
pub fn comparable_path(path: &Path) -> PathBuf {
#[cfg(test)]
COMPARABLE_PATH_INVOCATIONS.with(|count| count.set(count.get() + 1));
if let Ok(canonical) = path.canonicalize() {
return canonical;
}
let mut candidate = if path.is_absolute() {
path.to_path_buf()
} else {
env::current_dir()
.map(|cwd| cwd.join(path))
.unwrap_or_else(|_| path.to_path_buf())
};
let mut tail = Vec::<OsString>::new();
loop {
if let Ok(canonical) = candidate.canonicalize() {
let mut comparable = canonical;
for component in tail.iter().rev() {
comparable.push(component);
}
return comparable;
}
let Some(name) = candidate.file_name().map(|name| name.to_os_string()) else {
return candidate;
};
tail.push(name);
if !candidate.pop() {
return path.to_path_buf();
}
}
}
#[must_use]
pub fn path_is_same_or_descendant(path: &Path, root: &Path) -> bool {
let path = comparable_path(path);
let root = comparable_path(root);
path == root || path.starts_with(root)
}
pub fn init_store(store_root: PathBuf, dry_run: bool) -> DaloResult<InitReport> {
validate_store_path(&store_root)?;
let paths = StorePaths::new(store_root);
let mut operations = Vec::new();
for directory in [
&paths.root,
&paths.local_dir,
&paths.local_skills_dir,
&paths.local_instructions_dir,
&paths.local_agents_dir,
&paths.tools_dir,
&paths.generated_dir,
&paths.sources_dir,
&paths.audits_dir,
] {
operations.push(ensure_dir(directory, dry_run)?);
}
operations.push(ensure_toml_file(
&paths.config_file,
&UserConfig::default_for_store(&paths.root),
dry_run,
)?);
operations.push(ensure_toml_file(
&paths.lock_file,
&UserLock::empty(),
dry_run,
)?);
operations.push(ensure_state_file(&paths, dry_run)?);
operations.push(ensure_toml_file(
&paths.approvals_file,
&ApprovalsFile::empty(),
dry_run,
)?);
operations.push(ensure_git_repo(&paths.local_dir, dry_run)?);
let validation_warnings = validate_initialized_store(&paths);
Ok(InitReport {
store: paths.root,
dry_run,
operations,
validation_warnings,
})
}
fn validate_initialized_store(paths: &StorePaths) -> Vec<InitValidationWarning> {
let checks = [
(&paths.config_file, read_config(paths).map(|_| ())),
(&paths.lock_file, read_user_lock(paths).map(|_| ())),
(&paths.approvals_file, read_approvals(paths).map(|_| ())),
(&paths.state_file, read_state(paths).map(|_| ())),
];
checks
.into_iter()
.filter(|(path, _)| path.exists())
.filter_map(|(path, result)| {
result.err().map(|error| InitValidationWarning {
path: path.clone(),
message: error.to_string(),
})
})
.collect()
}
pub fn read_state(paths: &StorePaths) -> DaloResult<StateFile> {
if !paths.state_file.exists() {
return Err(DaloError::StoreNotInitialized {
path: paths.root.clone(),
});
}
let content = fs::read_to_string(&paths.state_file)?;
let mut state: StateFile =
toml::from_str(&content).map_err(|error| DaloError::CorruptState {
path: paths.state_file.clone(),
reason: error.to_string(),
})?;
if state.schema_version != STATE_SCHEMA_VERSION {
return Err(DaloError::UnsupportedSchema {
path: paths.state_file.clone(),
version: state.schema_version,
supported: STATE_SCHEMA_VERSION,
});
}
if state.materialization_dirs.is_empty() && !state.targets.is_empty() {
state.rebuild_materialization_dirs()?;
}
migrate_protected_skills(&mut state);
Ok(state)
}
fn migrate_protected_skills(state: &mut StateFile) {
let mut migrated = Vec::new();
for protected in std::mem::take(&mut state.protected_skills) {
if !protected.target_id.is_empty() {
migrated.push(protected);
continue;
}
let Some(path) = protected.path.as_ref() else {
migrated.push(protected);
continue;
};
let Some(dir) = state
.materialization_dirs
.iter()
.find(|dir| dir.path.join(&protected.slot_name) == *path)
else {
migrated.push(protected);
continue;
};
for target_id in &dir.logical_targets {
migrated.push(ProtectedSkillState {
target_id: target_id.clone(),
slot_name: protected.slot_name.clone(),
path: None,
extra: protected.extra.clone(),
});
}
}
migrated.sort_by(|left, right| {
left.target_id
.cmp(&right.target_id)
.then_with(|| left.slot_name.cmp(&right.slot_name))
.then_with(|| left.path.cmp(&right.path))
});
migrated.dedup();
state.protected_skills = migrated;
}
pub fn read_config(paths: &StorePaths) -> DaloResult<UserConfig> {
#[cfg(test)]
CONFIG_READ_INVOCATIONS.with(|count| count.set(count.get() + 1));
if !paths.config_file.exists() {
return Err(DaloError::StoreNotInitialized {
path: paths.root.clone(),
});
}
let content = fs::read_to_string(&paths.config_file)?;
let mut config: UserConfig = parse_store_toml(&paths.config_file, &content)?;
if config.version != 1 && config.version != CONFIG_VERSION {
return Err(DaloError::UnsupportedSchema {
path: paths.config_file.clone(),
version: config.version,
supported: CONFIG_VERSION,
});
}
config.version = CONFIG_VERSION;
ensure_unique_source_ids(&paths.config_file, &config)?;
for source in &config.sources {
if let Some(subpath) = &source.subpath
&& (source.kind != crate::source::SourceKind::Team
|| crate::source::validate_source_subpath(subpath).is_err())
{
return Err(DaloError::FileParse {
path: paths.config_file.clone(),
reason: format!(
"source `{}` has an invalid subpath; only team sources may use a relative directory inside their checkout",
source.id
),
});
}
}
validate_plugin_config(&paths.config_file, &config)?;
config.project_selections = crate::project::is_project_store(&paths.root)
.then(|| crate::project::declared_selections(&paths.root));
Ok(config)
}
fn validate_plugin_config(path: &Path, config: &UserConfig) -> DaloResult<()> {
let mut direct = std::collections::BTreeSet::new();
for reference in &config.plugins.direct {
if !valid_source_qualified_plugin_ref(reference) || !direct.insert(reference) {
return Err(DaloError::FileParse {
path: path.to_path_buf(),
reason: format!("invalid or duplicate direct plugin reference `{reference}`"),
});
}
}
if !config
.plugins
.direct
.windows(2)
.all(|pair| pair[0] < pair[1])
{
return Err(DaloError::FileParse {
path: path.to_path_buf(),
reason: "plugins.direct must be sorted".to_owned(),
});
}
let mut rule_ids = std::collections::BTreeSet::new();
for policy in &config.plugin_policy {
if !valid_plugin_name(&policy.rule_id) || !rule_ids.insert(policy.rule_id.as_str()) {
return Err(DaloError::FileParse {
path: path.to_path_buf(),
reason: format!(
"invalid or duplicate plugin policy rule_id `{}`",
policy.rule_id
),
});
}
if !valid_source_qualified_plugin_ref(&policy.plugin) || policy.reason.trim().is_empty() {
return Err(DaloError::FileParse {
path: path.to_path_buf(),
reason: format!("invalid plugin policy `{}`", policy.rule_id),
});
}
}
Ok(())
}
fn valid_source_qualified_plugin_ref(reference: &str) -> bool {
let mut parts = reference.split(':');
let (Some(source), Some(selector), None) = (parts.next(), parts.next(), parts.next()) else {
return false;
};
!source.is_empty()
&& !selector.is_empty()
&& !source.contains(['#', '/', '\\'])
&& !selector.contains(['#', '/', '\\'])
}
fn valid_plugin_name(value: &str) -> bool {
!value.is_empty()
&& value
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
&& !value.starts_with('-')
&& !value.ends_with('-')
&& !value.contains("--")
}
fn ensure_unique_source_ids(path: &Path, config: &UserConfig) -> DaloResult<()> {
let mut seen = std::collections::BTreeSet::new();
for source in &config.sources {
if !seen.insert(source.id.as_str()) {
return Err(DaloError::FileParse {
path: path.to_path_buf(),
reason: format!("duplicate source id `{}`", source.id),
});
}
}
Ok(())
}
pub fn read_user_lock(paths: &StorePaths) -> DaloResult<UserLock> {
if !paths.lock_file.exists() {
return Err(DaloError::StoreNotInitialized {
path: paths.root.clone(),
});
}
let content = fs::read_to_string(&paths.lock_file)?;
let mut lock: UserLock = parse_store_toml(&paths.lock_file, &content)?;
if !matches!(lock.schema_version, 1..=5) && lock.schema_version != USER_LOCK_SCHEMA_VERSION {
return Err(DaloError::UnsupportedSchema {
path: paths.lock_file.clone(),
version: lock.schema_version,
supported: USER_LOCK_SCHEMA_VERSION,
});
}
lock.schema_version = USER_LOCK_SCHEMA_VERSION;
Ok(lock)
}
pub fn write_config(paths: &StorePaths, config: &UserConfig) -> DaloResult<()> {
if !paths.root.exists() {
return Err(DaloError::StoreNotInitialized {
path: paths.root.clone(),
});
}
write_toml_atomic(&paths.config_file, config)
}
pub fn write_user_lock(paths: &StorePaths, lock: &UserLock) -> DaloResult<()> {
if !paths.root.exists() {
return Err(DaloError::StoreNotInitialized {
path: paths.root.clone(),
});
}
write_toml_atomic(&paths.lock_file, lock)
}
pub fn read_approvals(paths: &StorePaths) -> DaloResult<ApprovalsFile> {
if !paths.approvals_file.exists() {
return Err(DaloError::StoreNotInitialized {
path: paths.root.clone(),
});
}
let content = fs::read_to_string(&paths.approvals_file)?;
let approvals: ApprovalsFile = parse_store_toml(&paths.approvals_file, &content)?;
if approvals.schema_version != APPROVALS_SCHEMA_VERSION {
return Err(DaloError::UnsupportedSchema {
path: paths.approvals_file.clone(),
version: approvals.schema_version,
supported: APPROVALS_SCHEMA_VERSION,
});
}
Ok(approvals)
}
#[must_use]
pub fn persisted_schema_version(path: &Path, field: &str) -> Option<u32> {
let content = fs::read_to_string(path).ok()?;
let document: toml::Value = toml::from_str(&content).ok()?;
u32::try_from(document.get(field)?.as_integer()?).ok()
}
#[must_use]
pub fn persisted_path_only_protected_skills(path: &Path) -> Vec<String> {
let Ok(content) = fs::read_to_string(path) else {
return Vec::new();
};
let Ok(state) = toml::from_str::<StateFile>(&content) else {
return Vec::new();
};
state
.protected_skills
.into_iter()
.filter(|protected| protected.target_id.is_empty() && protected.path.is_some())
.map(|protected| protected.slot_name)
.collect()
}
fn parse_store_toml<T: serde::de::DeserializeOwned>(path: &Path, content: &str) -> DaloResult<T> {
toml::from_str(content).map_err(|error| DaloError::FileParse {
path: path.to_path_buf(),
reason: error.to_string(),
})
}
pub fn write_approvals(paths: &StorePaths, approvals: &ApprovalsFile) -> DaloResult<()> {
if !paths.root.exists() {
return Err(DaloError::StoreNotInitialized {
path: paths.root.clone(),
});
}
write_toml_atomic(&paths.approvals_file, approvals)
}
pub fn write_state(paths: &StorePaths, state: &StateFile) -> DaloResult<()> {
if !paths.root.exists() {
return Err(DaloError::StoreNotInitialized {
path: paths.root.clone(),
});
}
write_toml_atomic(&paths.state_file, state)
}
#[derive(Debug)]
pub struct StoreLock {
_file: fs::File,
}
#[derive(Debug)]
pub struct CatalogLock {
_file: fs::File,
}
impl CatalogLock {
pub fn acquire_shared(paths: &StorePaths) -> DaloResult<Self> {
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&paths.catalog_lock_file)?;
file.lock_shared()?;
Ok(Self { _file: file })
}
pub fn acquire_exclusive(paths: &StorePaths) -> DaloResult<Self> {
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&paths.catalog_lock_file)?;
file.lock()?;
Ok(Self { _file: file })
}
}
impl StoreLock {
pub fn acquire(paths: &StorePaths) -> DaloResult<Self> {
let delays = [
Duration::from_millis(0),
Duration::from_millis(100),
Duration::from_millis(250),
Duration::from_millis(500),
Duration::from_secs(1),
Duration::from_secs(2),
];
Self::acquire_with_delays(paths, &delays)
}
pub fn try_acquire(paths: &StorePaths) -> DaloResult<Option<Self>> {
Self::try_acquire_once(paths)
}
fn acquire_with_delays(paths: &StorePaths, delays: &[Duration]) -> DaloResult<Self> {
for delay in delays {
if !delay.is_zero() {
thread::sleep(*delay);
}
if let Some(lock) = Self::try_acquire_once(paths)? {
return Ok(lock);
}
}
Err(DaloError::StoreLocked {
path: paths.lock_guard_file.clone(),
})
}
fn try_acquire_once(paths: &StorePaths) -> DaloResult<Option<Self>> {
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&paths.lock_guard_file)?;
match file.try_lock() {
Ok(()) => {
file.set_len(0)?;
file.seek(SeekFrom::Start(0))?;
writeln!(file, "pid={}", std::process::id())?;
file.flush()?;
Ok(Some(Self { _file: file }))
}
Err(fs::TryLockError::WouldBlock) => Ok(None),
Err(fs::TryLockError::Error(error)) => Err(error.into()),
}
}
}
#[must_use]
pub fn store_lock_holder(paths: &StorePaths) -> Option<String> {
fs::read_to_string(&paths.lock_guard_file)
.ok()
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty())
}
fn ensure_dir(path: &Path, dry_run: bool) -> DaloResult<InitOperation> {
let status = if path.exists() {
if !path.is_dir() {
return Err(DaloError::InvalidStorePath {
path: path.to_path_buf(),
reason: "expected a directory".to_owned(),
});
}
InitOperationStatus::Existing
} else if dry_run {
InitOperationStatus::Planned
} else {
fs::create_dir_all(path)?;
InitOperationStatus::Created
};
Ok(InitOperation {
action: InitOperationAction::CreateDir,
path: path.to_path_buf(),
status,
})
}
fn ensure_toml_file<T>(path: &Path, value: &T, dry_run: bool) -> DaloResult<InitOperation>
where
T: Serialize,
{
let status = if path.exists() {
if !path.is_file() {
return Err(DaloError::InvalidStorePath {
path: path.to_path_buf(),
reason: "expected a file".to_owned(),
});
}
InitOperationStatus::Existing
} else if dry_run {
InitOperationStatus::Planned
} else {
write_toml_atomic(path, value)?;
InitOperationStatus::Created
};
Ok(InitOperation {
action: InitOperationAction::WriteFile,
path: path.to_path_buf(),
status,
})
}
fn ensure_state_file(paths: &StorePaths, dry_run: bool) -> DaloResult<InitOperation> {
let status = if paths.state_file.exists() {
if !paths.state_file.is_file() {
return Err(DaloError::InvalidStorePath {
path: paths.state_file.clone(),
reason: "expected a file".to_owned(),
});
}
match read_state(paths) {
Ok(_) => InitOperationStatus::Existing,
Err(DaloError::CorruptState { .. }) if dry_run => InitOperationStatus::Planned,
Err(DaloError::CorruptState { .. }) => {
backup_corrupt_file(&paths.state_file)?;
write_toml_atomic(&paths.state_file, &StateFile::empty())?;
InitOperationStatus::Repaired
}
Err(error) => return Err(error),
}
} else if dry_run {
InitOperationStatus::Planned
} else {
write_toml_atomic(&paths.state_file, &StateFile::empty())?;
InitOperationStatus::Created
};
Ok(InitOperation {
action: InitOperationAction::WriteFile,
path: paths.state_file.clone(),
status,
})
}
pub(crate) fn backup_corrupt_file(path: &Path) -> DaloResult<PathBuf> {
let Some(parent) = path.parent() else {
return Err(DaloError::InvalidStorePath {
path: path.to_path_buf(),
reason: "file has no parent directory".to_owned(),
});
};
let Some(file_name) = path.file_name() else {
return Err(DaloError::InvalidStorePath {
path: path.to_path_buf(),
reason: "file has no file name".to_owned(),
});
};
let stamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let mut backup_name = file_name.to_os_string();
backup_name.push(format!(
".corrupt-{}-{}",
stamp.as_secs(),
stamp.subsec_nanos()
));
let backup_path = parent.join(backup_name);
fs::rename(path, &backup_path)?;
sync_directory(parent)?;
Ok(backup_path)
}
fn ensure_git_repo(path: &Path, dry_run: bool) -> DaloResult<InitOperation> {
let git_dir = path.join(".git");
let status = if git_dir.exists() {
InitOperationStatus::Existing
} else if dry_run {
InitOperationStatus::Planned
} else {
git::init_repo(path)?;
InitOperationStatus::Created
};
Ok(InitOperation {
action: InitOperationAction::GitInit,
path: path.to_path_buf(),
status,
})
}
pub(crate) fn write_toml_atomic<T>(path: &Path, value: &T) -> DaloResult<()>
where
T: Serialize,
{
let Some(parent) = path.parent() else {
return Err(DaloError::InvalidStorePath {
path: path.to_path_buf(),
reason: "file has no parent directory".to_owned(),
});
};
let content = toml::to_string_pretty(value)?;
let mut temp_file = NamedTempFile::new_in(parent)?;
temp_file.write_all(content.as_bytes())?;
temp_file.flush()?;
temp_file.as_file().sync_all()?;
temp_file.persist(path).map_err(|error| error.error)?;
sync_directory(parent)?;
Ok(())
}
fn sync_directory(path: &Path) -> DaloResult<()> {
fs::File::open(path)?.sync_all()?;
Ok(())
}
fn validate_store_path(path: &Path) -> DaloResult<()> {
if path.as_os_str().is_empty() {
return Err(DaloError::InvalidStorePath {
path: path.to_path_buf(),
reason: "path is empty".to_owned(),
});
}
Ok(())
}
pub fn expand_user_path(path: &Path) -> DaloResult<PathBuf> {
if path == Path::new("~") {
return home_dir();
}
if let Ok(rest) = path.strip_prefix("~") {
return Ok(home_dir()?.join(rest));
}
Ok(path.to_path_buf())
}
fn home_dir() -> DaloResult<PathBuf> {
env::var_os("HOME")
.map(PathBuf::from)
.ok_or_else(|| DaloError::StorePath {
reason: "HOME is not set and no explicit store path was provided".to_owned(),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn init_store_should_create_expected_layout() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
let report = init_store(store_root.clone(), false).expect("init should succeed");
assert_eq!(report.store, store_root);
assert!(
report
.operations
.iter()
.all(|operation| { matches!(operation.status, InitOperationStatus::Created) })
);
assert!(store_root.join("config.toml").is_file());
assert!(store_root.join("lock.toml").is_file());
assert!(store_root.join("state.toml").is_file());
assert!(store_root.join("approvals.toml").is_file());
assert!(store_root.join("local/.git").is_dir());
assert!(store_root.join("local/skills").is_dir());
assert!(store_root.join("local/instructions").is_dir());
assert!(store_root.join("local/agents").is_dir());
assert!(store_root.join("sources").is_dir());
}
#[test]
fn init_store_should_not_write_during_dry_run() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
let report = init_store(store_root.clone(), true).expect("dry-run should succeed");
assert!(report.dry_run);
assert!(
report
.operations
.iter()
.all(|operation| { matches!(operation.status, InitOperationStatus::Planned) })
);
assert!(!store_root.exists());
}
#[test]
fn init_store_should_be_idempotent() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
init_store(store_root.clone(), false).expect("first init should succeed");
let report = init_store(store_root, false).expect("second init should succeed");
assert!(
report
.operations
.iter()
.all(|operation| { matches!(operation.status, InitOperationStatus::Existing) })
);
}
#[test]
fn read_state_should_rebuild_materialization_dirs_when_missing() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root);
let mut state = read_state(&paths).expect("state should be readable");
state.targets = vec![TargetState {
id: "generic".to_owned(),
path: PathBuf::from("/target"),
canonical_path: PathBuf::from("/target"),
enabled: true,
extra: Default::default(),
}];
state.materialization_dirs = Vec::new();
write_state(&paths, &state).expect("state should be written");
let loaded = read_state(&paths).expect("state should reload");
assert_eq!(loaded.materialization_dirs.len(), 1);
}
#[test]
fn read_state_should_fail_when_store_is_not_initialized() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let paths = StorePaths::new(temp_dir.path().join("missing-store"));
let error = read_state(&paths).expect_err("read should fail on uninitialized store");
assert!(matches!(error, DaloError::StoreNotInitialized { .. }));
}
#[test]
fn write_state_should_fail_when_store_root_is_absent() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let paths = StorePaths::new(temp_dir.path().join("missing-store"));
let error = write_state(&paths, &StateFile::empty())
.expect_err("write should fail when the store root is absent");
assert!(matches!(error, DaloError::StoreNotInitialized { .. }));
}
#[test]
fn read_state_should_report_actionable_corrupt_state() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root);
fs::write(&paths.state_file, "schema_version = ").expect("state should be corrupted");
let error = read_state(&paths).expect_err("corrupt state should fail");
assert!(matches!(error, DaloError::CorruptState { .. }));
assert!(error.to_string().contains("run `dalo init`"));
}
#[test]
fn read_state_should_tolerate_unknown_top_level_fields() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root.clone());
let mut content =
fs::read_to_string(&paths.state_file).expect("state should be readable as text");
content.push_str("\nfuture_additive_field = \"preserved by newer dalo\"\n");
fs::write(&paths.state_file, &content).expect("future state should be written");
let state = read_state(&paths).expect("unknown additive field should be tolerated");
write_state(&paths, &state).expect("unknown additive field should survive a rewrite");
let rewritten =
fs::read_to_string(&paths.state_file).expect("rewritten state should be readable");
let report = init_store(store_root, false).expect("init should not repair future state");
assert_eq!(state.schema_version, STATE_SCHEMA_VERSION);
assert!(report.operations.iter().any(|operation| {
operation.path == paths.state_file && operation.status == InitOperationStatus::Existing
}));
assert!(rewritten.contains("future_additive_field = \"preserved by newer dalo\""));
}
#[test]
fn read_state_should_tolerate_unknown_nested_fields() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
let target = temp_dir.path().join("target");
init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root);
let mut state = StateFile::empty();
state.targets.push(TargetState {
id: "generic".to_owned(),
path: target.clone(),
canonical_path: target,
enabled: true,
extra: Default::default(),
});
state
.rebuild_materialization_dirs()
.expect("materialization directories should rebuild");
write_state(&paths, &state).expect("state should be written");
let content = fs::read_to_string(&paths.state_file)
.expect("state should be readable")
.replace(
"enabled = true",
"enabled = true\nfuture_target_field = \"newer dalo metadata\"",
);
fs::write(&paths.state_file, content).expect("future nested field should be written");
let parsed = read_state(&paths).expect("unknown nested field should be tolerated");
write_state(&paths, &parsed).expect("unknown nested field should survive a rewrite");
let rewritten =
fs::read_to_string(&paths.state_file).expect("rewritten state should be readable");
assert_eq!(parsed.targets.len(), 1);
assert_eq!(parsed.targets[0].id, "generic");
assert!(rewritten.contains("future_target_field = \"newer dalo metadata\""));
}
#[test]
fn rebuild_materialization_dirs_should_preserve_extra_fields_when_target_moves() {
let mut state = StateFile::empty();
state.targets.push(TargetState {
id: "generic".to_owned(),
path: PathBuf::from("/old-target"),
canonical_path: PathBuf::from("/old-target"),
enabled: true,
extra: Default::default(),
});
state
.rebuild_materialization_dirs()
.expect("materialization directories should rebuild");
state.materialization_dirs[0].extra.insert(
"future_directory_field".to_owned(),
toml::Value::String("newer dalo metadata".to_owned()),
);
state.targets[0].path = PathBuf::from("/new-target");
state.targets[0].canonical_path = PathBuf::from("/new-target");
state
.rebuild_materialization_dirs()
.expect("moved materialization directory should rebuild");
assert_eq!(state.materialization_dirs[0].path, Path::new("/new-target"));
assert_eq!(
state.materialization_dirs[0]
.extra
.get("future_directory_field"),
Some(&toml::Value::String("newer dalo metadata".to_owned()))
);
}
#[test]
fn rebuild_materialization_dirs_should_reject_conflicting_extra_fields() {
let mut state = StateFile::empty();
state.targets = vec![
TargetState {
id: "first".to_owned(),
path: PathBuf::from("/first"),
canonical_path: PathBuf::from("/first"),
enabled: true,
extra: Default::default(),
},
TargetState {
id: "second".to_owned(),
path: PathBuf::from("/second"),
canonical_path: PathBuf::from("/second"),
enabled: true,
extra: Default::default(),
},
];
state
.rebuild_materialization_dirs()
.expect("separate materialization directories should rebuild");
state.materialization_dirs[0].extra.insert(
"future_directory_field".to_owned(),
toml::Value::String("first value".to_owned()),
);
state.materialization_dirs[1].extra.insert(
"future_directory_field".to_owned(),
toml::Value::String("second value".to_owned()),
);
let previous_dirs = state.materialization_dirs.clone();
state.targets[1].path = PathBuf::from("/first");
state.targets[1].canonical_path = PathBuf::from("/first");
let error = state
.rebuild_materialization_dirs()
.expect_err("conflicting opaque metadata should block a lossy merge");
assert!(matches!(
error,
DaloError::StateMetadataConflict { path, field }
if path == Path::new("/first") && field == "future_directory_field"
));
assert_eq!(state.materialization_dirs, previous_dirs);
}
#[test]
fn read_state_should_migrate_legacy_protected_path_to_target_slot() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
let target = temp_dir.path().join("target");
init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root);
let mut state = StateFile::empty();
state.targets.push(TargetState {
id: "generic".to_owned(),
path: target.clone(),
canonical_path: target.clone(),
enabled: true,
extra: Default::default(),
});
state
.rebuild_materialization_dirs()
.expect("materialization directories should rebuild");
state.protected_skills.push(ProtectedSkillState {
target_id: String::new(),
slot_name: "review".to_owned(),
path: Some(target.join("review")),
extra: Default::default(),
});
write_state(&paths, &state).expect("legacy state should be written");
let migrated = read_state(&paths).expect("legacy protection should migrate");
assert_eq!(migrated.protected_skills.len(), 1);
assert_eq!(migrated.protected_skills[0].target_id, "generic");
assert_eq!(migrated.protected_skills[0].slot_name, "review");
assert!(migrated.protected_skills[0].path.is_none());
}
#[test]
fn init_store_should_repair_corrupt_state_file() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root.clone());
fs::write(&paths.state_file, "schema_version = ").expect("state should be corrupted");
let report = init_store(store_root.clone(), false).expect("init should repair state");
assert!(report.operations.iter().any(|operation| {
operation.path == paths.state_file && operation.status == InitOperationStatus::Repaired
}));
assert_eq!(
read_state(&paths).expect("repaired state should parse"),
StateFile::empty()
);
let backups = fs::read_dir(&store_root)
.expect("store dir should be readable")
.filter_map(Result::ok)
.filter(|entry| {
entry
.file_name()
.to_string_lossy()
.starts_with("state.toml.corrupt-")
})
.collect::<Vec<_>>();
assert_eq!(backups.len(), 1);
assert_eq!(
fs::read_to_string(backups[0].path()).expect("backup should be readable"),
"schema_version = "
);
}
#[test]
fn read_config_should_reject_duplicate_source_ids() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root);
fs::write(
&paths.config_file,
"version = 1\n\n[settings]\nautosync = false\n\n\
[[sources]]\nid = \"company\"\nkind = \"team\"\npath = \"a\"\npriority = 10\nenabled = true\ntrusted = true\n\n\
[[sources]]\nid = \"company\"\nkind = \"team\"\npath = \"b\"\npriority = 20\nenabled = true\ntrusted = true\n",
)
.expect("config should be overwritten");
let error = read_config(&paths).expect_err("duplicate source ids should be rejected");
assert!(matches!(error, DaloError::FileParse { .. }));
}
#[test]
fn read_config_should_reject_unknown_fields() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root);
fs::write(
&paths.config_file,
"version = 1\n\n[settings]\nautosync = false\n\n\
[[sources]]\nid = \"company\"\nkind = \"team\"\npath = \"a\"\npriority = 10\nenabled = true\ntrusted = true\nseleciton = []\n",
)
.expect("config should be overwritten");
let error = read_config(&paths).expect_err("unknown fields should be rejected");
assert!(matches!(error, DaloError::FileParse { .. }));
assert!(error.to_string().contains("unknown field"));
assert!(error.to_string().contains("seleciton"));
}
#[test]
fn read_store_files_should_reject_truncated_toml() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root);
fs::write(&paths.config_file, "version = ").expect("config should be truncated");
let config_error = read_config(&paths).expect_err("truncated config should fail");
assert!(matches!(config_error, DaloError::FileParse { .. }));
fs::write(&paths.lock_file, "schema_version = ").expect("lock should be truncated");
let lock_error = read_user_lock(&paths).expect_err("truncated lock should fail");
assert!(matches!(lock_error, DaloError::FileParse { .. }));
fs::write(&paths.approvals_file, "schema_version = ")
.expect("approvals should be truncated");
let approvals_error = read_approvals(&paths).expect_err("truncated approvals should fail");
assert!(matches!(approvals_error, DaloError::FileParse { .. }));
}
#[test]
fn init_store_should_not_clobber_corrupt_config_lock_or_approvals() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root.clone());
fs::write(&paths.config_file, "version = ").expect("config should be truncated");
fs::write(&paths.lock_file, "schema_version = ").expect("lock should be truncated");
fs::write(&paths.approvals_file, "schema_version = ")
.expect("approvals should be truncated");
let report =
init_store(store_root, false).expect("init should leave non-state TOML files alone");
assert_eq!(report.validation_warnings.len(), 3);
assert!(
report
.validation_warnings
.iter()
.any(|warning| warning.path == paths.config_file)
);
assert!(
report
.validation_warnings
.iter()
.any(|warning| warning.path == paths.lock_file)
);
assert!(
report
.validation_warnings
.iter()
.any(|warning| warning.path == paths.approvals_file)
);
assert_eq!(
fs::read_to_string(&paths.config_file).expect("config should be readable"),
"version = "
);
assert_eq!(
fs::read_to_string(&paths.lock_file).expect("lock should be readable"),
"schema_version = "
);
assert_eq!(
fs::read_to_string(&paths.approvals_file).expect("approvals should be readable"),
"schema_version = "
);
}
#[test]
fn read_user_lock_should_reject_unsupported_schema_version() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root);
fs::write(&paths.lock_file, "schema_version = 999\n").expect("lock should be overwritten");
let error = read_user_lock(&paths).expect_err("read should reject the unsupported schema");
assert!(matches!(error, DaloError::UnsupportedSchema { .. }));
}
#[test]
fn read_user_lock_should_migrate_version_two_plugin_lock_in_memory() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root);
fs::write(
&paths.lock_file,
"schema_version = 2\n\n[[plugins]]\nsource_ref = \"local:demo\"\nslot_name = \"demo\"\npackage_hash = \"package\"\nclosure_hash = \"closure\"\norigins = []\npolicies = []\nstate = \"selected\"\nmembers = []\nblocking_reasons = []\n",
)
.expect("version two lock should be written");
let lock = read_user_lock(&paths).expect("version two lock should migrate");
assert_eq!(lock.schema_version, USER_LOCK_SCHEMA_VERSION);
assert_eq!(lock.plugins.len(), 1);
assert!(lock.plugins[0].dependencies.is_empty());
}
#[test]
fn read_state_should_reject_unsupported_schema_version() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root);
let mut state = StateFile::empty();
state.schema_version = 999;
write_state(&paths, &state).expect("state should be overwritten");
let error = read_state(&paths).expect_err("read should reject the unsupported schema");
assert!(matches!(error, DaloError::UnsupportedSchema { .. }));
}
#[test]
fn read_approvals_should_reject_unsupported_schema_version() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root);
let mut approvals = ApprovalsFile::empty();
approvals.schema_version = 999;
write_approvals(&paths, &approvals).expect("approvals should be overwritten");
let error = read_approvals(&paths).expect_err("read should reject the unsupported schema");
assert!(matches!(error, DaloError::UnsupportedSchema { .. }));
}
#[test]
fn read_config_should_reject_unsupported_schema_version() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let root = temp_dir.path().join("store");
init_store(root.clone(), false).expect("store should initialize");
let paths = StorePaths::new(root);
let mut config = read_config(&paths).expect("config should be readable");
config.version = 999;
write_config(&paths, &config).expect("config should be writable");
assert!(matches!(
read_config(&paths),
Err(DaloError::UnsupportedSchema { version: 999, .. })
));
}
#[test]
fn init_store_should_reject_empty_store_path() {
let error =
init_store(PathBuf::new(), false).expect_err("init should reject an empty path");
assert!(matches!(error, DaloError::InvalidStorePath { .. }));
}
#[test]
fn expand_user_path_should_not_lossily_rewrite_non_utf8_paths() {
use std::os::unix::ffi::OsStringExt;
let non_utf8 = PathBuf::from(OsString::from_vec(vec![0xff, b's', b't', b'o', b'r', b'e']));
assert_eq!(
expand_user_path(&non_utf8).expect("path should pass through"),
non_utf8
);
}
#[test]
fn store_lock_should_fail_when_already_held() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root);
let _lock = StoreLock::acquire(&paths).expect("first lock should be acquired");
let error = StoreLock::acquire_with_delays(&paths, &[Duration::from_millis(0)])
.expect_err("second lock should fail");
assert!(matches!(error, DaloError::StoreLocked { .. }));
}
#[test]
fn store_lock_try_acquire_should_return_immediately_when_held() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let paths = StorePaths::new(temp_dir.path().to_path_buf());
fs::create_dir_all(&paths.root).expect("store root should exist");
let _lock = StoreLock::acquire(&paths).expect("first lock should be acquired");
let started = std::time::Instant::now();
let second = StoreLock::try_acquire(&paths).expect("try acquire should not error");
assert!(second.is_none());
assert!(started.elapsed() < Duration::from_millis(50));
assert!(store_lock_holder(&paths).is_some_and(|holder| holder.starts_with("pid=")));
}
#[test]
fn store_lock_should_release_on_drop() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root);
let lock = StoreLock::acquire(&paths).expect("first lock should be acquired");
drop(lock);
let reacquired = StoreLock::acquire_with_delays(
&paths,
&[
Duration::from_millis(0),
Duration::from_millis(50),
Duration::from_millis(200),
Duration::from_millis(750),
Duration::from_secs(1),
],
)
.expect("the dropped guard should release the store lock");
assert!(paths.lock_guard_file.is_file());
assert!(
StoreLock::try_acquire(&paths)
.expect("try acquire should not error")
.is_none()
);
drop(reacquired);
}
#[test]
fn store_lock_should_ignore_stale_pid_metadata_when_file_is_unlocked() {
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
init_store(store_root.clone(), false).expect("init should succeed");
let paths = StorePaths::new(store_root);
fs::write(
&paths.lock_guard_file,
format!("pid={}\n", std::process::id()),
)
.expect("stale lock metadata should be written");
let _lock = StoreLock::acquire_with_delays(&paths, &[Duration::from_millis(0)])
.expect("unlocked stale metadata should not block acquisition");
assert!(paths.lock_guard_file.is_file());
}
#[test]
fn store_lock_should_grant_to_exactly_one_thread_for_unlocked_stale_file() {
use std::sync::Arc;
use std::sync::Barrier;
let temp_dir = tempfile::tempdir().expect("tempdir should be created");
let store_root = temp_dir.path().join("store");
init_store(store_root.clone(), false).expect("init should succeed");
let paths = Arc::new(StorePaths::new(store_root));
fs::write(&paths.lock_guard_file, "pid=2147480000\n")
.expect("stale lock metadata should be written");
let delays = Arc::new([Duration::from_millis(0)]);
let barrier = Arc::new(Barrier::new(2));
let mut handles = Vec::new();
for _ in 0..2 {
let paths = Arc::clone(&paths);
let delays = Arc::clone(&delays);
let barrier = Arc::clone(&barrier);
handles.push(thread::spawn(move || {
barrier.wait();
StoreLock::acquire_with_delays(&paths, delays.as_ref())
}));
}
let mut outcomes = Vec::new();
for handle in handles {
outcomes.push(handle.join().expect("thread should not panic"));
}
let successes = outcomes.iter().filter(|outcome| outcome.is_ok()).count();
assert_eq!(successes, 1);
}
#[test]
fn dalo_command_should_only_prefix_nondefault_stores() {
let default_store = resolve_store_path(None).expect("default store should resolve");
let custom_store = Path::new("/tmp/dalo user's store");
assert_eq!(dalo_command(&default_store, "sync"), "dalo sync");
assert_eq!(
dalo_command(custom_store, "sync"),
"dalo --store '/tmp/dalo user'\"'\"'s store' sync"
);
}
#[test]
fn contextualize_dalo_commands_should_preserve_prose_paths_and_explicit_flags() {
let custom_store = Path::new("/tmp/custom store");
let message = "dalo store is unavailable at `/tmp/dalo sync`; run `dalo sync` or `dalo --store '/tmp/old' init`";
assert_eq!(
contextualize_dalo_commands(custom_store, message),
"dalo store is unavailable at `/tmp/dalo sync`; run `dalo --store '/tmp/custom store' sync` or `dalo --store '/tmp/old' init`"
);
}
}