1use anyhow::Result;
2use apm_core::{config::{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 §ions {
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, &config, branch, &rel_path)?;
92 }
93
94 Ok(())
95}
96
97fn open_editor(root: &Path, config: &Config, branch: &str, rel_path: &str) -> Result<()> {
98 let prev_branch = std::process::Command::new("git")
100 .args(["rev-parse", "--abbrev-ref", "HEAD"])
101 .current_dir(root)
102 .output()
103 .ok()
104 .and_then(|o| String::from_utf8(o.stdout).ok())
105 .map(|s| s.trim().to_string())
106 .unwrap_or_else(|| config.project.default_branch.clone());
107
108 let _ = std::process::Command::new("git")
109 .args(["checkout", branch])
110 .current_dir(root)
111 .status();
112
113 let file_path = root.join(rel_path);
114 crate::editor::open(&file_path)?;
115
116 let _ = std::process::Command::new("git")
117 .args(["-c", "commit.gpgsign=false", "add", rel_path])
118 .current_dir(root)
119 .status();
120 let _ = std::process::Command::new("git")
121 .args(["-c", "commit.gpgsign=false", "commit", "--allow-empty", "-m", "write spec"])
122 .current_dir(root)
123 .status();
124
125 let _ = std::process::Command::new("git")
126 .args(["checkout", &prev_branch])
127 .current_dir(root)
128 .status();
129
130 Ok(())
131}