use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::backend::MemBackend;
use crate::storage::{ArchiveBackend, FilesystemBackend, InMemoryBackend};
use crate::workspace::{
McpSection, Mount, MountCapability, MountLifecycle, MountStorage, MutationsSection, Workspace,
WorkspaceSettings,
};
pub const WORKSPACE_STORE_DIR: &str = ".memstead";
#[derive(Debug, thiserror::Error)]
pub enum StoreError {
#[error("workspace store not found at {path} — run `memstead mem-repo init` first")]
NotInitialised { path: PathBuf },
#[error(
"workspace store io error at {path}: {source} — no memstead command repairs this; \
check filesystem permissions and disk state"
)]
Io {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error(
"workspace store parse error at {path}: {message} — no memstead command repairs this; \
fix the named file by hand or restore it from version control"
)]
Parse { path: PathBuf, message: String },
#[error(
"workspace store format mismatch at {path}: expected {expected}, found {found} — \
no memstead command repairs this; use an engine version whose format matches the file"
)]
FormatMismatch {
path: PathBuf,
expected: String,
found: String,
},
#[error(
"pre-rename workspace layout at {path} (found format {found}): migrate the workspace \
state in place — rewrite mounts.json to memstead-mounts-3 (record field `mem`, storage \
paths under mem-repo/), workspace.toml to memstead-git-branch-2 (tables `mem_management`, \
`cross_mem_links`), rename the gitdir container to mem-repo/, and move the metadata \
branch tree to mems/ — then retry"
)]
LegacyLayout { path: PathBuf, found: String },
#[error(
"retired binding format at {path}: this file is a gen-2 (version-less) or v1 binding, \
a format this engine no longer converts; re-author the binding with \
`memstead projection init`"
)]
LegacyProjectionStore { path: PathBuf },
#[error(
"unsupported binding format version {version} at {path}: this engine understands v2 (version 2)"
)]
UnknownBindingVersion { path: PathBuf, version: i64 },
#[error("workspace store error: {0}")]
Other(String),
}
impl StoreError {
pub fn code(&self) -> &'static str {
match self {
StoreError::NotInitialised { .. } => "WORKSPACE_NOT_INITIALISED",
StoreError::Io { .. } => "WORKSPACE_STORE_IO",
StoreError::Parse { .. } => "WORKSPACE_STORE_PARSE",
StoreError::FormatMismatch { .. } => "WORKSPACE_STORE_FORMAT_MISMATCH",
StoreError::LegacyLayout { .. } => "LEGACY_WORKSPACE_LAYOUT",
StoreError::LegacyProjectionStore { .. } => "PROJECTION_STORE_LEGACY",
StoreError::UnknownBindingVersion { .. } => "UNKNOWN_BINDING_VERSION",
StoreError::Other(_) => "WORKSPACE_STORE_ERROR",
}
}
}
pub trait WorkspaceStoreAdapter: Send + Sync {
fn load(&self, workspace_root: &Path) -> Result<Workspace, StoreError>;
fn save_state(&self, workspace_root: &Path, workspace: &Workspace) -> Result<(), StoreError>;
fn read_state_bytes(&self, workspace_root: &Path) -> Result<Option<Vec<u8>>, StoreError>;
fn parse_state_bytes(
&self,
workspace_root: &Path,
bytes: &[u8],
) -> Result<Vec<Mount>, StoreError>;
fn save_state_cas(
&self,
workspace_root: &Path,
workspace: &Workspace,
expected: Option<&[u8]>,
) -> Result<bool, StoreError>;
}
#[derive(Debug, Default, Clone, Copy)]
pub struct FileWorkspaceStore;
impl FileWorkspaceStore {
pub fn new() -> Self {
Self
}
pub fn workspace_toml_path(workspace_root: &Path) -> PathBuf {
workspace_root
.join(WORKSPACE_STORE_DIR)
.join("workspace.toml")
}
pub fn mounts_json_path(workspace_root: &Path) -> PathBuf {
workspace_root
.join(WORKSPACE_STORE_DIR)
.join("state")
.join("mounts.json")
}
}
const WORKSPACE_TOML_FORMAT: &str = "memstead-git-branch-2";
const WORKSPACE_TOML_FORMAT_LEGACY: &str = "memstead-git-branch-1";
const MOUNTS_JSON_FORMAT_V3: &str = "memstead-mounts-3";
const MOUNTS_JSON_FORMAT_V4: &str = "memstead-mounts-4";
static MEM_CACHE_DIR_PROVIDER: std::sync::OnceLock<fn() -> PathBuf> = std::sync::OnceLock::new();
const NO_ARCHIVE_CACHE_DIR: &str = "no-archive-cache";
pub fn set_mem_cache_dir_provider(provider: fn() -> PathBuf) {
let _ = MEM_CACHE_DIR_PROVIDER.set(provider);
}
pub fn registered_mem_cache_dir() -> Option<PathBuf> {
MEM_CACHE_DIR_PROVIDER.get().map(|f| f())
}
pub fn is_cache_file_name(mem: &str, file: &str) -> bool {
file.strip_prefix(&format!("{mem}-"))
.and_then(|r| r.strip_suffix(".mem"))
.is_some_and(|key| {
key.len() == 16
&& key
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
})
}
pub fn installed_archive_file(path: &Path) -> Option<String> {
cached_archive_file(path).or_else(|| {
let parent = path.parent()?;
let is_placeholder = parent
.file_name()
.is_some_and(|n| n == NO_ARCHIVE_CACHE_DIR)
&& parent
.parent()
.and_then(|p| p.file_name())
.is_some_and(|n| n == WORKSPACE_STORE_DIR);
is_placeholder
.then(|| path.file_name().map(|n| n.to_string_lossy().into_owned()))
.flatten()
})
}
pub fn cached_archive_file(path: &Path) -> Option<String> {
let dir = registered_mem_cache_dir()?;
let parent = path.parent()?;
let same = parent == dir
|| match (std::fs::canonicalize(parent), std::fs::canonicalize(&dir)) {
(Ok(a), Ok(b)) => a == b,
_ => false,
};
if !same {
return None;
}
path.file_name().map(|n| n.to_string_lossy().into_owned())
}
const MOUNTS_JSON_FORMAT_LEGACY: [&str; 2] = ["memstead-mounts-1", "memstead-mounts-2"];
#[derive(Deserialize)]
struct MountsFormatProbe {
format: String,
}
fn check_workspace_toml_format(format: &str, toml_path: &Path) -> Result<(), StoreError> {
if format == WORKSPACE_TOML_FORMAT {
return Ok(());
}
if format == WORKSPACE_TOML_FORMAT_LEGACY {
return Err(StoreError::LegacyLayout {
path: toml_path.to_path_buf(),
found: format.to_string(),
});
}
Err(StoreError::FormatMismatch {
path: toml_path.to_path_buf(),
expected: WORKSPACE_TOML_FORMAT.to_string(),
found: format.to_string(),
})
}
fn absolutize_mount_path(value: PathBuf, workspace_root: &Path) -> PathBuf {
if value.is_absolute() {
value
} else {
workspace_root.join(value)
}
}
fn relativize_mount_path(value: &Path, workspace_root: &Path) -> PathBuf {
match value.strip_prefix(workspace_root) {
Ok(rel) => rel.to_path_buf(),
Err(_) => value.to_path_buf(),
}
}
pub fn is_workspace_root(dir: &Path) -> bool {
FileWorkspaceStore::workspace_toml_path(dir).is_file()
}
pub fn is_mem_repo_shaped(workspace_root: &Path) -> bool {
workspace_root.join("mem-repo").join(".git").is_dir()
}
pub fn workspace_shape_label(workspace_root: &Path) -> &'static str {
if is_mem_repo_shaped(workspace_root) {
"mem-repo"
} else {
"filesystem-mem"
}
}
impl WorkspaceStoreAdapter for FileWorkspaceStore {
fn load(&self, workspace_root: &Path) -> Result<Workspace, StoreError> {
let memstead_dir = workspace_root.join(WORKSPACE_STORE_DIR);
if !memstead_dir.is_dir() {
return Err(StoreError::NotInitialised {
path: workspace_root.to_path_buf(),
});
}
let toml_path = Self::workspace_toml_path(workspace_root);
let toml_text = std::fs::read_to_string(&toml_path).map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
StoreError::NotInitialised {
path: workspace_root.to_path_buf(),
}
} else {
StoreError::Io {
path: toml_path.clone(),
source: e,
}
}
})?;
let toml_doc: WorkspaceTomlDoc =
toml::from_str(&toml_text).map_err(|e| StoreError::Parse {
path: toml_path.clone(),
message: e.to_string(),
})?;
check_workspace_toml_format(&toml_doc.format, &toml_path)?;
let mounts_path = Self::mounts_json_path(workspace_root);
let mounts: Vec<Mount> = match std::fs::read_to_string(&mounts_path) {
Ok(text) => parse_mounts_text(&text, &mounts_path, workspace_root)?,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
Err(e) => {
return Err(StoreError::Io {
path: mounts_path,
source: e,
});
}
};
warn_if_legacy_schemas_dir(toml_doc.schemas_dir.as_deref());
let settings = build_settings(
toml_doc.mem_management,
toml_doc.cross_mem_links,
toml_doc.mcp,
toml_doc.mutations,
toml_doc.plugin,
)?;
Ok(Workspace { mounts, settings })
}
fn save_state(&self, workspace_root: &Path, workspace: &Workspace) -> Result<(), StoreError> {
let mounts_path = Self::mounts_json_path(workspace_root);
ensure_state_dir(&mounts_path)?;
let text = render_mounts_text(workspace, workspace_root, &mounts_path)?;
std::fs::write(&mounts_path, text).map_err(|e| StoreError::Io {
path: mounts_path,
source: e,
})?;
Ok(())
}
fn read_state_bytes(&self, workspace_root: &Path) -> Result<Option<Vec<u8>>, StoreError> {
let mounts_path = Self::mounts_json_path(workspace_root);
match std::fs::read(&mounts_path) {
Ok(b) => Ok(Some(b)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(StoreError::Io {
path: mounts_path,
source: e,
}),
}
}
fn parse_state_bytes(
&self,
workspace_root: &Path,
bytes: &[u8],
) -> Result<Vec<Mount>, StoreError> {
let mounts_path = Self::mounts_json_path(workspace_root);
let text = std::str::from_utf8(bytes).map_err(|e| StoreError::Parse {
path: mounts_path.clone(),
message: e.to_string(),
})?;
parse_mounts_text(text, &mounts_path, workspace_root)
}
fn save_state_cas(
&self,
workspace_root: &Path,
workspace: &Workspace,
expected: Option<&[u8]>,
) -> Result<bool, StoreError> {
let mounts_path = Self::mounts_json_path(workspace_root);
ensure_state_dir(&mounts_path)?;
let text = render_mounts_text(workspace, workspace_root, &mounts_path)?;
let lock_path = mounts_path.with_extension("json.lock");
let mut held = None;
for attempt in 0..50 {
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&lock_path)
{
Ok(f) => {
held = Some(f);
break;
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
if attempt == 49 {
let _ = std::fs::remove_file(&lock_path);
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
Err(e) => {
return Err(StoreError::Io {
path: lock_path,
source: e,
});
}
}
}
let _lock = match held {
Some(f) => f,
None => std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&lock_path)
.map_err(|e| StoreError::Io {
path: lock_path.clone(),
source: e,
})?,
};
let release = || {
let _ = std::fs::remove_file(&lock_path);
};
let current = match std::fs::read(&mounts_path) {
Ok(b) => Some(b),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => {
release();
return Err(StoreError::Io {
path: mounts_path,
source: e,
});
}
};
if current.as_deref() != expected {
release();
return Ok(false);
}
let result = std::fs::write(&mounts_path, text).map_err(|e| StoreError::Io {
path: mounts_path,
source: e,
});
release();
result.map(|_| true)
}
}
fn ensure_state_dir(mounts_path: &Path) -> Result<(), StoreError> {
if let Some(parent) = mounts_path.parent() {
std::fs::create_dir_all(parent).map_err(|e| StoreError::Io {
path: parent.to_path_buf(),
source: e,
})?;
}
Ok(())
}
fn render_mounts_text(
workspace: &Workspace,
workspace_root: &Path,
mounts_path: &Path,
) -> Result<String, StoreError> {
let mounts: Vec<MountWire> = workspace
.mounts
.iter()
.map(|m| MountWire::from_mount(m, workspace_root))
.collect();
let format = if mounts
.iter()
.any(|m| matches!(m.storage, MountStorageWire::CachedArchive { .. }))
{
MOUNTS_JSON_FORMAT_V4
} else {
MOUNTS_JSON_FORMAT_V3
};
let doc = MountsJsonDoc {
format: format.to_string(),
mounts,
};
serde_json::to_string_pretty(&doc).map_err(|e| StoreError::Parse {
path: mounts_path.to_path_buf(),
message: e.to_string(),
})
}
fn parse_mounts_text(
text: &str,
mounts_path: &Path,
workspace_root: &Path,
) -> Result<Vec<Mount>, StoreError> {
let probe: MountsFormatProbe = serde_json::from_str(text).map_err(|e| StoreError::Parse {
path: mounts_path.to_path_buf(),
message: e.to_string(),
})?;
if MOUNTS_JSON_FORMAT_LEGACY.contains(&probe.format.as_str()) {
return Err(StoreError::LegacyLayout {
path: mounts_path.to_path_buf(),
found: probe.format,
});
}
if probe.format != MOUNTS_JSON_FORMAT_V3 && probe.format != MOUNTS_JSON_FORMAT_V4 {
return Err(StoreError::FormatMismatch {
path: mounts_path.to_path_buf(),
expected: MOUNTS_JSON_FORMAT_V4.to_string(),
found: probe.format,
});
}
let doc: MountsJsonDoc = serde_json::from_str(text).map_err(|e| StoreError::Parse {
path: mounts_path.to_path_buf(),
message: e.to_string(),
})?;
Ok(doc
.mounts
.into_iter()
.map(|w| w.into_mount(workspace_root))
.collect())
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct WorkspaceTomlDoc {
format: String,
#[serde(default)]
persistence_adapter: PersistenceAdapterDecl,
#[serde(default)]
mem_management: MemManagementWire,
#[serde(default)]
cross_mem_links: toml::Table,
#[serde(default)]
schemas_dir: Option<std::path::PathBuf>,
#[serde(default)]
mcp: McpSection,
#[serde(default)]
mutations: MutationsSection,
#[serde(default)]
plugin: std::collections::HashMap<String, toml::Table>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
struct MemManagementWire {
#[serde(default)]
create: Vec<CreateRuleWire>,
#[serde(default)]
delete: Vec<DeleteRuleWire>,
}
#[derive(Debug, Serialize, Deserialize)]
struct CreateRuleWire {
pattern: String,
#[serde(default)]
schemas: Vec<String>,
#[serde(default)]
default_cross_links: Option<toml::Value>,
}
#[derive(Debug, Serialize, Deserialize)]
struct DeleteRuleWire {
pattern: String,
}
pub fn parse_workspace_settings(
workspace_root: &Path,
) -> Result<crate::workspace::WorkspaceSettings, StoreError> {
let memstead_dir = workspace_root.join(WORKSPACE_STORE_DIR);
if !memstead_dir.is_dir() {
return Err(StoreError::NotInitialised {
path: workspace_root.to_path_buf(),
});
}
let toml_path = FileWorkspaceStore::workspace_toml_path(workspace_root);
let toml_text = std::fs::read_to_string(&toml_path).map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
StoreError::NotInitialised {
path: workspace_root.to_path_buf(),
}
} else {
StoreError::Io {
path: toml_path.clone(),
source: e,
}
}
})?;
let toml_doc: WorkspaceTomlDoc = toml::from_str(&toml_text).map_err(|e| StoreError::Parse {
path: toml_path.clone(),
message: e.to_string(),
})?;
check_workspace_toml_format(&toml_doc.format, &toml_path)?;
warn_if_legacy_schemas_dir(toml_doc.schemas_dir.as_deref());
build_settings(
toml_doc.mem_management,
toml_doc.cross_mem_links,
toml_doc.mcp,
toml_doc.mutations,
toml_doc.plugin,
)
}
fn build_settings(
vm: MemManagementWire,
cross_mem_links_raw: toml::Table,
mcp: McpSection,
mutations: MutationsSection,
plugin: std::collections::HashMap<String, toml::Table>,
) -> Result<WorkspaceSettings, StoreError> {
let mut create_rules = Vec::with_capacity(vm.create.len());
for r in vm.create {
let default_cross_links = match r.default_cross_links {
None => None,
Some(value) => {
let location = format!(
"[[mem_management.create]] pattern={}.default_cross_links",
r.pattern
);
Some(parse_cross_link_value(&location, &value)?)
}
};
create_rules.push(crate::workspace::CreateRuleSetting {
pattern: r.pattern,
schemas: r.schemas,
default_cross_links,
});
}
let mut cross_mem_links = std::collections::BTreeMap::new();
for (mem, value) in &cross_mem_links_raw {
let location = format!("[cross_mem_links].{mem}");
let parsed = parse_cross_link_value(&location, value)?;
cross_mem_links.insert(mem.clone(), parsed);
}
Ok(WorkspaceSettings {
mem_create_rules: create_rules,
mem_delete_rules: vm
.delete
.into_iter()
.map(|r| crate::workspace::DeleteRuleSetting { pattern: r.pattern })
.collect(),
cross_mem_links,
mcp,
mutations,
plugin,
})
}
fn warn_if_legacy_schemas_dir(schemas_dir: Option<&std::path::Path>) {
if let Some(dir) = schemas_dir {
tracing::warn!(
"`schemas_dir` (= {:?}) in workspace.toml is retired and ignored — \
authored schemas are read from the fixed `<workspace>/.memstead/schemas/`. \
Remove the key to silence this warning.",
dir
);
}
}
fn parse_cross_link_value(
location: &str,
value: &toml::Value,
) -> Result<memstead_schema::workspace_config::CrossLinkValue, StoreError> {
memstead_schema::workspace_config::CrossLinkValue::parse_toml(location, value).map_err(|e| {
StoreError::Parse {
path: std::path::PathBuf::from("workspace.toml"),
message: e.to_string(),
}
})
}
#[derive(Debug, Serialize, Deserialize)]
struct PersistenceAdapterDecl {
name: String,
}
impl Default for PersistenceAdapterDecl {
fn default() -> Self {
Self {
name: "file-two-layer".to_string(),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
struct MountsJsonDoc {
format: String,
mounts: Vec<MountWire>,
}
#[derive(Debug, Serialize, Deserialize)]
struct MountWire {
mem: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
schema: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
migration_target: Option<String>,
storage: MountStorageWire,
capability: CapabilityWire,
lifecycle: LifecycleWire,
cross_linkable: bool,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "kebab-case")]
enum MountStorageWire {
Folder {
path: PathBuf,
},
GitBranch {
gitdir: PathBuf,
branch: String,
},
Archive {
path: PathBuf,
},
CachedArchive {
file: String,
},
InMemory,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
enum CapabilityWire {
ReadOnly,
Write,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
enum LifecycleWire {
Eager,
Lazy,
}
impl MountWire {
fn from_mount(m: &Mount, workspace_root: &Path) -> Self {
Self {
mem: m.mem.clone(),
schema: m.schema.as_ref().map(|s| s.to_string()),
migration_target: m.migration_target.as_ref().map(|t| t.to_string()),
storage: match &m.storage {
MountStorage::Folder { path } => MountStorageWire::Folder {
path: relativize_mount_path(path, workspace_root),
},
MountStorage::GitBranch { gitdir, branch } => MountStorageWire::GitBranch {
gitdir: relativize_mount_path(gitdir, workspace_root),
branch: branch.clone(),
},
MountStorage::Archive { path } => match cached_archive_file(path).or_else(|| {
let placeholder = workspace_root
.join(WORKSPACE_STORE_DIR)
.join(NO_ARCHIVE_CACHE_DIR);
(path.parent() == Some(placeholder.as_path()))
.then(|| path.file_name().map(|n| n.to_string_lossy().into_owned()))
.flatten()
}) {
Some(file) => MountStorageWire::CachedArchive { file },
None => MountStorageWire::Archive {
path: relativize_mount_path(path, workspace_root),
},
},
MountStorage::InMemory => MountStorageWire::InMemory,
},
capability: match m.capability {
MountCapability::ReadOnly => CapabilityWire::ReadOnly,
MountCapability::Write => CapabilityWire::Write,
},
lifecycle: match m.lifecycle {
MountLifecycle::Eager => LifecycleWire::Eager,
MountLifecycle::Lazy => LifecycleWire::Lazy,
},
cross_linkable: m.cross_linkable,
}
}
fn into_mount(self, workspace_root: &Path) -> Mount {
let mem_name = self.mem.clone();
Mount {
mem: self.mem,
schema: self.schema.map(|s| {
s.parse()
.expect("schema pin on disk must be `<name>@<version>`")
}),
migration_target: self.migration_target.map(|t| {
t.parse()
.expect("migration_target on disk must be `<name>@<version>`")
}),
storage: match self.storage {
MountStorageWire::Folder { path } => MountStorage::Folder {
path: absolutize_mount_path(path, workspace_root),
},
MountStorageWire::GitBranch { gitdir, branch } => MountStorage::GitBranch {
gitdir: absolutize_mount_path(gitdir, workspace_root),
branch,
},
MountStorageWire::Archive { path } => {
let path = absolutize_mount_path(path, workspace_root);
let file = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.filter(|f| !path.exists() && is_cache_file_name(&mem_name, f));
match (file, registered_mem_cache_dir()) {
(Some(file), Some(dir)) => MountStorage::Archive {
path: dir.join(file),
},
_ => MountStorage::Archive { path },
}
}
MountStorageWire::CachedArchive { file } => MountStorage::Archive {
path: match registered_mem_cache_dir() {
Some(dir) => dir.join(file),
None => workspace_root
.join(WORKSPACE_STORE_DIR)
.join(NO_ARCHIVE_CACHE_DIR)
.join(file),
},
},
MountStorageWire::InMemory => MountStorage::InMemory,
},
capability: match self.capability {
CapabilityWire::ReadOnly => MountCapability::ReadOnly,
CapabilityWire::Write => MountCapability::Write,
},
lifecycle: match self.lifecycle {
LifecycleWire::Eager => MountLifecycle::Eager,
LifecycleWire::Lazy => MountLifecycle::Lazy,
},
cross_linkable: self.cross_linkable,
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum InstantiateError {
#[error(
"mem {mem}: git-branch storage needs the memstead-git-branch crate \
(`cargo add memstead-git-branch`). Simplest: open the workspace with \
`memstead_git_branch::workspace_store::engine_from_workspace_root(root)` \
instead of the memstead-base constructor. Alternative, if you build the \
Engine yourself: `engine.set_backend_factory(\
memstead_git_branch::storage::instantiate_full_backend)` before mounting"
)]
GitBranchBackendUnavailable { mem: String },
}
impl InstantiateError {
pub fn code(&self) -> &'static str {
match self {
InstantiateError::GitBranchBackendUnavailable { .. } => "UNSUPPORTED_WORKSPACE_SHAPE",
}
}
}
pub fn instantiate_local_backend(mount: &Mount) -> Result<Box<dyn MemBackend>, InstantiateError> {
match &mount.storage {
MountStorage::Folder { path } => Ok(Box::new(FilesystemBackend::new(path.clone()))),
MountStorage::Archive { path } => Ok(Box::new(ArchiveBackend::new(path.clone()))),
MountStorage::InMemory => Ok(Box::new(InMemoryBackend::new())),
MountStorage::GitBranch { .. } => Err(InstantiateError::GitBranchBackendUnavailable {
mem: mount.mem.clone(),
}),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Layout {
Empty,
New,
}
pub fn detect_layout(workspace_root: &Path) -> Layout {
if is_workspace_root(workspace_root) {
Layout::New
} else {
Layout::Empty
}
}
pub fn standalone_workspace(workspace_root: &Path) -> Option<Workspace> {
let config = memstead_schema::config::load_and_validate(workspace_root).ok()?;
let schema = config.schema.clone()?;
let name = config.name.clone().unwrap_or_else(|| {
workspace_root
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| "mem".to_string())
});
let mount = Mount {
mem: name,
schema: Some(schema),
storage: MountStorage::Folder {
path: workspace_root.to_path_buf(),
},
capability: MountCapability::Write,
lifecycle: MountLifecycle::Eager,
cross_linkable: false,
migration_target: None,
};
Some(Workspace {
mounts: vec![mount],
settings: WorkspaceSettings::default(),
})
}
#[cfg(test)]
mod tests;