Skip to main content

git_workflow/commands/
new.rs

1//! `gw new` command - Create new branch from origin/main
2
3use crate::error::{GwError, Result};
4use crate::git;
5use crate::output;
6
7/// Execute the `new` command
8pub fn run(branch_name: Option<String>, verbose: bool) -> Result<()> {
9    // Ensure we're in a git repo
10    if !git::is_git_repo() {
11        return Err(GwError::NotAGitRepository);
12    }
13
14    let branch_name = branch_name.ok_or(GwError::BranchNameRequired)?;
15
16    println!();
17    output::info(&format!("Creating branch: {}", output::bold(&branch_name)));
18
19    // Check if branch already exists
20    if git::branch_exists(&branch_name) {
21        output::error(&format!("Branch '{}' already exists locally", branch_name));
22        println!();
23        output::action(&format!(
24            "git checkout {}  # Switch to existing branch",
25            branch_name
26        ));
27        output::action(&format!(
28            "git branch -d {}  # Delete and recreate",
29            branch_name
30        ));
31        return Err(GwError::BranchAlreadyExists(branch_name));
32    }
33
34    // Fetch latest
35    output::info("Fetching from origin...");
36    git::fetch_prune(verbose)?;
37    output::success("Fetched");
38
39    // Create branch from origin/main
40    git::checkout_new_branch(&branch_name, "origin/main", verbose)?;
41    output::success(&format!(
42        "Created branch {} from origin/main",
43        output::bold(&branch_name)
44    ));
45
46    // Show current position
47    let commit_short = git::short_commit()?;
48    let commit_msg = git::head_commit_message()?;
49
50    output::ready("Ready to work", &branch_name);
51    println!("Base: {commit_short} {commit_msg}");
52
53    output::hints(&[
54        "# Make changes, then:",
55        "git add <files> && git commit -m \"feat: description\"",
56        &format!("git push -u origin {branch_name}"),
57        "gh pr create -a \"@me\" -t \"Title\"",
58    ]);
59
60    Ok(())
61}