diff options
| -rwxr-xr-x | reposync | 98 |
1 files changed, 98 insertions, 0 deletions
diff --git a/reposync b/reposync new file mode 100755 index 0000000..60be131 --- /dev/null +++ b/reposync @@ -0,0 +1,98 @@ +#!/bin/sh -e +# +# script to sync repos +# required /etc/reposync.conf +# +# /etc/reposync.conf format: +# <git url>|<branch>|<local path to sync> +# + +log() { + msg="$1" + if [ "$LOG" ]; then + echo "$(date +'%Y-%m-%d %H:%M:%S') $msg" | tee -a "$LOGFILE" + else + echo "$msg" + fi +} + +run_cmd() { + if [ "$DRY_RUN" ]; then + log " [dry-run] $*" + else + log " $*" + eval "$@" + fi +} + +syncrepo() { + url=$1 + branch=$2 + path=$3 + + # if url is empty, do nothing + if [ ! "$url" ]; then + exit 0 + fi + + # if $path empty, your format is wrong + if [ ! "$path" ]; then + echo "/etc/reposync.conf format: <git url>|<branch>|<local path to sync>" + exit + fi + + if [ "$FORCE" ]; then + if [ -d "$path" ]; then + log "=> Force removing repo directory $path..." + run_cmd "rm -rf \"$path\"" + fi + fi + + if [ ! -d "$path/.git" ]; then + log "=> Sync repo $path..." + run_cmd "mkdir -p \"$path\"" + run_cmd "git clone --branch \"$branch\" --single-branch \"$url\" \"$path\"" + else + log "=> Updating repo $path..." + run_cmd "cd \"$path\" && git fetch origin \"$branch\"" + run_cmd "cd \"$path\" && git reset --hard \"origin/$branch\"" + run_cmd "cd \"$path\" && git clean -fdx" + fi +} + +usage() { + echo "Usage: $0 [-n|-l|-f]" + echo " -n dry-run" + echo " -l logging (/var/log/reposync.log)" + echo " -f force sync" + exit 1 +} + +while [ "$1" ]; do + case "$1" in + -n) DRY_RUN=1;; + -l) LOG=1;; + -f) FORCE=1;; + -h) usage;; + esac + shift +done + +command -v git >/dev/null 2>&1 || { + echo "error: git is not installed." >&2 + exit 1 +} + +LOGFILE="/var/log/reposync.log" +CONFFILE="/etc/reposync.conf" + +if [ ! -f "$CONFFILE" ]; then + echo "error: config file not found: $CONFFILE" >&2 + exit 1 +fi + +grep -Ev '^#|^$' "$CONFFILE" | while IFS='|' read -r url branch path _; do + syncrepo "$url" "$branch" "$path" +done + +exit 0 |