initial
This commit is contained in:
@@ -0,0 +1,40 @@
|
|||||||
|
---
|
||||||
|
name: bash-defensive-patterns
|
||||||
|
description: Master defensive Bash programming techniques for production-grade scripts. Use when writing robust shell scripts, CI/CD pipelines, or system utilities requiring fault tolerance and safety.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Bash Defensive Patterns
|
||||||
|
|
||||||
|
Comprehensive guidance for writing production-ready Bash scripts using defensive programming techniques, error handling, and safety best practices to prevent common pitfalls and ensure reliability.
|
||||||
|
|
||||||
|
## When to Use This Skill
|
||||||
|
|
||||||
|
- Writing production automation scripts
|
||||||
|
- Building CI/CD pipeline scripts
|
||||||
|
- Creating system administration utilities
|
||||||
|
- Developing error-resilient deployment automation
|
||||||
|
- Writing scripts that must handle edge cases safely
|
||||||
|
- Building maintainable shell script libraries
|
||||||
|
- Implementing comprehensive logging and monitoring
|
||||||
|
- Creating scripts that must work across different platforms
|
||||||
|
|
||||||
|
## Detailed patterns and worked examples
|
||||||
|
|
||||||
|
Detailed pattern documentation lives in `references/details.md`. Read that file when the navigation tier above is insufficient.
|
||||||
|
|
||||||
|
## Best Practices Summary
|
||||||
|
|
||||||
|
1. **Always use strict mode** - `set -Eeuo pipefail`
|
||||||
|
2. **Quote all variables** - `"$variable"` prevents word splitting
|
||||||
|
3. **Use [[]] conditionals** - More robust than [ ]
|
||||||
|
4. **Implement error trapping** - Catch and handle errors gracefully
|
||||||
|
5. **Validate all inputs** - Check file existence, permissions, formats
|
||||||
|
6. **Use functions for reusability** - Prefix with meaningful names
|
||||||
|
7. **Implement structured logging** - Include timestamps and levels
|
||||||
|
8. **Support dry-run mode** - Allow users to preview changes
|
||||||
|
9. **Handle temporary files safely** - Use mktemp, cleanup with trap
|
||||||
|
10. **Design for idempotency** - Scripts should be safe to rerun
|
||||||
|
11. **Document requirements** - List dependencies and minimum versions
|
||||||
|
12. **Test error paths** - Ensure error handling works correctly
|
||||||
|
13. **Use `command -v`** - Safer than `which` for checking executables
|
||||||
|
14. **Prefer printf over echo** - More predictable across systems
|
||||||
@@ -0,0 +1,498 @@
|
|||||||
|
# bash-defensive-patterns — detailed patterns and worked examples
|
||||||
|
|
||||||
|
## Core Defensive Principles
|
||||||
|
|
||||||
|
### 1. Strict Mode
|
||||||
|
|
||||||
|
Enable bash strict mode at the start of every script to catch errors early.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
set -Eeuo pipefail # Exit on error, unset variables, pipe failures
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key flags:**
|
||||||
|
|
||||||
|
- `set -E`: Inherit ERR trap in functions
|
||||||
|
- `set -e`: Exit on any error (command returns non-zero)
|
||||||
|
- `set -u`: Exit on undefined variable reference
|
||||||
|
- `set -o pipefail`: Pipe fails if any command fails (not just last)
|
||||||
|
|
||||||
|
### 2. Error Trapping and Cleanup
|
||||||
|
|
||||||
|
Implement proper cleanup on script exit or error.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
trap 'echo "Error on line $LINENO"' ERR
|
||||||
|
TMPDIR=$(mktemp -d)
|
||||||
|
trap 'echo "Cleaning up..."; rm -rf "$TMPDIR"' EXIT
|
||||||
|
|
||||||
|
# Script code here
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Variable Safety
|
||||||
|
|
||||||
|
Always quote variables to prevent word splitting and globbing issues.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Wrong - unsafe
|
||||||
|
cp $source $dest
|
||||||
|
|
||||||
|
# Correct - safe
|
||||||
|
cp "$source" "$dest"
|
||||||
|
|
||||||
|
# Required variables - fail with message if unset
|
||||||
|
: "${REQUIRED_VAR:?REQUIRED_VAR is not set}"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Array Handling
|
||||||
|
|
||||||
|
Use arrays safely for complex data handling.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Safe array iteration
|
||||||
|
declare -a items=("item 1" "item 2" "item 3")
|
||||||
|
|
||||||
|
for item in "${items[@]}"; do
|
||||||
|
echo "Processing: $item"
|
||||||
|
done
|
||||||
|
|
||||||
|
# Reading output into array safely
|
||||||
|
mapfile -t lines < <(some_command)
|
||||||
|
readarray -t numbers < <(seq 1 10)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. Conditional Safety
|
||||||
|
|
||||||
|
Use `[[ ]]` for Bash-specific features, `[ ]` for POSIX.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Bash - safer
|
||||||
|
if [[ -f "$file" && -r "$file" ]]; then
|
||||||
|
content=$(<"$file")
|
||||||
|
fi
|
||||||
|
|
||||||
|
# POSIX - portable
|
||||||
|
if [ -f "$file" ] && [ -r "$file" ]; then
|
||||||
|
content=$(cat "$file")
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Test for existence before operations
|
||||||
|
if [[ -z "${VAR:-}" ]]; then
|
||||||
|
echo "VAR is not set or is empty"
|
||||||
|
fi
|
||||||
|
```
|
||||||
|
|
||||||
|
## Fundamental Patterns
|
||||||
|
|
||||||
|
### Pattern 1: Safe Script Directory Detection
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
# Correctly determine script directory
|
||||||
|
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
|
||||||
|
SCRIPT_NAME="$(basename -- "${BASH_SOURCE[0]}")"
|
||||||
|
|
||||||
|
echo "Script location: $SCRIPT_DIR/$SCRIPT_NAME"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pattern 2: Comprehensive Function Templat
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
# Prefix for functions: handle_*, process_*, check_*, validate_*
|
||||||
|
# Include documentation and error handling
|
||||||
|
|
||||||
|
validate_file() {
|
||||||
|
local -r file="$1"
|
||||||
|
local -r message="${2:-File not found: $file}"
|
||||||
|
|
||||||
|
if [[ ! -f "$file" ]]; then
|
||||||
|
echo "ERROR: $message" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
process_files() {
|
||||||
|
local -r input_dir="$1"
|
||||||
|
local -r output_dir="$2"
|
||||||
|
|
||||||
|
# Validate inputs
|
||||||
|
[[ -d "$input_dir" ]] || { echo "ERROR: input_dir not a directory" >&2; return 1; }
|
||||||
|
|
||||||
|
# Create output directory if needed
|
||||||
|
mkdir -p "$output_dir" || { echo "ERROR: Cannot create output_dir" >&2; return 1; }
|
||||||
|
|
||||||
|
# Process files safely
|
||||||
|
while IFS= read -r -d '' file; do
|
||||||
|
echo "Processing: $file"
|
||||||
|
# Do work
|
||||||
|
done < <(find "$input_dir" -maxdepth 1 -type f -print0)
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pattern 3: Safe Temporary File Handling
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
# Create temporary directory
|
||||||
|
TMPDIR=$(mktemp -d) || { echo "ERROR: Failed to create temp directory" >&2; exit 1; }
|
||||||
|
trap 'rm -rf -- "$TMPDIR"' EXIT
|
||||||
|
|
||||||
|
# Create temporary files in directory
|
||||||
|
TMPFILE1="$TMPDIR/temp1.txt"
|
||||||
|
TMPFILE2="$TMPDIR/temp2.txt"
|
||||||
|
|
||||||
|
# Use temporary files
|
||||||
|
touch "$TMPFILE1" "$TMPFILE2"
|
||||||
|
|
||||||
|
echo "Temp files created in: $TMPDIR"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pattern 4: Robust Argument Parsing
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
# Default values
|
||||||
|
VERBOSE=false
|
||||||
|
DRY_RUN=false
|
||||||
|
OUTPUT_FILE=""
|
||||||
|
THREADS=4
|
||||||
|
|
||||||
|
usage() {
|
||||||
|
cat <<EOF
|
||||||
|
Usage: $0 [OPTIONS]
|
||||||
|
|
||||||
|
Options:
|
||||||
|
-v, --verbose Enable verbose output
|
||||||
|
-d, --dry-run Run without making changes
|
||||||
|
-o, --output FILE Output file path
|
||||||
|
-j, --jobs NUM Number of parallel jobs
|
||||||
|
-h, --help Show this help message
|
||||||
|
EOF
|
||||||
|
exit "${1:-0}"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Parse arguments
|
||||||
|
while [[ $# -gt 0 ]]; do
|
||||||
|
case "$1" in
|
||||||
|
-v|--verbose)
|
||||||
|
VERBOSE=true
|
||||||
|
shift
|
||||||
|
;;
|
||||||
|
-d|--dry-run)
|
||||||
|
DRY_RUN=true
|
||||||
|
shift
|
||||||
|
;;
|
||||||
|
-o|--output)
|
||||||
|
OUTPUT_FILE="$2"
|
||||||
|
shift 2
|
||||||
|
;;
|
||||||
|
-j|--jobs)
|
||||||
|
THREADS="$2"
|
||||||
|
shift 2
|
||||||
|
;;
|
||||||
|
-h|--help)
|
||||||
|
usage 0
|
||||||
|
;;
|
||||||
|
--)
|
||||||
|
shift
|
||||||
|
break
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "ERROR: Unknown option: $1" >&2
|
||||||
|
usage 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# Validate required arguments
|
||||||
|
[[ -n "$OUTPUT_FILE" ]] || { echo "ERROR: -o/--output is required" >&2; usage 1; }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pattern 5: Structured Logging
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
# Logging functions
|
||||||
|
log_info() {
|
||||||
|
echo "[$(date +'%Y-%m-%d %H:%M:%S')] INFO: $*" >&2
|
||||||
|
}
|
||||||
|
|
||||||
|
log_warn() {
|
||||||
|
echo "[$(date +'%Y-%m-%d %H:%M:%S')] WARN: $*" >&2
|
||||||
|
}
|
||||||
|
|
||||||
|
log_error() {
|
||||||
|
echo "[$(date +'%Y-%m-%d %H:%M:%S')] ERROR: $*" >&2
|
||||||
|
}
|
||||||
|
|
||||||
|
log_debug() {
|
||||||
|
if [[ "${DEBUG:-0}" == "1" ]]; then
|
||||||
|
echo "[$(date +'%Y-%m-%d %H:%M:%S')] DEBUG: $*" >&2
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Usage
|
||||||
|
log_info "Starting script"
|
||||||
|
log_debug "Debug information"
|
||||||
|
log_warn "Warning message"
|
||||||
|
log_error "Error occurred"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pattern 6: Process Orchestration with Signals
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
# Track background processes
|
||||||
|
PIDS=()
|
||||||
|
|
||||||
|
cleanup() {
|
||||||
|
log_info "Shutting down..."
|
||||||
|
|
||||||
|
# Terminate all background processes
|
||||||
|
for pid in "${PIDS[@]}"; do
|
||||||
|
if kill -0 "$pid" 2>/dev/null; then
|
||||||
|
kill -TERM "$pid" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
# Wait for graceful shutdown
|
||||||
|
for pid in "${PIDS[@]}"; do
|
||||||
|
wait "$pid" 2>/dev/null || true
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
trap cleanup SIGTERM SIGINT
|
||||||
|
|
||||||
|
# Start background tasks
|
||||||
|
background_task &
|
||||||
|
PIDS+=($!)
|
||||||
|
|
||||||
|
another_task &
|
||||||
|
PIDS+=($!)
|
||||||
|
|
||||||
|
# Wait for all background processes
|
||||||
|
wait
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pattern 7: Safe File Operations
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
# Use -i flag to move safely without overwriting
|
||||||
|
safe_move() {
|
||||||
|
local -r source="$1"
|
||||||
|
local -r dest="$2"
|
||||||
|
|
||||||
|
if [[ ! -e "$source" ]]; then
|
||||||
|
echo "ERROR: Source does not exist: $source" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -e "$dest" ]]; then
|
||||||
|
echo "ERROR: Destination already exists: $dest" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
mv "$source" "$dest"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Safe directory cleanup
|
||||||
|
safe_rmdir() {
|
||||||
|
local -r dir="$1"
|
||||||
|
|
||||||
|
if [[ ! -d "$dir" ]]; then
|
||||||
|
echo "ERROR: Not a directory: $dir" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Use -I flag to prompt before rm (BSD/GNU compatible)
|
||||||
|
rm -rI -- "$dir"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Atomic file writes
|
||||||
|
atomic_write() {
|
||||||
|
local -r target="$1"
|
||||||
|
local tmpfile
|
||||||
|
# Temp file in the target's directory, so the rename stays on one filesystem
|
||||||
|
tmpfile=$(mktemp "$(dirname -- "$target")/.atomic_write.XXXXXX") || return 1
|
||||||
|
|
||||||
|
# Write to temp file first
|
||||||
|
cat > "$tmpfile"
|
||||||
|
|
||||||
|
# Atomic rename
|
||||||
|
mv "$tmpfile" "$target"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pattern 8: Idempotent Script Design
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
# Check if resource already exists
|
||||||
|
ensure_directory() {
|
||||||
|
local -r dir="$1"
|
||||||
|
|
||||||
|
if [[ -d "$dir" ]]; then
|
||||||
|
log_info "Directory already exists: $dir"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
mkdir -p "$dir" || {
|
||||||
|
log_error "Failed to create directory: $dir"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
log_info "Created directory: $dir"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Ensure configuration state
|
||||||
|
ensure_config() {
|
||||||
|
local -r config_file="$1"
|
||||||
|
local -r default_value="$2"
|
||||||
|
|
||||||
|
if [[ ! -f "$config_file" ]]; then
|
||||||
|
echo "$default_value" > "$config_file"
|
||||||
|
log_info "Created config: $config_file"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Rerunning script multiple times should be safe
|
||||||
|
ensure_directory "/var/cache/myapp"
|
||||||
|
ensure_config "/etc/myapp/config" "DEBUG=false"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pattern 9: Safe Command Substitution
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
# Use $() instead of backticks
|
||||||
|
name=$(<"$file") # Modern, safe variable assignment from file
|
||||||
|
output=$(command -v python3) # Get command location safely
|
||||||
|
|
||||||
|
# Handle command substitution with error checking
|
||||||
|
result=$(command -v node) || {
|
||||||
|
log_error "node command not found"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# For multiple lines
|
||||||
|
mapfile -t lines < <(grep "pattern" "$file")
|
||||||
|
|
||||||
|
# NUL-safe iteration
|
||||||
|
while IFS= read -r -d '' file; do
|
||||||
|
echo "Processing: $file"
|
||||||
|
done < <(find /path -type f -print0)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Pattern 10: Dry-Run Support
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
DRY_RUN="${DRY_RUN:-false}"
|
||||||
|
|
||||||
|
run_cmd() {
|
||||||
|
if [[ "$DRY_RUN" == "true" ]]; then
|
||||||
|
echo "[DRY RUN] Would execute: $*"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
"$@"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Usage
|
||||||
|
run_cmd cp "$source" "$dest"
|
||||||
|
run_cmd rm "$file"
|
||||||
|
run_cmd chown "$owner" "$target"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Advanced Defensive Techniques
|
||||||
|
|
||||||
|
### Named Parameters Pattern
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
process_data() {
|
||||||
|
local input_file=""
|
||||||
|
local output_dir=""
|
||||||
|
local format="json"
|
||||||
|
|
||||||
|
# Parse named parameters
|
||||||
|
while [[ $# -gt 0 ]]; do
|
||||||
|
case "$1" in
|
||||||
|
--input=*)
|
||||||
|
input_file="${1#*=}"
|
||||||
|
;;
|
||||||
|
--output=*)
|
||||||
|
output_dir="${1#*=}"
|
||||||
|
;;
|
||||||
|
--format=*)
|
||||||
|
format="${1#*=}"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "ERROR: Unknown parameter: $1" >&2
|
||||||
|
return 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
shift
|
||||||
|
done
|
||||||
|
|
||||||
|
# Validate required parameters
|
||||||
|
[[ -n "$input_file" ]] || { echo "ERROR: --input is required" >&2; return 1; }
|
||||||
|
[[ -n "$output_dir" ]] || { echo "ERROR: --output is required" >&2; return 1; }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Dependency Checking
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
check_dependencies() {
|
||||||
|
local -a missing_deps=()
|
||||||
|
local -a required=("jq" "curl" "git")
|
||||||
|
|
||||||
|
for cmd in "${required[@]}"; do
|
||||||
|
if ! command -v "$cmd" &>/dev/null; then
|
||||||
|
missing_deps+=("$cmd")
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [[ ${#missing_deps[@]} -gt 0 ]]; then
|
||||||
|
echo "ERROR: Missing required commands: ${missing_deps[*]}" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
check_dependencies
|
||||||
|
```
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
# docker-build-push (Gitea Actions)
|
||||||
|
|
||||||
|
A composite Gitea Action that computes the next version via
|
||||||
|
[`get-next-version`](../get-next-version/action.yml:1), builds a Docker
|
||||||
|
image (optionally for a specific multi-stage `target`), logs in to the
|
||||||
|
target registry, pushes the image, and (by default) tags the commit with
|
||||||
|
the version that was just built.
|
||||||
|
|
||||||
|
## How it works
|
||||||
|
|
||||||
|
1. **Get next version** — calls the sibling
|
||||||
|
[`get-next-version`](../get-next-version/action.yml:1) action via
|
||||||
|
`self:captbrick/gitea-actions/get-next-version@master`, forwarding
|
||||||
|
`main_branch`, `major`, `minor`, `image_registry`, `image_repository`,
|
||||||
|
and `target` as its `image_name` input. When `image_registry` is empty,
|
||||||
|
`get-next-version` falls back to its own default (`gitea.livingeach.day`)
|
||||||
|
internally, so this action doesn't need to repeat that default. The image
|
||||||
|
repository is lowercased by `get-next-version`, because Docker repository
|
||||||
|
names must be lowercase. When `target` is set, `get-next-version` appends
|
||||||
|
it to the image repository and computes a
|
||||||
|
distinct `version_tag` (see [Multiple images from one Dockerfile](#multiple-images-from-one-dockerfile)
|
||||||
|
below). `get-next-version` exports `VERSION`, `VERSION_TAG`,
|
||||||
|
`IMAGE_REGISTRY` and `IMAGE_TAG` into `$GITEA_ENV`, which the remaining
|
||||||
|
steps consume directly, and also re-exposes `version` / `version_tag` /
|
||||||
|
`image_tag` as this action's own outputs.
|
||||||
|
2. **Prepare cache refs** — when `cache` is enabled (default), computes two
|
||||||
|
registry-backed BuildKit cache refs below the final lowercased image
|
||||||
|
repository's dedicated `cache` repository: one for the base branch and one
|
||||||
|
for the current/head branch. Branch names are lowercased and sanitized so
|
||||||
|
refs like `feature/foo` become valid Docker tags such as `feature-foo`. For
|
||||||
|
merge commits, the action also tries to detect the merged source branch from
|
||||||
|
the commit message and adds that branch cache as an extra cache source.
|
||||||
|
3. **Docker login** — runs when either `push` or `cache` is enabled, because
|
||||||
|
registry cache import/export needs registry authentication too.
|
||||||
|
4. **Set up QEMU** — always run via `docker/setup-qemu-action`, so the runner
|
||||||
|
can emulate non-native architectures and has a Buildx builder with full
|
||||||
|
feature support (registry cache export, multi-platform output), regardless
|
||||||
|
of how many entries `platforms` has.
|
||||||
|
5. **Build and push image** — always runs `docker buildx build`, passing
|
||||||
|
`--build-arg APP_VERSION=$VERSION`, `--tag $IMAGE_TAG`, `-f <dockerfile>`,
|
||||||
|
optional `--target <target>`, and `--platform <platforms>` (default
|
||||||
|
`linux/amd64`). When `cache` is enabled, adds `--cache-from` for the base,
|
||||||
|
detected merge-source, and branch cache refs and `--cache-to` for the
|
||||||
|
branch cache ref. Pushing is consolidated into this single step: when
|
||||||
|
`push: 'true'`, `--push` is added so the result (single- or multi-platform)
|
||||||
|
is published straight from Buildx. With `push: 'false'`, no output flag is
|
||||||
|
added at all — the build still runs and still updates the registry cache
|
||||||
|
(when `cache: 'true'`), but produces no local image; it only warms the
|
||||||
|
cache. See [Building for multiple platforms](#building-for-multiple-platforms)
|
||||||
|
below.
|
||||||
|
6. **Create version tag** — gated behind the `push` input (default on);
|
||||||
|
commits a Git tag named after `$VERSION_TAG` using the
|
||||||
|
`gitea-actions[bot]` identity and pushes it. Setting `push: 'false'`
|
||||||
|
skips the image push and Git tag creation/push; if `cache` is still enabled,
|
||||||
|
the build can still log in and update the branch cache.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
name: Docker Build & Push
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- uses: self:captbrick/gitea-actions/docker-build-push@master
|
||||||
|
with:
|
||||||
|
main_branch: master
|
||||||
|
major: 1
|
||||||
|
minor: 1
|
||||||
|
registry_username: ${{ secrets.REGISTRY_USERNAME }}
|
||||||
|
registry_password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||||
|
```
|
||||||
|
|
||||||
|
> The workflow needs `permissions: contents: write` so the action can push
|
||||||
|
> the Git tag it creates. The checkout step needs `fetch-depth: 0` so the
|
||||||
|
> full tag history is available to `get-next-version`. Set `push: 'false'`
|
||||||
|
> to build without pushing the final image or creating a Git tag — the build
|
||||||
|
> runs but produces no accessible image (just warms the cache, if enabled).
|
||||||
|
> With the default `cache: 'true'`, the action still logs in and updates the
|
||||||
|
> branch BuildKit cache; set `cache: 'false'` as well to skip registry
|
||||||
|
> interaction entirely.
|
||||||
|
|
||||||
|
### Multiple images from one Dockerfile
|
||||||
|
|
||||||
|
Use `target` when a single multi-stage Dockerfile produces more than one
|
||||||
|
image (e.g. `frontend` and `backend`). `target` is forwarded to
|
||||||
|
`get-next-version` as its `image_name` input, which:
|
||||||
|
|
||||||
|
- appends `/<target>` to the image repository, so each target is pushed to
|
||||||
|
its own repository path (e.g. `gitea.livingeach.day/owner/repo/frontend:1.0.6`
|
||||||
|
and `gitea.livingeach.day/owner/repo/backend:1.0.6`), while `version` itself
|
||||||
|
(`1.0.6`) stays the same for every target built from the same commit;
|
||||||
|
- prepends `<target>-` to `version_tag`, so the Git tag created for each
|
||||||
|
target mirrors the image repository naming (e.g. `frontend-1.0.6`,
|
||||||
|
`backend-1.0.6`) and pushing one doesn't collide with the others.
|
||||||
|
|
||||||
|
A common pattern is to first warm up the shared layer cache with a
|
||||||
|
non-tagged, non-pushed `build-all` target, then build and push each real
|
||||||
|
target:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- name: Warm up build cache
|
||||||
|
uses: self:captbrick/gitea-actions/docker-build-push@master
|
||||||
|
with:
|
||||||
|
main_branch: master
|
||||||
|
target: build-all
|
||||||
|
push: 'false'
|
||||||
|
registry_username: ${{ secrets.REGISTRY_USERNAME }}
|
||||||
|
registry_password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||||
|
|
||||||
|
- name: Build & push frontend
|
||||||
|
uses: self:captbrick/gitea-actions/docker-build-push@master
|
||||||
|
with:
|
||||||
|
main_branch: master
|
||||||
|
target: frontend
|
||||||
|
registry_username: ${{ secrets.REGISTRY_USERNAME }}
|
||||||
|
registry_password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||||
|
|
||||||
|
- name: Build & push backend
|
||||||
|
uses: self:captbrick/gitea-actions/docker-build-push@master
|
||||||
|
with:
|
||||||
|
main_branch: master
|
||||||
|
target: backend
|
||||||
|
registry_username: ${{ secrets.REGISTRY_USERNAME }}
|
||||||
|
registry_password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||||
|
```
|
||||||
|
|
||||||
|
> `push: 'false'` on the warm-up step means it skips Docker login, push,
|
||||||
|
> and tagging entirely, so its `target: build-all` value never produces a
|
||||||
|
> pushed image or a Git tag — it only primes Docker's layer cache for the
|
||||||
|
> `frontend` and `backend` builds that follow.
|
||||||
|
|
||||||
|
### Registry build cache
|
||||||
|
|
||||||
|
Registry-backed BuildKit cache is enabled by default with `cache: 'true'`.
|
||||||
|
The action prepares cache refs using a dedicated `cache` repository below the
|
||||||
|
computed `IMAGE_REPOSITORY` and `cache_registry` when set, otherwise the
|
||||||
|
computed `IMAGE_REGISTRY`:
|
||||||
|
|
||||||
|
- `<image-repository>/cache:<base-branch>` is used as a stable fallback cache source;
|
||||||
|
- `<image-repository>/cache:<merged-source-branch>` is used as an additional cache source on merge
|
||||||
|
commits when the source branch can be detected;
|
||||||
|
- `<image-repository>/cache:<current-or-head-branch>` is used as both a cache source and the
|
||||||
|
cache destination (`mode=max`).
|
||||||
|
|
||||||
|
For pull requests, the base ref comes from `GITHUB_BASE_REF` and the branch
|
||||||
|
ref comes from `GITHUB_HEAD_REF`. For non-PR builds, missing refs fall back to
|
||||||
|
`main_branch` / `GITHUB_REF_NAME`. Ref names are lowercased and sanitized for
|
||||||
|
Docker tag compatibility. On merge commits, the action parses common merge
|
||||||
|
commit subjects such as `Merge pull request #123 from owner/feature` and
|
||||||
|
`Merge branch 'feature'` to add the source branch cache as an extra
|
||||||
|
`--cache-from` ref. This lets a post-merge build on `master` reuse layers from
|
||||||
|
the merged feature branch cache before writing the updated `master` cache.
|
||||||
|
|
||||||
|
Because the cache is stored in the registry, `cache: 'true'` requires Docker
|
||||||
|
login even when `push: 'false'`. Disable it with `cache: 'false'` when you want
|
||||||
|
an unauthenticated local-only build.
|
||||||
|
|
||||||
|
Set `cache_registry` when cache layers should be stored in a different registry
|
||||||
|
than the final image. For example, the final image can still be pushed to
|
||||||
|
`gitea.livingeach.day/owner/repo`, while cache refs are stored under
|
||||||
|
`zot-registry.zot-registry.svc.cluster.local:5000/owner/repo/cache:<branch>`.
|
||||||
|
The action logs in to the cache registry when it differs from `IMAGE_REGISTRY`.
|
||||||
|
|
||||||
|
### Building for multiple platforms
|
||||||
|
|
||||||
|
By default `platforms` is `linux/amd64`, matching a single-platform
|
||||||
|
`docker buildx build`. To also publish, for example, an `arm64` variant
|
||||||
|
(needed to run the image on Apple Silicon or ARM hosts — without it you'll
|
||||||
|
hit `no match for platform in manifest` when pulling), set a single foreign
|
||||||
|
platform or a comma-separated list:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- uses: self:captbrick/gitea-actions/docker-build-push@master
|
||||||
|
with:
|
||||||
|
main_branch: master
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
|
registry_username: ${{ secrets.REGISTRY_USERNAME }}
|
||||||
|
registry_password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||||
|
```
|
||||||
|
|
||||||
|
`docker/setup-qemu-action` always runs before the build, so the runner can
|
||||||
|
emulate non-native architecture(s) (needed even for a single foreign platform
|
||||||
|
like `platforms: linux/arm64`, not just comma-separated lists) and has a
|
||||||
|
full-featured Buildx builder available (registry cache export, multi-platform
|
||||||
|
output).
|
||||||
|
|
||||||
|
Push is consolidated into the build step itself (`docker buildx build
|
||||||
|
--push`): with `push: 'true'`, this works the same way whether `platforms`
|
||||||
|
has one or several entries, pushing the result (single image or multi-arch
|
||||||
|
manifest list) straight to the registry. With `push: 'false'`, no output
|
||||||
|
flag is added regardless of platform count — the build runs and still
|
||||||
|
updates the registry cache (when `cache: 'true'`), but produces no
|
||||||
|
accessible image; use `push: 'false'` only to warm the cache, not to inspect
|
||||||
|
the image locally. (Buildx also can't `--load` a multi-platform result into
|
||||||
|
the local Docker daemon even if that were attempted.)
|
||||||
|
|
||||||
|
## Inputs
|
||||||
|
|
||||||
|
| Name | Description | Required | Default |
|
||||||
|
| -------------------- | ------------------------------------------------------------------------------------- | -------- | ---------------------- |
|
||||||
|
| `main_branch` | Name of the main branch (e.g., `master` or `main`); forwarded to `get-next-version` | yes | |
|
||||||
|
| `major` | Major version number; forwarded to `get-next-version` | no | `'1'` |
|
||||||
|
| `minor` | Minor version number; forwarded to `get-next-version` | no | `'0'` |
|
||||||
|
| `image_registry` | Container registry used to build the image tag and to log in to; forwarded to `get-next-version` when set, otherwise its default (`gitea.livingeach.day`) is used | no | `''` |
|
||||||
|
| `image_repository` | Image repository used to build the image tag; forwarded to `get-next-version` when set, otherwise its default (full `owner/repo` path) is used. It is always lowercased before building `IMAGE_TAG`, because Docker repository names must be lowercase | no | `''` |
|
||||||
|
| `target` | Dockerfile build stage/target (`docker build --target`); also forwarded to `get-next-version` as `image_name` — see [Multiple images from one Dockerfile](#multiple-images-from-one-dockerfile) | no | `''` |
|
||||||
|
| `registry_username` | Username (or service principal app ID) used to log in to the registry | yes | |
|
||||||
|
| `registry_password` | Password (or service principal secret) used to log in to the registry | yes | |
|
||||||
|
| `dockerfile` | Path to the Dockerfile to build | no | `Dockerfile` |
|
||||||
|
| `context` | Docker build context path | no | `.` |
|
||||||
|
| `push` | Whether to push the built image and create/push a Git tag matching `version_tag`; Docker login also runs when `cache` is enabled | no | `'true'` |
|
||||||
|
| `cache` | Whether to use registry-backed Docker BuildKit cache with branch/base cache refs and detected merge-source cache refs | no | `'true'` |
|
||||||
|
| `cache_registry` | Optional registry used for BuildKit cache refs; defaults to the computed `IMAGE_REGISTRY` when empty | no | `''` |
|
||||||
|
| `platforms` | Comma-separated `docker buildx build --platform` list, e.g. `linux/amd64,linux/arm64` — see [Building for multiple platforms](#building-for-multiple-platforms) | no | `'linux/amd64'` |
|
||||||
|
|
||||||
|
## Outputs
|
||||||
|
|
||||||
|
| Name | Description |
|
||||||
|
| ------------- | ------------------------------------------------------------------- |
|
||||||
|
| `version` | Next application version computed by `get-next-version` (e.g., `1.0.6` or `1.0.6-feature.1`) |
|
||||||
|
| `version_tag` | Version string used for the Git tag (equals `version`, or `target-version` when `target` is set) |
|
||||||
|
| `image_tag` | Full image tag that was built and pushed (e.g., `gitea.livingeach.day/owner/repo:1.0.6`, or `gitea.livingeach.day/owner/repo/frontend:1.0.6` when `target` is set) |
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
name: Docker Build & Push
|
||||||
|
description: Computes the next version (via get-next-version), builds a Docker image (optionally for a specific multi-stage target), logs in to the registry, pushes the image, and optionally tags the commit with the version.
|
||||||
|
|
||||||
|
inputs:
|
||||||
|
main_branch:
|
||||||
|
description: Name of the main branch (e.g., master or main). Forwarded to get-next-version.
|
||||||
|
required: true
|
||||||
|
major:
|
||||||
|
description: Major version number. Forwarded to get-next-version.
|
||||||
|
required: false
|
||||||
|
default: '1'
|
||||||
|
minor:
|
||||||
|
description: Minor version number. Forwarded to get-next-version.
|
||||||
|
required: false
|
||||||
|
default: '0'
|
||||||
|
image_registry:
|
||||||
|
description: Optional container registry used to build the image tag and to log in to. Forwarded to get-next-version, which defaults to gitea.livingeach.day when empty.
|
||||||
|
required: false
|
||||||
|
default: ''
|
||||||
|
image_repository:
|
||||||
|
description: "Optional image repository used to build the image tag. Forwarded to get-next-version, which defaults to the full repository path (owner/repo) when empty — that matches a scoped registry namespace like gitea.livingeach.day/owner/repo. Registries with a flat namespace can override this."
|
||||||
|
required: false
|
||||||
|
default: ''
|
||||||
|
target:
|
||||||
|
description: "Optional Dockerfile build stage/target to build (docker build --target). Also used as the default image_name, so each target gets its own registry/repository/image:version tag and Git version tag. Leave empty for a single-image Dockerfile, or use a warm-up-only target (e.g. build-all) together with push set to 'false' to prime the layer cache before building the real per-target images."
|
||||||
|
required: false
|
||||||
|
default: ''
|
||||||
|
image_name:
|
||||||
|
description: Optional image name below image_repository. When empty, target is used. Image tags are built as image_registry/image_repository/image_name:version when either image_name or target is set.
|
||||||
|
required: false
|
||||||
|
default: ''
|
||||||
|
registry_username:
|
||||||
|
description: Username (or service principal app ID) used to log in to the registry.
|
||||||
|
required: true
|
||||||
|
registry_password:
|
||||||
|
description: Password (or service principal secret) used to log in to the registry.
|
||||||
|
required: true
|
||||||
|
dockerfile:
|
||||||
|
description: Path to the Dockerfile to build.
|
||||||
|
required: false
|
||||||
|
default: Dockerfile
|
||||||
|
context:
|
||||||
|
description: Docker build context path.
|
||||||
|
required: false
|
||||||
|
default: '.'
|
||||||
|
push:
|
||||||
|
description: Whether to log in, push the built image to the registry, and (after a successful push) create and push a Git tag matching version_tag. Requires workflow permissions contents write.
|
||||||
|
required: false
|
||||||
|
default: 'true'
|
||||||
|
cache:
|
||||||
|
description: Whether to use registry-backed Docker BuildKit cache. Cache refs are stored below the computed image repository in a dedicated /cache repository and tagged with safe base/branch names; merge commits also try the merged source branch cache when it can be detected.
|
||||||
|
required: false
|
||||||
|
default: 'true'
|
||||||
|
cache_registry:
|
||||||
|
description: Optional registry to use for BuildKit cache refs. Defaults to the computed IMAGE_REGISTRY when empty.
|
||||||
|
required: false
|
||||||
|
default: ''
|
||||||
|
lfs:
|
||||||
|
description: Whether to fetch Git LFS files during checkout. Enable this for repositories that store Docker build inputs, such as WAR/ZIP artifacts, in Git LFS.
|
||||||
|
required: false
|
||||||
|
default: 'false'
|
||||||
|
platforms:
|
||||||
|
description: Comma-separated list of target platforms to build for (docker buildx build --platform), e.g. linux/amd64,linux/arm64. QEMU and Buildx are always set up so non-native platforms (even a single one, e.g. just linux/arm64) can be emulated. Push always happens inline via buildx --push; with push 'false' no image output is produced (the build only warms the cache), which is the only option anyway for more than one platform since buildx cannot load a multi-platform image into the local Docker daemon.
|
||||||
|
required: false
|
||||||
|
default: 'linux/amd64'
|
||||||
|
|
||||||
|
outputs:
|
||||||
|
version:
|
||||||
|
description: Next application version computed by get-next-version (e.g., 1.0.6 or 1.0.6-feature.1).
|
||||||
|
value: ${{ steps.next-version.outputs.version }}
|
||||||
|
version_tag:
|
||||||
|
description: Version string used for the Git tag (equals version, or target-version when target is set).
|
||||||
|
value: ${{ steps.next-version.outputs.version_tag }}
|
||||||
|
image_tag:
|
||||||
|
description: Full image tag that was built and pushed (e.g., gitea.livingeach.day/owner/repo:1.0.6, or gitea.livingeach.day/owner/repo-frontend:1.0.6 when target is set).
|
||||||
|
value: ${{ steps.next-version.outputs.image_tag }}
|
||||||
|
|
||||||
|
runs:
|
||||||
|
using: composite
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
lfs: ${{ inputs.lfs }}
|
||||||
|
|
||||||
|
- name: Get next version
|
||||||
|
id: next-version
|
||||||
|
uses: self:captbrick/gitea-actions/get-next-version@master
|
||||||
|
with:
|
||||||
|
main_branch: ${{ inputs.main_branch }}
|
||||||
|
major: ${{ inputs.major }}
|
||||||
|
minor: ${{ inputs.minor }}
|
||||||
|
image_registry: ${{ inputs.image_registry }}
|
||||||
|
image_repository: ${{ inputs.image_repository }}
|
||||||
|
image_name: ${{ inputs.image_name || inputs.target }}
|
||||||
|
|
||||||
|
- name: Prepare cache refs
|
||||||
|
if: inputs.cache == 'true'
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
sanitize_ref() {
|
||||||
|
local value="$1"
|
||||||
|
value="$(printf '%s' "$value" \
|
||||||
|
| tr '[:upper:]' '[:lower:]' \
|
||||||
|
| sed -E 's#[^a-z0-9._-]+#-#g; s#^-+##; s#-+$##')"
|
||||||
|
|
||||||
|
if [[ -z "$value" ]]; then
|
||||||
|
printf 'ERROR: Cache ref value cannot be empty after sanitization.\n' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
printf '%s' "$value"
|
||||||
|
}
|
||||||
|
|
||||||
|
detect_merge_source_ref() {
|
||||||
|
local message source
|
||||||
|
message="$(git log -1 --pretty=%B 2>/dev/null || true)"
|
||||||
|
|
||||||
|
if [[ "$message" =~ ^Merge[[:space:]]pull[[:space:]]request[[:space:]]#[0-9]+[[:space:]]from[[:space:]]([^[:space:]]+) ]]; then
|
||||||
|
source="${BASH_REMATCH[1]}"
|
||||||
|
printf '%s' "${source#*/}"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ "$message" =~ ^Merge[[:space:]]branch[[:space:]]\'([^\']+)\' ]]; then
|
||||||
|
printf '%s' "${BASH_REMATCH[1]}"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
base_ref="${GITHUB_BASE_REF:-$MAIN_BRANCH}"
|
||||||
|
branch_ref="${GITHUB_HEAD_REF:-${GITHUB_REF_NAME:-$MAIN_BRANCH}}"
|
||||||
|
safe_base_ref="$(sanitize_ref "$base_ref")"
|
||||||
|
safe_branch_ref="$(sanitize_ref "$branch_ref")"
|
||||||
|
cache_registry="${CACHE_REGISTRY:-$IMAGE_REGISTRY}"
|
||||||
|
cache_repository="${IMAGE_REPOSITORY}/cache"
|
||||||
|
|
||||||
|
printf 'DOCKER_CACHE_REGISTRY=%s\n' "$cache_registry" >> "$GITEA_ENV"
|
||||||
|
printf 'DOCKER_BASE_CACHE=%s/%s:%s\n' "$cache_registry" "$cache_repository" "$safe_base_ref" >> "$GITEA_ENV"
|
||||||
|
printf 'DOCKER_BRANCH_CACHE=%s/%s:%s\n' "$cache_registry" "$cache_repository" "$safe_branch_ref" >> "$GITEA_ENV"
|
||||||
|
|
||||||
|
if merge_source_ref="$(detect_merge_source_ref)" && [[ -n "$merge_source_ref" && "$merge_source_ref" != "$branch_ref" && "$merge_source_ref" != "$base_ref" ]]; then
|
||||||
|
safe_merge_source_ref="$(sanitize_ref "$merge_source_ref")"
|
||||||
|
printf 'DOCKER_MERGE_SOURCE_CACHE=%s/%s:%s\n' "$cache_registry" "$cache_repository" "$safe_merge_source_ref" >> "$GITEA_ENV"
|
||||||
|
fi
|
||||||
|
env:
|
||||||
|
MAIN_BRANCH: ${{ inputs.main_branch }}
|
||||||
|
CACHE_REGISTRY: ${{ inputs.cache_registry }}
|
||||||
|
|
||||||
|
- name: Docker login
|
||||||
|
if: inputs.push == 'true' || inputs.cache == 'true'
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
if [[ "$PUSH" == 'true' ]]; then
|
||||||
|
docker login --username "$REGISTRY_USERNAME" --password "$REGISTRY_PASSWORD" "$IMAGE_REGISTRY"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ "$CACHE" == 'true' && "${DOCKER_CACHE_REGISTRY:-$IMAGE_REGISTRY}" != "$IMAGE_REGISTRY" ]]; then
|
||||||
|
docker login --username "$REGISTRY_USERNAME" --password "$REGISTRY_PASSWORD" "${DOCKER_CACHE_REGISTRY:-$IMAGE_REGISTRY}"
|
||||||
|
elif [[ "$CACHE" == 'true' && "$PUSH" != 'true' ]]; then
|
||||||
|
docker login --username "$REGISTRY_USERNAME" --password "$REGISTRY_PASSWORD" "$IMAGE_REGISTRY"
|
||||||
|
fi
|
||||||
|
env:
|
||||||
|
PUSH: ${{ inputs.push }}
|
||||||
|
CACHE: ${{ inputs.cache }}
|
||||||
|
REGISTRY_USERNAME: ${{ inputs.registry_username }}
|
||||||
|
REGISTRY_PASSWORD: ${{ inputs.registry_password }}
|
||||||
|
|
||||||
|
- name: Set up QEMU
|
||||||
|
uses: docker/setup-qemu-action@v3
|
||||||
|
|
||||||
|
- name: Build and push image
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -Eeuo pipefail
|
||||||
|
args=(--build-arg "APP_VERSION=$VERSION" -f "$DOCKERFILE" --tag "$IMAGE_TAG" --platform "$PLATFORMS")
|
||||||
|
if [[ -n "$TARGET" ]]; then
|
||||||
|
args+=(--target "$TARGET")
|
||||||
|
fi
|
||||||
|
if [[ "$CACHE" == 'true' ]]; then
|
||||||
|
args+=(--cache-from "type=registry,ref=$DOCKER_BASE_CACHE")
|
||||||
|
if [[ -n "${DOCKER_MERGE_SOURCE_CACHE:-}" ]]; then
|
||||||
|
args+=(--cache-from "type=registry,ref=$DOCKER_MERGE_SOURCE_CACHE")
|
||||||
|
fi
|
||||||
|
args+=(--cache-from "type=registry,ref=$DOCKER_BRANCH_CACHE")
|
||||||
|
args+=(--cache-to "type=registry,ref=$DOCKER_BRANCH_CACHE,mode=max")
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ "$PUSH" == 'true' ]]; then
|
||||||
|
# Push straight from buildx so the result (single image or
|
||||||
|
# multi-arch manifest list) is published to the registry.
|
||||||
|
args+=(--push)
|
||||||
|
fi
|
||||||
|
|
||||||
|
docker buildx build "${args[@]}" "$CONTEXT"
|
||||||
|
env:
|
||||||
|
DOCKERFILE: ${{ inputs.dockerfile }}
|
||||||
|
CONTEXT: ${{ inputs.context }}
|
||||||
|
TARGET: ${{ inputs.target }}
|
||||||
|
CACHE: ${{ inputs.cache }}
|
||||||
|
PUSH: ${{ inputs.push }}
|
||||||
|
PLATFORMS: ${{ inputs.platforms }}
|
||||||
|
|
||||||
|
- name: Create version tag
|
||||||
|
if: inputs.push == 'true'
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -Eeuo pipefail
|
||||||
|
git config user.name "gitea-actions[bot]"
|
||||||
|
git config user.email "actions@gitea.livingeach.day"
|
||||||
|
git tag "$VERSION_TAG"
|
||||||
|
git push origin "$VERSION_TAG"
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
name: Get Next Version
|
||||||
|
description: Computes the next production or dev 1.0.x application version from existing Git tags.
|
||||||
|
|
||||||
|
inputs:
|
||||||
|
main_branch:
|
||||||
|
description: Name of the main branch (e.g., master or main). Main branch gets the next production version; other branches get the next dev pre-release.
|
||||||
|
required: true
|
||||||
|
major:
|
||||||
|
description: Major version number.
|
||||||
|
required: false
|
||||||
|
default: '1'
|
||||||
|
minor:
|
||||||
|
description: Minor version number.
|
||||||
|
required: false
|
||||||
|
default: '0'
|
||||||
|
image_registry:
|
||||||
|
description: Optional image registry used to build IMAGE_TAG. Defaults to gitea.livingeach.day.
|
||||||
|
required: false
|
||||||
|
default: ''
|
||||||
|
image_repository:
|
||||||
|
description: Optional image repository used to build IMAGE_TAG. Defaults to the full current repository path (owner/repo). Always lowercased, since Docker repository names must be lowercase.
|
||||||
|
required: false
|
||||||
|
default: ''
|
||||||
|
image_name:
|
||||||
|
description: Optional image name below image_repository. When set, image tags are built as image_registry/image_repository/image_name:version and Git version tags are prefixed with a sanitized form of image_name to avoid collisions in multi-image builds.
|
||||||
|
required: false
|
||||||
|
default: ''
|
||||||
|
|
||||||
|
outputs:
|
||||||
|
version:
|
||||||
|
description: Next application version (e.g., 1.0.6 or 1.0.6-feature.1).
|
||||||
|
value: ${{ steps.next-version.outputs.version }}
|
||||||
|
version_series:
|
||||||
|
description: Major/minor/patch search prefix used to find tags (e.g., 1.0.).
|
||||||
|
value: ${{ steps.next-version.outputs.version_series }}
|
||||||
|
latest_matching_tag:
|
||||||
|
description: Latest matching existing production or dev version tag, if any.
|
||||||
|
value: ${{ steps.next-version.outputs.latest_matching_tag }}
|
||||||
|
next_patch:
|
||||||
|
description: Next patch version number.
|
||||||
|
value: ${{ steps.next-version.outputs.next_patch }}
|
||||||
|
prerelease_suffix:
|
||||||
|
description: Branch pre-release suffix including counter; empty on the main branch.
|
||||||
|
value: ${{ steps.next-version.outputs.prerelease_suffix }}
|
||||||
|
latest_release_tag:
|
||||||
|
description: Latest existing production version tag, if any.
|
||||||
|
value: ${{ steps.next-version.outputs.latest_release_tag }}
|
||||||
|
prerelease_number:
|
||||||
|
description: Branch pre-release counter; empty on the main branch.
|
||||||
|
value: ${{ steps.next-version.outputs.prerelease_number }}
|
||||||
|
image_tag:
|
||||||
|
description: Full image tag (e.g., gitea.livingeach.day/owner/repo:1.0.6, or gitea.livingeach.day/owner/repo/image:1.0.6 when image_name is set).
|
||||||
|
value: ${{ steps.next-version.outputs.image_tag }}
|
||||||
|
version_tag:
|
||||||
|
description: Version string to use for the Git tag (equals version, or sanitized-image-name-version when image_name is set, to avoid collisions when tagging multiple images from the same commit).
|
||||||
|
value: ${{ steps.next-version.outputs.version_tag }}
|
||||||
|
|
||||||
|
runs:
|
||||||
|
using: composite
|
||||||
|
steps:
|
||||||
|
- name: Get next version
|
||||||
|
id: next-version
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
main_branch='${{ inputs.main_branch }}'
|
||||||
|
major='${{ inputs.major }}'
|
||||||
|
minor='${{ inputs.minor }}'
|
||||||
|
image_registry='${{ inputs.image_registry }}'
|
||||||
|
image_repository='${{ inputs.image_repository }}'
|
||||||
|
image_name='${{ inputs.image_name }}'
|
||||||
|
|
||||||
|
if [[ -z "$main_branch" ]]; then
|
||||||
|
printf 'ERROR: main_branch input must not be empty.\n' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
image_registry="${image_registry:-gitea.livingeach.day}"
|
||||||
|
image_repository="${image_repository:-${GITHUB_REPOSITORY}}"
|
||||||
|
image_repository="$(printf '%s' "$image_repository" | tr '[:upper:]' '[:lower:]')"
|
||||||
|
|
||||||
|
if [[ -n "$image_name" ]]; then
|
||||||
|
image_name="$(printf '%s' "$image_name" \
|
||||||
|
| tr '[:upper:]' '[:lower:]' \
|
||||||
|
| sed -E 's#[^a-z0-9._/-]+#-#g; s#^/+##; s#/+$##')"
|
||||||
|
|
||||||
|
if [[ -z "$image_name" ]]; then
|
||||||
|
printf 'ERROR: image_name cannot be converted to a valid image path segment.\n' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
image_repository="${image_repository}/${image_name}"
|
||||||
|
tag_prefix="$(printf '%s' "$image_name" \
|
||||||
|
| sed -E 's#[^a-z0-9]+#-#g; s#^-+##; s#-+$##')-"
|
||||||
|
else
|
||||||
|
tag_prefix=''
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! [[ "$major" =~ ^[0-9]+$ ]]; then
|
||||||
|
printf 'ERROR: major must be a non-negative integer.\n' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! [[ "$minor" =~ ^[0-9]+$ ]]; then
|
||||||
|
printf 'ERROR: minor must be a non-negative integer.\n' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
version_series="${major}.${minor}."
|
||||||
|
|
||||||
|
git fetch --tags --force
|
||||||
|
|
||||||
|
latest_release_tag="$(git tag --list "${tag_prefix}${version_series}*" | grep -E "^${tag_prefix}${major}\.${minor}\.[0-9]+$" | sort -Vr | head -n 1 || true)"
|
||||||
|
if [[ -n "$latest_release_tag" ]]; then
|
||||||
|
latest_release_version="${latest_release_tag#"$tag_prefix"}"
|
||||||
|
latest_release_patch="${latest_release_version#"$version_series"}"
|
||||||
|
next_patch=$((latest_release_patch + 1))
|
||||||
|
else
|
||||||
|
next_patch=0
|
||||||
|
fi
|
||||||
|
|
||||||
|
next_release_version="${major}.${minor}.${next_patch}"
|
||||||
|
prerelease_number=''
|
||||||
|
latest_matching_tag="$latest_release_tag"
|
||||||
|
|
||||||
|
if [[ "$GITHUB_REF_NAME" == "$main_branch" ]]; then
|
||||||
|
prerelease_suffix=''
|
||||||
|
version="$next_release_version"
|
||||||
|
else
|
||||||
|
prerelease_identifier="$(printf '%s' "$GITHUB_REF_NAME" \
|
||||||
|
| tr '[:upper:]' '[:lower:]' \
|
||||||
|
| sed -E 's/[^a-z0-9]+/-/g; s/^-+//; s/-+$//')"
|
||||||
|
|
||||||
|
if [[ -z "$prerelease_identifier" ]]; then
|
||||||
|
printf 'ERROR: Branch name %s cannot be converted to a valid version suffix.\n' "$GITHUB_REF_NAME" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
latest_prerelease_tag="$(git tag --list "${tag_prefix}${next_release_version}-${prerelease_identifier}.*" | grep -E "^${tag_prefix}${major}\.${minor}\.${next_patch}-${prerelease_identifier}\.[0-9]+$" | sort -Vr | head -n 1 || true)"
|
||||||
|
if [[ -n "$latest_prerelease_tag" ]]; then
|
||||||
|
latest_prerelease_number="${latest_prerelease_tag#"${tag_prefix}${next_release_version}-${prerelease_identifier}."}"
|
||||||
|
prerelease_number=$((latest_prerelease_number + 1))
|
||||||
|
latest_matching_tag="$latest_prerelease_tag"
|
||||||
|
else
|
||||||
|
prerelease_number=1
|
||||||
|
fi
|
||||||
|
|
||||||
|
prerelease_suffix="-${prerelease_identifier}.${prerelease_number}"
|
||||||
|
version="${next_release_version}${prerelease_suffix}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
image_tag="${image_registry}/${image_repository}:${version}"
|
||||||
|
|
||||||
|
if [[ -n "$tag_prefix" ]]; then
|
||||||
|
version_tag="${tag_prefix}${version}"
|
||||||
|
else
|
||||||
|
version_tag="$version"
|
||||||
|
fi
|
||||||
|
|
||||||
|
{
|
||||||
|
printf 'VERSION=%s\n' "$version"
|
||||||
|
printf 'VERSION_TAG=%s\n' "$version_tag"
|
||||||
|
printf 'PRERELEASE_SUFFIX=%s\n' "$prerelease_suffix"
|
||||||
|
printf 'IMAGE_REGISTRY=%s\n' "$image_registry"
|
||||||
|
printf 'IMAGE_REPOSITORY=%s\n' "$image_repository"
|
||||||
|
printf 'IMAGE_TAG=%s\n' "$image_tag"
|
||||||
|
} >> "$GITEA_ENV"
|
||||||
|
|
||||||
|
{
|
||||||
|
printf 'version=%s\n' "$version"
|
||||||
|
printf 'version_tag=%s\n' "$version_tag"
|
||||||
|
printf 'version_series=%s\n' "$version_series"
|
||||||
|
printf 'latest_matching_tag=%s\n' "$latest_matching_tag"
|
||||||
|
printf 'latest_release_tag=%s\n' "$latest_release_tag"
|
||||||
|
printf 'next_patch=%s\n' "$next_patch"
|
||||||
|
printf 'prerelease_suffix=%s\n' "$prerelease_suffix"
|
||||||
|
printf 'prerelease_number=%s\n' "$prerelease_number"
|
||||||
|
printf 'image_tag=%s\n' "$image_tag"
|
||||||
|
} >> "$GITEA_OUTPUT"
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"skills": {
|
||||||
|
"bash-defensive-patterns": {
|
||||||
|
"source": "wshobson/agents",
|
||||||
|
"sourceType": "github",
|
||||||
|
"skillPath": "plugins/shell-scripting/skills/bash-defensive-patterns/SKILL.md",
|
||||||
|
"computedHash": "273cd627fc3b12b9313f6a5fbfd2bb7ac9ee469716d01fb2104477f7b47a9bf9"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user