Skip to main content

apm/
util.rs

1use anyhow::Result;
2use apm_core::{config::Config, git, ticket, ticket_fmt, worktree};
3use std::io::{self, BufRead, Write};
4use std::path::{Path, PathBuf};
5
6/// Run `git fetch --all` when `aggressive` is true; emit a warning on failure.
7pub fn fetch_if_aggressive(root: &Path, aggressive: bool) {
8    if aggressive {
9        if let Err(e) = git::fetch_all(root) {
10            eprintln!("warning: fetch failed: {e:#}");
11        }
12    }
13}
14
15/// Run `git fetch <branch>` when `aggressive` is true; emit a warning on failure.
16pub fn fetch_branch_if_aggressive(root: &Path, branch: &str, aggressive: bool) {
17    if aggressive {
18        if let Err(e) = git::fetch_branch(root, branch) {
19            eprintln!("warning: fetch failed: {e:#}");
20        }
21    }
22}
23
24/// Print `prompt`, flush stdout, read one line, return true iff the answer is "y".
25pub fn prompt_yes_no(prompt: &str) -> io::Result<bool> {
26    print!("{prompt}");
27    io::stdout().flush()?;
28    let mut line = String::new();
29    io::stdin().lock().read_line(&mut line)?;
30    Ok(line.trim().eq_ignore_ascii_case("y"))
31}
32
33/// Resolve a ticket ID argument to its worktree path and canonical ticket ID.
34/// Loads config and tickets from git internally.
35pub fn worktree_for_ticket(root: &Path, id_arg: &str) -> Result<(PathBuf, String)> {
36    let config = Config::load(root)?;
37    let tickets = ticket::load_all_from_git(root, &config.tickets.dir)?;
38    let id = ticket::resolve_id_in_slice(&tickets, id_arg)?;
39    let t = tickets
40        .iter()
41        .find(|t| t.frontmatter.id == id)
42        .ok_or_else(|| anyhow::anyhow!("ticket {id:?} not found"))?;
43    let branch = t
44        .frontmatter
45        .branch
46        .clone()
47        .or_else(|| ticket_fmt::branch_name_from_path(&t.path))
48        .unwrap_or_else(|| format!("ticket/{id}"));
49    let wt = worktree::find_worktree_for_branch(root, &branch)
50        .ok_or_else(|| anyhow::anyhow!("no worktree for ticket {id:?}"))?;
51    Ok((wt, id))
52}