#!/bin/bash # sync-gitea.sh - 自动同步到 Gitea 仓库 # # 用法: # ./sync-gitea.sh # 正常提交和推送 # ./sync-gitea.sh --init # 初始化仓库 # ./sync-gitea.sh --commit # 仅提交 # ./sync-gitea.sh --push # 仅推送 set -e # 配置 REPO_DIR="/Users/x/websafe" GITEA_URL="https://git.hk.hao.work" REPO_NAME="websafe-kb" GITEA_TOKEN="267bc2e8b189b8fb6daf56e41a9e5ad47d543968" GIT_USER="hao" GIT_EMAIL="hao@users.noreply.git.hk.hao.work" cd "$REPO_DIR" # 颜色定义 RED='\033[91m' GREEN='\033[92m' YELLOW='\033[93m' BLUE='\033[94m' END='\033[0m' log_info() { echo -e "${BLUE}[INFO]${END} $1" } log_success() { echo -e "${GREEN}[SUCCESS]${END} $1" } log_warning() { echo -e "${YELLOW}[WARNING]${END} $1" } log_error() { echo -e "${RED}[ERROR]${END} $1" } # 初始化仓库 init_repo() { log_info "初始化 Git 仓库..." if [ -d ".git" ]; then log_warning "Git 仓库已存在" else git init git config user.name "$GIT_USER" git config user.email "$GIT_EMAIL" log_success "Git 仓库初始化完成" fi # 添加远程仓库 if git remote | grep -q "origin"; then git remote set-url origin "${GITEA_URL}/${GIT_USER}/${REPO_NAME}.git" log_info "远程仓库 URL 已更新" else git remote add origin "${GITEA_URL}/${GIT_USER}/${REPO_NAME}.git" log_success "远程仓库已添加" fi # 配置凭证 git config credential.helper store echo "https://${GIT_USER}:${GITEA_TOKEN}@git.hk.hao.work" > ~/.git-credentials 2>/dev/null || true chmod 600 ~/.git-credentials 2>/dev/null || true log_success "初始化完成" } # 提交更改 commit_changes() { log_info "检查更改..." # 添加所有文件 git add -A # 检查是否有更改 if git diff --staged --quiet; then log_info "没有需要提交的更改" return 0 fi # 生成提交信息 local timestamp=$(date '+%Y-%m-%d %H:%M:%S') local changed_files=$(git diff --staged --name-only | wc -l | tr -d ' ') local commit_msg="更新: ${changed_files} 个文件 - ${timestamp}" # 如果提供了自定义提交信息 if [ -n "$1" ]; then commit_msg="$1" fi git commit -m "$commit_msg" log_success "提交完成: $commit_msg" } # 推送到远程 push_changes() { log_info "推送到远程仓库..." # 获取当前分支 local branch=$(git branch --show-current 2>/dev/null || echo "main") # 如果分支为空,使用 main if [ -z "$branch" ]; then branch="main" fi # 推送 if git push -u origin "$branch" 2>&1; then log_success "推送完成: $branch" else log_error "推送失败" return 1 fi } # 完整同步 full_sync() { commit_changes push_changes } # 显示帮助 show_help() { echo "用法: $0 [选项]" echo "" echo "选项:" echo " --init 初始化 Git 仓库" echo " --commit 仅提交更改" echo " --push 仅推送到远程" echo " --status 显示仓库状态" echo " --help 显示此帮助" echo "" echo "无参数运行时执行完整同步 (提交 + 推送)" } # 显示状态 show_status() { log_info "仓库状态:" echo "" git status -s echo "" local ahead=$(git rev-list --count @{upstream}..HEAD 2>/dev/null || echo "0") local behind=$(git rev-list --count HEAD..@{upstream} 2>/dev/null || echo "0") log_info "领先远程 $ahead 个提交, 落后 $behind 个提交" } # 主程序 case "${1:-}" in --init) init_repo ;; --commit) commit_changes "$2" ;; --push) push_changes ;; --status) show_status ;; --help|-h) show_help ;; *) full_sync ;; esac