Skip to main content

apm/cmd/
new.rs

1use anyhow::Result;
2use apm_core::{config::{resolve_identity, resolve_caller_name}, epic, ticket};
3use std::path::Path;
4use crate::ctx::CmdContext;
5
6pub fn run(root: &Path, title: String, no_edit: bool, side_note: bool, context: Option<String>, context_section: Option<String>, no_aggressive: bool, sections: Vec<String>, sets: Vec<String>, epic: Option<String>, depends_on: Vec<String>) -> Result<()> {
7    let config = CmdContext::load_config_only(root)?;
8
9    if context_section.is_some() && context.is_none() {
10        anyhow::bail!("--context-section requires --context");
11    }
12
13    if !sets.is_empty() && sections.is_empty() {
14        anyhow::bail!("--set requires --section");
15    }
16    if sections.len() != sets.len() {
17        anyhow::bail!(
18            "--section and --set must be paired: {} --section flag(s) but {} --set flag(s)",
19            sections.len(),
20            sets.len()
21        );
22    }
23
24    if !config.ticket.sections.is_empty() {
25        for name in &sections {
26            if !config.ticket.sections.iter().any(|s| s.name.eq_ignore_ascii_case(name)) {
27                anyhow::bail!("unknown section {:?}; not defined in [ticket.sections]", name);
28            }
29        }
30    }
31
32    let aggressive = config.sync.aggressive && !no_aggressive;
33    if side_note && !config.agents.side_tickets {
34        anyhow::bail!("side tickets are disabled in .apm/config.toml (agents.side_tickets = false)");
35    }
36
37    let author = resolve_identity(root);
38    let actor = resolve_caller_name();
39
40    let (epic_id, target_branch, base_branch) = if let Some(ref id) = epic {
41        match epic::find_epic_branch(root, id) {
42            Some(branch) => (Some(id.clone()), Some(branch.clone()), Some(branch)),
43            None => anyhow::bail!("No epic branch found for id '{id}'"),
44        }
45    } else {
46        (None, None, None)
47    };
48
49    let depends_on_parsed: Option<Vec<String>> = if depends_on.is_empty() {
50        None
51    } else {
52        Some(
53            depends_on
54                .iter()
55                .flat_map(|s| s.split(','))
56                .map(|s| s.trim().to_string())
57                .filter(|s| !s.is_empty())
58                .collect(),
59        )
60    };
61
62    if let Some(ref dep_ids) = depends_on_parsed {
63        if !dep_ids.is_empty() {
64            let all_tickets = apm_core::ticket::load_all_from_git(root, &config.tickets.dir)?;
65            let strategy = apm_core::validate::active_completion_strategy(&config);
66            apm_core::validate::check_depends_on_rules(
67                &strategy,
68                epic_id.as_deref(),
69                target_branch.as_deref(),
70                dep_ids,
71                &all_tickets,
72                &config.project.default_branch,
73            )?;
74        }
75    }
76
77    let section_sets: Vec<(String, String)> = sections.into_iter().zip(sets).collect();
78    let mut warnings = Vec::new();
79    let t = ticket::create(root, &config, title, author, actor, context, context_section, aggressive, section_sets, epic_id, target_branch, depends_on_parsed, base_branch, &mut warnings)?;
80    for w in &warnings {
81        eprintln!("{w}");
82    }
83    let id = &t.frontmatter.id;
84    let branch = t.frontmatter.branch.as_deref().unwrap_or("");
85    let filename = t.path.file_name().unwrap().to_string_lossy();
86    let rel_path = format!("{}/{}", config.tickets.dir.to_string_lossy(), filename);
87
88    println!("Created ticket {id}: {filename} (branch: {branch})");
89
90    if !no_edit {
91        open_editor(root, branch, &rel_path)?;
92    }
93
94    Ok(())
95}
96
97fn open_editor(root: &Path, branch: &str, rel_path: &str) -> Result<()> {
98    let content = apm_core::git_util::read_from_branch(root, branch, rel_path)?;
99
100    let fname = std::path::Path::new(rel_path)
101        .file_name().unwrap().to_string_lossy().into_owned();
102    let tmp_path = std::env::temp_dir()
103        .join(format!("apm-{}-{}", std::process::id(), fname));
104    std::fs::write(&tmp_path, &content)?;
105
106    crate::editor::open(&tmp_path)?;
107
108    let new_content = std::fs::read_to_string(&tmp_path)?;
109
110    apm_core::git_util::commit_to_branch(root, branch, rel_path, &new_content, "write spec")?;
111
112    let _ = std::fs::remove_file(&tmp_path);
113
114    Ok(())
115}