Add design persistence, world rendering, metrics overlay and logs

M3: STL/OBJ import with mesh validation, mass/COM/inertia, material database, RON scene with content-addressed blobs and v0->v1 migration. M4: deterministic heightmap terrain, trimesh colliders, wgpu renderer with instancing and depth, winit app with 1 kHz physics, fly camera, on-screen metrics overlay and per-frame CSV/dev logs. Docs: UI, logging, network and headless CLI plans.
This commit is contained in:
Loki 2026-11-16 23:34:05 +01:00
parent 878d144b77
commit 190ef9cc4b
111 changed files with 14801 additions and 63 deletions

View file

@ -1 +1,143 @@
//! fabrilis-storage :: blob - stub (see docs/ARCHITECTURE.md)
//! Content-addressed blob storage.
//!
//! A blob is named by an FNV-1a 64-bit hash of its bytes, so equal contents are
//! stored once and a file can be checked against its name (docs/STORAGE.md). The
//! hash detects accidental corruption and deduplicates saves; it is not a
//! cryptographic digest and does not resist a deliberate collision.
use core::fmt;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use serde::de::Error as DeError;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
/// FNV-1a 64-bit offset basis.
const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
/// FNV-1a 64-bit prime.
const PRIME: u64 = 0x0000_0100_0000_01b3;
/// Hex digits in a serialised hash.
const HEX_DIGITS: usize = 16;
/// Distinguishes temporary files written by concurrent saves in one process.
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
/// The content hash of a blob.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BlobHash(u64);
impl BlobHash {
/// Hashes the bytes with FNV-1a 64.
#[must_use]
pub fn hash(bytes: &[u8]) -> Self {
let mut value = OFFSET_BASIS;
for &byte in bytes {
value ^= u64::from(byte);
value = value.wrapping_mul(PRIME);
}
Self(value)
}
/// The hash as 16 lowercase hex digits, the blob's file name.
#[must_use]
pub fn to_hex(self) -> String {
format!("{:016x}", self.0)
}
/// Parses 16 hex digits, uppercase or lowercase.
#[must_use]
pub fn from_hex(text: &str) -> Option<Self> {
if text.len() != HEX_DIGITS || !text.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return None;
}
u64::from_str_radix(text, 16).ok().map(Self)
}
}
impl fmt::Display for BlobHash {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{:016x}", self.0)
}
}
impl Serialize for BlobHash {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.to_hex())
}
}
impl<'de> Deserialize<'de> for BlobHash {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
Self::from_hex(&text).ok_or_else(|| DeError::custom("blob hash must be 16 hex digits"))
}
}
/// A directory of blobs named by their content hash.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlobStore {
root: PathBuf,
}
impl BlobStore {
/// Uses `root` as the directory that holds the blob files.
#[must_use]
pub fn new(root: impl Into<PathBuf>) -> Self {
Self { root: root.into() }
}
/// The directory holding the blobs.
#[must_use]
pub fn root(&self) -> &Path {
&self.root
}
/// Writes `bytes` unless the same contents are already stored.
///
/// The file is written under a temporary name and renamed into place, so a
/// reader never sees a partial blob even if the process stops mid-write.
pub fn put(&self, bytes: &[u8]) -> io::Result<BlobHash> {
let hash = BlobHash::hash(bytes);
let path = self.path(hash);
if path.is_file() {
return Ok(hash);
}
fs::create_dir_all(&self.root)?;
let temp = temp_path(&self.root);
fs::write(&temp, bytes)?;
if let Err(error) = fs::rename(&temp, &path) {
let _ = fs::remove_file(&temp);
return Err(error);
}
Ok(hash)
}
/// Reads the blob back; a missing file is an [`io::ErrorKind::NotFound`].
pub fn get(&self, hash: BlobHash) -> io::Result<Vec<u8>> {
fs::read(self.path(hash))
}
/// The file that holds `hash`, whether or not it exists yet.
#[must_use]
pub fn path(&self, hash: BlobHash) -> PathBuf {
self.root.join(hash.to_hex())
}
/// True when the blob is stored.
#[must_use]
pub fn contains(&self, hash: BlobHash) -> bool {
self.path(hash).is_file()
}
}
/// A temporary file name that cannot collide with a hash file.
fn temp_path(root: &Path) -> PathBuf {
let counter = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
let pid = std::process::id();
root.join(format!(".{pid}-{counter}.blob-tmp"))
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,99 @@
//! Blob hashing, hex round trips and content-addressed storage.
#![allow(
clippy::unwrap_used,
reason = "a test aborts on failure, which is the intent"
)]
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use super::{BlobHash, BlobStore};
/// A directory removed on drop.
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(label: &str) -> Self {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"fabrilis-blob-{label}-{}-{counter}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self { path }
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
#[test]
fn fnv1a_matches_the_reference_vectors() {
assert_eq!(BlobHash::hash(b"").to_hex(), "cbf29ce484222325");
assert_eq!(BlobHash::hash(b"a").to_hex(), "af63dc4c8601ec8c");
assert_eq!(BlobHash::hash(b"foobar").to_hex(), "85944171f73967e8");
}
#[test]
fn hex_round_trips_and_rejects_bad_input() {
let hash = BlobHash::hash(b"payload");
let hex = hash.to_hex();
assert_eq!(hex.len(), 16);
assert_eq!(BlobHash::from_hex(&hex), Some(hash));
assert_eq!(BlobHash::from_hex(&hex.to_uppercase()), Some(hash));
assert_eq!(BlobHash::from_hex(""), None);
assert_eq!(BlobHash::from_hex("xyz"), None);
assert_eq!(BlobHash::from_hex("0123456789abcde"), None);
assert_eq!(BlobHash::from_hex("0123456789abcdeg"), None);
}
#[test]
fn serde_uses_the_hex_string_form() {
let hash = BlobHash::hash(b"scene");
let text = ron::to_string(&hash).unwrap();
assert_eq!(text, format!("\"{}\"", hash.to_hex()));
assert_eq!(ron::from_str::<BlobHash>(&text).unwrap(), hash);
assert!(ron::from_str::<BlobHash>("\"not-a-hash\"").is_err());
}
#[test]
fn put_get_and_contains_round_trip() {
let temp = TempDir::new("round-trip");
let store = BlobStore::new(&temp.path);
let hash = store.put(b"hello blob").unwrap();
assert!(store.contains(hash));
assert_eq!(store.get(hash).unwrap(), b"hello blob");
assert_eq!(store.path(hash), temp.path.join(hash.to_hex()));
assert!(store.path(hash).is_file());
}
#[test]
fn storing_the_same_bytes_twice_keeps_one_file() {
let temp = TempDir::new("dedup");
let store = BlobStore::new(&temp.path);
let first = store.put(b"same").unwrap();
let second = store.put(b"same").unwrap();
assert_eq!(first, second);
let files = std::fs::read_dir(&temp.path).unwrap().count();
assert_eq!(files, 1);
}
#[test]
fn a_missing_blob_is_not_found() {
let temp = TempDir::new("missing");
let store = BlobStore::new(&temp.path);
let hash = BlobHash::hash(b"never stored");
assert!(!store.contains(hash));
let error = store.get(hash).unwrap_err();
assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
}

View file

@ -1 +1,123 @@
//! fabrilis-storage :: format - stub (see docs/ARCHITECTURE.md)
//! Versioned RON files.
//!
//! Every saved file is an [`Envelope`] with a `format_version` field, so a newer
//! build can reject data it does not understand and an older one can migrate it
//! forward through the chain in [`crate::migrate`].
use core::fmt;
use std::collections::BTreeMap;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use crate::migrate::{self, MigrateError, Migration};
/// The format version written by this build.
pub const CURRENT_VERSION: u32 = 1;
/// A payload with the version of the schema it follows.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Envelope<T> {
/// Schema version of `payload`.
pub format_version: u32,
/// The document itself.
pub payload: T,
}
/// Serialises `payload` as a pretty RON envelope at [`CURRENT_VERSION`].
pub fn to_ron<T: Serialize>(payload: &T) -> Result<String, FormatError> {
let envelope = Envelope {
format_version: CURRENT_VERSION,
payload,
};
ron::ser::to_string_pretty(&envelope, ron::ser::PrettyConfig::default())
.map_err(|error| FormatError::Encode(error.to_string()))
}
/// Reads an envelope written at [`CURRENT_VERSION`].
///
/// Older documents are rejected because no migration steps are known here; use
/// [`from_ron_with_migrations`] to supply them.
pub fn from_ron<T: DeserializeOwned>(text: &str) -> Result<T, FormatError> {
from_ron_with_migrations(text, &BTreeMap::new())
}
/// Reads an envelope, migrates an older payload forward, then decodes it.
///
/// A version newer than [`CURRENT_VERSION`] is always rejected: a newer file may
/// contain fields this build would silently drop.
pub fn from_ron_with_migrations<T: DeserializeOwned>(
text: &str,
steps: &BTreeMap<u32, Migration>,
) -> Result<T, FormatError> {
let envelope: Envelope<ron::Value> =
ron::from_str(text).map_err(|error| FormatError::Parse(error.to_string()))?;
if envelope.format_version > CURRENT_VERSION {
return Err(FormatError::TooNew {
found: envelope.format_version,
current: CURRENT_VERSION,
});
}
let payload = migrate::migrate_value(
envelope.payload,
envelope.format_version,
CURRENT_VERSION,
steps,
)?;
payload
.into_rust()
.map_err(|error| FormatError::Decode(error.to_string()))
}
/// Why a file could not be read or written.
#[derive(Debug)]
pub enum FormatError {
/// The text is not a RON envelope.
Parse(String),
/// The payload could not be serialised.
Encode(String),
/// The payload does not match the requested type after migration.
Decode(String),
/// The file was written by a newer build.
TooNew {
/// Version found in the file.
found: u32,
/// Version this build understands.
current: u32,
},
/// A migration step failed.
Migration(MigrateError),
}
impl From<MigrateError> for FormatError {
fn from(error: MigrateError) -> Self {
Self::Migration(error)
}
}
impl fmt::Display for FormatError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Parse(reason) => write!(formatter, "cannot parse the RON envelope: {reason}"),
Self::Encode(reason) => write!(formatter, "cannot encode the RON payload: {reason}"),
Self::Decode(reason) => write!(formatter, "cannot decode the RON payload: {reason}"),
Self::TooNew { found, current } => write!(
formatter,
"format version {found} is newer than the supported version {current}"
),
Self::Migration(error) => write!(formatter, "migration failed: {error}"),
}
}
}
impl std::error::Error for FormatError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Migration(error) => Some(error),
_ => None,
}
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,90 @@
//! Envelope versioning and guarded decoding.
#![allow(
clippy::unwrap_used,
reason = "a test aborts on failure, which is the intent"
)]
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use super::{CURRENT_VERSION, FormatError, from_ron, from_ron_with_migrations, to_ron};
use crate::migrate::{MigrateError, Migration};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Document {
answer: f64,
}
/// A step from version 0 to version 1: add one to `answer`.
fn add_one(mut value: ron::Value) -> Result<ron::Value, MigrateError> {
let ron::Value::Map(ref mut document) = value else {
return Err(MigrateError::step(0, "document is not a map"));
};
let Some(answer) = document.get_mut(&ron::Value::from("answer")) else {
return Err(MigrateError::step(0, "document has no answer"));
};
let ron::Value::Number(number) = answer else {
return Err(MigrateError::step(0, "answer is not a number"));
};
let incremented = (*number).into_f64() + 1.0;
*answer = ron::Value::from(incremented);
Ok(value)
}
fn steps() -> BTreeMap<u32, Migration> {
let mut steps = BTreeMap::new();
let _previous = steps.insert(0, add_one as Migration);
steps
}
#[test]
fn a_payload_round_trips_at_the_current_version() {
let text = to_ron(&Document { answer: 42.0 }).unwrap();
assert!(text.contains("format_version: 1"));
assert!(text.contains("payload:"));
let document: Document = from_ron(&text).unwrap();
assert_eq!(document, Document { answer: 42.0 });
}
#[test]
fn a_newer_version_is_rejected() {
let text = format!(
"(format_version: {}, payload: (answer: 1.0))",
CURRENT_VERSION + 1
);
let error = from_ron::<Document>(&text).unwrap_err();
assert!(matches!(error, FormatError::TooNew { .. }));
}
#[test]
fn an_older_version_needs_a_registered_step() {
let text = "(format_version: 0, payload: (answer: 41.0))";
let error = from_ron::<Document>(text).unwrap_err();
assert!(matches!(
error,
FormatError::Migration(MigrateError::MissingStep { version: 0, .. })
));
}
#[test]
fn an_older_version_is_migrated_before_decoding() {
let text = "(format_version: 0, payload: (answer: 41.0))";
let document: Document = from_ron_with_migrations(text, &steps()).unwrap();
assert_eq!(document, Document { answer: 42.0 });
}
#[test]
fn a_payload_of_the_wrong_shape_is_a_decode_error() {
let text = "(format_version: 1, payload: 7.0)";
let error = from_ron::<Document>(text).unwrap_err();
assert!(matches!(error, FormatError::Decode(_)));
}
#[test]
fn malformed_text_is_a_parse_error() {
let error = from_ron::<Document>("this is not RON").unwrap_err();
assert!(matches!(error, FormatError::Parse(_)));
}

