Skip to main content

apm/cmd/
spec.rs

1use anyhow::{bail, Result};
2use apm_core::{config::Config, git, spec, ticket, ticket_fmt};
3use std::{io::Read, path::Path};
4
5pub fn run(root: &Path, id_arg: &str, section: Option<String>, set: Option<String>, set_file: Option<String>, check: bool, mark: Option<String>, no_aggressive: bool) -> Result<()> {
6    if set.is_some() && section.is_none() { bail!("--set requires --section"); }
7    if set_file.is_some() && section.is_none() { bail!("--set-file requires --section"); }
8    if mark.is_some() && section.is_none() { bail!("--mark requires --section"); }
9    let config = Config::load(root)?;
10    let aggressive = config.sync.aggressive && !no_aggressive;
11    let branches = git::ticket_branches(root)?;
12    let branch = ticket_fmt::resolve_ticket_branch(&branches, id_arg)?;
13    let id = branch.strip_prefix("ticket/").and_then(|s| s.split('-').next()).unwrap_or(id_arg).to_string();
14    let rel_path = format!("{}/{}.md", config.tickets.dir.to_string_lossy(), branch.trim_start_matches("ticket/"));
15
16    crate::util::fetch_branch_if_aggressive(root, &branch, aggressive);
17
18    let content = git::read_from_branch(root, &branch, &rel_path)?;
19    if let (Some(ref name), Some(ref item)) = (&section, &mark) {
20        let new = spec::mark_item(&content, name, item)?;
21        git::commit_to_branch(root, &branch, &rel_path, &new, &format!("ticket({id}): mark \"{item}\" in {name}"))?;
22        if aggressive {
23            if let Err(e) = git::push_branch(root, &branch) {
24                eprintln!("warning: push failed: {e:#}");
25            }
26        }
27        println!("ticket #{id}: marked \"{item}\" in {name:?}"); return Ok(());
28    }
29    let mut t = ticket::Ticket::parse(&root.join(&rel_path), &content)?;
30    let mut doc = t.document()?;
31    if check {
32        let errors = doc.validate(&config.ticket.sections);
33        if errors.is_empty() { println!("all required sections present"); return Ok(()); }
34        errors.iter().for_each(|e| eprintln!("{e}")); std::process::exit(1);
35    }
36    let config_active = !config.ticket.sections.is_empty();
37    let Some(ref name) = section else {
38        for (section_name, value) in &doc.sections {
39            println!("### {section_name}\n\n{value}\n");
40        }
41        return Ok(());
42    };
43    if config_active && !config.has_section(name) {
44        bail!("unknown section {:?}; not defined in [ticket.sections]", name);
45    }
46    let set_resolved = match (set, set_file) {
47        (Some(v), _) => Some(v),
48        (None, Some(path)) => Some(std::fs::read_to_string(&path).map_err(|e| anyhow::anyhow!("--set-file: {}: {e}", path))?),
49        (None, None) => None,
50    };
51    if let Some(value) = set_resolved {
52        let text = if value == "-" { let mut b = String::new(); std::io::stdin().read_to_string(&mut b)?; b } else { value };
53        let trimmed = text.trim().to_string();
54        let formatted = if config_active {
55            let section_config = config.find_section(name).unwrap();
56            spec::apply_section_type(&section_config.type_, trimmed)
57        } else {
58            trimmed
59        };
60        spec::set_section(&mut doc, name, formatted);
61        t.body = doc.serialize();
62        git::commit_to_branch(root, &branch, &rel_path, &t.serialize()?, &format!("ticket({id}): set section {name}"))?;
63        if aggressive {
64            if let Err(e) = git::push_branch(root, &branch) {
65                eprintln!("warning: push failed: {e:#}");
66            }
67        }
68        println!("ticket #{id}: section {name:?} updated");
69    } else {
70        if let Some(text) = spec::get_section(&doc, name) { println!("{text}"); }
71    }
72    Ok(())
73}