use std::path::Path;
use anyhow::{Context, Result};
use tracing::instrument;
use crate::detect;
use crate::integrations::subprocess;
use crate::model::Task;
#[instrument(name = "doob::parse_todo_list", skip(raw))]
pub fn parse_todo_list(raw: &[u8]) -> Result<serde_json::Value> {
tracing::info!(integration = "doob", "parsing todo list JSON");
serde_json::from_slice(raw).context("doob todo list: invalid JSON")
}
pub fn find_next_pending(value: &serde_json::Value) -> Option<serde_json::Value> {
value
.get("todos")
.and_then(|t| t.as_array())
.and_then(|todos| {
todos
.iter()
.find(|t| t.get("status").and_then(|s| s.as_str()) == Some("pending"))
.cloned()
})
}
#[instrument(name = "doob::todo_list", fields(integration = "doob"))]
pub fn todo_list(project: &str) -> Result<serde_json::Value> {
let raw = subprocess::run(
"doob",
&["todo", "list", "-p", project, "--json"],
"doob not found on PATH",
)?;
parse_todo_list(raw.as_bytes())
}
pub fn todo_next(project: &str) -> Result<Option<serde_json::Value>> {
let v = todo_list(project)?;
Ok(find_next_pending(&v))
}
pub fn todo_next_for_root(root: &Path) -> Result<Option<serde_json::Value>> {
let project = detect::package_name(root)?;
todo_next(&project)
}
#[instrument(name = "doob::todo_done_args")]
pub fn todo_done_args(uuid: &str) -> Vec<String> {
tracing::debug!(integration = "doob", %uuid, "building todo_done args");
vec!["todo".into(), "complete".into(), uuid.into()]
}
pub fn todo_add_args(project: &str, title: &str) -> Vec<String> {
vec![
"todo".into(),
"add".into(),
"-p".into(),
project.into(),
title.into(),
"--json".into(),
]
}
pub trait TodoPublisher {
fn publish(&mut self, project: &str, title: &str) -> Result<String>;
}
pub struct DoobCli;
impl TodoPublisher for DoobCli {
fn publish(&mut self, project: &str, title: &str) -> Result<String> {
todo_add(project, title)
}
}
pub fn publish_tasks(
publisher: &mut impl TodoPublisher,
project: &str,
tasks: &mut [Task],
) -> Result<usize> {
let mut published = 0;
for task in tasks {
if let Some(id) = todo_id(task).map(str::to_owned) {
if task.doob_id().is_none() {
task.set_doob_id(id);
}
continue;
}
let id = publisher.publish(project, &task.title)?;
task.set_doob_id(id);
published += 1;
}
Ok(published)
}
pub fn todo_id(task: &Task) -> Option<&str> {
task.doob_id().or_else(|| {
task.notes
.strip_prefix("doob:")
.map(str::trim)
.filter(|id| !id.is_empty())
})
}
pub fn todos_to_tasks(value: &serde_json::Value) -> Vec<Task> {
value
.get("todos")
.and_then(|t| t.as_array())
.map(|todos| {
todos
.iter()
.filter(|t| t.get("status").and_then(|s| s.as_str()) == Some("pending"))
.filter_map(|t| {
let id = t.get("id")?.as_str()?;
let title = t.get("content")?.as_str()?;
let mut task = Task::new(format!("doob-{}", &id[..8.min(id.len())]), title);
task.notes = format!("doob:{id}");
task.set_doob_id(id);
Some(task)
})
.collect()
})
.unwrap_or_default()
}
#[instrument(name = "doob::todo_add", fields(integration = "doob"))]
pub fn todo_add(project: &str, title: &str) -> Result<String> {
let args = todo_add_args(project, title);
let args_ref: Vec<&str> = args.iter().map(String::as_str).collect();
let raw = subprocess::run("doob", &args_ref, "doob not found on PATH")?;
parse_added_todo_id(&raw)
}
fn parse_added_todo_id(raw: &str) -> Result<String> {
let value: serde_json::Value =
serde_json::from_str(raw).context("doob todo add: invalid JSON")?;
let id = value
.get("id")
.and_then(serde_json::Value::as_str)
.or_else(|| value.get("todo")?.get("id")?.as_str())
.or_else(|| value.as_array()?.first()?.get("id")?.as_str())
.or_else(|| value.get("todos")?.as_array()?.first()?.get("id")?.as_str())
.or_else(|| {
value
.get("created")?
.as_array()?
.first()?
.get("id")?
.as_str()
})
.filter(|id| !id.is_empty())
.context("doob todo add: JSON response missing todo id")?;
Ok(id.to_string())
}
#[instrument(name = "doob::todo_done", fields(integration = "doob"))]
pub fn todo_done(uuid: &str) -> Result<()> {
let args = todo_done_args(uuid);
let args_ref: Vec<&str> = args.iter().map(String::as_str).collect();
subprocess::run("doob", &args_ref, "doob not found on PATH")?;
Ok(())
}
#[instrument(name = "doob::handoff_sync", fields(integration = "doob"))]
pub fn handoff_sync(yaml_path: &Path, project: &str, current_item_ids: &[String]) -> Result<()> {
let tmp_dir = std::env::temp_dir().join(project);
let _ = std::fs::create_dir_all(&tmp_dir);
let tmp_file = tmp_dir.join(
yaml_path
.file_name()
.context("HANDOFF YAML has no filename")?,
);
std::fs::copy(yaml_path, &tmp_file)?;
let tmp_str = tmp_file
.to_str()
.context("temp HANDOFF path is not valid UTF-8")?;
subprocess::run(
"doob",
&["handoff", "sync", "--file", tmp_str],
"doob not found on PATH",
)?;
let _ = std::fs::remove_file(&tmp_file);
let _ = std::fs::remove_dir(&tmp_dir);
cleanup_stale_items(project, current_item_ids);
Ok(())
}
fn cleanup_stale_items(project: &str, current_ids: &[String]) {
let out = subprocess::run(
"doob",
&["handoff", "list", "--project", project, "--json"],
"doob not found",
);
let Ok(raw) = out else { return };
let Ok(items) = serde_json::from_str::<Vec<serde_json::Value>>(&raw) else {
return;
};
for item in &items {
let Some(handoff_id) = item.get("handoff_id").and_then(|v| v.as_str()) else {
continue;
};
let status = item.get("status").and_then(|v| v.as_str()).unwrap_or("");
if status == "done" || status == "parked" {
continue;
}
if !current_ids.iter().any(|id| id == handoff_id) {
let _ = subprocess::run(
"doob",
&["handoff", "update-status", handoff_id, "done"],
"doob not found",
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use tracing_test::traced_test;
#[test]
#[traced_test]
fn parse_todo_list_emits_trace_event() {
let raw = br#"{"todos":[]}"#;
let _ = parse_todo_list(raw).unwrap();
assert!(
logs_contain("doob"),
"expected a tracing event containing 'doob'"
);
}
#[test]
#[traced_test]
fn todo_done_args_emits_trace_event() {
let args = todo_done_args("abc-123");
assert!(!args.is_empty());
assert!(
logs_contain("doob"),
"expected a tracing event containing 'doob'"
);
}
}