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    // Detect default remote branch (origin/main or origin/master)
40    let default_remote = git::get_default_remote_branch()?;
41
42    // Create branch from default remote
43    git::checkout_new_branch(&branch_name, &default_remote, verbose)?;
44    output::success(&format!(
45        "Created branch {} from {}",
46        output::bold(&branch_name),
47        default_remote
48    ));
49
50    // Show current position
51    let commit_short = git::short_commit()?;
52    let commit_msg = git::head_commit_message()?;
53
54    output::ready("Ready to work", &branch_name);
55    println!("Base: {commit_short} {commit_msg}");
56
57    output::hints(&[
58        "# Make changes, then:",
59        "git add <files> && git commit -m \"feat: description\"",
60        &format!("git push -u origin {branch_name}"),
61        "gh pr create -a \"@me\" -t \"Title\"",
62    ]);
63
64    Ok(())
65}