summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorChristopher Warner <cwarner@kernelcode.com>2026-10-10 18:49:01 -0400
committerChristopher Warner <cwarner@kernelcode.com>2026-10-10 18:49:01 -0400
commitbe0d09e2cb91ef391d7455334fc5ed15d6f5649a (patch)
treebc3b8d3c3b79de695761b750789aeb2ddaf8df49 /src
parentb5e522306f3f4153f633618b8d1e36dc8bbf6371 (diff)
downloadiphone-notes-be0d09e2cb91ef391d7455334fc5ed15d6f5649a.tar.gz
iphone-notes-be0d09e2cb91ef391d7455334fc5ed15d6f5649a.tar.bz2
iphone-notes-be0d09e2cb91ef391d7455334fc5ed15d6f5649a.tar.xz
iphone-notes-be0d09e2cb91ef391d7455334fc5ed15d6f5649a.zip
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 <cursoragent@cursor.com>
Diffstat (limited to 'src')
-rw-r--r--src/browser.rs122
-rw-r--r--src/helpers.rs32
-rw-r--r--src/main.rs55
3 files changed, 203 insertions, 6 deletions
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<CreatedNote> {
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<Cr
const noteList = dataManager.allNotes || dataManager.__CW__allNotes;
const sample =
mv?.selectedNote ||
- (noteList?.objectAt ? noteList.objectAt(0) : noteList?.[0]) ||
+ noteAt(noteList, 0) ||
null;
const Note = sample?.constructor;
if (!Note?.createNoteWithTitleText && !Note?.createEmptyNote) {{
@@ -213,7 +250,7 @@ async fn create_via_notes_app(page: &Page, title: &str, body: &str) -> Result<Cr
mv?.selectedFolder ||
dataManager.defaultFolder ||
dataManager.inboxFolder ||
- (folderList?.objectAt ? folderList.objectAt(0) : folderList?.[0]) ||
+ noteAt(folderList, 0) ||
null;
if (!folder) throw new Error("Could not resolve a Notes folder");
let note;
@@ -238,6 +275,57 @@ async fn create_via_notes_app(page: &Page, title: &str, body: &str) -> Result<Cr
Ok(note)
}
+/// Find an existing note by title and replace its content (does not create).
+async fn update_via_notes_app(page: &Page, match_title: &str, title: &str, body: &str) -> Result<CreatedNote> {
+ 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();
@@ -128,6 +145,21 @@ mod tests {
}
#[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(
"feat: add icloud.com/notes helper and agent skill"
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<String>,
},
+ /// Headless update an existing note (by title) — never creates
+ Update {
+ /// Existing note title to find (required)
+ #[arg(long)]
+ title: Option<String>,
+ /// Optional distinct title to search for (defaults to --title)
+ #[arg(long = "match-title")]
+ match_title: Option<String>,
+ /// Replacement body text
+ #[arg(long)]
+ body: Option<String>,
+ /// Read body from file (`-` = stdin)
+ #[arg(long = "body-file")]
+ body_file: Option<PathBuf>,
+ /// Positional title fallback
+ #[arg(value_name = "TITLE")]
+ positional_title: Option<String>,
+ },
}
#[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()