File size: 1,955 Bytes
38c0d61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
58
59
60
61
62
63
#!/bin/bash

# Script to handle git rebase with branch name detection

# Confirmation prompt to ensure user understands the script's impact
echo "WARNING: This script performs destructive operations on your git repository."
echo "It will delete and rename branches, and force push changes."
read -p "Are you sure you want to proceed? (y/N): " CONFIRM
if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then
    echo "Operation cancelled by user."
    exit 1
fi
echo "Proceeding with the script..."

# Function to check if a branch exists
branch_exists() {
    git rev-parse --verify "$1" >/dev/null 2>&1
}

# Check for 'main' branch
if branch_exists "main"; then
    TARGET_BRANCH="main"
    echo "Found 'main' branch. Using it as the target."
# Check for 'master' branch if 'main' is not found
elif branch_exists "master"; then
    TARGET_BRANCH="master"
    echo "Found 'master' branch. Using it as the target."
else
    # Neither 'main' nor 'master' found, prompt user for branch name
    echo "Neither 'main' nor 'master' branch found."
    read -p "Please enter the target branch name (or press Enter to exit): " TARGET_BRANCH
    if [ -z "$TARGET_BRANCH" ]; then
        echo "No branch name provided. Exiting."
        exit 1
    fi
    if ! branch_exists "$TARGET_BRANCH"; then
        echo "Branch '$TARGET_BRANCH' does not exist. Exiting."
        exit 1
    fi
    echo "Using '$TARGET_BRANCH' as the target branch."
fi

# Execute the git commands with the determined branch
echo "Creating orphan branch 'latest_branch'..."
git checkout --orphan latest_branch

echo "Adding all changes..."
git add -A

echo "Committing changes..."
git commit -am "commit message"

echo "Deleting the target branch '$TARGET_BRANCH'..."
git branch -D "$TARGET_BRANCH"

echo "Renaming current branch to '$TARGET_BRANCH'..."
git branch -m "$TARGET_BRANCH"

echo "Force pushing to origin '$TARGET_BRANCH'..."
git push -f origin "$TARGET_BRANCH"

echo "Script completed successfully."