feat(import): Logseq graph importer

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-10-21 03:38:22 +02:00
1 parent fbcfcf678f
commit a2a6cd8cfb
21 files changed
+1828

No files matched your search

Generated
+63
View File
@@ -97,6 +97,37 @@ dependencies = [
"libc",
]
[[package]]
name = "crossbeam-deque"
version = "0.8.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
dependencies = [
"crossbeam-epoch",
"crossbeam-utils",
]
[[package]]
name = "crossbeam-epoch"
version = "0.9.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
[[package]]
name = "either"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
[[package]]
name = "errno"
version = "0.3.14"
@@ -317,6 +348,26 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rayon"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
dependencies = [
"either",
"rayon-core",
]
[[package]]
name = "rayon-core"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
dependencies = [
"crossbeam-deque",
"crossbeam-utils",
]
[[package]]
name = "rusqlite"
version = "0.37.0"
@@ -453,6 +504,18 @@ dependencies = [
"uuid",
]
[[package]]
name = "synapse-import"
version = "0.1.0"
dependencies = [
"chrono",
"rayon",
"serde_json",
"synapse-core",
"tempfile",
"uuid",
]
[[package]]
name = "tempfile"
version = "3.27.0"
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "synapse-import"
version = "0.1.0"
edition.workspace = true
license.workspace = true
description = "Logseq graph importer into a Synapse graph"
[dependencies]
synapse-core.workspace = true
chrono.workspace = true
uuid.workspace = true
serde_json.workspace = true
# Parallel parsing of thousands of files.
rayon = "1"
[dev-dependencies]
tempfile = "3"
+54
View File
@@ -0,0 +1,54 @@
//! `cargo run -p synapse-import --example import -- <logseq_dir> <graph_dir> [--skip-existing]`
use std::path::PathBuf;
use synapse_core::Graph;
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 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]");
std::process::exit(2);
};
let graph = Graph::open(dst).expect("open graph");
let opts = ImportOptions {
existing: if skip {
ExistingPages::Skip
} else {
ExistingPages::Update
},
};
let started = std::time::Instant::now();
let mut last = (None, 0);
let report = import_logseq(src, &graph, &opts, |p| {
let step = (p.done * 20).checked_div(p.total).unwrap_or(0);
if last != (Some(p.phase), step) {
eprintln!("{:?}: {}/{}", p.phase, p.done, p.total);
last = (Some(p.phase), step);
}
})
.expect("import failed");
println!(
"pages {} | journals {} | blocks {} | assets {} ({} bytes) | updated {} | unchanged {} | {:.2?}",
report.pages,
report.journals,
report.blocks,
report.assets,
report.bytes,
report.updated,
report.unchanged,
started.elapsed()
);
for f in &report.org_files {
println!("org (raw): {f}");
}
for w in &report.warnings {
println!("warning: {w}");
}
}
+229
View File
@@ -0,0 +1,229 @@
//! The few `logseq/config.edn` settings the importer needs, plus Logseq date formats.
use chrono::NaiveDate;
use std::path::Path;
#[derive(Debug, Clone)]
pub struct Config {
/// `:journal/file-name-format` (default `yyyy_MM_dd`).
pub journal_file_format: DateFormat,
/// `:journal/page-title-format` (default `MMM do, yyyy`).
pub journal_title_format: DateFormat,
/// `:file/name-format :triple-lowbar` (otherwise legacy: `.` separates namespaces).
pub triple_lowbar: bool,
}
impl Default for Config {
fn default() -> Self {
Self {
journal_file_format: DateFormat::new("yyyy_MM_dd"),
journal_title_format: DateFormat::new("MMM do, yyyy"),
triple_lowbar: false,
}
}
}
impl Config {
pub fn load(graph_dir: &Path) -> Self {
match std::fs::read_to_string(graph_dir.join("logseq/config.edn")) {
Ok(text) => Self::from_edn(&text),
Err(_) => Self::default(),
}
}
pub fn from_edn(text: &str) -> Self {
let text: String = text
.lines()
.filter(|l| !l.trim_start().starts_with(';'))
.collect::<Vec<_>>()
.join("\n");
let mut c = Self::default();
if let Some(f) = edn_string(&text, ":journal/file-name-format") {
c.journal_file_format = DateFormat::new(&f);
}
if let Some(f) = edn_string(&text, ":journal/page-title-format") {
c.journal_title_format = DateFormat::new(&f);
}
c.triple_lowbar = text
.split_once(":file/name-format")
.is_some_and(|(_, rest)| rest.trim_start().starts_with(":triple-lowbar"));
c
}
}
fn edn_string(text: &str, key: &str) -> Option<String> {
let rest = text.split_once(key)?.1.trim_start().strip_prefix('"')?;
Some(rest.split_once('"')?.0.to_string())
}
#[derive(Debug, Clone, PartialEq)]
enum Tok {
Year4,
Year2,
Month(u8), // 1, 2 digits, 3 = short name, 4 = full name
Day, // d / dd
DayOrd, // do (1st, 2nd...)
Weekday,
Lit(char),
}
/// Parser for the Java-style date patterns Logseq uses.
#[derive(Debug, Clone)]
pub struct DateFormat {
toks: Vec<Tok>,
}
const MONTHS: [&str; 12] = [
"january",
"february",
"march",
"april",
"may",
"june",
"july",
"august",
"september",
"october",
"november",
"december",
];
impl DateFormat {
pub fn new(fmt: &str) -> Self {
let cs: Vec<char> = fmt.chars().collect();
let mut toks = Vec::new();
let mut i = 0;
while i < cs.len() {
let c = cs[i];
let run = cs[i..].iter().take_while(|&&x| x == c).count();
match c {
'y' => toks.push(if run >= 3 { Tok::Year4 } else { Tok::Year2 }),
'M' => toks.push(Tok::Month(run.min(4) as u8)),
'd' if cs.get(i + run) == Some(&'o') && run == 1 => {
toks.push(Tok::DayOrd);
i += 1;
}
'd' => toks.push(Tok::Day),
'E' => toks.push(Tok::Weekday),
_ => {
toks.extend(std::iter::repeat_n(Tok::Lit(c), run));
i += run;
continue;
}
}
i += run;
}
Self { toks }
}
/// Parses `s` completely; `None` if it does not match the format.
pub fn parse(&self, s: &str) -> Option<NaiveDate> {
let mut rest = s.trim();
let (mut y, mut m, mut d) = (None, None, None);
for t in &self.toks {
match t {
Tok::Year4 => {
let (v, r) = num(rest, 4, 4)?;
(y, rest) = (Some(v), r);
}
Tok::Year2 => {
let (v, r) = num(rest, 2, 2)?;
(y, rest) = (Some(2000 + v), r);
}
Tok::Month(n @ (1 | 2)) => {
let (v, r) = num(rest, if *n == 1 { 1 } else { 2 }, 2)?;
(m, rest) = (Some(v), r);
}
Tok::Month(n) => {
let (v, r) = month_name(rest, *n == 3)?;
(m, rest) = (Some(v), r);
}
Tok::Day => {
let (v, r) = num(rest, 1, 2)?;
(d, rest) = (Some(v), r);
}
Tok::DayOrd => {
let (v, r) = num(rest, 1, 2)?;
let r = r.get(2..).filter(|_| {
matches!(
r[..2].to_ascii_lowercase().as_str(),
"st" | "nd" | "rd" | "th"
)
})?;
(d, rest) = (Some(v), r);
}
Tok::Weekday => {
let n = rest.chars().take_while(|c| c.is_alphabetic()).count();
if n < 3 {
return None;
}
rest = &rest[n..];
}
Tok::Lit(c) => rest = rest.strip_prefix(*c)?,
}
}
if !rest.is_empty() {
return None;
}
NaiveDate::from_ymd_opt(y? as i32, m?, d?)
}
}
fn num(s: &str, min: usize, max: usize) -> Option<(u32, &str)> {
let n = s.bytes().take(max).take_while(u8::is_ascii_digit).count();
if n < min {
return None;
}
Some((s[..n].parse().ok()?, &s[n..]))
}
fn month_name(s: &str, short: bool) -> Option<(u32, &str)> {
let lower = s.to_ascii_lowercase();
for (i, name) in MONTHS.iter().enumerate() {
let n = if short { 3 } else { name.len() };
if lower.starts_with(&name[..n]) {
return Some((i as u32 + 1, &s[n..]));
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
fn d(y: i32, m: u32, d: u32) -> Option<NaiveDate> {
NaiveDate::from_ymd_opt(y, m, d)
}
#[test]
fn parses_formats() {
assert_eq!(
DateFormat::new("yyyy_MM_dd").parse("2024_03_15"),
d(2024, 3, 15)
);
assert_eq!(
DateFormat::new("MMM do, yyyy").parse("Mar 1st, 2024"),
d(2024, 3, 1)
);
assert_eq!(
DateFormat::new("EEEE, dd-MM-yyyy").parse("Friday, 15-03-2024"),
d(2024, 3, 15)
);
assert_eq!(
DateFormat::new("MMMM d, yyyy").parse("March 5, 2024"),
d(2024, 3, 5)
);
assert_eq!(DateFormat::new("yyyy_MM_dd").parse("2024_13_01"), None);
assert_eq!(DateFormat::new("yyyy_MM_dd").parse("2024_03_15x"), None);
}
#[test]
fn reads_edn() {
let c = Config::from_edn(
";; :journal/file-name-format \"bad\"\n{:journal/file-name-format \"yyyy-MM-dd\"\n :file/name-format :triple-lowbar}",
);
assert!(c.triple_lowbar);
assert_eq!(c.journal_file_format.parse("2024-03-15"), d(2024, 3, 15));
}
}
+606
View File
@@ -0,0 +1,606 @@
//! Logseq graph importer into a [`synapse_core::Graph`].
//!
//! Pipeline: scan → stream assets into the blob store → parse files in parallel (rayon) →
//! create page rows (so origin journals and timestamps are exact) → write blocks on one thread.
//! Block ids are deterministic (`id::` when present, else UUIDv5 of page + ordinal), which
//! makes re-imports idempotent.
mod config;
mod names;
mod outline;
mod rewrite;
use chrono::{Local, NaiveDate, TimeZone};
use config::Config;
use outline::{PBlock, parse_markdown, parse_org_raw, split_aliases};
use rayon::prelude::*;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use synapse_core::parse::extract_refs;
use synapse_core::{Block, Graph, NewPage, PageId, Properties, Result, title_key};
use uuid::Uuid;
pub use config::DateFormat;
/// Namespace for deterministic block ids of blocks without a Logseq `id::`.
const BLOCK_NS: Uuid = Uuid::from_u128(0x2b6d_41c9_0e87_4f3a_9d15_c7a8_e340_5b12);
const CHUNK: usize = 256;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ExistingPages {
/// Rewrite pages whose content differs (blocks are upserted by id, stale ones deleted).
#[default]
Update,
/// Leave pages that already have blocks untouched.
Skip,
}
#[derive(Debug, Clone, Default)]
pub struct ImportOptions {
pub existing: ExistingPages,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Phase {
Scanning,
Assets,
Parsing,
Pages,
Blocks,
}
#[derive(Debug, Clone, Copy)]
pub struct Progress {
pub phase: Phase,
pub done: usize,
pub total: usize,
}
#[derive(Debug, Clone, Default)]
pub struct Report {
/// Regular pages created or updated.
pub pages: usize,
/// Journal pages created or updated.
pub journals: usize,
/// Blocks written.
pub blocks: usize,
/// Asset files streamed into the blob store.
pub assets: usize,
/// Total size of those asset files.
pub bytes: u64,
/// Pages/journals that already existed and were rewritten.
pub updated: usize,
/// Pages/journals left alone (identical content, or `ExistingPages::Skip`).
pub unchanged: usize,
/// `.org` files imported as raw blocks (relative paths).
pub org_files: Vec<String>,
pub warnings: Vec<String>,
}
struct FileEntry {
path: PathBuf,
rel: String,
stem: String,
org: bool,
journal: bool,
}
struct Doc {
rel: String,
title: String,
key: String,
journal: Option<NaiveDate>,
org: bool,
created: i64,
updated: i64,
props: Properties,
aliases: Vec<String>,
blocks: Vec<PBlock>,
/// Lower-cased page titles referenced by this doc (journals only; origin computation).
refs: Vec<String>,
warnings: Vec<String>,
}
/// Imports the Logseq graph in `src` into `graph`.
pub fn import_logseq(
src: &Path,
graph: &Graph,
opts: &ImportOptions,
mut progress: impl FnMut(Progress),
) -> Result<Report> {
if !src.join("pages").is_dir() && !src.join("journals").is_dir() {
return Err(synapse_core::Error::Invalid(format!(
"{} is not a Logseq graph (no pages/ or journals/)",
src.display()
)));
}
let mut report = Report::default();
let cfg = Config::load(src);
progress(Progress {
phase: Phase::Scanning,
done: 0,
total: 0,
});
let files = scan(src, &mut report.warnings);
let asset_files = scan_assets(&src.join("assets"));
// ---- assets: streamed one by one (constant memory, multi-GB safe)
let mut asset_map: HashMap<String, String> = HashMap::new();
for (i, (rel, path)) in asset_files.iter().enumerate() {
progress(Progress {
phase: Phase::Assets,
done: i,
total: asset_files.len(),
});
let name = path.file_name().map(|n| n.to_string_lossy().into_owned());
let mime = name.as_deref().and_then(rewrite::guess_mime);
match graph.put_asset_file(path, mime) {
Ok(a) => {
report.assets += 1;
report.bytes += a.size;
asset_map.insert(rel.clone(), a.hash);
}
Err(e) => report.warnings.push(format!("asset {rel}: {e}")),
}
}
// ---- parse in parallel, in chunks so progress can be reported from this thread
let mut docs: Vec<Doc> = Vec::with_capacity(files.len());
for chunk in files.chunks(CHUNK) {
progress(Progress {
phase: Phase::Parsing,
done: docs.len(),
total: files.len(),
});
let parsed: Vec<Doc> = chunk
.par_iter()
.map(|f| parse_doc(f, &cfg, &asset_map))
.collect();
docs.extend(parsed);
}
let docs = dedupe(docs, &mut report.warnings);
// ---- origin journals: earliest journal referencing each page (aliases resolved)
let mut alias_to_key: HashMap<String, String> = HashMap::new();
for d in &docs {
for a in &d.aliases {
alias_to_key.insert(title_key(a), d.key.clone());
}
}
let mut origin: HashMap<String, NaiveDate> = HashMap::new();
for d in &docs {
let Some(date) = d.journal else { continue };
for r in &d.refs {
let key = alias_to_key.get(r).unwrap_or(r);
origin
.entry(key.clone())
.and_modify(|o| *o = (*o).min(date))
.or_insert(date);
}
}
// Every core write commits on its own; without fsyncs that is cheap. A crash mid-import
// only needs a re-import (idempotent), so durability per commit is not required.
let _ = graph.conn().pragma_update(None, "synchronous", "OFF");
let result = write_all(graph, opts, &docs, &origin, &mut report, &mut progress);
let _ = graph.conn().pragma_update(None, "synchronous", "NORMAL");
result?;
Ok(report)
}
fn write_all(
graph: &Graph,
opts: &ImportOptions,
docs: &[Doc],
origin: &HashMap<String, NaiveDate>,
report: &mut Report,
progress: &mut impl FnMut(Progress),
) -> Result<()> {
// ---- page rows first (so stubs created by block refs can't pre-empt exact metadata)
let mut order: Vec<usize> = (0..docs.len()).collect();
order.sort_by(|&a, &b| {
(docs[a].journal.is_none(), docs[a].journal, &docs[a].key).cmp(&(
docs[b].journal.is_none(),
docs[b].journal,
&docs[b].key,
))
});
let mut ids: HashMap<usize, (PageId, bool)> = HashMap::new();
for (n, &i) in order.iter().enumerate() {
progress(Progress {
phase: Phase::Pages,
done: n,
total: order.len(),
});
let d = &docs[i];
match ensure_page(graph, d, origin.get(&d.key).copied()) {
Ok(r) => {
ids.insert(i, r);
}
Err(e) => report.warnings.push(format!("{}: {e}", d.rel)),
}
}
// ---- aliases before any block, so `[[alias]]` refs don't spawn stub pages
for (&i, &(pid, _)) in &ids {
set_aliases(graph, &docs[i], pid, &mut report.warnings)?;
}
// ---- blocks
for (n, &i) in order.iter().enumerate() {
progress(Progress {
phase: Phase::Blocks,
done: n,
total: order.len(),
});
let Some(&(pid, existed)) = ids.get(&i) else {
continue;
};
let d = &docs[i];
match write_doc(graph, d, pid, existed, opts, report) {
Ok(()) => {}
Err(e) => report.warnings.push(format!("{}: {e}", d.rel)),
}
}
progress(Progress {
phase: Phase::Blocks,
done: order.len(),
total: order.len(),
});
Ok(())
}
fn scan(src: &Path, warnings: &mut Vec<String>) -> Vec<FileEntry> {
let mut out = Vec::new();
for (dir, journal) in [("pages", false), ("journals", true)] {
let Ok(rd) = fs::read_dir(src.join(dir)) else {
continue;
};
for e in rd.flatten() {
let path = e.path();
let name = e.file_name().to_string_lossy().into_owned();
if name.starts_with('.') || !path.is_file() {
continue;
}
let Some((stem, ext)) = name.rsplit_once('.') else {
continue;
};
let org = match ext.to_ascii_lowercase().as_str() {
"md" | "markdown" => false,
"org" => true,
_ => {
warnings.push(format!("{dir}/{name}: unsupported file type, skipped"));
continue;
}
};
out.push(FileEntry {
path,
rel: format!("{dir}/{name}"),
stem: stem.to_string(),
org,
journal,
});
}
}
out.sort_by(|a, b| a.rel.cmp(&b.rel));
out
}
/// All files under `assets/` as `(path relative to assets with '/', absolute path)`.
fn scan_assets(root: &Path) -> Vec<(String, PathBuf)> {
let mut out = Vec::new();
let mut stack = vec![root.to_path_buf()];
while let Some(dir) = stack.pop() {
let Ok(rd) = fs::read_dir(&dir) else { continue };
for e in rd.flatten() {
let p = e.path();
if e.file_name().to_string_lossy().starts_with('.') {
continue;
}
if p.is_dir() {
stack.push(p);
} else if p.is_file()
&& let Ok(rel) = p.strip_prefix(root)
{
let rel = rel
.components()
.map(|c| c.as_os_str().to_string_lossy().into_owned())
.collect::<Vec<_>>()
.join("/");
out.push((rel, p));
}
}
}
out.sort();
out
}
fn ms(t: SystemTime) -> i64 {
t.duration_since(SystemTime::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or(0)
}
fn day_of(ms: i64) -> NaiveDate {
Local
.timestamp_millis_opt(ms)
.single()
.map(|d| d.date_naive())
.unwrap_or_default()
}
fn parse_doc(f: &FileEntry, cfg: &Config, assets: &HashMap<String, String>) -> Doc {
let mut warnings = Vec::new();
let (mut created, mut updated) = (0, 0);
if let Ok(m) = fs::metadata(&f.path) {
updated = m.modified().map(ms).unwrap_or(0);
created = m.created().map(ms).unwrap_or(updated).min(updated);
}
let text = match fs::read(&f.path) {
Ok(b) => {
let s = String::from_utf8_lossy(&b).into_owned();
s.strip_prefix('\u{feff}').map(str::to_string).unwrap_or(s)
}
Err(e) => {
warnings.push(format!("{}: {e}", f.rel));
String::new()
}
};
let journal = if f.journal {
let d = names::journal_date(&f.stem, cfg);
if d.is_none() {
warnings.push(format!(
"{}: not a journal file name, imported as a page",
f.rel
));
}
d
} else {
None
};
let (mut props, mut blocks) = if f.org {
(Properties::new(), parse_org_raw(&text))
} else {
let o = parse_markdown(&text);
(o.page_props, o.blocks)
};
let mut title = match journal {
Some(d) => synapse_core::journal_title(d),
None => names::title_from_stem(&f.stem, cfg),
};
if journal.is_none()
&& let Some(t) = props
.remove("title")
.and_then(|v| v.as_str().map(str::to_string))
&& !t.trim().is_empty()
{
title = t.trim().to_string();
}
let aliases = props
.get("alias")
.and_then(|v| v.as_str())
.map(split_aliases)
.unwrap_or_default();
let mut missing = Vec::new();
for b in &mut blocks {
b.content = rewrite::rewrite_dates(&b.content, &cfg.journal_title_format);
b.content = rewrite::rewrite_assets(&b.content, assets, &mut missing);
for v in b.properties.values_mut() {
if let Some(s) = v.as_str() {
let s = rewrite::rewrite_dates(s, &cfg.journal_title_format);
*v = serde_json::Value::String(rewrite::rewrite_assets(&s, assets, &mut missing));
}
}
}
missing.sort();
missing.dedup();
for m in missing {
warnings.push(format!("{}: missing asset {m}", f.rel));
}
let mut refs = Vec::new();
if journal.is_some() {
let mut seen = HashSet::new();
for b in &blocks {
let prop_text = b
.properties
.values()
.filter_map(|v| v.as_str())
.collect::<Vec<_>>()
.join("\n");
for t in [&b.content, &prop_text] {
for (title, _) in extract_refs(t).pages {
let k = title_key(&title);
if seen.insert(k.clone()) {
refs.push(k);
}
}
}
}
}
Doc {
rel: f.rel.clone(),
key: title_key(&title),
title,
journal,
org: f.org,
created,
updated,
props,
aliases,
blocks,
refs,
warnings,
}
}
/// Drops docs whose title (or journal date) is already taken; `.md` wins over `.org`.
fn dedupe(mut docs: Vec<Doc>, warnings: &mut Vec<String>) -> Vec<Doc> {
docs.sort_by(|a, b| (a.org, &a.rel).cmp(&(b.org, &b.rel)));
let mut seen: HashMap<String, String> = HashMap::new();
let mut out = Vec::with_capacity(docs.len());
for mut d in docs {
warnings.append(&mut d.warnings);
if let Some(first) = seen.get(&d.key) {
warnings.push(format!("{}: same page as {first}, skipped", d.rel));
continue;
}
seen.insert(d.key.clone(), d.rel.clone());
out.push(d);
}
out
}
/// Finds or creates the page row. Returns `(id, already existed)`.
fn ensure_page(g: &Graph, d: &Doc, origin: Option<NaiveDate>) -> Result<(PageId, bool)> {
if let Some(date) = d.journal {
let existed = g.get_page(synapse_core::store::journal_id(date))?.is_some();
let p = g.journal(date)?;
return Ok((p.id, existed));
}
if let Some(p) = g.page_by_title(&d.title)? {
if title_key(&p.title) != d.key {
return Err(synapse_core::Error::Conflict(format!(
"title {:?} is already an alias of {:?}",
d.title, p.title
)));
}
return Ok((p.id, true));
}
let p = g.create_page(NewPage {
title: d.title.clone(),
origin_journal: Some(origin.unwrap_or_else(|| day_of(d.created))),
properties: d.props.clone(),
created_at: Some(d.created),
updated_at: Some(d.updated),
})?;
Ok((p.id, false))
}
fn write_doc(
g: &Graph,
d: &Doc,
pid: PageId,
existed: bool,
opts: &ImportOptions,
report: &mut Report,
) -> Result<()> {
let existing = if existed { g.page_tree(pid)? } else { vec![] };
if existed && opts.existing == ExistingPages::Skip && !existing.is_empty() {
report.unchanged += 1;
return Ok(());
}
// Final ids: Logseq `id::` when free, else deterministic.
let mut ids: Vec<Uuid> = Vec::with_capacity(d.blocks.len());
let mut used: HashSet<Uuid> = HashSet::new();
for (i, b) in d.blocks.iter().enumerate() {
let fallback = || Uuid::new_v5(&BLOCK_NS, format!("{}\0{i}", d.key).as_bytes());
let id = match b.explicit_id {
Some(id) => {
let taken_elsewhere =
!used.contains(&id) && g.get_block(id)?.is_some_and(|x| x.page_id != pid);
if used.contains(&id) || taken_elsewhere {
report.warnings.push(format!(
"{}: duplicate block id {id}, generated a new one",
d.rel
));
fallback()
} else {
id
}
}
None => fallback(),
};
used.insert(id);
ids.push(id);
}
let blocks: Vec<Block> = d
.blocks
.iter()
.enumerate()
.map(|(i, b)| Block {
id: ids[i],
page_id: pid,
parent_id: b.parent.map(|p| ids[p]),
position: b.position.clone(),
content: b.content.clone(),
properties: b.properties.clone(),
collapsed: b.collapsed,
created_at: d.created,
updated_at: d.updated,
})
.collect();
let page = g.get_page(pid)?;
let props_differ = page.as_ref().is_some_and(|p| p.properties != d.props);
let old: HashMap<Uuid, &Block> = existing.iter().map(|(_, b)| (b.id, b)).collect();
let same_blocks = old.len() == blocks.len()
&& blocks.iter().all(|b| {
old.get(&b.id).is_some_and(|o| {
(
o.parent_id,
&o.position,
&o.content,
&o.properties,
o.collapsed,
) == (
b.parent_id,
&b.position,
&b.content,
&b.properties,
b.collapsed,
)
})
});
if existed && same_blocks && !props_differ {
report.unchanged += 1;
} else {
for b in &blocks {
g.put_block(b)?;
}
let stale: Vec<Uuid> = old
.keys()
.filter(|id| !used.contains(id))
.copied()
.collect();
for id in stale {
match g.delete_block(id) {
Ok(()) | Err(synapse_core::Error::NotFound(_)) => {}
Err(e) => return Err(e),
}
}
if props_differ {
g.set_page_properties(pid, d.props.clone())?;
}
report.blocks += blocks.len();
if d.journal.is_some() {
report.journals += 1;
} else {
report.pages += 1;
}
if existed {
report.updated += 1;
}
if d.org {
report.org_files.push(d.rel.clone());
}
}
Ok(())
}
fn set_aliases(g: &Graph, d: &Doc, pid: PageId, warnings: &mut Vec<String>) -> Result<()> {
for a in &d.aliases {
if title_key(a) != d.key
&& g.page_by_title(a)?.is_none_or(|p| p.id != pid)
&& let Err(e) = g.set_alias(a, Some(pid))
{
warnings.push(format!("{}: alias {a:?}: {e}", d.rel));
}
}
Ok(())
}
+71
View File
@@ -0,0 +1,71 @@
//! Logseq file-name encodings.
use crate::config::Config;
use chrono::NaiveDate;
/// Percent-decodes `%XX` sequences (invalid ones are kept verbatim).
pub fn percent_decode(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
if b[i] == b'%'
&& let Some(v) = s
.get(i + 1..i + 3)
.filter(|h| h.bytes().all(|c| c.is_ascii_hexdigit()))
.and_then(|h| u8::from_str_radix(h, 16).ok())
{
out.push(v);
i += 3;
continue;
}
out.push(b[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
/// Page title encoded in a file stem (`a___b` / `a.b` → `a/b`, `%2F` → `/`).
pub fn title_from_stem(stem: &str, cfg: &Config) -> String {
let sep = if cfg.triple_lowbar { "___" } else { "." };
stem.split(sep)
.map(percent_decode)
.collect::<Vec<_>>()
.join("/")
}
/// Journal date of a file stem, using the configured format with common fallbacks.
pub fn journal_date(stem: &str, cfg: &Config) -> Option<NaiveDate> {
cfg.journal_file_format
.parse(stem)
.or_else(|| NaiveDate::parse_from_str(stem, "%Y_%m_%d").ok())
.or_else(|| NaiveDate::parse_from_str(stem, "%Y-%m-%d").ok())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decodes_titles() {
let tl = Config {
triple_lowbar: true,
..Config::default()
};
assert_eq!(title_from_stem("a___b%3F", &tl), "a/b?");
assert_eq!(title_from_stem("a%2Fb", &tl), "a/b");
assert_eq!(title_from_stem("a.b", &Config::default()), "a/b");
assert_eq!(title_from_stem("100%", &tl), "100%");
assert_eq!(title_from_stem("caf%C3%A9", &tl), "café");
}
#[test]
fn journal_names() {
let c = Config::default();
assert_eq!(
journal_date("2024_03_15", &c),
NaiveDate::from_ymd_opt(2024, 3, 15)
);
assert_eq!(journal_date("notes", &c), None);
}
}
+369
View File
@@ -0,0 +1,369 @@
//! Parser for Logseq Markdown outlines (and raw `.org` files) into a block tree.
use serde_json::Value;
use synapse_core::Properties;
use synapse_core::parse::property_split;
use synapse_core::position::between;
use uuid::Uuid;
#[derive(Debug, Clone)]
pub struct PBlock {
/// Logseq `id::` when present and valid.
pub explicit_id: Option<Uuid>,
/// Index of the parent in the block list.
pub parent: Option<usize>,
pub position: String,
pub content: String,
pub properties: Properties,
pub collapsed: bool,
}
#[derive(Debug, Default)]
pub struct Outline {
/// Page-level properties (first property-only block or lines before the first bullet).
pub page_props: Properties,
pub blocks: Vec<PBlock>,
}
struct Raw {
indent: usize,
parent: Option<usize>,
lines: Vec<String>,
}
fn indent_width(line: &str) -> usize {
line.chars()
.take_while(|c| *c == ' ' || *c == '\t')
.map(|c| if c == '\t' { 4 } else { 1 })
.sum()
}
/// Removes up to `width` columns of leading whitespace.
fn strip_indent(line: &str, width: usize) -> &str {
let mut w = 0;
for (i, c) in line.char_indices() {
if w >= width || (c != ' ' && c != '\t') {
return &line[i..];
}
w += if c == '\t' { 4 } else { 1 };
}
""
}
fn bullet_text(line: &str) -> Option<&str> {
let t = line.trim_start_matches([' ', '\t']);
if t == "-" {
Some("")
} else {
t.strip_prefix("- ")
}
}
fn is_fence(line: &str) -> bool {
line.trim_start().starts_with("```")
}
pub fn parse_markdown(text: &str) -> Outline {
let mut pre: Vec<&str> = Vec::new();
let mut raws: Vec<Raw> = Vec::new();
let mut stack: Vec<usize> = Vec::new();
let mut in_fence = false;
for line in text.lines() {
let bullet = if in_fence { None } else { bullet_text(line) };
if let Some(first) = bullet {
let indent = indent_width(line);
while stack.last().is_some_and(|&i| raws[i].indent >= indent) {
stack.pop();
}
raws.push(Raw {
indent,
parent: stack.last().copied(),
lines: vec![first.to_string()],
});
stack.push(raws.len() - 1);
in_fence = is_fence(first);
} else if let Some(cur) = raws.last_mut() {
if is_fence(line) {
in_fence = !in_fence;
}
cur.lines
.push(strip_indent(line, cur.indent + 2).to_string());
} else {
pre.push(line);
}
}
let mut out = Outline::default();
let mut pre_text_lines = parse_pre(&pre, &mut out.page_props);
// Plain Markdown without bullets: one root block per paragraph.
let mut lead: Vec<Raw> = Vec::new();
if raws.is_empty() {
for para in split_paragraphs(&mut pre_text_lines) {
lead.push(Raw {
indent: 0,
parent: None,
lines: para,
});
}
} else if pre_text_lines.iter().any(|l| !l.trim().is_empty()) {
lead.push(Raw {
indent: 0,
parent: None,
lines: pre_text_lines,
});
}
let shift = lead.len();
let all: Vec<Raw> = lead
.into_iter()
.chain(raws.into_iter().map(|mut r| {
r.parent = r.parent.map(|p| p + shift);
r
}))
.collect();
// Build blocks; positions are assigned sequentially per parent.
let mut last_pos: std::collections::HashMap<Option<usize>, String> = Default::default();
let mut first_block_props = false;
let first_has_kids = all.iter().any(|r| r.parent == Some(0));
for (i, raw) in all.into_iter().enumerate() {
let (content, props) = split_props(raw.lines);
let (explicit_id, collapsed, props) = take_structural(props);
if i == 0
&& raw.parent.is_none()
&& content.trim().is_empty()
&& !props.is_empty()
&& out.page_props.is_empty()
&& !first_has_kids
{
// First block holds only properties: they belong to the page.
first_block_props = true;
out.page_props = props;
continue;
}
let position = between(last_pos.get(&raw.parent).map(String::as_str), None);
last_pos.insert(raw.parent, position.clone());
out.blocks.push(PBlock {
explicit_id,
parent: raw.parent,
position,
content,
properties: props,
collapsed,
});
}
fix_parents(&mut out.blocks, first_block_props);
out
}
/// When the first block was consumed as page properties, every stored parent index (which
/// counted that block) is shifted down by one.
fn fix_parents(blocks: &mut [PBlock], skipped_first: bool) {
if skipped_first {
for b in blocks {
b.parent = b.parent.map(|p| p - 1);
}
}
}
/// Splits the lines before the first bullet into page properties and leftover text.
fn parse_pre(pre: &[&str], props: &mut Properties) -> Vec<String> {
let mut lines: Vec<&str> = pre.to_vec();
// YAML front matter.
if lines.first().is_some_and(|l| l.trim() == "---")
&& let Some(end) = lines[1..].iter().position(|l| l.trim() == "---")
{
for l in &lines[1..=end] {
if let Some((k, v)) = l.split_once(':') {
props.insert(k.trim().to_string(), Value::String(v.trim().to_string()));
}
}
lines.drain(..end + 2);
}
let mut i = 0;
while i < lines.len() {
if let Some((k, v)) = property_split(lines[i]) {
props.insert(k.to_string(), Value::String(v.to_string()));
} else if !lines[i].trim().is_empty() {
break;
}
i += 1;
}
lines[i..].iter().map(|s| s.to_string()).collect()
}
fn split_paragraphs(lines: &mut Vec<String>) -> Vec<Vec<String>> {
let mut out: Vec<Vec<String>> = Vec::new();
let mut cur: Vec<String> = Vec::new();
let mut fence = false;
for l in lines.drain(..) {
if is_fence(&l) {
fence = !fence;
}
if l.trim().is_empty() && !fence {
if !cur.is_empty() {
out.push(std::mem::take(&mut cur));
}
} else {
cur.push(l);
}
}
if !cur.is_empty() {
out.push(cur);
}
out
}
/// Separates `key:: value` lines (right after the first line, or from the start when the first
/// line is itself a property) from the text content.
fn split_props(mut lines: Vec<String>) -> (String, Properties) {
while lines.last().is_some_and(|l| l.trim().is_empty()) {
lines.pop();
}
let mut props = Properties::new();
let first_is_prop = lines.first().is_some_and(|l| property_split(l).is_some());
let start = usize::from(!first_is_prop);
let mut end = start;
while end < lines.len() {
match property_split(&lines[end]) {
Some((k, v)) => {
props.insert(k.to_string(), Value::String(v.to_string()));
end += 1;
}
None => break,
}
}
lines.drain(start..end);
// Properties may also trail a multi-line block.
let mut tail = lines.len();
while tail > 1 && property_split(&lines[tail - 1]).is_some() {
tail -= 1;
}
if tail < lines.len()
&& !lines[..tail]
.iter()
.filter(|l| is_fence(l))
.count()
.is_multiple_of(2)
{
tail = lines.len();
}
for l in lines.drain(tail..) {
if let Some((k, v)) = property_split(&l) {
props.insert(k.to_string(), Value::String(v.to_string()));
}
}
(lines.join("\n"), props)
}
fn take_structural(mut props: Properties) -> (Option<Uuid>, bool, Properties) {
let id = props
.remove("id")
.and_then(|v| v.as_str().and_then(|s| Uuid::parse_str(s.trim()).ok()));
let collapsed = props
.remove("collapsed")
.is_some_and(|v| v.as_str().is_some_and(|s| s.trim() == "true"));
(id, collapsed, props)
}
/// `.org` files are imported as raw text: one root block per top-level heading.
pub fn parse_org_raw(text: &str) -> Vec<PBlock> {
let mut chunks: Vec<Vec<&str>> = vec![Vec::new()];
for l in text.lines() {
if l.starts_with("* ") && chunks.last().is_some_and(|c| !c.is_empty()) {
chunks.push(Vec::new());
}
chunks.last_mut().unwrap().push(l);
}
let mut prev: Option<String> = None;
let mut out = Vec::new();
for c in chunks {
let content = c.join("\n").trim_end().to_string();
if content.trim().is_empty() {
continue;
}
let position = between(prev.as_deref(), None);
prev = Some(position.clone());
out.push(PBlock {
explicit_id: None,
parent: None,
position,
content,
properties: Properties::new(),
collapsed: false,
});
}
out
}
/// Aliases from an `alias::` value: comma separated, optionally `[[wrapped]]`.
pub fn split_aliases(value: &str) -> Vec<String> {
let mut out = Vec::new();
let mut cur = String::new();
let mut depth = 0;
for c in value.chars() {
match c {
'[' => depth += 1,
']' => depth = (depth - 1).max(0),
',' if depth == 0 => {
out.push(std::mem::take(&mut cur));
continue;
}
_ => {}
}
cur.push(c);
}
out.push(cur);
out.into_iter()
.map(|a| {
a.trim()
.trim_start_matches("[[")
.trim_end_matches("]]")
.trim()
.to_string()
})
.filter(|a| !a.is_empty())
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nesting_and_multiline() {
let o = parse_markdown(
"- a\n\t- b\n\t more\n\t k:: v\n\t\t- c\n- d\n ```\n - not a bullet\n ```\n",
);
let b = &o.blocks;
assert_eq!(b.len(), 4);
assert_eq!(b[1].parent, Some(0));
assert_eq!(b[1].content, "b\nmore");
assert_eq!(b[1].properties["k"], "v");
assert_eq!(b[2].parent, Some(1));
assert_eq!(b[3].parent, None);
assert!(b[3].content.contains("- not a bullet"));
assert!(b[0].position < b[3].position);
}
#[test]
fn page_props_and_structural() {
let o = parse_markdown(
"alias:: x, [[y z]]\n\n- id:: 11111111-1111-4111-8111-111111111111\n hello\n collapsed:: true\n - child\n",
);
assert_eq!(o.page_props["alias"], "x, [[y z]]");
assert_eq!(o.blocks.len(), 2);
assert!(o.blocks[0].explicit_id.is_some());
assert!(o.blocks[0].collapsed);
assert_eq!(o.blocks[1].parent, Some(0));
let o = parse_markdown("- title:: T\n alias:: a\n- real\n - kid\n");
assert_eq!(o.page_props["title"], "T");
assert_eq!(o.blocks.len(), 2);
assert_eq!(o.blocks[1].parent, Some(0));
}
#[test]
fn aliases() {
assert_eq!(split_aliases("a, [[b, c]], d"), vec!["a", "b, c", "d"]);
}
}
+153
View File
@@ -0,0 +1,153 @@
//! Content rewrites applied to every block: asset links and Logseq date page links.
use crate::config::DateFormat;
use crate::names::percent_decode;
use std::collections::HashMap;
const NEEDLE: &str = "../assets/";
/// Replaces `../assets/<path>` with `asset://<blake3>` keeping the surrounding Markdown
/// syntax. Paths not found in `assets` are left untouched and pushed to `missing`.
pub fn rewrite_assets(
content: &str,
assets: &HashMap<String, String>,
missing: &mut Vec<String>,
) -> String {
if !content.contains(NEEDLE) {
return content.to_string();
}
let mut out = String::with_capacity(content.len());
let mut last = 0;
for (idx, _) in content.match_indices(NEEDLE) {
if idx < last {
continue;
}
let tail = &content[idx..];
let end = match content[..idx].chars().next_back() {
Some('(') => tail.find([')', '\n']),
Some(q @ ('"' | '\'')) => tail.find([q, '\n']),
_ => tail.find(|c: char| {
c.is_whitespace() || matches!(c, ')' | ']' | '}' | '"' | '\'' | '<' | '>')
}),
}
.unwrap_or(tail.len());
let raw = &tail[..end];
let (path, suffix) = match raw.find(['?', '#']) {
Some(i) => raw.split_at(i),
None => (raw, ""),
};
let enc = &path[NEEDLE.len()..];
let dec = percent_decode(enc);
match assets.get(&dec).or_else(|| assets.get(enc)) {
Some(hash) => {
out.push_str(&content[last..idx]);
out.push_str("asset://");
out.push_str(hash);
out.push_str(suffix);
last = idx + end;
}
None => missing.push(dec),
}
}
out.push_str(&content[last..]);
out
}
/// Rewrites `[[Mar 15th, 2024]]` (the configured journal title format) to `[[2024-03-15]]`,
/// the title Synapse gives journal pages. Code fences are left alone.
pub fn rewrite_dates(content: &str, fmt: &DateFormat) -> String {
if !content.contains("[[") {
return content.to_string();
}
let mut fence = false;
let mut lines = Vec::new();
for line in content.split('\n') {
if line.trim_start().starts_with("```") {
fence = !fence;
}
lines.push(if fence || !line.contains("[[") {
line.to_string()
} else {
rewrite_line(line, fmt)
});
}
lines.join("\n")
}
fn rewrite_line(line: &str, fmt: &DateFormat) -> String {
let mut out = String::with_capacity(line.len());
let mut rest = line;
while let Some(open) = rest.find("[[") {
let after = &rest[open + 2..];
let Some(close) = after.find("]]") else { break };
let inner = &after[..close];
out.push_str(&rest[..open + 2]);
match fmt.parse(inner).filter(|_| !inner.contains("[[")) {
Some(d) => out.push_str(&d.format("%Y-%m-%d").to_string()),
None => out.push_str(inner),
}
out.push_str("]]");
rest = &after[close + 2..];
}
out.push_str(rest);
out
}
pub fn guess_mime(name: &str) -> Option<&'static str> {
let ext = name.rsplit_once('.')?.1.to_ascii_lowercase();
Some(match ext.as_str() {
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"webp" => "image/webp",
"svg" => "image/svg+xml",
"bmp" => "image/bmp",
"pdf" => "application/pdf",
"mp4" => "video/mp4",
"webm" => "video/webm",
"mov" => "video/quicktime",
"mkv" => "video/x-matroska",
"mp3" => "audio/mpeg",
"wav" => "audio/wav",
"ogg" => "audio/ogg",
"m4a" => "audio/mp4",
"txt" | "md" => "text/plain",
"json" => "application/json",
"csv" => "text/csv",
"zip" => "application/zip",
"html" => "text/html",
_ => return None,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rewrites_asset_links() {
let mut map = HashMap::new();
map.insert("my pic.png".to_string(), "abc".to_string());
map.insert("doc.pdf".to_string(), "def".to_string());
let mut missing = Vec::new();
let s = "![alt](../assets/my%20pic.png) [d](../assets/doc.pdf#p=2) {{video ../assets/nope.mp4}}";
let out = rewrite_assets(s, &map, &mut missing);
assert_eq!(
out,
"![alt](asset://abc) [d](asset://def#p=2) {{video ../assets/nope.mp4}}"
);
assert_eq!(missing, vec!["nope.mp4"]);
}
#[test]
fn rewrites_dates() {
let f = DateFormat::new("MMM do, yyyy");
assert_eq!(
rewrite_dates(
"see [[Mar 15th, 2024]] and [[Other]] #[[Jan 1st, 2020]]",
&f
),
"see [[2024-03-15]] and [[Other]] #[[2020-01-01]]"
);
}
}
@@ -0,0 +1 @@
PNGDATA
@@ -0,0 +1 @@
PDFDATA
@@ -0,0 +1 @@
- Early thought on [[Ideas]] and #[[Alpha Alias]]
@@ -0,0 +1,3 @@
- Met about [[Ideas]]
- Linked to [[Mar 16th, 2024]]
- Embeds ((11111111-1111-4111-8111-111111111111))
@@ -0,0 +1,5 @@
{:meta/version 1
;; :journal/file-name-format "bad"
:journal/page-title-format "MMM do, yyyy"
:journal/file-name-format "yyyy_MM_dd"
:file/name-format :triple-lowbar}
@@ -0,0 +1,9 @@
alias:: an, [[Alpha Alias]]
type:: [[Note]]
- First block
id:: 11111111-1111-4111-8111-111111111111
- Second
with a continuation line
collapsed:: true
- hidden child
@@ -0,0 +1,2 @@
- Idea one
- Idea two
@@ -0,0 +1,4 @@
* Heading one
some text
** sub
* Heading two
@@ -0,0 +1,7 @@
- Picture ![diagram](../assets/pic%20one.png)
- Doc [spec](../assets/sub/doc.pdf)
- Missing ![x](../assets/nope.png)
- ```rust
- not a bullet
```
id:: 22222222-2222-4222-8222-222222222222
@@ -0,0 +1,4 @@
- Root of the project
- Tasks
- TODO write the importer
- see [[Alpha Notes]] and ((22222222-2222-4222-8222-222222222222))
@@ -0,0 +1,2 @@
- title:: Fancy Title: Q&A
- body
+184
View File
@@ -0,0 +1,184 @@
use std::path::{Path, PathBuf};
use synapse_core::Graph;
use synapse_import::{ExistingPages, ImportOptions, Phase, Report, import_logseq};
fn fixture() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/graph")
}
fn run(g: &Graph, opts: &ImportOptions) -> Report {
import_logseq(&fixture(), g, opts, |_| {}).unwrap()
}
fn texts(g: &Graph, title: &str) -> Vec<(usize, String)> {
let p = g.page_by_title(title).unwrap().expect(title);
g.page_tree(p.id)
.unwrap()
.into_iter()
.map(|(d, b)| (d, b.content))
.collect()
}
#[test]
fn imports_fixture_graph() {
let dir = tempfile::tempdir().unwrap();
let g = Graph::open(dir.path()).unwrap();
let mut phases = Vec::new();
let r = import_logseq(&fixture(), &g, &ImportOptions::default(), |p| {
phases.push(p.phase)
})
.unwrap();
assert!(phases.contains(&Phase::Assets) && phases.contains(&Phase::Blocks));
assert_eq!(r.journals, 2);
assert_eq!(r.pages, 6);
assert_eq!(r.assets, 2);
assert_eq!(r.org_files, vec!["pages/Legacy.org"]);
assert!(
r.warnings
.iter()
.any(|w| w.contains("missing asset nope.png"))
);
// namespace from file name, nesting
let t = texts(&g, "Project/Alpha");
assert_eq!(t[0], (0, "Root of the project".into()));
assert_eq!(t[2], (1, "TODO write the importer".into()));
// title:: override
assert!(g.page_by_title("Fancy Title: Q&A").unwrap().is_some());
// properties, aliases, block id kept, collapsed
let an = g.page_by_title("Alpha Notes").unwrap().unwrap();
assert_eq!(an.properties["type"], "[[Note]]");
assert_eq!(g.page_by_title("an").unwrap().unwrap().id, an.id);
assert_eq!(g.page_by_title("Alpha Alias").unwrap().unwrap().id, an.id);
let tree = g.page_tree(an.id).unwrap();
let first = g
.get_block("11111111-1111-4111-8111-111111111111".parse().unwrap())
.unwrap()
.unwrap();
assert_eq!(first.content, "First block");
assert_eq!(tree[1].1.content, "Second\nwith a continuation line");
assert!(tree[1].1.collapsed);
assert_eq!(tree[2].1.parent_id, Some(tree[1].1.id));
// block refs keep working
let b = g.block_backrefs(first.id).unwrap();
assert_eq!(b.len(), 1);
// assets rewritten, original name kept
let media = texts(&g, "Media");
let hash = blake3_hex(b"PNGDATA");
assert_eq!(media[0].1, format!("Picture ![diagram](asset://{hash})"));
assert!(media[2].1.contains("../assets/nope.png"));
assert!(media[3].1.contains("- not a bullet"));
let a = g.asset(&hash).unwrap().unwrap();
assert_eq!(a.original_name.as_deref(), Some("pic one.png"));
assert!(g.blobs().contains(&hash));
// org raw
let org = texts(&g, "Legacy");
assert_eq!(org.len(), 2);
assert!(org[0].1.starts_with("* Heading one"));
// journals: date links normalised, origin = earliest referencing journal
let j = g.page_by_title("2024-03-15").unwrap().unwrap();
assert!(j.is_journal());
let jt = texts(&g, "2024-03-15");
assert!(jt[1].1.contains("[[2024-03-16]]"));
let ideas = g.page_by_title("Ideas").unwrap().unwrap();
assert_eq!(
ideas.origin_journal,
chrono::NaiveDate::from_ymd_opt(2024, 3, 10)
);
// alias reference counts for the aliased page's origin
assert_eq!(
an.origin_journal,
chrono::NaiveDate::from_ymd_opt(2024, 3, 10)
);
// timestamps come from the file
let mtime = std::fs::metadata(fixture().join("pages/Ideas.md"))
.unwrap()
.modified()
.unwrap();
let ms = mtime
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis() as i64;
assert_eq!(ideas.updated_at, ms);
}
#[test]
fn reimport_is_idempotent() {
let dir = tempfile::tempdir().unwrap();
let g = Graph::open(dir.path()).unwrap();
run(&g, &ImportOptions::default());
let pages = g.list_pages(true, 1000, 0).unwrap().len();
let ops = g.last_seq().unwrap();
let r = run(&g, &ImportOptions::default());
assert_eq!((r.pages, r.journals, r.blocks, r.updated), (0, 0, 0, 0));
assert_eq!(r.unchanged, 8);
assert_eq!(g.list_pages(true, 1000, 0).unwrap().len(), pages);
// only aliases / asset dedup may log; no block or page ops
let new_ops = g.ops_since(ops, 1000).unwrap();
assert!(
new_ops.iter().all(|o| !matches!(
o.op,
synapse_core::Op::UpsertBlock { .. } | synapse_core::Op::UpsertPage { .. }
)),
"{new_ops:?}"
);
}
#[test]
fn reimport_updates_changed_pages_and_skip_mode() {
let src = tempfile::tempdir().unwrap();
copy_dir(&fixture(), src.path());
let dir = tempfile::tempdir().unwrap();
let g = Graph::open(dir.path()).unwrap();
let o = ImportOptions::default();
import_logseq(src.path(), &g, &o, |_| {}).unwrap();
std::fs::write(
src.path().join("pages/Ideas.md"),
"- Idea one\n- Idea three\n",
)
.unwrap();
let skip = ImportOptions {
existing: ExistingPages::Skip,
};
let r = import_logseq(src.path(), &g, &skip, |_| {}).unwrap();
assert_eq!(r.updated, 0);
assert_eq!(texts(&g, "Ideas")[1].1, "Idea two");
let r = import_logseq(src.path(), &g, &o, |_| {}).unwrap();
assert_eq!((r.pages, r.updated), (1, 1));
let t = texts(&g, "Ideas");
assert_eq!(t.len(), 2);
assert_eq!(t[1].1, "Idea three");
}
#[test]
fn rejects_non_graph() {
let dir = tempfile::tempdir().unwrap();
let g = Graph::open(dir.path().join("g")).unwrap();
assert!(import_logseq(dir.path(), &g, &ImportOptions::default(), |_| {}).is_err());
}
fn blake3_hex(data: &[u8]) -> String {
let dir = tempfile::tempdir().unwrap();
let store = synapse_core::blob::BlobStore::open(dir.path()).unwrap();
store.put_reader(data).unwrap().0
}
fn copy_dir(from: &Path, to: &Path) {
for e in std::fs::read_dir(from).unwrap().flatten() {
let dst = to.join(e.file_name());
if e.path().is_dir() {
std::fs::create_dir_all(&dst).unwrap();
copy_dir(&e.path(), &dst);
} else {
std::fs::copy(e.path(), dst).unwrap();
}
}
}
+43
View File
@@ -0,0 +1,43 @@
# Logseq import
Crate `synapse-import`: `import_logseq(src, &graph, &ImportOptions, progress) -> Report`.
CLI: `cargo run --release -p synapse-import --example import -- <logseq_dir> <graph_dir> [--skip-existing]`.
## Pipeline
1. **Scan** `pages/`, `journals/` (`.md`, `.org`) and `assets/` (recursive). Settings are read from
`logseq/config.edn`: `:journal/file-name-format`, `:journal/page-title-format`,
`:file/name-format` (`:triple-lowbar` → `___` is the namespace separator, otherwise `.`).
2. **Assets**: every file in `assets/` is streamed into the blob store (`put_asset_file`, constant
memory) keeping its original file name.
3. **Parse** (rayon): outline → block tree. Fractional positions via `position::between`.
4. **Pages**, then **aliases**, then **blocks**, written on one thread.
## Mapping
- File name → title: `a___b.md` → `a/b`, `%2F`/url-encoding decoded. A `title::` page property
overrides it. Journals `2024_03_15.md` → journal page `2024-03-15`.
- `[[Mar 15th, 2024]]` (configured title format) is rewritten to `[[2024-03-15]]`.
- Page properties = lines before the first bullet, YAML front matter, or a first block that holds
only properties. `alias::` also registers aliases. Block `key:: value` lines go to block
properties (not the content); `id::` becomes the block id (so `((uuid))` refs keep working);
`collapsed:: true` sets the flag.
- Assets: `../assets/x%20y.png` → `asset://<blake3>` in place (`![alt](asset://…)`; `?`/`#`
suffixes kept). Missing files are left as is and reported.
- `.org` files: one raw root block per top-level heading, no parsing; listed in `Report::org_files`.
- Timestamps: page `created_at` = file birth time (≤ mtime), `updated_at` = mtime; blocks inherit
them. `origin_journal` = earliest journal referencing the page (aliases resolved), else the
file's creation day. Journal pages keep core's midnight timestamps.
## Re-import
Idempotent. Blocks without `id::` get UUIDv5 ids from `(page title, ordinal)`, so a re-import
upserts the same rows; identical pages are counted in `Report::unchanged` and not touched. Pages
that changed are rewritten and stale blocks deleted (`ExistingPages::Update`, default);
`ExistingPages::Skip` leaves any page that already has blocks alone (keeps edits made in Synapse).
## Report / progress
`Progress { phase, done, total }` (phases: Scanning, Assets, Parsing, Pages, Blocks) and
`Report { pages, journals, blocks, assets, bytes, updated, unchanged, org_files, warnings }`.
## Known limits
- Not parsed: org-mode syntax, whiteboards, `draws/`, namespace parent stubs, Logseq queries.
- Sequential commits (core has no nestable transaction): ~7k blocks/s; 10k pages × 20 blocks ≈ 30 s,
typical graphs a few seconds.