#!/usr/bin/env bash

# git.sh 是 Git 相关操作集合。
# 约定：业务主脚本负责日志、锁、参数解析；本文件只封装 Git 命令。

library_git_clone_or_update() {
    local url="$1"
    local branch="$2"
    local dest="$3"

    if [[ -d "$dest/.git" ]]; then
        git -C "$dest" fetch --all --prune
        if [[ -n "$branch" ]]; then
            library_git_checkout "$dest" "$branch"
            git -C "$dest" pull --ff-only origin "$branch"
        else
            git -C "$dest" pull --ff-only
        fi
    else
        rm -rf "$dest"
        if [[ -n "$branch" ]]; then
            git clone --branch "$branch" "$url" "$dest"
        else
            git clone "$url" "$dest"
        fi
    fi
}

library_git_fetch() {
    local repo="$1"
    git -C "$repo" fetch --all --prune
}

library_git_checkout() {
    local repo="$1"
    local branch="$2"
    local current
    current="$(git -C "$repo" branch --show-current)"
    if [[ "$current" != "$branch" ]]; then
        git -C "$repo" checkout "$branch"
    fi
}

library_git_pull() {
    local repo="$1"
    git -C "$repo" pull --ff-only
}

library_git_branch_list() {
    local repo="$1"
    git -C "$repo" branch -a --format='%(refname:short)'
}

library_git_branch_current() {
    local repo="$1"
    git -C "$repo" branch --show-current
}
