Skip to main content

flow_git/
branch.rs

1use thiserror::Error;
2
3#[derive(Error, Debug)]
4pub enum BranchError {
5    #[error("Git error: {0}")]
6    Git(String),
7    #[error("IO error: {0}")]
8    Io(#[from] std::io::Error),
9}
10
11/// Get the current branch name.
12///
13/// # Errors
14///
15/// Returns an error if the branch cannot be determined.
16pub fn current() -> Result<String, BranchError> {
17    let output = std::process::Command::new("git")
18        .args(["branch", "--show-current"])
19        .output()?;
20
21    if !output.status.success() {
22        return Err(BranchError::Git(
23            String::from_utf8_lossy(&output.stderr).to_string(),
24        ));
25    }
26
27    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
28}
29
30/// List all remote branches.
31///
32/// # Errors
33///
34/// Returns an error if the branches cannot be listed.
35pub fn list_remote() -> Result<Vec<String>, BranchError> {
36    let output = std::process::Command::new("git")
37        .args(["branch", "-r", "--format=%(refname:short)"])
38        .output()?;
39
40    if !output.status.success() {
41        return Err(BranchError::Git(
42            String::from_utf8_lossy(&output.stderr).to_string(),
43        ));
44    }
45
46    Ok(String::from_utf8_lossy(&output.stdout)
47        .lines()
48        .map(std::string::ToString::to_string)
49        .collect())
50}