feat(core): hubs, tag pages and types, with ffi, history and import support

Hubs and templates are page kinds; tags are pages of kind tag linked by a TAGGED
edge; types are plain names on the page. Schema v5. Snapshots carry
synapse-kind/tags/types. Also adapts search, import and server tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-10-26 02:45:22 +01:00
1 parent 91a8276966
commit b800248d67
35 files changed
+7983 -141

No files matched your search

+4 -2
View File
@@ -1,4 +1,4 @@
//! `cargo run -p synapse-import --example import -- <logseq_dir> <graph_dir> [--skip-existing]`
//! `cargo run -p synapse-import --example import -- <logseq_dir> <graph_dir> [--skip-existing] [--keep-legacy]`
use std::path::PathBuf;
use synapse_core::Graph;
@@ -7,13 +7,14 @@ use synapse_import::{ExistingPages, ImportOptions, import_logseq};
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let skip = args.iter().any(|a| a == "--skip-existing");
let keep_legacy = args.iter().any(|a| a == "--keep-legacy");
let paths: Vec<PathBuf> = args
.iter()
.filter(|a| !a.starts_with("--"))
.map(PathBuf::from)
.collect();
let [src, dst] = paths.as_slice() else {
eprintln!("usage: import <logseq_dir> <graph_dir> [--skip-existing]");
eprintln!("usage: import <logseq_dir> <graph_dir> [--skip-existing] [--keep-legacy]");
std::process::exit(2);
};
let graph = Graph::open(dst).expect("open graph");
@@ -23,6 +24,7 @@ fn main() {
} else {
ExistingPages::Update
},
skip_legacy_pages: !keep_legacy,
};
let started = std::time::Instant::now();
let mut last = (None, 0);
+76 -3
View File
@@ -39,9 +39,22 @@ pub enum ExistingPages {
Skip,
}
#[derive(Debug, Clone, Default)]
#[derive(Debug, Clone)]
pub struct ImportOptions {
pub existing: ExistingPages,
/// Skip the files of Logseq's organisational pages (`contents`, `card`, `favorites`,
/// `hls__*`; see [`is_skipped_legacy`]) and drop the empty stubs their refs would create
/// in this import. Other built-in names (`TODO`, `NOW`, ...) are imported normally.
pub skip_legacy_pages: bool,
}
impl Default for ImportOptions {
fn default() -> Self {
Self {
existing: ExistingPages::default(),
skip_legacy_pages: true,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -78,6 +91,8 @@ pub struct Report {
pub unchanged: usize,
/// `.org` files imported as raw blocks (relative paths).
pub org_files: Vec<String>,
/// Legacy organisational pages left out (relative paths), see `skip_legacy_pages`.
pub skipped_legacy: Vec<String>,
pub warnings: Vec<String>,
}
@@ -163,7 +178,16 @@ pub fn import_logseq(
.collect();
docs.extend(parsed);
}
let docs = dedupe(docs, &mut report.warnings);
let mut docs = dedupe(docs, &mut report.warnings);
if opts.skip_legacy_pages {
docs.retain(|d| {
let legacy = d.journal.is_none() && is_skipped_legacy(&d.title);
if legacy {
report.skipped_legacy.push(d.rel.clone());
}
!legacy
});
}
// ---- origin journals: earliest journal referencing each page (aliases resolved)
let mut alias_to_key: HashMap<String, String> = HashMap::new();
@@ -187,10 +211,52 @@ pub fn import_logseq(
// One transaction for the whole write phase: much faster, and a failed import leaves the
// graph untouched.
track::init(graph)?;
graph.transaction(|g| write_all(g, opts, &docs, &origin, &mut report, &mut progress))?;
graph.transaction(|g| {
let before: HashSet<PageId> = if opts.skip_legacy_pages {
page_ids(g)?
} else {
HashSet::new()
};
write_all(g, opts, &docs, &origin, &mut report, &mut progress)?;
if opts.skip_legacy_pages {
drop_legacy_stubs(g, &before)?;
}
Ok(())
})?;
Ok(report)
}
/// Logseq files the importer leaves out when `skip_legacy_pages` is set: `contents`, `card`,
/// `favorites` and PDF highlight pages (`hls__*`).
pub fn is_skipped_legacy(title: &str) -> bool {
let key = title_key(title);
key.starts_with("hls__") || ["contents", "card", "favorites"].contains(&key.as_str())
}
fn page_ids(g: &Graph) -> Result<HashSet<PageId>> {
Ok(g.list_pages(false, u32::MAX, 0)?
.into_iter()
.map(|p| p.id)
.collect())
}
/// Refs to `[[contents]]`, `[[card]]`, ... make core create empty stub pages; remove the ones
/// this import created (pages that existed before are never touched).
fn drop_legacy_stubs(g: &Graph, before: &HashSet<PageId>) -> Result<()> {
let stubs: Vec<PageId> = g
.list_pages(false, u32::MAX, 0)?
.into_iter()
.filter(|p| !before.contains(&p.id) && is_skipped_legacy(&p.title))
.map(|p| p.id)
.collect();
for id in stubs {
if g.page_tree(id)?.is_empty() {
g.delete_page(id)?;
}
}
Ok(())
}
fn write_all(
graph: &Graph,
opts: &ImportOptions,
@@ -218,6 +284,13 @@ fn write_all(
let d = &docs[i];
let o = origin.get(&d.key).copied();
match graph.transaction(|g| ensure_page(g, d, o)) {
// Hubs are Synapse-only pages without blocks: a re-import never writes them.
Ok((pid, true)) if graph.get_page(pid)?.is_some_and(|p| p.is_hub()) => {
report.warnings.push(format!(
"{}: {:?} is a hub in Synapse, skipped",
d.rel, d.title
));
}
Ok(r) => {
ids.insert(i, r);
}
+79
View File
@@ -146,6 +146,7 @@ fn reimport_updates_changed_pages_and_skip_mode() {
.unwrap();
let skip = ImportOptions {
existing: ExistingPages::Skip,
..Default::default()
};
let r = import_logseq(src.path(), &g, &skip, |_| {}).unwrap();
assert_eq!(r.updated, 0);
@@ -334,3 +335,81 @@ fn renamed_page_is_not_duplicated() {
let t = texts(&g, "Renamed");
assert_eq!(t.len(), 2);
}
#[test]
fn skips_legacy_pages_and_their_stubs() {
let files = [
("pages/contents.md", "- [[Alpha]]\n"),
("pages/TODO.md", "- old\n"),
("pages/hls__book_1.md", "- highlight\n"),
(
"pages/Alpha.md",
"- see [[contents]], [[card]], [[favorites]] and [[TODO]]\n",
),
];
let src = mini_graph(&files);
let dir = tempfile::tempdir().unwrap();
let g = Graph::open(dir.path()).unwrap();
// A page that already exists is never removed, even with a legacy title and no blocks.
let card = g.ensure_page("card", None).unwrap();
let r = imp(src.path(), &g);
assert_eq!(r.pages, 2, "Alpha and TODO");
assert_eq!(
r.skipped_legacy,
["pages/contents.md", "pages/hls__book_1.md"]
);
for t in ["contents", "favorites", "hls__book_1"] {
assert!(g.page_by_title(t).unwrap().is_none(), "{t}");
}
assert_eq!(
texts(&g, "TODO").len(),
1,
"other built-ins import normally"
);
assert_eq!(g.page_by_title("card").unwrap().unwrap().id, card.id);
let keep = ImportOptions {
skip_legacy_pages: false,
..Default::default()
};
let dir2 = tempfile::tempdir().unwrap();
let g2 = Graph::open(dir2.path()).unwrap();
let r = import_logseq(src.path(), &g2, &keep, |_| {}).unwrap();
assert!(r.skipped_legacy.is_empty());
assert!(g2.page_by_title("contents").unwrap().is_some());
}
#[test]
fn reimport_never_writes_hubs() {
let src = mini_graph(&[
("pages/Area.md", "- [[Note]]\n- more\n"),
("pages/Note.md", "- body\n"),
]);
let dir = tempfile::tempdir().unwrap();
let g = Graph::open(dir.path()).unwrap();
imp(src.path(), &g);
let area = g.page_by_title("Area").unwrap().unwrap();
let note = g.page_by_title("Note").unwrap().unwrap();
g.convert_to_hub(
area.id,
&synapse_core::HubConversion {
title: "Area".into(),
description: "d".into(),
members: vec![note.id],
keep_outline_as: None,
},
)
.unwrap();
std::fs::write(src.path().join("pages/Area.md"), "- [[Note]]\n- changed\n").unwrap();
let r = imp(src.path(), &g);
assert!(
r.warnings.iter().any(|w| w.contains("is a hub")),
"{:?}",
r.warnings
);
let area = g.page_by_title("Area").unwrap().unwrap();
assert!(area.is_hub());
assert!(g.page_tree(area.id).unwrap().is_empty());
assert_eq!(g.hub_members(area.id).unwrap(), vec![note.id]);
}