Files
GitHub.webhook-scripts/src/bin/switch_branch.sh
Clemens Schwaighofer 08e9ff9e67 Add help and fix problem with Host name set for new clone
The host name ise set as ssh config entry with ssh key, so we use the short name set for the remote host name
2025-11-17 11:12:54 +09:00

48 lines
1.9 KiB
Bash
Executable File

#!/usr/bin/env bash
# AUTHOR: Clemens Schwaighofer
# DATE: 2025/7/15
# DESC: Switch a branch, run this script if we have to switch to a different branch
# If not the new branch will merge into the branch that was originally selected
REPOSITORY="$1";
BRANCH="$2";
REMOTE_NAME="$3";
if [ "${REPOSITORY}" == "--help" ]; then
echo "$0 <Repo.git> <branch> [<remote name, defaults to origin>]";
exit;
fi;
if [ -z "${REMOTE_NAME}" ]; then
REMOTE_NAME="origin"
fi;
BASE_FOLDER=$(dirname "$(readlink -f "$0")")"/";
# shellcheck source=init.sh
. "${BASE_FOLDER}init.sh";
GIT_REPOSITORY_FOLDER="${GIT_WEBHOOK_BASE_FOLDER}${CLONE_BASE}${REPOSITORY}";
if [ ! -d "${GIT_REPOSITORY_FOLDER}" ]; then
echo "[!] ${REPOSITORY} not found in clone folder";
echo "[!] Full path: ${GIT_REPOSITORY_FOLDER}";
exit;
fi;
LOG_FILE="${GIT_WEBHOOK_BASE_FOLDER}${LOG_FOLDER}${REPOSITORY}.log";
unique_id=$(uuidgen | tr -d '-' | head -c 8);
echo "[$(date +"%Y-%m-%d %H:%M:%S")] [${unique_id}] [START] On repository ${GIT_REPOSITORY_FOLDER} switch to branch ${REMOTE_NAME}/${BRANCH}" | tee -a "$LOG_FILE";
# add new branch to remote
GIT_COMMAND=("${GIT_COMMAND_BASE[@]}" "-C" "${GIT_REPOSITORY_FOLDER}" "remote" "set-branches" "--add" "${REMOTE_NAME}" "${BRANCH}")
"${GIT_COMMAND[@]}" 2>&1 | tee -a "$LOG_FILE";
# fetch new branch
GIT_COMMAND=("${GIT_COMMAND_BASE[@]}" "-C" "${GIT_REPOSITORY_FOLDER}" "fetch" "--depth" "1" "${REMOTE_NAME}" "${BRANCH}")
"${GIT_COMMAND[@]}" 2>&1 | tee -a "$LOG_FILE";
# checkout new branch
GIT_COMMAND=("${GIT_COMMAND_BASE[@]}" "-C" "${GIT_REPOSITORY_FOLDER}" "checkout" "${BRANCH}");
"${GIT_COMMAND[@]}" 2>&1 | tee -a "$LOG_FILE";
# get the latest changes from branch
GIT_COMMAND=("${GIT_COMMAND_BASE[@]}" "-C" "${GIT_REPOSITORY_FOLDER}" "pull" "${REMOTE_NAME}" "${BRANCH}")
"${GIT_COMMAND[@]}" 2>&1 | tee -a "$LOG_FILE";
echo "[$(date +"%Y-%m-%d %H:%M:%S")] [${unique_id}] [END] branch switch done" | tee -a "$LOG_FILE";
# __END__