Skip to content

Commit

Permalink
chore: branch from commit repo feature
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelramos committed Nov 11, 2024
1 parent 7a874d0 commit 3aea711
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
26 changes: 26 additions & 0 deletions crates/git/src/repo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -367,4 +367,30 @@ impl Repository {

Ok(current_branch)
}

pub fn get_branch_from_commit(&self, sha: &str) -> Result<Option<String>, RepositoryError> {
let branch = execute(
"git",
self.location.as_path(),
[
"--no-pager",
"branch",
"--no-color",
"--no-column",
"--format",
r#"%(refname:lstrip=2)"#,
"--contains",
sha,
],
|stdout, _| {
if stdout.is_empty() {
Ok(None)
} else {
Ok(Some(stdout.to_string()))
}
},
)?;

Ok(branch)
}
}
31 changes: 31 additions & 0 deletions crates/git/tests/git_repo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -533,4 +533,35 @@ mod repo_tests {

Ok(())
}

#[test]
fn test_branch_from_commit_repo() -> Result<(), RepositoryError> {
let monorepo_root_dir = create_monorepo()?;

let repo = Repository::new(monorepo_root_dir.as_path());
repo.create_branch("feature/awesome")?;

let main_file_path = monorepo_root_dir.join("main.mjs");
let mut main_file = File::create(main_file_path.as_path())?;
main_file.write_all(b"const msg = 'Hello';")?;

repo.add_all()?;

execute(
"git",
monorepo_root_dir.as_path(),
["commit", "-m", "chore: add main.mjs file"],
|_, stdout| Ok(stdout.status.success()),
)?;

let sha = repo.get_current_sha()?;
let branch = repo.get_branch_from_commit(sha.as_str())?;

assert!(branch.is_some());
assert_eq!(branch.unwrap(), "feature/awesome");

remove_dir_all(&monorepo_root_dir)?;

Ok(())
}
}

0 comments on commit 3aea711

Please sign in to comment.