upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/src/funcs/create_local_branch_from_user_input.rs
blob: 94abb625e6c71e7eca2e3aa41f60af2b6e8cbdb4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use std::path::PathBuf;

use dialoguer::{Input, theme::ColorfulTheme};
use git2::{Repository, Oid};

use crate::repo_config::RepoConfig;

use super::checkout_branch::checkout_branch;


/// prompts user for name of local branch, creates the branch (checking if it is valid, if not looping) and returns it.
pub fn create_local_branch_from_user_input(
    repo_dir_path: &PathBuf,
    git_repo: &Repository,
    suggestion:&Option<String>,
    commit_id:&String,
    branch_id: &String,
) -> String {

    let target_commit = git_repo.find_commit(
        Oid::from_str(
            commit_id
        )
            .expect("commit_id supplied to be a valid Oid")
    )
        .expect("commit_id supplied exists in git repository");

    loop {
        let response: String = Input::with_theme(&ColorfulTheme::default())
            .with_prompt("local branch name")
            .with_initial_text(match &suggestion {
                None => "".to_string(),
                Some(s) => s.to_string(),
            })
            .report(true)
            .interact_text()
            .unwrap();
        match git_repo.branch(
            &response,
            &target_commit,
            false,
        ) {
            Ok(branch) => {
                // check out branch
                checkout_branch(git_repo, branch);
                // set mapping
                let mut repo_config = RepoConfig::open(repo_dir_path);
                repo_config.set_mapping(&response, branch_id);
                break response;
            },
            Err(_) => {
                println!("not a valid nevent, note or hex string. try again. (or a local branch with that name exists)");
                continue
            },
        }
    }
}