From be0d09e2cb91ef391d7455334fc5ed15d6f5649a Mon Sep 17 00:00:00 2001 From: Christopher Warner Date: Sat, 10 Oct 2026 18:49:01 -0400 Subject: feat: update existing Apple Notes by title instead of duplicating Add `icloud-note update` that finds a note by title and replaces its content in place so revision requests do not create a second note. Co-authored-by: Cursor --- src/browser.rs | 122 +++++++++++++++++++++++++++++++++++++++++++++++++++++++-- src/helpers.rs | 32 +++++++++++++++ src/main.rs | 55 ++++++++++++++++++++++++-- 3 files changed, 203 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/browser.rs b/src/browser.rs index 187b535..b3b72d8 100644 --- a/src/browser.rs +++ b/src/browser.rs @@ -185,13 +185,50 @@ async fn wait_for_notes_app(page: &Page, timeout: Duration, allow_login_wait: bo bail!("NotesApp did not become ready. Run: icloud-note login"); } +fn note_list_helpers_js() -> &'static str { + r#" + function noteLen(list) { + if (!list) return 0; + if (typeof list.get === "function" && typeof list.get("length") === "number") + return list.get("length"); + return list.length || 0; + } + function noteAt(list, i) { + if (!list) return null; + if (typeof list.objectAt === "function") return list.objectAt(i); + if (typeof list.get === "function") return list.objectAt?.(i) ?? list[i]; + return list[i]; + } + function findByTitle(list, want) { + const norm = (s) => String(s || "").trim().toLowerCase(); + const target = norm(want); + let best = null; + let bestMod = -1; + const n = noteLen(list); + for (let i = 0; i < n; i++) { + const note = noteAt(list, i); + if (!note) continue; + const title = note.Title ?? note.title ?? ""; + if (norm(title) !== target) continue; + const mod = Number(note.ModificationDate || note.modificationDate || 0); + if (!best || mod >= bestMod) { + best = note; + bestMod = mod; + } + } + return best; + } + "# +} + async fn create_via_notes_app(page: &Page, title: &str, body: &str) -> Result { let full = format_note_text(title, body); - // Pass text via JSON.stringify embedded in JS to avoid injection issues let text_js = serde_json::to_string(&full)?; + let helpers = note_list_helpers_js(); let expr = format!( r#"async () => {{ const text = {text_js}; + {helpers} const iframe = document.querySelector("iframe"); const w = iframe?.contentWindow; const app = w?.NotesApp; @@ -201,7 +238,7 @@ async fn create_via_notes_app(page: &Page, title: &str, body: &str) -> Result Result Result Result { + let full = format_note_text(title, body); + let text_js = serde_json::to_string(&full)?; + let match_js = serde_json::to_string(match_title)?; + let helpers = note_list_helpers_js(); + let expr = format!( + r#"async () => {{ + const text = {text_js}; + const matchTitle = {match_js}; + {helpers} + const iframe = document.querySelector("iframe"); + const w = iframe?.contentWindow; + const app = w?.NotesApp; + if (!app?.dataManager) throw new Error("NotesApp unavailable"); + const dataManager = app.dataManager; + const mv = app.mainViewModel; + const noteList = dataManager.allNotes || dataManager.__CW__allNotes; + const note = findByTitle(noteList, matchTitle); + if (!note) {{ + throw new Error("No note titled " + JSON.stringify(matchTitle)); + }} + const Note = note.constructor; + // Preferred path: replace TopoText via NotesApp helpers + if (typeof Note.createInitialTopoTextString === "function" + && dataManager.topoTextManager + && typeof dataManager.topoTextManager.load === "function") {{ + const replacement = Note.createInitialTopoTextString(text); + dataManager.topoTextManager.load(note.id, replacement); + if (typeof note.userDidChangeTopoText === "function") {{ + note.userDidChangeTopoText(); + }} + }} else if (typeof note.userDidChangeTopoText === "function") {{ + note.userDidChangeTopoText(text); + }} else {{ + throw new Error("No supported update path on Note model"); + }} + if (note.Title !== undefined) {{ + note.Title = text.split("\n")[0] || matchTitle; + }} + await note.save(true); + return {{ + title: String(note.Title || text.split("\n")[0] || matchTitle), + record_name: String(note.recordName || note.id || "") + }}; + }}"# + ); + let note: CreatedNote = page.evaluate(expr).await?.into_value()?; + Ok(note) +} + fn mark_session(paths: &Paths) -> Result<()> { std::fs::write(&paths.marker_path, b"ok\n")?; #[cfg(unix)] @@ -300,3 +388,31 @@ pub async fn cmd_create(paths: &Paths, title: &str, body: &str) -> Result<()> { Ok(()) } +/// Update an existing note matched by title. Never creates a new note. +pub async fn cmd_update( + paths: &Paths, + match_title: &str, + title: &str, + body: &str, +) -> Result<()> { + if !paths.has_session() { + bail!("No saved session. Run: icloud-note login"); + } + let (mut browser, handle) = launch(paths, false).await?; + let page = browser.new_page("about:blank").await?; + wait_for_notes_app(&page, Duration::from_secs(90), false).await?; + let note = update_via_notes_app(&page, match_title, title, body) + .await + .context("update note via NotesApp")?; + sleep(Duration::from_secs(2)).await; + mark_session(paths)?; + if note.record_name.is_empty() { + println!("updated: {}", note.title); + } else { + println!("updated: {} ({})", note.title, note.record_name); + } + browser.close().await?; + let _ = handle.await; + Ok(()) +} + diff --git a/src/helpers.rs b/src/helpers.rs index c6a8163..3ea7e37 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -51,6 +51,23 @@ pub fn require_create_content(title: &str, body: &str) -> Result<(String, String Ok((title, body)) } +/// Update requires a title to locate the existing note. +pub fn require_update_content(title: &str, body: &str) -> Result<(String, String), String> { + let title = title.trim().to_string(); + let body = body.trim_end().to_string(); + if title.is_empty() { + return Err( + "Provide --title (existing note title to update)".to_string(), + ); + } + Ok((title, body)) +} + +/// Case-insensitive title equality for matching Notes.app titles. +pub fn titles_match(a: &str, b: &str) -> bool { + a.trim().eq_ignore_ascii_case(b.trim()) +} + /// Conventional Commits 1.0.0 subject line (no regex crate). pub fn is_conventional_commit_subject(subject: &str) -> bool { let line = subject.trim(); @@ -127,6 +144,21 @@ mod tests { assert_eq!(b, "hi"); } + #[test] + fn update_content_requires_title() { + assert!(require_update_content("", "body").is_err()); + let (t, b) = require_update_content(" Hello ", "body\n").unwrap(); + assert_eq!(t, "Hello"); + assert_eq!(b, "body"); + } + + #[test] + fn titles_match_case_insensitive() { + assert!(titles_match("Hello", "hello")); + assert!(titles_match(" Foo ", "foo")); + assert!(!titles_match("a", "b")); + } + #[test] fn conventional_subjects() { assert!(is_conventional_commit_subject( diff --git a/src/main.rs b/src/main.rs index ccd21e2..ca893b5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,7 +7,7 @@ use clap::{Parser, Subcommand}; use icloud_note::browser; use icloud_note::config::{dry_run, Paths}; -use icloud_note::helpers::{format_note_text, require_create_content}; +use icloud_note::helpers::{format_note_text, require_create_content, require_update_content}; #[derive(Parser, Debug)] #[command( @@ -29,7 +29,7 @@ enum Command { Status, /// One-time Apple ID sign-in (visible browser) Login, - /// Headless create a note + /// Headless create a new note Create { /// Note title (or positional) #[arg(long)] @@ -44,6 +44,24 @@ enum Command { #[arg(value_name = "TITLE")] positional_title: Option, }, + /// Headless update an existing note (by title) — never creates + Update { + /// Existing note title to find (required) + #[arg(long)] + title: Option, + /// Optional distinct title to search for (defaults to --title) + #[arg(long = "match-title")] + match_title: Option, + /// Replacement body text + #[arg(long)] + body: Option, + /// Read body from file (`-` = stdin) + #[arg(long = "body-file")] + body_file: Option, + /// Positional title fallback + #[arg(value_name = "TITLE")] + positional_title: Option, + }, } #[tokio::main] @@ -115,6 +133,35 @@ async fn run() -> Result<()> { } browser::cmd_create(&paths, &title, &body).await } + Command::Update { + title, + match_title, + body, + body_file, + positional_title, + } => { + let title = title.or(positional_title).unwrap_or_default(); + let body_raw = read_body(body, body_file)?; + let (title, body) = require_update_content(&title, &body_raw) + .map_err(|e| anyhow::anyhow!(e))?; + let match_title = match_title + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + .unwrap_or(title.as_str()) + .to_string(); + if dry_run() { + let text = format_note_text(&title, &body); + println!( + "dry-run: would update note match={} title={} chars={}", + serde_json::to_string(&match_title)?, + serde_json::to_string(&title)?, + text.len() + ); + return Ok(()); + } + browser::cmd_update(&paths, &match_title, &title, &body).await + } } } @@ -151,10 +198,12 @@ fn print_help(paths: &Paths) { icloud-note status icloud-note login # only command that opens a visible browser icloud-note create --title TITLE [--body TEXT | --body-file PATH|-] + icloud-note update --title TITLE [--body TEXT | --body-file PATH|-] + # updates existing note by title; never creates Config: {} Profile: {} -create/status always run headless (no window). +create/update/status always run headless (no window). ", paths.config_dir.display(), paths.profile_dir.display() -- cgit v1.2.3