gnostr_asyncgit/sync/branch/
rename.rs

1//! renaming of branches
2
3use scopetime::scope_time;
4
5use crate::{
6    error::Result,
7    sync::{repository::repo, RepoPath},
8};
9
10/// Rename the branch reference
11pub fn rename_branch(repo_path: &RepoPath, branch_ref: &str, new_name: &str) -> Result<()> {
12    scope_time!("rename_branch");
13
14    let repo = repo(repo_path)?;
15    let branch_as_ref = repo.find_reference(branch_ref)?;
16    let mut branch = git2::Branch::wrap(branch_as_ref);
17    branch.rename(new_name, true)?;
18
19    Ok(())
20}
21
22#[cfg(test)]
23mod test {
24    use super::{
25        super::{checkout_branch, create_branch, RepoPath},
26        rename_branch,
27    };
28    use crate::sync::tests::repo_init;
29
30    #[test]
31    fn test_rename_branch() {
32        let (_td, repo) = repo_init().unwrap();
33        let root = repo.path().parent().unwrap();
34        let repo_path: &RepoPath = &root.as_os_str().to_str().unwrap().into();
35
36        create_branch(repo_path, "branch1").unwrap();
37
38        checkout_branch(repo_path, "branch1").unwrap();
39
40        assert_eq!(
41            repo.branches(None)
42                .unwrap()
43                .next()
44                .unwrap()
45                .unwrap()
46                .0
47                .name()
48                .unwrap()
49                .unwrap(),
50            "branch1"
51        );
52
53        rename_branch(repo_path, "refs/heads/branch1", "AnotherName").unwrap();
54
55        assert_eq!(
56            repo.branches(None)
57                .unwrap()
58                .next()
59                .unwrap()
60                .unwrap()
61                .0
62                .name()
63                .unwrap()
64                .unwrap(),
65            "AnotherName"
66        );
67    }
68}