forked from OkusiAssociates/bash-coding-standard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbcs
More file actions
executable file
·1657 lines (1457 loc) · 62.7 KB
/
bcs
File metadata and controls
executable file
·1657 lines (1457 loc) · 62.7 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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
#shellcheck disable=SC2015
# bcs - Bash Coding Standard CLI toolkit
# Six subcommands for viewing, generating, and checking compliance with the Bash Coding Standard.
set -euo pipefail
shopt -s inherit_errexit extglob nullglob
declare -rx PATH="$HOME"/.local/bin:/usr/local/bin:/usr/bin:/bin
# Script metadata
declare -r VERSION=2.0.1
#shellcheck disable=SC2155
declare -r SCRIPT_PATH=$(realpath -- "$0")
declare -r SCRIPT_DIR=${SCRIPT_PATH%/*} SCRIPT_NAME=${SCRIPT_PATH##*/}
# Global variables
declare -ar BCS_SEARCH_PATHS=(
"$SCRIPT_DIR"/data
"${SCRIPT_DIR%/bin}/share/yatti/BCS/data"
"${PREFIX:-/usr/local}"/share/yatti/BCS/data
/usr/share/yatti/BCS/data
)
declare -ar VALID_EFFORTS=(low medium high max)
declare -ar VALID_TEMPLATES=(minimal basic complete library)
declare -ar VALID_TIERS=(core recommended style disabled)
declare -ar VALID_TIER_FILTERS=(core recommended style)
# Rule tier map: BCS#### -> default tier (loaded from section bodies)
declare -A BCS_TIERS=()
# Policy overrides: BCS#### -> override tier (loaded from policy.conf cascade)
declare -A BCS_POLICY=()
declare -i _TIERS_LOADED=0 _POLICY_LOADED=0
# Model-tier to concrete API model mapping per backend
declare -A ANTHROPIC_MODELS=([fast]=claude-haiku-4-5 [balanced]=claude-sonnet-4-6 [thorough]=claude-opus-4-6)
declare -A OLLAMA_MODELS=([fast]=qwen3.5:9b [balanced]=qwen3.5:14b [thorough]=qwen3.5:14b)
declare -A GOOGLE_MODELS=([fast]=gemini-2.5-flash-lite [balanced]=gemini-2.5-flash [thorough]=gemini-2.5-pro)
declare -A OPENAI_MODELS=([fast]=gpt-4.1-mini [balanced]=gpt-5.4-mini [thorough]=gpt-5.4)
# Effort-level to max output tokens mapping for API backends
declare -A EFFORT_TOKENS=([low]=4000 [medium]=8000 [high]=32000 [max]=64000)
# ---- Messaging System ----
declare -i VERBOSE=1 DEBUG=0
if [[ -t 1 && -t 2 ]]; then
declare -r RED=$'\033[0;31m' GREEN=$'\033[0;32m' YELLOW=$'\033[0;33m' \
CYAN=$'\033[0;36m' BOLD=$'\033[1m' NC=$'\033[0m'
else
declare -r RED='' GREEN='' YELLOW='' CYAN='' BOLD='' NC=''
fi
_msg() { >&2 printf "$SCRIPT_NAME: $1 %s\n" "${@:2}"; }
error() { _msg "$RED✗$NC" "$@"; }
die() { (($# < 2)) || error "${@:2}"; exit "${1:-0}"; }
warn() { _msg "$YELLOW▲$NC" "$@"; }
vecho() { ((VERBOSE)) || return 0; _msg '' "$@"; }
info() { ((VERBOSE)) || return 0; _msg "$CYAN◉$NC" "$@"; }
success() { ((VERBOSE)) || return 0; _msg "$GREEN✓$NC" "$@"; }
debug() { ((DEBUG)) || return 0; _msg "${RED}DEBUG$NC" "$@"; }
noarg() { (($# > 1)) || die 22 "Option ${1@Q} requires an argument"; }
# ---- Configuration and Globals ----
# Load all conf files (cascade: system first, user overrides system)
# Emit bcs.conf cascade paths (system first, user last).
# Extracted as a helper so tests can override it.
_conf_search_paths() {
printf '%s\n' \
/etc/"$SCRIPT_NAME".conf \
/etc/"$SCRIPT_NAME"/"$SCRIPT_NAME".conf \
/usr/local/etc/"$SCRIPT_NAME"/"$SCRIPT_NAME".conf \
"${XDG_CONFIG_HOME:-$HOME/.config}"/"$SCRIPT_NAME"/"$SCRIPT_NAME".conf
}
read_conf() {
local -- conf_file mode
local -i loaded=0
local -a search_paths=()
readarray -t search_paths < <(_conf_search_paths)
for conf_file in "${search_paths[@]}"; do
[[ -f $conf_file ]] || continue
# The file is sourced as shell, so loose permissions are an RCE surface.
# Policy:
# - world-writable -> die 13 (no legitimate setup; always compromise risk)
# - group-writable -> warn (contextual; may be legitimate in admin groups)
# - owner-only -> silent
# Octal digit without write bit: 0, 1, 4, 5. With write bit: 2, 3, 6, 7.
# The ?([0-7]) prefix handles modes with setuid/setgid/sticky bits (e.g. 4755).
mode=$(stat -c '%a' "$conf_file" 2>/dev/null) ||:
case $mode in
''|?([0-7])[0-7][0145][0145])
: ;; # stat failed, or safe perms
?([0-7])[0-7][0-7][2367])
die 13 "$conf_file: world-writable (mode $mode) -- refusing to source as shell; run: chmod o-w ${conf_file@Q}" ;;
*)
warn "$conf_file: group-writable mode $mode -- file is sourced as shell; chmod g-w recommended" ;;
esac
#shellcheck source=/dev/null
source "$conf_file"
loaded+=1
done
((loaded))
}
# Help functions
show_main_help() {
cat <<HELP
${BOLD}bcs$NC $VERSION - Bash Coding Standard CLI toolkit
${BOLD}Usage:$NC $SCRIPT_NAME [COMMAND] [OPTIONS]
${BOLD}Commands:$NC
display View the standard document (default)
template Generate a BCS-compliant script template
check AI-powered compliance checking
codes List all BCS rule codes
generate Regenerate standard from section files
help Show help for a command
${BOLD}Global Options:$NC
-v, --verbose Verbose output (default)
-q, --quiet No verbose output
-V, --version Show version $VERSION
-h, --help Show this help
${BOLD}Examples:$NC
$SCRIPT_NAME View the standard
$SCRIPT_NAME template -t complete Generate a complete template
$SCRIPT_NAME check myscript.sh Check script compliance
$SCRIPT_NAME codes List all BCS rule codes
$SCRIPT_NAME help template Help for template command
${BOLD}Customisation:$NC
policy.conf Override any rule's tier (system/user/repo cascade)
BCS9800-BCS9899 Reserved namespace for site-local user rules
(data/98-user.md, data/98-user.d/*.md)
See ${BOLD}$SCRIPT_NAME help codes$NC for policy syntax and user-rule format.
HELP
}
show_display_help() {
cat <<HELP
${BOLD}bcs display$NC - View the Bash Coding Standard
${BOLD}Usage:$NC $SCRIPT_NAME [display] [OPTIONS]
${BOLD}Options:$NC
-c, --cat Plain text output (no formatting)
-f, --file Show full path to the standard document
-S, --symlink Symlink BASH-CODING-STANDARD.md into current directory
-v, --verbose Show info messages (${BOLD}default$NC)
-q, --quiet Suppress info messages
-h, --help Show this help
When stdout is a terminal and md2ansi is available, the standard is
displayed with ANSI formatting piped through less. Otherwise, plain
text output is used.
HELP
}
show_template_help() {
cat <<HELP
${BOLD}bcs template$NC - Generate BCS-compliant script templates
${BOLD}Usage:$NC $SCRIPT_NAME template [OPTIONS]
${BOLD}Options:$NC
-t, --type TYPE Template type (minimal, ${BOLD}basic$NC, complete, library)
(default: basic)
-n, --name NAME Script name for placeholders
-d, --desc TEXT Script description
-V, --version VER Version string (default: ${BOLD}1.0.0$NC)
-o, --output FILE Output file (default: ${BOLD}stdout$NC)
-x, --executable Make output file executable
-f, --force Overwrite existing files
-v, --verbose Show info messages (${BOLD}default$NC)
-q, --quiet Suppress info messages
-h, --help Show this help
${BOLD}Template Types:$NC
minimal Bare essentials (~16 lines)
basic Standard with metadata (~26 lines)
complete Full toolkit with all utilities (~119 lines)
library Sourceable library pattern (~40 lines)
${BOLD}Examples:$NC
$SCRIPT_NAME template -t minimal
$SCRIPT_NAME template -t complete -n deploy -d 'Deploy script' -o deploy.sh -x
$SCRIPT_NAME template -t library -n auth -o lib-auth.sh
HELP
}
show_check_help() {
cat <<HELP
${BOLD}bcs check$NC - AI-powered BCS compliance checking
${BOLD}Usage:$NC $SCRIPT_NAME check [OPTIONS] SCRIPT
${BOLD}Options:$NC
-m, --model MODEL Quality tier or model name (${BOLD}balanced$NC, fast, thorough, or direct)
-e, --effort LEVEL Analysis depth (${BOLD}medium$NC, low, high, max)
-s, --strict Treat warnings as violations
-S, --no-strict Don't treat warnings as violations (${BOLD}default$NC)
--shellcheck Prepend shellcheck --format=json -x output to LLM context (${BOLD}default$NC)
--no-shellcheck Skip shellcheck static-analysis context
-T, --tier TIER Report only findings at this tier (core|recommended|style)
-M, --min-tier TIER Report findings at this tier or higher severity
-j, --json Emit findings as a single JSON object on stdout
(shellcheck --format=json1-compatible envelope)
-D, --debug Announce raw-response dump path on success;
dump is always written and auto-announced on failure
-v, --verbose Show info messages (${BOLD}default$NC)
-q, --quiet Suppress info messages
-h, --help Show this help
${BOLD}Raw Response Dump:$NC
Every API response is saved to \${XDG_STATE_HOME:-~/.local/state}/bcs/last-response.txt
(or /tmp/bcs-last-response.XXXXXX via mktemp if no state dir). On failure or
--debug, the path is printed to stderr so you can inspect the raw JSON
without re-running the check. The Claude Code CLI backend does not dump --
it returns text directly, not JSON.
${BOLD}Model selection:$NC
The -m value determines which backend handles the check:
fast|balanced|thorough Probe available backends (claude, ollama,
anthropic, openai, google) and use the first
reachable one with that tier's default model.
claude-* Anthropic API (e.g. claude-opus-4-6)
gemini-* Google Gemini API (e.g. gemini-2.5-pro)
gpt-* | o[0-9]* OpenAI API (e.g. gpt-5.4, o3-mini)
claude-code Claude Code CLI at the balanced tier
claude-code:<tier-or-model> Claude Code CLI with specific tier/model
(anything else) Local Ollama (e.g. minimax-m2:cloud)
Note: Ollama models named 'claude-*', 'gemini-*', 'gpt-*' or 'o[0-9]*' are
unreachable through -m — rename the local model if you need to target it.
${BOLD}Effort Levels:$NC
low Clear violations only (fast, concise)
medium Violations and significant warnings
high All violations and warnings (thorough)
max Exhaustive line-by-line audit
${BOLD}Tiers & Severity:$NC
Rules carry a ${BOLD}**Tier:**$NC field. The check command maps tier to severity:
core -> [ERROR] (non-zero exit when any [ERROR] found)
recommended -> [WARN]
style -> [WARN]
disabled -> not reported
Use ${BOLD}-T core$NC for CI gates (fail only on core violations) or
${BOLD}-M recommended$NC to skip style findings during development.
${BOLD}Policy Overrides:$NC
Place ${BOLD}policy.conf$NC at any of these cascading locations (later wins):
/etc/bcs/policy.conf (system)
\${XDG_CONFIG_HOME:-~/.config}/bcs/policy.conf (user)
.bcs/policy.conf (project / repo-local)
Syntax: ${BOLD}BCS#### = core|recommended|style|disabled$NC
See ${BOLD}bcs.policy.sample$NC in the BCS source tree for examples.
${BOLD}User Rules:$NC
Custom rules may be added in BCS9800-BCS9899 space via:
\$BCS_DATA/98-user.md (single file)
\$BCS_DATA/98-user.d/*.md (drop-in directory)
Either may be symlinks to user-owned files. User rules are included in the
generated BASH-CODING-STANDARD.md and respected by bcs check / bcs codes.
${BOLD}Configuration:$NC
Config files are sourced as bash in cascade order (later overrides earlier):
/etc/bcs.conf (system — flat file)
/etc/bcs/bcs.conf (system — directory)
/usr/local/etc/bcs/bcs.conf (local install)
~/.config/bcs/bcs.conf (user — XDG standard)
Any file may set a subset of values; unset keys inherit from earlier layers.
CLI flags override config file settings; config overrides env vars.
${BOLD}Environment / Config Variables:$NC
BCS_MODEL Default quality tier or model name (overridden by -m)
BCS_EFFORT Default analysis depth (overridden by -e)
BCS_STRICT Treat warnings as violations: 0 or 1
BCS_TIER Default --tier filter (core|recommended|style)
BCS_MIN_TIER Default --min-tier filter (core|recommended|style)
BCS_DEBUG Default --debug (0 or 1); announces raw-response dump path
BCS_JSON Default --json (0 or 1); structured JSON output on stdout
BCS_SHELLCHECK Prepend shellcheck --format=json -x as static-analysis context (0 or 1; default 1)
BCS_OLLAMA_MODEL Override Ollama model (supports :cloud tags, e.g. minimax-m2:cloud)
BCS_ANTHROPIC_MODEL Override Anthropic model selection
BCS_GOOGLE_MODEL Override Google model selection
BCS_OPENAI_MODEL Override OpenAI model selection
OLLAMA_HOST Ollama server address (default: localhost:11434)
ANTHROPIC_API_KEY Anthropic API key (for anthropic backend)
GOOGLE_API_KEY Google API key (for google backend)
GEMINI_API_KEY Alternative Google key (GOOGLE_API_KEY takes priority)
OPENAI_API_KEY OpenAI API key (for openai backend)
${BOLD}Inline suppression:$NC
#bcscheck disable=BCS0606 # Suppress a rule for the next line or block
${BOLD}JSON Output:$NC
With ${BOLD}-j/--json$NC, stdout contains a single JSON object shaped like:
{ "source": "bcs", "meta": { ... }, "comments": [ ... ] }
The schema mirrors ${BOLD}shellcheck --format=json1$NC so existing tooling can
consume findings with minimal adjustment. Info messages still go to stderr
when verbose. Exit code 5 is returned if the LLM produced invalid JSON
(the raw response is preserved in \$BCS_RESPONSE_DUMP for inspection).
${BOLD}Examples:$NC
$SCRIPT_NAME check myscript.sh
$SCRIPT_NAME check -m minimax-m2:cloud myscript.sh
$SCRIPT_NAME check --effort high --strict deploy.sh
$SCRIPT_NAME check -m claude-code:thorough -e max deploy.sh
$SCRIPT_NAME check -j myscript.sh | jq '.comments[]'
HELP
}
show_codes_help() {
cat <<HELP
${BOLD}bcs codes$NC - List all BCS rule codes
${BOLD}Usage:$NC $SCRIPT_NAME codes [OPTIONS]
${BOLD}Options:$NC
-T, --tier TIER Show only rules at this tier (core|recommended|style|disabled)
-E, --explain BCS#### Print the full body of a single rule and exit
-p, --plain Omit tier decoration (just "BCS#### Title")
-x, --exclude-disabled Skip rules that have been disabled via policy.conf
-h, --help Show this help
Lists all BCS rule codes and titles extracted from section files and any
user rules (98-user.md, 98-user.d/*.md). Each code is decorated with its
effective tier (default from the rule body, overridden by policy.conf).
Use ${BOLD}--explain$NC to drill into a specific rule after a failed ${BOLD}bcs check$NC run --
prints the full rule body (heading, tier, rationale, examples).
${BOLD}Example Output:$NC
BCS0101 [core] Strict Mode
BCS0102 [recommended] Shebang
BCS0107 [style] Function Organization
[...]
${BOLD}Explain a rule:$NC
$SCRIPT_NAME codes -E BCS0606 # Print BCS0606 rule body
$SCRIPT_NAME codes --explain BCS0101 # Same; long form
HELP
}
show_generate_help() {
cat <<HELP
${BOLD}bcs generate$NC - Regenerate BASH-CODING-STANDARD.md from section files
${BOLD}Usage:$NC $SCRIPT_NAME generate [OPTIONS]
${BOLD}Options:$NC
-o, --output FILE Output file (default: ${BOLD}data/BASH-CODING-STANDARD.md$NC)
-v, --verbose Show info messages (${BOLD}default$NC)
-q, --quiet Suppress info messages
-h, --help Show this help
Concatenates all data/[0-9]*.md section files into a single
BASH-CODING-STANDARD.md document.
User rules in data/98-user.md and data/98-user.d/*.md are spliced into
the output after section 12, before the coda. These files may be symlinks
to user-owned rule files outside the BCS tree.
HELP
}
# ---- Helpers: paths, tiers, policy ----
# Find BASH-CODING-STANDARD.md using FHS-compliant search
_find_bcs_md() {
local -- path
for path in "${BCS_SEARCH_PATHS[@]}"; do
if [[ -f $path/BASH-CODING-STANDARD.md ]]; then
echo "$path"/BASH-CODING-STANDARD.md
return 0
fi
done
return 1
}
# Find data directory containing section files
_find_data_dir() {
local -- path
for path in "${BCS_SEARCH_PATHS[@]}"; do
if [[ -d $path ]]; then
echo "$path"
return 0
fi
done
return 1
}
# Find md2ansi for formatted output
_find_md2ansi() {
local -a search_paths=(
"$SCRIPT_DIR"/examples/md2ansi
"$SCRIPT_DIR"/lib/md2ansi
)
local -- path
for path in "${search_paths[@]}"; do
[[ -x $path ]] && { echo "$path"; return 0; } ||:
done
command -v md2ansi 2>/dev/null # Falls through to PATH search; non-zero = not found
}
# Tier & policy loading
# Scan section files and populate BCS_TIERS from **Tier:** lines.
# Tier markers live in rule bodies, one line each. Section overview
# headings (BCS##00, e.g. BCS0100) carry no **Tier:** field and are
# silently skipped, leaving BCS_TIERS keyed only by enforceable rules.
_load_tiers() {
((_TIERS_LOADED)) && return 0
local -- data_dir
data_dir=$(_find_data_dir) || return 1
local -- current_code='' line
local -a files=("$data_dir"/[0-9]*.md)
[[ -d $data_dir/98-user.d ]] && files+=("$data_dir"/98-user.d/*.md) ||:
while IFS= read -r line; do
if [[ $line =~ ^##[[:space:]]+(BCS[0-9]+)[[:space:]] ]]; then
current_code=${BASH_REMATCH[1]}
elif [[ -n $current_code && $line =~ ^\*\*Tier:\*\*[[:space:]]+([a-z]+) ]]; then
BCS_TIERS[$current_code]=${BASH_REMATCH[1]}
current_code=''
fi
done < <(cat "${files[@]}" 2>/dev/null ||:)
_TIERS_LOADED=1
}
# Emit policy.conf cascade paths (system first, project-local last).
# Extracted as a helper so tests can override it.
_policy_search_paths() {
printf '%s\n' \
/etc/bcs/policy.conf \
"${XDG_CONFIG_HOME:-$HOME/.config}"/bcs/policy.conf \
.bcs/policy.conf
}
# Load policy.conf cascade (system -> user -> project; later wins).
# Policy files are parsed line-by-line -- NEVER sourced as shell.
_load_policy() {
((_POLICY_LOADED)) && return 0
local -a search_paths=()
readarray -t search_paths < <(_policy_search_paths)
local -- path line code tier
local -i lineno
for path in "${search_paths[@]}"; do
[[ -f $path && -r $path ]] || continue
lineno=0
while IFS= read -r line; do
lineno+=1
line=${line%%\#*} # strip comments
line=${line#"${line%%[![:space:]]*}"} # ltrim
line=${line%"${line##*[![:space:]]}"} # rtrim
[[ -n $line ]] || continue
if [[ $line =~ ^(BCS[0-9]+)[[:space:]]*=[[:space:]]*([a-z]+)$ ]]; then
code=${BASH_REMATCH[1]}
tier=${BASH_REMATCH[2]}
if [[ " ${VALID_TIERS[*]} " == *" $tier "* ]]; then
BCS_POLICY[$code]=$tier
else
warn "$path:$lineno: invalid tier ${tier@Q} (valid: ${VALID_TIERS[*]})"
fi
else
warn "$path:$lineno: malformed policy line ${line@Q}"
fi
done < "$path"
done
_POLICY_LOADED=1
}
# Effective tier for a BCS code (policy override wins over default).
# Returns empty string for codes with no tier (section overviews).
_effective_tier() {
local -- code=$1
_load_tiers
_load_policy
if [[ -n ${BCS_POLICY[$code]:-} ]]; then
echo "${BCS_POLICY[$code]}"
else
echo "${BCS_TIERS[$code]:-}"
fi
}
# Emit a markdown policy-override block for inclusion in LLM prompts.
# Produces no output when no overrides are defined.
_policy_summary() {
_load_policy
((${#BCS_POLICY[@]})) || return 0
local -- code
printf '\n=== POLICY OVERRIDES ===\n'
printf 'Apply these overrides to the rule tiers defined in the standard:\n'
while IFS= read -r code; do
printf -- '- %s: tier = %s\n' "$code" "${BCS_POLICY[$code]}"
done < <(printf '%s\n' "${!BCS_POLICY[@]}" | sort)
printf '\nWhen determining severity, use the OVERRIDE tier, not the default.\n'
printf 'Rules with override tier = "disabled" must NOT be reported.\n'
}
# ---- LLM backends ----
# Dump the raw HTTP response body to $BCS_RESPONSE_DUMP if set.
# cmd_check sets this to a file path so that empty/malformed results
# can be diagnosed without re-running the check.
_dump_response() {
[[ -n ${BCS_RESPONSE_DUMP:-} ]] || return 0
printf '%s\n' "$1" > "$BCS_RESPONSE_DUMP" 2>/dev/null ||:
}
# ---- JSON output helpers ----
# Strip optional markdown code fences from an LLM response. Used by JSON
# mode for backends without native JSON-mode parameters (Anthropic Messages
# API, Claude Code CLI). Removes ``` or ```json at start and ``` at end,
# plus surrounding whitespace.
_strip_json_fences() {
local -- s=$1
s=${s#"${s%%[![:space:]]*}"}
s=${s%"${s##*[![:space:]]}"}
[[ $s != '```'* ]] || { s=${s#'```'}; s=${s#json}; s=${s#$'\n'}; }
[[ $s != *'```' ]] || { s=${s%'```'}; s=${s%$'\n'}; }
s=${s#"${s%%[![:space:]]*}"}
s=${s%"${s##*[![:space:]]}"}
printf '%s' "$s"
}
# Validate a bare JSON array of findings and wrap it in the top-level
# envelope with meta fields. Emits the final JSON object on stdout.
# Returns non-zero and emits nothing on validation failure.
#
# Arguments:
# $1 raw LLM response (may include fences)
# $2 absolute script path
# $3 backend name
# $4 model name (resolved)
# $5 effort level
# $6 strict (0|1)
# $7 elapsed seconds
_render_json_output() {
local -- raw=$1 script_file=$2 backend=$3 model=$4 effort=$5
local -- strict=$6 elapsed_s=$7
local -- cleaned arr
cleaned=$(_strip_json_fences "$raw")
[[ -n $cleaned ]] || return 1
# Normalize to a bare array. OpenAI's json_object mode requires the
# top level be an object, so models often wrap the array as
# {"findings": [...]} or similar. Accept either form.
if jq -e 'type == "array"' <<< "$cleaned" &>/dev/null; then
arr=$cleaned
elif jq -e 'type == "object"' <<< "$cleaned" &>/dev/null; then
arr=$(jq -c '(.findings // .comments // .violations // .results // empty)
| select(type == "array")' <<< "$cleaned" 2>/dev/null) ||:
[[ -n $arr ]] || return 1
else
return 1
fi
# Validate every element has the required finding keys.
jq -e 'all(.[]; type == "object"
and has("line") and has("level") and has("bcsCode"))' \
<<< "$arr" &>/dev/null || return 1
local -- strict_bool
((strict)) && strict_bool=true || strict_bool=false
jq -n \
--arg tool 'bcs' \
--arg version "$VERSION" \
--arg file "$script_file" \
--arg backend "$backend" \
--arg model "$model" \
--arg effort "$effort" \
--argjson strict "$strict_bool" \
--argjson elapsed_s "$elapsed_s" \
--argjson comments "$arr" \
'{source: "bcs",
meta: {tool: $tool, version: $version, file: $file, backend: $backend,
model: $model, effort: $effort, strict: $strict, elapsed_s: $elapsed_s},
comments: ($comments | map(. + {file: $file,
column: (.column // 1),
endLine: (.endLine // .line),
endColumn: (.endColumn // 1),
fix: null,
fixSuggestion: (.fixSuggestion // "")}))}' \
|| return 1
}
# Auto-detect available LLM backend (claude → ollama → anthropic → openai → google)
# The Claude Code CLI wins first when available: it runs locally like ollama
# but without needing a model server, and avoids spending API credits on
# unconfigured default invocations.
_detect_backend() {
command -v claude &>/dev/null && { echo claude; return 0; } ||:
local -- host=${OLLAMA_HOST:-localhost:11434}
curl -sf --connect-timeout 2 http://"$host"/api/tags &>/dev/null && { echo ollama; return 0; } ||:
[[ -n ${ANTHROPIC_API_KEY:-} ]] && { echo anthropic; return 0; } ||:
[[ -n ${OPENAI_API_KEY:-} ]] && { echo openai; return 0; } ||:
[[ -n ${GOOGLE_API_KEY:-${GEMINI_API_KEY:-}} ]] && { echo google; return 0; } ||:
return 1
}
# Sniff backend from a direct model name. Used by cmd_check() whenever the
# user passes a concrete model ID rather than a tier keyword.
# Matches vendor prefixes; anything unrecognised falls back to ollama.
#
# ▲ LOAD-BEARING CASE ORDER ▲
# The `claude-code*` case MUST precede `claude-*`. If reordered, the
# claude-code sentinel routes to the Anthropic Messages API instead of
# the Claude Code CLI -- silently, with no error -- because `claude-*`
# also matches `claude-code`. Do not reorder these cases.
_sniff_backend() {
case $1 in
claude|claude:*|claude-code|claude-code:*)
echo claude ;;
claude-*) echo anthropic ;;
gemini-*) echo google ;;
gpt-*|o[0-9]*) echo openai ;;
*) echo ollama ;;
esac
}
# Run shellcheck over the script-under-check and return its JSON report.
# Never aborts the caller: missing binary or parse failure emits empty output
# so cmd_check() can proceed without static-analysis context.
_run_shellcheck() {
local -- file=$1 json=''
local -i rc=0
command -v shellcheck &>/dev/null || {
info 'shellcheck not in PATH; skipping static-analysis context'
return 0
}
# exit 0 = clean, 1 = findings present (both fine); >=2 = parse failure.
# Capture rc via fallback so set -e does not trip on the expected exit 1.
json=$(shellcheck --format=json -x -- "$file" 2>/dev/null) || rc=$?
((rc <= 1)) || { warn "shellcheck failed (exit $rc); continuing without context"; return 0; }
printf '%s\n' "$json"
}
# Wrap a shellcheck JSON report in a markdown block suitable for prepending
# to the LLM user prompt. Returns empty string when the report is empty or
# `[]` so clean scripts never contribute an empty section to the prompt.
_render_shellcheck_block() {
local -- json=$1
[[ -z $json || $json == '[]' ]] && return 0
cat <<MD
## Static analysis context (shellcheck --format=json -x)
The following findings come from a deterministic static analyser. Use
them as supporting context for your BCS review; do not re-emit them as
BCS findings unless they map to a specific BCS rule.
\`\`\`json
$json
\`\`\`
MD
}
# LLM backend: Anthropic Messages API
_llm_anthropic() {
local -- model=$1 effort=$2 sys=$3 usr=$4
[[ -n ${ANTHROPIC_API_KEY:-} ]] || die 18 'ANTHROPIC_API_KEY not set'
local -- api_model=${BCS_ANTHROPIC_MODEL:-${ANTHROPIC_MODELS[$model]:-$model}}
local -i max_tokens=${EFFORT_TOKENS[$effort]}
# Anthropic Messages API has no native JSON-mode flag; rely on prompt
# discipline plus _strip_json_fences fallback applied by cmd_check.
local -- payload
payload=$(jq -n \
--arg model "$api_model" \
--argjson max_tokens "$max_tokens" \
--arg system "$sys" \
--arg user "$usr" \
'{model: $model, max_tokens: $max_tokens, system: $system,
messages: [{role: "user", content: $user}]}') || die 1 'Failed to build JSON payload'
local -- raw body
local -i http_code
raw=$(curl -s --max-time 300 -w $'\n%{http_code}' \
-H 'Content-Type: application/json' \
-H 'x-api-key: '"$ANTHROPIC_API_KEY" \
-H 'anthropic-version: 2023-06-01' \
-d @- \
'https://api.anthropic.com/v1/messages' <<< "$payload") || die 5 'Anthropic API connection failed'
http_code=${raw##*$'\n'}
body=${raw%$'\n'"$http_code"}
_dump_response "$body"
if ! ((http_code >= 200 && http_code < 300)); then
local -- errmsg
errmsg=$(jq -r '.error.message // empty' <<< "$body" 2>/dev/null) ||:
die 5 "Anthropic API error (HTTP $http_code)" ${errmsg:+"$errmsg"}
fi
jq -r '.content[0].text // empty' <<< "$body"
echo "___TOKENS___ $(jq -r '"in=\(.usage.input_tokens // 0) out=\(.usage.output_tokens // 0)"' <<< "$body")"
}
# LLM backend: Ollama chat API
_llm_ollama() {
local -- model=$1 effort=$2 sys=$3 usr=$4
local -- ollama_model=${BCS_OLLAMA_MODEL:-${OLLAMA_MODELS[$model]:-$model}}
local -- ollama_host=${OLLAMA_HOST:-localhost:11434}
local -i num_predict=${EFFORT_TOKENS[$effort]}
# Native JSON mode via "format": "json" (supported by qwen2.5+, llama3.1+,
# gemma2+). When BCS_JSON_MODE=1, forces the model to emit only valid JSON.
local -- payload
if ((${BCS_JSON_MODE:-0})); then
payload=$(jq -n \
--arg model "$ollama_model" \
--argjson num_predict "$num_predict" \
--arg system "$sys" \
--arg user "$usr" \
'{model: $model, stream: false, format: "json",
options: {num_predict: $num_predict},
messages: [{role: "system", content: $system}, {role: "user", content: $user}]}') \
|| die 1 'Failed to build JSON payload'
else
payload=$(jq -n \
--arg model "$ollama_model" \
--argjson num_predict "$num_predict" \
--arg system "$sys" \
--arg user "$usr" \
'{model: $model, stream: false, options: {num_predict: $num_predict},
messages: [{role: "system", content: $system}, {role: "user", content: $user}]}') \
|| die 1 'Failed to build JSON payload'
fi
local -- raw body
local -i http_code
raw=$(curl -s --max-time 600 -w $'\n%{http_code}' \
-H 'Content-Type: application/json' \
-d @- \
"http://$ollama_host/api/chat" <<< "$payload") || die 5 'Ollama API connection failed'
http_code=${raw##*$'\n'}
body=${raw%$'\n'"$http_code"}
_dump_response "$body"
if ! ((http_code >= 200 && http_code < 300)); then
local -- errmsg
errmsg=$(jq -r '.error // empty' <<< "$body" 2>/dev/null) ||:
die 5 "Ollama API error (HTTP $http_code)" ${errmsg:+"$errmsg"}
fi
local -- content
content=$(jq -r '.message.content // empty' <<< "$body")
# Strip <think>...</think> tags from qwen3 models
[[ $content != *'</think>'* ]] || { content=${content##*</think>}; content=${content#$'\n'}; }
echo "$content"
echo "___TOKENS___ $(jq -r '"in=\(.prompt_eval_count // 0) out=\(.eval_count // 0)"' <<< "$body")"
}
# LLM backend: OpenAI chat completions API
_llm_openai() {
local -- model=$1 effort=$2 sys=$3 usr=$4
[[ -n ${OPENAI_API_KEY:-} ]] || die 18 'OPENAI_API_KEY not set'
local -- api_model=${BCS_OPENAI_MODEL:-${OPENAI_MODELS[$model]:-$model}}
local -i max_tokens=${EFFORT_TOKENS[$effort]}
# Native JSON mode via response_format:{type:"json_object"} (GPT-4+).
# Forces the model to emit only valid JSON. System/user prompt must
# mention "JSON" somewhere -- our JSON-mode prompt satisfies that.
local -- payload
if ((${BCS_JSON_MODE:-0})); then
payload=$(jq -n \
--arg model "$api_model" \
--argjson max_tokens "$max_tokens" \
--arg system "$sys" \
--arg user "$usr" \
'{model: $model, max_completion_tokens: $max_tokens,
response_format: {type: "json_object"},
messages: [{role: "system", content: $system}, {role: "user", content: $user}]}') \
|| die 1 'Failed to build JSON payload'
else
payload=$(jq -n \
--arg model "$api_model" \
--argjson max_tokens "$max_tokens" \
--arg system "$sys" \
--arg user "$usr" \
'{model: $model, max_completion_tokens: $max_tokens,
messages: [{role: "system", content: $system}, {role: "user", content: $user}]}') \
|| die 1 'Failed to build JSON payload'
fi
local -- raw body
local -i http_code
raw=$(curl -s --max-time 300 -w $'\n%{http_code}' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer '"$OPENAI_API_KEY" \
-d @- \
'https://api.openai.com/v1/chat/completions' <<< "$payload") || die 5 'OpenAI API connection failed'
http_code=${raw##*$'\n'}
body=${raw%$'\n'"$http_code"}
_dump_response "$body"
if ! ((http_code >= 200 && http_code < 300)); then
local -- errmsg
errmsg=$(jq -r '.error.message // empty' <<< "$body" 2>/dev/null) ||:
die 5 "OpenAI API error (HTTP $http_code)" ${errmsg:+"$errmsg"}
fi
jq -r '.choices[0].message.content // empty' <<< "$body"
echo "___TOKENS___ $(jq -r '"in=\(.usage.prompt_tokens // 0) out=\(.usage.completion_tokens // 0)"' <<< "$body")"
}
# LLM backend: Google Gemini API
_llm_google() {
local -- model=$1 effort=$2 sys=$3 usr=$4
local -- api_key=${GOOGLE_API_KEY:-${GEMINI_API_KEY:-}}
[[ -n $api_key ]] || die 18 'GOOGLE_API_KEY or GEMINI_API_KEY not set'
local -- api_model=${BCS_GOOGLE_MODEL:-${GOOGLE_MODELS[$model]:-$model}}
local -i max_tokens=${EFFORT_TOKENS[$effort]}
# Native JSON mode via generationConfig.response_mime_type. Gemini 1.5+
# supports "application/json" to force a structured-output response.
local -- payload
if ((${BCS_JSON_MODE:-0})); then
payload=$(jq -n \
--argjson max_tokens "$max_tokens" \
--arg system "$sys" \
--arg user "$usr" \
'{systemInstruction: {parts: [{text: $system}]},
contents: [{role: "user", parts: [{text: $user}]}],
generationConfig: {maxOutputTokens: $max_tokens,
response_mime_type: "application/json"}}') \
|| die 1 'Failed to build JSON payload'
else
payload=$(jq -n \
--argjson max_tokens "$max_tokens" \
--arg system "$sys" \
--arg user "$usr" \
'{systemInstruction: {parts: [{text: $system}]},
contents: [{role: "user", parts: [{text: $user}]}],
generationConfig: {maxOutputTokens: $max_tokens}}') \
|| die 1 'Failed to build JSON payload'
fi
local -- url=https://generativelanguage.googleapis.com/v1beta/models/"$api_model":generateContent
local -- raw body
local -i http_code
raw=$(curl -s --max-time 300 -w $'\n%{http_code}' \
-H 'Content-Type: application/json' \
-H 'x-goog-api-key: '"$api_key" \
-d @- \
"$url" <<< "$payload") || die 5 'Google API connection failed'
http_code=${raw##*$'\n'}
body=${raw%$'\n'"$http_code"}
_dump_response "$body"
if ! ((http_code >= 200 && http_code < 300)); then
local -- errmsg
errmsg=$(jq -r '.error.message // empty' <<< "$body" 2>/dev/null) ||:
die 5 "Google API error (HTTP $http_code)" ${errmsg:+"$errmsg"}
fi
jq -r '.candidates[0].content.parts[0].text // empty' <<< "$body"
local -- tkn
tkn=$(jq -r \
'"in=\(.usageMetadata.promptTokenCount // 0) out=\(.usageMetadata.candidatesTokenCount // 0)"' \
<<< "$body")
echo "___TOKENS___ $tkn"
}
# LLM backend: Claude Code CLI. Builds the prompt with @file references
# (resolved by the CLI itself) rather than inlining the standard or script,
# and runs `claude -p` from a clean temp dir with bypassPermissions.
_llm_claude_cli() {
local -- model=$1 effort=$2 bcs_file=$3 script_file=$4
local -i strict=$5
local -- tier_instr=${6:-} filter_instr=${7:-} policy_text=${8:-}
local -- shellcheck_block=${9:-}
command -v claude &>/dev/null || die 18 'Claude CLI required for claude backend'
model=${BCS_ANTHROPIC_MODEL:-${ANTHROPIC_MODELS[$model]:-$model}}
local -- prompt
if ((${BCS_JSON_MODE:-0})); then
prompt="You are a Bash script compliance validator emitting structured JSON output.
Analyze @$script_file against the Bash Coding Standard defined in @$bcs_file.
$tier_instr
Level mapping for JSON output:
- Tier \"core\" -> level \"error\"
- Tier \"recommended\" -> level \"warning\"
- Tier \"style\" -> level \"warning\"
- Tier \"disabled\" -> OMIT entirely
Respect inline suppression: \`#bcscheck disable=BCSxxxx\` exempts the next line/block.
Return a JSON array of finding objects. Each finding object has this shape:
{
\"line\": <1-indexed integer>,
\"endLine\": <1-indexed integer, same as line if single-line>,
\"level\": \"error\" | \"warning\" | \"info\",
\"code\": <integer, BCS code without the BCS prefix (e.g. 101 for BCS0101)>,
\"bcsCode\": \"BCS####\",
\"tier\": \"core\" | \"recommended\" | \"style\",
\"message\": \"<one sentence describing the violation>\",
\"fixSuggestion\": \"<human-readable remediation advice>\"
}
Example of a valid response (one finding):
[
{
\"line\": 4,
\"endLine\": 4,
\"level\": \"error\",
\"code\": 101,
\"bcsCode\": \"BCS0101\",
\"tier\": \"core\",
\"message\": \"Missing set -euo pipefail strict mode declaration.\",
\"fixSuggestion\": \"Add 'set -euo pipefail' and 'shopt -s inherit_errexit' right after the shebang.\"
}
]
Return ONLY the JSON array. No markdown code fences. No commentary. No preamble.
If there are no findings, return []."
else
prompt="You are a Bash script compliance validator.
Analyze @$script_file against the Bash Coding Standard defined in @$bcs_file.
$tier_instr
For each finding, report:
- The BCS code (e.g., BCS0101)
- The rule's tier (core, recommended, style)
- Severity: [ERROR] for core-tier violations, [WARN] for recommended/style
- The specific line(s) affected
- What is wrong and how to fix it
At the end, provide a summary table: | BCS Code | Tier | Severity | Line(s) | Description |.
Respect inline suppression: eg, #bcscheck disable=BCS0101 exempts the next line/block."
fi
[[ -z $filter_instr ]] || prompt+=$'\n\n'"$filter_instr"
[[ -z $policy_text ]] || prompt+=$'\n'"$policy_text"
[[ -z $shellcheck_block ]] || prompt+=$'\n\n'"$shellcheck_block"
if ((strict)); then
if ((${BCS_JSON_MODE:-0})); then
prompt+=$'\n\nSTRICT MODE: Map recommended/style violations to level "error" instead of "warning".'
else
prompt+=$'\n\nSTRICT MODE: Treat all warnings as [ERROR].'
fi
fi
# cd to clean temp dir -- prevents claude from loading local CLAUDE.md
local -- check_dir
check_dir=$(mktemp -d -t 'bcs-XXXXX') || die 1 'Failed to create temp dir'
#bcscheck disable=BCS0603
#shellcheck disable=SC2064
trap "cd '$PWD' 2>/dev/null; rm -rf '$check_dir'" RETURN
cd "$check_dir"
[[ ! -d /run/user/"$EUID" ]] || declare -x TMPDIR=/run/user/"$EUID"
local -a claude_args=(--model "$model" --permission-mode bypassPermissions)
[[ -z $effort ]] || claude_args+=(--effort "$effort")
#shellcheck disable=SC1007
CLAUDECODE= claude "${claude_args[@]}" -p "$prompt" 2>/dev/null
}
# ---- Subcommands ----
# Subcommand: display
cmd_display() {
local -i force_cat=0
local -- bcs_file
while (($#)); do case $1 in
-c|--cat) force_cat=1 ;;
-f|--file) _find_bcs_md || die 3 'BASH-CODING-STANDARD.md not found'; return 0 ;;
-S|--symlink) bcs_file=$(_find_bcs_md) || die 3 'BASH-CODING-STANDARD.md not found'
ln -sf "$bcs_file" .
info "Symlinked BASH-CODING-STANDARD.md → $bcs_file"
return 0
;;
-v|--verbose) VERBOSE=1 ;;
-q|--quiet) VERBOSE=0 ;;
-h|--help) show_display_help; return 0 ;;
--) shift; break ;;
-[cfSvqh]?*) set -- "${1:0:2}" "-${1:2}" "${@:2}"; continue ;;
-*) die 22 "Invalid option ${1@Q}" ;;
*) die 2 "Unexpected argument ${1@Q}" ;;
esac; shift; done
bcs_file=$(_find_bcs_md) || die 3 'BASH-CODING-STANDARD.md not found'
if ((force_cat)); then
cat -- "$bcs_file"
return 0
fi
# Try md2ansi for formatted output if terminal