-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathversion
More file actions
executable file
·443 lines (362 loc) · 12.3 KB
/
version
File metadata and controls
executable file
·443 lines (362 loc) · 12.3 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
#!/usr/bin/env bash
#shellcheck disable=SC2155,SC2034
# Manage semantic versions in files containing VERSION marker blocks
set -euo pipefail
shopt -s inherit_errexit shift_verbose extglob nullglob
# ============================================================================
# Script Metadata
# ============================================================================
### VERSION managed by version
declare -r VERSION=1.2.2
###
declare -r SCRIPT_PATH=$(realpath -- "${BASH_SOURCE[0]}")
declare -r SCRIPT_DIR=${SCRIPT_PATH%/*} SCRIPT_NAME=${SCRIPT_PATH##*/}
# ============================================================================
# Global Variable Declarations
# ============================================================================
# Marker pattern for version blocks
declare -r MARKER_PATTERN='^### VERSION'
declare -r MARKER_DEFAULT="### VERSION managed by $SCRIPT_NAME"
declare -r MARKER_END='###'
# Configuration
declare -- TARGET_DIR='.'
declare -a TARGET_FILES=()
# Runtime flags
declare -i VERBOSE=0
declare -i DRY_RUN=0
declare -i QUIET=0
# Version components (populated during operations)
declare -i MAJOR=0 MINOR=0 PATCH=0 BUILD=0
declare -- HAS_BUILD=''
# ============================================================================
# Color Definitions
# ============================================================================
if [[ -t 1 && -t 2 ]]; then
declare -r RED=$'\033[0;31m' GREEN=$'\033[0;32m' YELLOW=$'\033[0;33m' CYAN=$'\033[0;36m' NC=$'\033[0m'
else
declare -r RED='' GREEN='' YELLOW='' CYAN='' NC=''
fi
# ============================================================================
# Utility Functions
# ============================================================================
_msg() {
local -- prefix="$SCRIPT_NAME:" msg
case ${FUNCNAME[1]} in
vecho) : ;;
info) prefix+=" ${CYAN}◉${NC}" ;;
warn) prefix+=" ${YELLOW}▲${NC}" ;;
success) prefix+=" ${GREEN}✓${NC}" ;;
error) prefix+=" ${RED}✗${NC}" ;;
*) ;;
esac
for msg in "$@"; do printf '%s %s\n' "$prefix" "$msg"; done
}
vecho() { ((VERBOSE)) || return 0; _msg "$@"; }
info() { ((QUIET)) && return 0; >&2 _msg "$@"; }
warn() { ((QUIET)) && return 0; >&2 _msg "$@"; }
success() { ((QUIET)) && return 0; >&2 _msg "$@"; }
error() { >&2 _msg "$@"; }
die() { (($# < 2)) || error "${@:2}"; exit "${1:-1}"; }
noarg() { (($# > 1)) || die 22 "Option ${1@Q} requires an argument"; }
# ============================================================================
# Business Logic Functions
# ============================================================================
show_help() {
cat <<EOT
$SCRIPT_NAME $VERSION - Semantic version manager for marker blocks
Usage: $SCRIPT_NAME [OPTIONS] COMMAND [ARGS]
Commands:
get Show version(s) from discovered files
set VERSION Set version (X.Y.Z or X.Y.Z.B)
bump COMPONENT Increment major|minor|patch|build
Options:
-d, --directory DIR Target directory (default: .)
-f, --file FILE Target file (repeatable)
-n, --dry-run Show changes without writing
-q, --quiet Version number only
-v, --verbose Detailed output
-V, --version Show script version
-h, --help Show this help
Marker Block (add to target files):
### VERSION [optional description]
declare -r VERSION=1.0.0
###
Note: Bare '### VERSION' will be expanded to '### VERSION managed by $SCRIPT_NAME'
Supported Patterns:
VERSION=X.Y.Z | declare -- VERSION=X.Y.Z | declare -r VERSION=X.Y.Z | readonly VERSION=X.Y.Z
Examples:
$SCRIPT_NAME get # Show all versions
$SCRIPT_NAME -q get # Version number only
$SCRIPT_NAME set 2.0.0 # Set to 2.0.0
$SCRIPT_NAME bump patch # 1.0.0 → 1.0.1
$SCRIPT_NAME bump build # 1.0.1 → 1.0.1.1
$SCRIPT_NAME -d src/ bump minor # Bump in directory
$SCRIPT_NAME -n bump major # Dry-run
Exit Codes: 0=success, 1=error, 2=not found, 22=invalid argument
EOT
}
# Validate semver: X.Y.Z or X.Y.Z.B → returns 0/1
validate_semver() {
local -- version=$1
[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(\.[0-9]+)?$ ]]
}
# Parse version → sets MAJOR, MINOR, PATCH, BUILD, HAS_BUILD globals
parse_version() {
local -- version=$1
local -a parts
IFS='.' read -ra parts <<< "$version"
MAJOR=${parts[0]}
MINOR=${parts[1]}
PATCH=${parts[2]}
if ((${#parts[@]} >= 4)); then
BUILD=${parts[3]}
HAS_BUILD=1
else
BUILD=0
HAS_BUILD=''
fi
}
# Find files with VERSION marker → populates TARGET_FILES array
discover_files() {
local -- dir=${1:-.}
local -- file
[[ -d "$dir" ]] || die 2 "Directory not found ${dir@Q}"
TARGET_FILES=()
while IFS= read -r file; do
[[ -f "$file" ]] || continue
TARGET_FILES+=("$file")
done < <(grep -rl "${MARKER_PATTERN}" "$dir" 2>/dev/null || true)
((${#TARGET_FILES[@]} > 0)) || {
warn "No files found with VERSION marker in ${dir@Q}"
return 1
}
vecho "Found ${#TARGET_FILES[@]} file(s) with VERSION marker"
}
# Extract version string from file's marker block → stdout or return 1
extract_version() {
local -- file=$1
local -- version_line version
# Find line between markers containing VERSION=
# Supports: VERSION=, declare -- VERSION=, declare -r VERSION=, readonly VERSION=
version_line=$(sed -n "/${MARKER_PATTERN}/,/${MARKER_END}/p" "$file" 2>/dev/null \
| grep -E '^(declare[[:space:]]+(-r|--)[[:space:]]+|readonly[[:space:]]+)?VERSION=' \
| head -1) || true
[[ -n "$version_line" ]] || return 1
# Extract version value (handle all formats)
version=${version_line#*VERSION=}
version=${version//\"/}
version=${version//\'/}
version=${version%%[[:space:]]*}
echo "$version"
}
# Extract prefix (declare -r, declare --, readonly, or empty) → stdout
extract_prefix() {
local -- file=$1
local -- version_line prefix
version_line=$(sed -n "/${MARKER_PATTERN}/,/${MARKER_END}/p" "$file" 2>/dev/null \
| grep -E '^(declare[[:space:]]+(-r|--)[[:space:]]+|readonly[[:space:]]+)?VERSION=' \
| head -1) || true
[[ -n "$version_line" ]] || return 1
# Extract prefix
if [[ "$version_line" =~ ^(declare[[:space:]]+-r[[:space:]]+) ]]; then
echo 'declare -r '
elif [[ "$version_line" =~ ^(declare[[:space:]]+--[[:space:]]+) ]]; then
echo 'declare -- '
elif [[ "$version_line" =~ ^(readonly[[:space:]]+) ]]; then
echo 'readonly '
else
echo ''
fi
}
# cmd: get — display versions from TARGET_FILES
cmd_get() {
local -- file version
local -i found=0
for file in "${TARGET_FILES[@]}"; do
version=$(extract_version "$file") || {
warn "Could not extract version from ${file@Q}"
continue
}
if ((QUIET)); then
echo "$version"
else
printf '%s: %s\n' "$file" "$version"
fi
found+=1
done
((found > 0)) || die 1 'No versions found in any file'
}
# Update version in file, preserving declaration style
update_file_version() {
local -- file=$1
local -- new_version=$2
local -- current_version prefix
current_version=$(extract_version "$file") || {
error "Cannot read version from ${file@Q}"
return 1
}
prefix=$(extract_prefix "$file") || prefix=''
if ((DRY_RUN)); then
info "[DRY-RUN] Would update ${file@Q}: $current_version -> $new_version"
return 0
fi
# Use sed to update the version line within the marker block
# Preserve the original prefix (declare -- , declare -r , readonly , or none)
sed -i "/${MARKER_PATTERN}/,/${MARKER_END}/ {
s/^\(declare[[:space:]]*-r[[:space:]]*\)VERSION=.*/\1VERSION=$new_version/
s/^\(declare[[:space:]]*--[[:space:]]*\)VERSION=.*/\1VERSION=$new_version/
s/^\(readonly[[:space:]]*\)VERSION=.*/\1VERSION=$new_version/
}" "$file"
# Handle plain VERSION= (no prefix)
if [[ -z "$prefix" ]]; then
sed -i "/${MARKER_PATTERN}/,/${MARKER_END}/ {
s/^VERSION=.*/VERSION=$new_version/
}" "$file"
fi
# Normalize bare marker to include default suffix
sed -i "s/^### VERSION\$/${MARKER_DEFAULT}/" "$file"
# Verify the update
local -- updated_version
updated_version=$(extract_version "$file") || {
error "Failed to verify version update in ${file@Q}"
return 1
}
[[ "$updated_version" == "$new_version" ]] || {
error "Version mismatch after update: expected ${new_version@Q}, got ${updated_version@Q}"
return 1
}
success "Updated ${file@Q}: $current_version -> $new_version"
}
# cmd: set VERSION — apply version to all TARGET_FILES
cmd_set() {
local -- version=$1
local -- file
local -i updated=0 failed=0
validate_semver "$version" || die 22 "Invalid version format ${version@Q} (expected X.Y.Z or X.Y.Z.B)"
for file in "${TARGET_FILES[@]}"; do
if update_file_version "$file" "$version"; then
updated+=1
else
failed+=1
fi
done
((QUIET)) || info "Updated $updated file(s), $failed failure(s)"
((failed == 0)) || return 1
}
# Compute bumped version → stdout (resets lower components per semver)
bump_component() {
local -- version=$1
local -- component=$2
parse_version "$version"
case $component in
major)
MAJOR+=1
MINOR=0
PATCH=0
BUILD=0
;;
minor)
MINOR+=1
PATCH=0
BUILD=0
;;
patch)
PATCH+=1
BUILD=0
;;
build)
BUILD+=1
HAS_BUILD=1
;;
*)
error "Unknown component ${component@Q}"
return 1
;;
esac
# Output new version (include build only if original had it or bumping build)
if [[ -n "$HAS_BUILD" ]]; then
echo "$MAJOR.$MINOR.$PATCH.$BUILD"
else
echo "$MAJOR.$MINOR.$PATCH"
fi
}
# cmd: bump COMPONENT — increment version in all TARGET_FILES
cmd_bump() {
local -- component=$1
local -- file version new_version
local -i updated=0 failed=0
for file in "${TARGET_FILES[@]}"; do
version=$(extract_version "$file") || {
warn "Skipping ${file@Q}: cannot extract version"
failed+=1
continue
}
new_version=$(bump_component "$version" "$component") || {
error "Failed to bump $component for ${file@Q}"
failed+=1
continue
}
if update_file_version "$file" "$new_version"; then
updated+=1
else
failed+=1
fi
done
((QUIET)) || info "Bumped $component in $updated file(s), $failed failure(s)"
((failed == 0)) || return 1
}
# ============================================================================
# main() Function
# ============================================================================
main() {
local -- cmd=''
local -- arg=''
# Parse command-line arguments
while (($#)); do case $1 in
-d|--directory) noarg "$@"; shift
TARGET_DIR=$1 ;;
-f|--file) noarg "$@"; shift
TARGET_FILES+=("$1") ;;
-n|--dry-run) DRY_RUN=1 ;;
-q|--quiet) QUIET=1; VERBOSE=0 ;;
-v|--verbose) VERBOSE+=1 ;;
-V|--version) echo "$SCRIPT_NAME $VERSION"; exit 0 ;;
-h|--help) show_help; exit 0 ;;
-[dfnqvVh]*) #shellcheck disable=SC2046
set -- '' $(printf -- '-%c ' $(grep -o . <<<"${1:1}")) "${@:2}" ;;
-*) die 22 "Invalid option ${1@Q}" ;;
get|set|bump) [[ -z "$cmd" ]] || die 22 'Multiple commands specified'
cmd=$1 ;;
major|minor|patch|build)
[[ "$cmd" == "bump" ]] || die 22 "Component ${1@Q} requires bump command"
arg=$1 ;;
*) if [[ "$cmd" == "set" && -z "$arg" ]]; then
arg=$1
else
die 22 "Unexpected argument ${1@Q}"
fi ;;
esac; shift; done
# Make flags readonly after parsing
readonly -- VERBOSE DRY_RUN QUIET
readonly -- TARGET_DIR
# Default to 'get' if no command specified
[[ -n "$cmd" ]] || cmd='get'
# Discover files if not explicitly specified
if ((${#TARGET_FILES[@]} == 0)); then
discover_files "$TARGET_DIR" || exit 1
fi
readonly -a TARGET_FILES
# Execute command
case $cmd in
get) cmd_get ;;
set) [[ -n "$arg" ]] || die 22 'set requires VERSION argument'
cmd_set "$arg" ;;
bump) [[ -n "$arg" ]] || die 22 'bump requires COMPONENT (major|minor|patch|build)'
cmd_bump "$arg" ;;
esac
}
# ============================================================================
# Script Invocation
# ============================================================================
main "$@"
#fin