View file

@ -1 +1,101 @@
//! fabrilis-storage :: migrate - stub (see docs/ARCHITECTURE.md)
//! Forward-only schema migrations over RON values.
//!
//! A migration upgrades the payload of one format version to the next. Steps are
//! kept in a [`BTreeMap`] so the chain is explicit and missing links are reported
//! instead of silently skipped (docs/STORAGE.md).
use core::fmt;
use std::collections::BTreeMap;
/// A step from version `version` to `version + 1` over the payload.
pub type Migration = fn(ron::Value) -> Result<ron::Value, MigrateError>;
/// Why a migration chain could not be applied.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MigrateError {
/// The caller asked to go backwards; saved data is never downgraded.
Downgrade {
/// Version of the loaded value.
from: u32,
/// Requested version, lower than `from`.
to: u32,
},
/// No step is registered for the version that needs upgrading.
MissingStep {
/// Version without a step.
version: u32,
/// Version the chain was asked to reach.
to: u32,
},
/// A step rejected the value it was given.
Step {
/// Version the failing step reads.
version: u32,
/// What was wrong with the value.
reason: String,
},
}
impl MigrateError {
/// Builds [`Self::Step`] for a step that rejects its input.
#[must_use]
pub fn step(version: u32, reason: impl Into<String>) -> Self {
Self::Step {
version,
reason: reason.into(),
}
}
}
impl fmt::Display for MigrateError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Downgrade { from, to } => {
write!(
formatter,
"cannot migrate version {from} back to version {to}"
)
}
Self::MissingStep { version, to } => write!(
formatter,
"no migration from version {version} while migrating to version {to}"
),
Self::Step { version, reason } => {
write!(
formatter,
"migration from version {version} failed: {reason}"
)
}
}
}
}
impl std::error::Error for MigrateError {}
/// Applies the steps from `from` up to `to`, one version at a time.
///
/// `steps[version]` must upgrade version `version` to `version + 1`. `from == to`
/// is a no-op. A downgrade, a missing step or a rejecting step is an error; the
/// value is left untouched on failure.
pub fn migrate_value(
mut value: ron::Value,
from: u32,
to: u32,
steps: &BTreeMap<u32, Migration>,
) -> Result<ron::Value, MigrateError> {
if to < from {
return Err(MigrateError::Downgrade { from, to });
}
let mut version = from;
while version < to {
let step = steps
.get(&version)
.ok_or(MigrateError::MissingStep { version, to })?;
value = step(value)?;
version += 1;
}
Ok(value)
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,94 @@
//! Migration chains: ordering, missing links and downgrades.
#![allow(
clippy::unwrap_used,
reason = "a test aborts on failure, which is the intent"
)]
use std::collections::BTreeMap;
use super::{MigrateError, Migration, migrate_value};
/// Version 0 → 1: adds the field `a`.
fn insert_a(mut value: ron::Value) -> Result<ron::Value, MigrateError> {
let ron::Value::Map(ref mut document) = value else {
return Err(MigrateError::step(0, "document is not a map"));
};
let _previous = document.insert("a", 1);
Ok(value)
}
/// Version 1 → 2: adds the field `b`.
fn insert_b(mut value: ron::Value) -> Result<ron::Value, MigrateError> {
let ron::Value::Map(ref mut document) = value else {
return Err(MigrateError::step(1, "document is not a map"));
};
let _previous = document.insert("b", 2);
Ok(value)
}
fn empty_document() -> ron::Value {
ron::Value::Map(ron::Map::new())
}
#[test]
fn a_two_step_chain_applies_in_order() {
let mut steps = BTreeMap::new();
let _previous = steps.insert(0, insert_a as Migration);
let _previous = steps.insert(1, insert_b as Migration);
let migrated = migrate_value(empty_document(), 0, 2, &steps).unwrap();
let ron::Value::Map(document) = migrated else {
panic!("a migration must return a map");
};
assert_eq!(
document.get(&ron::Value::from("a")),
Some(&ron::Value::from(1))
);
assert_eq!(
document.get(&ron::Value::from("b")),
Some(&ron::Value::from(2))
);
}
#[test]
fn a_missing_step_stops_the_chain() {
let mut steps = BTreeMap::new();
let _previous = steps.insert(0, insert_a as Migration);
let error = migrate_value(empty_document(), 0, 2, &steps).unwrap_err();
assert_eq!(error, MigrateError::MissingStep { version: 1, to: 2 });
}
#[test]
fn a_downgrade_is_rejected_before_any_step_runs() {
let error = migrate_value(empty_document(), 2, 0, &BTreeMap::new()).unwrap_err();
assert_eq!(error, MigrateError::Downgrade { from: 2, to: 0 });
}
#[test]
fn equal_versions_are_a_no_op() {
let value = empty_document();
let migrated = migrate_value(value.clone(), 3, 3, &BTreeMap::new()).unwrap();
assert_eq!(migrated, value);
}
#[test]
fn a_rejecting_step_reports_its_version() {
fn reject(value: ron::Value) -> Result<ron::Value, MigrateError> {
let _ignored = value;
Err(MigrateError::step(0, "malformed payload"))
}
let mut steps = BTreeMap::new();
let _previous = steps.insert(0, reject as Migration);
let error = migrate_value(empty_document(), 0, 1, &steps).unwrap_err();
assert!(matches!(
error,
MigrateError::Step {
version: 0,
ref reason
} if reason == "malformed payload"
));
}

