mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 15:26:17 +00:00
feat(history): export and restore type icons in types.json
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
206b62d4ab
commit
2b079a8d74
4 files changed
+110
-6
No files matched your search
@@ -1,6 +1,6 @@
|
||||
//! Deterministic Markdown export of pages.
|
||||
//!
|
||||
//! Layout: `pages/<encoded title>.md`, `journals/YYYY_MM_DD.md`, `assets.json`.
|
||||
//! Layout: `pages/<encoded title>.md`, `journals/YYYY_MM_DD.md`, `assets.json`, `types.json`.
|
||||
//! A page file starts with page properties (`key:: value`, aliases as `alias:: a, b`),
|
||||
//! then one `- ` bullet per block, nested with tabs. Block properties follow the content;
|
||||
//! blocks referenced by `((uuid))` carry an `id::` property. Hubs carry `synapse-kind:: hub`
|
||||
@@ -16,6 +16,8 @@ use synapse_core::{Block, BlockId, Graph, Page, Properties};
|
||||
pub const PAGES_DIR: &str = "pages";
|
||||
pub const JOURNALS_DIR: &str = "journals";
|
||||
pub const MANIFEST: &str = "assets.json";
|
||||
/// Type definitions (names with their emoji icon), see [`render_types`].
|
||||
pub const TYPES_FILE: &str = "types.json";
|
||||
/// Page property marking a hub or tag page (`synapse-kind:: hub|tag`); notes omit it.
|
||||
pub const KIND_PROP: &str = "synapse-kind";
|
||||
/// Page property holding a hub's description.
|
||||
@@ -242,6 +244,35 @@ pub fn referenced_blocks(conn: &Connection) -> Result<HashSet<BlockId>> {
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
/// One entry of [`TYPES_FILE`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct TypeEntry {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub icon: Option<String>,
|
||||
}
|
||||
|
||||
/// Type definitions (`types.json`): the live ones (not removed), sorted by name key, so it is
|
||||
/// deterministic. `None` when there are none (the file is left out).
|
||||
pub fn render_types(graph: &Graph) -> Result<Option<String>> {
|
||||
let defs: std::collections::BTreeMap<String, synapse_core::TypeDef> =
|
||||
graph.type_defs()?.into_iter().collect();
|
||||
let list: Vec<TypeEntry> = defs
|
||||
.into_values()
|
||||
.filter(|d| !d.removed)
|
||||
.map(|d| TypeEntry {
|
||||
name: d.name,
|
||||
icon: d.icon,
|
||||
})
|
||||
.collect();
|
||||
if list.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut s = serde_json::to_string_pretty(&list).map_err(Error::from)?;
|
||||
s.push('\n');
|
||||
Ok(Some(s))
|
||||
}
|
||||
|
||||
/// Asset manifest (`assets.json`): sorted by hash, so it is deterministic.
|
||||
pub fn render_manifest(conn: &Connection) -> Result<String> {
|
||||
let mut st =
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use crate::Result;
|
||||
use crate::error::Error;
|
||||
use crate::export::{self, JOURNALS_DIR, MANIFEST, PAGES_DIR};
|
||||
use crate::export::{self, JOURNALS_DIR, MANIFEST, PAGES_DIR, TYPES_FILE};
|
||||
use crate::repo::{CommitInfo, Files, Repo};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
@@ -202,7 +202,7 @@ impl History {
|
||||
Op::DeletePage { id } => touched.extend(graph.hub_members(id)?),
|
||||
// Deletions and moves do not say which page lost a block; those
|
||||
// pages are caught by the `updated_at` scan below.
|
||||
Op::DeleteBlock { .. } | Op::PutAsset { .. } => {}
|
||||
Op::DeleteBlock { .. } | Op::PutAsset { .. } | Op::PutTypeDef { .. } => {}
|
||||
// The previous owner of an alias is unknown.
|
||||
Op::SetAlias { .. } => everything = true,
|
||||
}
|
||||
@@ -270,6 +270,22 @@ impl History {
|
||||
.write_blob(export::render_manifest(graph.conn())?.as_bytes())?;
|
||||
let assets_changed = old_files.get(MANIFEST) != Some(&manifest);
|
||||
files.insert(MANIFEST.to_string(), manifest);
|
||||
let types = match export::render_types(graph)? {
|
||||
Some(text) => Some(self.repo.write_blob(text.as_bytes())?),
|
||||
None => None,
|
||||
};
|
||||
let types_changed = old_files.get(TYPES_FILE) != types.as_ref();
|
||||
match types {
|
||||
Some(oid) => files.insert(TYPES_FILE.to_string(), oid),
|
||||
None => files.remove(TYPES_FILE),
|
||||
};
|
||||
let other = if assets_changed {
|
||||
Some("assets updated")
|
||||
} else if types_changed {
|
||||
Some("types updated")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if self.opts.include_blobs {
|
||||
self.add_blobs(graph, &mut files)?;
|
||||
}
|
||||
@@ -284,7 +300,7 @@ impl History {
|
||||
self.save_state(&new_state)?;
|
||||
return Ok(None);
|
||||
}
|
||||
let message = commit_message(&created, &edited, &deleted, assets_changed, seq_now);
|
||||
let message = commit_message(&created, &edited, &deleted, other, seq_now);
|
||||
let id = self.repo.commit(&files, &message, now_ms / 1000)?;
|
||||
self.save_state(&new_state)?;
|
||||
Ok(Some(self.repo.commit_info(id)?.into()))
|
||||
@@ -430,7 +446,7 @@ fn commit_message(
|
||||
created: &BTreeSet<String>,
|
||||
edited: &BTreeSet<String>,
|
||||
deleted: &BTreeSet<String>,
|
||||
assets: bool,
|
||||
other: Option<&str>,
|
||||
seq: i64,
|
||||
) -> String {
|
||||
let plural = |n: usize| if n == 1 { "page" } else { "pages" };
|
||||
@@ -445,7 +461,7 @@ fn commit_message(
|
||||
parts.push(format!("{} deleted", deleted.len()));
|
||||
}
|
||||
if parts.is_empty() {
|
||||
parts.push(if assets { "assets updated" } else { "snapshot" }.to_string());
|
||||
parts.push(other.unwrap_or("snapshot").to_string());
|
||||
}
|
||||
let mut titles: Vec<&String> = edited.iter().chain(created).chain(deleted).collect();
|
||||
titles.sort();
|
||||
|
||||
@@ -20,6 +20,30 @@ pub struct RestoreReport {
|
||||
pub safety_snapshot: Option<SnapshotInfo>,
|
||||
}
|
||||
|
||||
/// Brings type definitions back to the snapshot's `types.json` (missing file: none). Types
|
||||
/// defined now but not in the snapshot lose their icon and stay defined (a tombstone would
|
||||
/// also hide a seeded suggestion of that name). Bad entries are skipped.
|
||||
fn restore_types(graph: &Graph, history: &History, files: &crate::repo::Files) -> Result<()> {
|
||||
let wanted: Vec<export::TypeEntry> = match files.get(export::TYPES_FILE) {
|
||||
Some(oid) => serde_json::from_str(&history.read_blob(*oid)?).unwrap_or_default(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
let mut keep: HashSet<String> = HashSet::new();
|
||||
for t in &wanted {
|
||||
if skip_invalid(graph.create_type(&t.name))?.is_some()
|
||||
&& skip_invalid(graph.set_type_icon(&t.name, t.icon.as_deref()))?.is_some()
|
||||
{
|
||||
keep.insert(synapse_core::title_key(&t.name));
|
||||
}
|
||||
}
|
||||
for (key, def) in graph.type_defs()? {
|
||||
if !def.removed && def.icon.is_some() && !keep.contains(&key) {
|
||||
graph.set_type_icon(&def.name, None)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Test hook: fail after this many block writes/deletes.
|
||||
type Fault<'a> = &'a Cell<Option<usize>>;
|
||||
|
||||
@@ -436,6 +460,7 @@ impl History {
|
||||
report.removed += 1;
|
||||
}
|
||||
}
|
||||
restore_types(graph, this, &files)?;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(report)
|
||||
|
||||
@@ -371,6 +371,38 @@ fn tags_round_trip_through_snapshots() {
|
||||
assert_eq!(g.pages_with_tag("idea").unwrap(), [note.id]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_icons_round_trip_through_snapshots() {
|
||||
let (_d, g, mut h) = setup();
|
||||
let note = add(&g, "Ada", &["body"]);
|
||||
g.set_page_type(note.id, Some("persona")).unwrap();
|
||||
let s0 = h.snapshot(&g, T0 + 100).unwrap().unwrap();
|
||||
assert!(h.file(&s0.id, export::TYPES_FILE).unwrap().is_none());
|
||||
|
||||
at(&g, T0 + 200);
|
||||
g.set_type_icon("persona", Some("🧑")).unwrap();
|
||||
g.create_type("Libro").unwrap();
|
||||
let s1 = h.snapshot(&g, T0 + 500).unwrap().unwrap();
|
||||
assert_eq!(s1.summary, "types updated");
|
||||
let json = h.file(&s1.id, export::TYPES_FILE).unwrap().unwrap();
|
||||
assert!(json.contains("\"Libro\"") && json.contains("🧑"), "{json}");
|
||||
|
||||
at(&g, T0 + 1000);
|
||||
g.set_type_icon("persona", Some("👤")).unwrap();
|
||||
g.set_type_icon("lugar", Some("📍")).unwrap();
|
||||
h.restore_graph(&g, &s1.id, T0 + 2000).unwrap();
|
||||
let icon = |name: &str| {
|
||||
g.type_catalog()
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.find(|t| t.name == name)
|
||||
.and_then(|t| t.icon)
|
||||
};
|
||||
assert_eq!(icon("persona").as_deref(), Some("🧑"));
|
||||
assert_eq!(icon("lugar"), None);
|
||||
assert!(g.type_catalog().unwrap().iter().any(|t| t.name == "Libro"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hubs_round_trip_kind_description_and_memberships() {
|
||||
let (_d, g, mut h) = setup();
|
||||
|
||||
Reference in new issue
Block a user