Automating Git Repository Updates and Deployment Checks
Owner: SnippetBot
Created: 2026-08-22 00:00:46
Size: 2.04 KB
Expires: Never
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
REPO_URL="https://github.com/your-org/your-repo.git" # Replace with your repository URL
TARGET_DIR="/srv/www/my-app" # Replace with your deployment target directory
BRANCH="main" # Replace with your target branch
# --- Configuration for Error Handling (similar to previous snippet) ---
set -e
set -u
set -o pipefail
log() {
local type="$1"
local message="$2"
echo "$(date '+%Y-%m-%d %H:%M:%S') [GIT_DEPLOY] [${type}] ${message}"
}
error_exit() {
log "ERROR" "An error occurred. Exiting."
exit 1
}
trap 'error_exit' ERR
# --- Main Logic ---
log "INFO" "Starting Git deployment process for ${REPO_URL} on branch ${BRANCH}."
# Check if target directory exists and is a git repository
if [ -d "${TARGET_DIR}" ]; then
if [ -d "${TARGET_DIR}/.git" ]; then
log "INFO" "Repository already exists at ${TARGET_DIR}. Pulling latest changes..."
cd "${TARGET_DIR}"
git fetch origin
git reset --hard "origin/${BRANCH}" # Ensures local matches remote, discards local changes
# Alternative: git pull origin ${BRANCH} (if local changes are allowed or handled elsewhere)
log "INFO" "Repository updated."
else
log "ERROR" "${TARGET_DIR} exists but is not a Git repository. Please ensure it's empty or remove it."
exit 1
fi
else
log "INFO" "Target directory ${TARGET_DIR} does not exist. Cloning repository..."
mkdir -p "${TARGET_DIR}"
git clone --branch "${BRANCH}" "${REPO_URL}" "${TARGET_DIR}"
log "INFO" "Repository cloned into ${TARGET_DIR}."
fi
# Optional: Perform post-deployment steps (e.g., install dependencies, restart services)
log "INFO" "Running post-deployment steps (e.g., npm install, service restart)..."
cd "${TARGET_DIR}"
# Example: Install Node.js dependencies
# if [ -f "package.json" ]; then
# npm install --production
# log "INFO" "Node.js dependencies installed."
# fi
# Example: Restart a service (e.g., Nginx, Gunicorn, PHP-FPM)
# sudo systemctl restart your_web_app_service
log "INFO" "Post-deployment steps completed."
log "INFO" "Git deployment process finished successfully for ${TARGET_DIR}."