View file

@ -1 +1,104 @@
//! fabrilis-storage :: project - stub (see docs/ARCHITECTURE.md)
//! A project folder: the save format described in docs/STORAGE.md.
//!
//! A project is a directory with a `blobs/` subdirectory for content-addressed
//! files and small RON documents at its root. Text files are written through a
//! temporary file and renamed into place, so an interrupted save cannot leave a
//! half-written document behind.
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use crate::blob::BlobStore;
/// Subdirectory holding the blobs.
const BLOB_DIRECTORY: &str = "blobs";
/// Distinguishes temporary files written by concurrent saves in one process.
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
/// An existing project directory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Project {
root: PathBuf,
}
impl Project {
/// Creates the directory, its parents and the blob store.
pub fn create(root: impl Into<PathBuf>) -> io::Result<Self> {
let root = root.into();
fs::create_dir_all(&root)?;
fs::create_dir_all(root.join(BLOB_DIRECTORY))?;
Ok(Self { root })
}
/// Opens an existing directory; a missing path is [`io::ErrorKind::NotFound`].
pub fn open(root: impl Into<PathBuf>) -> io::Result<Self> {
let root = root.into();
if root.is_dir() {
Ok(Self { root })
} else {
Err(io::Error::new(
io::ErrorKind::NotFound,
format!("project directory {} does not exist", root.display()),
))
}
}
/// The project directory.
#[must_use]
pub fn root(&self) -> &Path {
&self.root
}
/// The blob store under `root/blobs`.
#[must_use]
pub fn blobs(&self) -> BlobStore {
BlobStore::new(self.root.join(BLOB_DIRECTORY))
}
/// A file path inside the project; the file need not exist.
#[must_use]
pub fn path(&self, name: &str) -> PathBuf {
self.root.join(name)
}
/// Writes a text document atomically.
pub fn write_text(&self, name: &str, text: &str) -> io::Result<()> {
write_atomic(&self.path(name), text)
}
/// Reads a text document written with [`Self::write_text`].
pub fn read_text(&self, name: &str) -> io::Result<String> {
fs::read_to_string(self.path(name))
}
}
/// Writes through a temporary file in the same directory, then renames.
fn write_atomic(path: &Path, text: &str) -> io::Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let temp = temp_path(path);
fs::write(&temp, text)?;
if let Err(error) = fs::rename(&temp, path) {
let _ = fs::remove_file(&temp);
return Err(error);
}
Ok(())
}
/// A temporary sibling of `path` that cannot collide with the target name.
fn temp_path(path: &Path) -> PathBuf {
let counter = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
let pid = std::process::id();
let name = path
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("file");
path.with_file_name(format!(".{name}.{pid}-{counter}.tmp"))
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,94 @@
//! Project folders: creation, atomic text files and the blob directory.
#![allow(
clippy::unwrap_used,
reason = "a test aborts on failure, which is the intent"
)]
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use super::Project;
/// A directory removed on drop.
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(label: &str) -> Self {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"fabrilis-project-{label}-{}-{counter}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self { path }
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
#[test]
fn create_makes_the_root_and_the_blob_directory() {
let temp = TempDir::new("create");
let root = temp.path.join("new-project");
let project = Project::create(&root).unwrap();
assert_eq!(project.root(), root);
assert!(root.is_dir());
assert!(root.join("blobs").is_dir());
}
#[test]
fn open_requires_an_existing_directory() {
let temp = TempDir::new("open");
let missing = temp.path.join("absent");
let error = Project::open(&missing).unwrap_err();
assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
let project = Project::create(&temp.path).unwrap();
assert_eq!(Project::open(project.root()).unwrap().root(), temp.path);
}
#[test]
fn text_round_trips_and_replaces_atomically() {
let temp = TempDir::new("text");
let project = Project::create(&temp.path).unwrap();
project.write_text("scene.ron", "first").unwrap();
assert_eq!(project.read_text("scene.ron").unwrap(), "first");
project.write_text("scene.ron", "second").unwrap();
assert_eq!(project.read_text("scene.ron").unwrap(), "second");
let leftovers: Vec<String> = std::fs::read_dir(project.root())
.unwrap()
.filter_map(|entry| entry.ok())
.map(|entry| entry.file_name().to_string_lossy().into_owned())
.filter(|name| name.starts_with('.'))
.collect();
assert!(leftovers.is_empty(), "temporary files left: {leftovers:?}");
}
#[test]
fn paths_are_rooted_in_the_project() {
let temp = TempDir::new("path");
let project = Project::create(&temp.path).unwrap();
assert_eq!(project.path("scene.ron"), temp.path.join("scene.ron"));
}
#[test]
fn blobs_live_in_the_blobs_subdirectory() {
let temp = TempDir::new("blobs");
let project = Project::create(&temp.path).unwrap();
let store = project.blobs();
let hash = store.put(b"mesh").unwrap();
assert!(store.contains(hash));
assert!(project.path("blobs").join(hash.to_hex()).is_file());
}