-
-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathcoverage.sh
More file actions
1591 lines (1405 loc) · 62.2 KB
/
Copy pathcoverage.sh
File metadata and controls
1591 lines (1405 loc) · 62.2 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
# shellcheck disable=SC2094
# Coverage data storage
# Use :- to preserve inherited values from parent bashunit processes
_BASHUNIT_COVERAGE_DATA_FILE="${_BASHUNIT_COVERAGE_DATA_FILE:-}"
_BASHUNIT_COVERAGE_TRACKED_FILES="${_BASHUNIT_COVERAGE_TRACKED_FILES:-}"
# Simple file-based cache for tracked files (Bash 3.2 compatible)
# The tracked cache file stores files that have already been processed
_BASHUNIT_COVERAGE_TRACKED_CACHE_FILE="${_BASHUNIT_COVERAGE_TRACKED_CACHE_FILE:-}"
# File to store which tests hit each line (for detailed coverage tooltips)
_BASHUNIT_COVERAGE_TEST_HITS_FILE="${_BASHUNIT_COVERAGE_TEST_HITS_FILE:-}"
# Auto-discover coverage paths from test file names
# When no explicit coverage paths are set, find source files matching test file base names
# Example: tests/unit/assert_test.sh -> finds src/assert.sh, src/assert_*.sh
function bashunit::coverage::auto_discover_paths() {
local project_root
project_root="$(pwd)"
local -a discovered_paths=()
for test_file in "$@"; do
# Extract base name: tests/unit/assert_test.sh -> assert_test.sh
local file_basename
file_basename=$(basename "$test_file")
# Remove test suffixes to get source name: assert_test.sh -> assert
local source_name="${file_basename%_test.sh}"
[[ "$source_name" == "$file_basename" ]] && source_name="${file_basename%Test.sh}"
[[ "$source_name" == "$file_basename" ]] && continue # Not a test file pattern
# Find matching source files recursively
while IFS= read -r -d '' found_file; do
# Skip test files and vendor directories
[[ "$found_file" == *test* ]] && continue
[[ "$found_file" == *Test* ]] && continue
[[ "$found_file" == *vendor* ]] && continue
[[ "$found_file" == *node_modules* ]] && continue
discovered_paths+=("$found_file")
done < <(find "$project_root" -name "${source_name}*.sh" -type f -print0 2>/dev/null)
done
# Return unique paths, comma-separated
if [[ ${#discovered_paths[@]} -gt 0 ]]; then
printf '%s\n' "${discovered_paths[@]}" | sort -u | tr '\n' ',' | sed 's/,$//'
fi
}
function bashunit::coverage::init() {
if ! bashunit::env::is_coverage_enabled; then
return 0
fi
# Skip coverage init if we're a subprocess of another coverage-enabled bashunit
# This prevents nested bashunit calls (e.g., in acceptance tests) from
# interfering with the parent's coverage tracking
if [[ -n "${_BASHUNIT_COVERAGE_DATA_FILE:-}" ]]; then
export BASHUNIT_COVERAGE=false
return 0
fi
# Create coverage data directory
local coverage_dir
coverage_dir="${BASHUNIT_TEMP_DIR:-/tmp}/bashunit-coverage-$$"
mkdir -p "$coverage_dir"
_BASHUNIT_COVERAGE_DATA_FILE="${coverage_dir}/hits.dat"
_BASHUNIT_COVERAGE_TRACKED_FILES="${coverage_dir}/files.dat"
_BASHUNIT_COVERAGE_TRACKED_CACHE_FILE="${coverage_dir}/cache.dat"
_BASHUNIT_COVERAGE_TEST_HITS_FILE="${coverage_dir}/test_hits.dat"
# Initialize empty files
: > "$_BASHUNIT_COVERAGE_DATA_FILE"
: > "$_BASHUNIT_COVERAGE_TRACKED_FILES"
: > "$_BASHUNIT_COVERAGE_TRACKED_CACHE_FILE"
: > "$_BASHUNIT_COVERAGE_TEST_HITS_FILE"
export _BASHUNIT_COVERAGE_DATA_FILE
export _BASHUNIT_COVERAGE_TRACKED_FILES
export _BASHUNIT_COVERAGE_TRACKED_CACHE_FILE
export _BASHUNIT_COVERAGE_TEST_HITS_FILE
}
function bashunit::coverage::enable_trap() {
if ! bashunit::env::is_coverage_enabled; then
return 0
fi
# Enable trap inheritance into functions
set -T
# Set DEBUG trap to record line execution
# Use ${VAR:-} to handle unset variables when set -u is active (in subshells)
# shellcheck disable=SC2154
trap 'bashunit::coverage::record_line "${BASH_SOURCE:-}" "${LINENO:-}"' DEBUG
}
function bashunit::coverage::disable_trap() {
trap - DEBUG
set +T
}
# Normalize file path to absolute
function bashunit::coverage::normalize_path() {
local file="$1"
# Normalize path to absolute
if [[ -f "$file" ]]; then
echo "$(cd "$(dirname "$file")" && pwd)/$(basename "$file")"
else
echo "$file"
fi
}
function bashunit::coverage::record_line() {
local file="$1"
local lineno="$2"
# Skip if no file or line
[[ -z "$file" || -z "$lineno" ]] && return 0
# Skip if coverage data file doesn't exist (trap inherited by child process)
[[ -z "$_BASHUNIT_COVERAGE_DATA_FILE" ]] && return 0
# Skip if not tracking this file (uses cache internally)
bashunit::coverage::should_track "$file" || return 0
# Normalize file path using cache (must match tracked_files for hit counting)
local normalized_file
normalized_file=$(bashunit::coverage::normalize_path "$file")
# In parallel mode, use a per-process file to avoid race conditions
local data_file="$_BASHUNIT_COVERAGE_DATA_FILE"
local test_hits_file="$_BASHUNIT_COVERAGE_TEST_HITS_FILE"
if bashunit::parallel::is_enabled; then
data_file="${_BASHUNIT_COVERAGE_DATA_FILE}.$$"
test_hits_file="${_BASHUNIT_COVERAGE_TEST_HITS_FILE}.$$"
fi
# Record the hit (only if parent directory exists)
if [[ -d "$(dirname "$data_file")" ]]; then
echo "${normalized_file}:${lineno}" >> "$data_file"
# Also record which test caused this hit (if we're in a test context)
if [[ -n "${_BASHUNIT_COVERAGE_CURRENT_TEST_FILE:-}" && -n "${_BASHUNIT_COVERAGE_CURRENT_TEST_FN:-}" ]]; then
# Format: source_file:line|test_file:test_function
echo "${normalized_file}:${lineno}|${_BASHUNIT_COVERAGE_CURRENT_TEST_FILE}:${_BASHUNIT_COVERAGE_CURRENT_TEST_FN}" >> "$test_hits_file"
fi
fi
}
function bashunit::coverage::should_track() {
local file="$1"
# Skip empty paths
[[ -z "$file" ]] && return 1
# Skip if tracked files list doesn't exist (trap inherited by child process)
[[ -z "$_BASHUNIT_COVERAGE_TRACKED_FILES" ]] && return 1
# Check file-based cache for previous decision (Bash 3.2 compatible)
# Cache format: "file:0" for excluded, "file:1" for tracked
# In parallel mode, use per-process cache to avoid race conditions
local cache_file="$_BASHUNIT_COVERAGE_TRACKED_CACHE_FILE"
if bashunit::parallel::is_enabled && [[ -n "$cache_file" ]]; then
cache_file="${cache_file}.$$"
# Initialize per-process cache if needed
[[ ! -f "$cache_file" ]] && [[ -d "$(dirname "$cache_file")" ]] && : > "$cache_file"
fi
if [[ -n "$cache_file" && -f "$cache_file" ]]; then
local cached_decision
# Use || true to prevent exit in strict mode when grep finds no match
cached_decision=$(grep "^${file}:" "$cache_file" 2>/dev/null | head -1) || true
if [[ -n "$cached_decision" ]]; then
[[ "${cached_decision##*:}" == "1" ]] && return 0 || return 1
fi
fi
# Normalize path
local normalized_file
normalized_file=$(bashunit::coverage::normalize_path "$file")
# Check exclusion patterns
# Save and restore IFS to avoid corrupting caller's environment
local old_ifs="$IFS"
IFS=','
local pattern
for pattern in $BASHUNIT_COVERAGE_EXCLUDE; do
# shellcheck disable=SC2254
case "$normalized_file" in
*$pattern*)
IFS="$old_ifs"
# Cache exclusion decision (use per-process cache in parallel mode)
[[ -n "$cache_file" && -f "$cache_file" ]] && echo "${file}:0" >> "$cache_file"
return 1
;;
esac
done
# Check inclusion paths
local matched=false
local path
for path in $BASHUNIT_COVERAGE_PATHS; do
# Resolve relative paths
local resolved_path
if [[ "$path" == /* ]]; then
resolved_path="$path"
else
resolved_path="$(pwd)/$path"
fi
if [[ "$normalized_file" == "$resolved_path"* ]]; then
matched=true
break
fi
done
IFS="$old_ifs"
if [[ "$matched" == "false" ]]; then
# Cache exclusion decision (use per-process cache in parallel mode)
[[ -n "$cache_file" && -f "$cache_file" ]] && echo "${file}:0" >> "$cache_file"
return 1
fi
# Cache tracking decision (use per-process cache in parallel mode)
[[ -n "$cache_file" && -f "$cache_file" ]] && echo "${file}:1" >> "$cache_file"
# Track this file for later reporting
# In parallel mode, use a per-process file to avoid race conditions
local tracked_file="$_BASHUNIT_COVERAGE_TRACKED_FILES"
if bashunit::parallel::is_enabled; then
tracked_file="${_BASHUNIT_COVERAGE_TRACKED_FILES}.$$"
fi
# Only write if parent directory exists
if [[ -d "$(dirname "$tracked_file")" ]]; then
# Check if not already written to avoid duplicates
if ! grep -q "^${normalized_file}$" "$tracked_file" 2>/dev/null; then
echo "$normalized_file" >> "$tracked_file"
fi
fi
return 0
}
function bashunit::coverage::aggregate_parallel() {
# Aggregate per-process coverage files created during parallel execution
local base_file="$_BASHUNIT_COVERAGE_DATA_FILE"
local tracked_base="$_BASHUNIT_COVERAGE_TRACKED_FILES"
local test_hits_base="$_BASHUNIT_COVERAGE_TEST_HITS_FILE"
# Find and merge all per-process coverage data files
# Use nullglob to handle case when no files match
local pid_files
pid_files=$(ls -1 "${base_file}."* 2>/dev/null) || true
if [[ -n "$pid_files" ]]; then
while IFS= read -r pid_file; do
[[ -f "$pid_file" ]] || continue
cat "$pid_file" >> "$base_file"
rm -f "$pid_file"
done <<< "$pid_files"
fi
# Find and merge all per-process tracked files lists
pid_files=$(ls -1 "${tracked_base}."* 2>/dev/null) || true
if [[ -n "$pid_files" ]]; then
while IFS= read -r pid_file; do
[[ -f "$pid_file" ]] || continue
cat "$pid_file" >> "$tracked_base"
rm -f "$pid_file"
done <<< "$pid_files"
fi
# Find and merge all per-process test hits files
if [[ -n "$test_hits_base" ]]; then
pid_files=$(ls -1 "${test_hits_base}."* 2>/dev/null) || true
if [[ -n "$pid_files" ]]; then
while IFS= read -r pid_file; do
[[ -f "$pid_file" ]] || continue
cat "$pid_file" >> "$test_hits_base"
rm -f "$pid_file"
done <<< "$pid_files"
fi
fi
# Deduplicate tracked files
if [[ -f "$tracked_base" ]]; then
sort -u "$tracked_base" -o "$tracked_base"
fi
}
# Pre-compiled regex pattern for function declarations (performance optimization)
# Matches: function foo() { OR foo() { OR function foo() OR foo()
# Does NOT match single-line functions with body: function foo() { echo "hi"; }
_BASHUNIT_COVERAGE_FUNC_PATTERN='^[[:space:]]*(function[[:space:]]+)?'
_BASHUNIT_COVERAGE_FUNC_PATTERN+='[a-zA-Z_][a-zA-Z0-9_:]*[[:space:]]*\(\)[[:space:]]*\{?[[:space:]]*$'
# Check if a line is executable (used by get_executable_lines and report_lcov)
# Arguments: line content, line number
# Returns: 0 if executable, 1 if not
function bashunit::coverage::is_executable_line() {
local line="$1"
local lineno="$2"
# Unused but kept for API compatibility
: "$lineno"
# Skip empty lines (line with only whitespace)
[[ -z "${line// }" ]] && return 1
# Skip comment-only lines (including shebang)
[[ "$line" =~ ^[[:space:]]*# ]] && return 1
# Skip function declaration lines (but not single-line functions with body)
[[ "$line" =~ $_BASHUNIT_COVERAGE_FUNC_PATTERN ]] && return 1
# Skip lines with only braces
[[ "$line" =~ ^[[:space:]]*[\{\}][[:space:]]*$ ]] && return 1
# Skip control flow keywords (then, else, fi, do, done, esac, in, ;;, ;&, ;;&)
[[ "$line" =~ ^[[:space:]]*(then|else|fi|do|done|esac|in|;;|;;&|;&)[[:space:]]*(#.*)?$ ]] && return 1
# Skip case patterns like "--option)" or "*)"
[[ "$line" =~ ^[[:space:]]*[^\)]+\)[[:space:]]*$ ]] && return 1
# Skip standalone ) for arrays/subshells
[[ "$line" =~ ^[[:space:]]*\)[[:space:]]*(#.*)?$ ]] && return 1
return 0
}
function bashunit::coverage::get_executable_lines() {
local file="$1"
local count=0
local lineno=0
while IFS= read -r line || [[ -n "$line" ]]; do
((lineno++))
bashunit::coverage::is_executable_line "$line" "$lineno" && ((count++))
done < "$file"
echo "$count"
}
function bashunit::coverage::get_hit_lines() {
local file="$1"
if [[ ! -f "$_BASHUNIT_COVERAGE_DATA_FILE" ]]; then
echo "0"
return
fi
# Get unique hit line numbers
local hit_lines
hit_lines=$( (grep "^${file}:" "$_BASHUNIT_COVERAGE_DATA_FILE" 2>/dev/null || true) | \
cut -d: -f2 | sort -u)
if [[ -z "$hit_lines" ]]; then
echo "0"
return
fi
# Only count hits that correspond to executable lines
# This prevents >100% coverage when DEBUG trap fires on non-executable lines
local count=0
local line_num
for line_num in $hit_lines; do
local line_content
line_content=$(sed -n "${line_num}p" "$file" 2>/dev/null) || continue
if bashunit::coverage::is_executable_line "$line_content" "$line_num"; then
((count++))
fi
done
echo "$count"
}
function bashunit::coverage::get_line_hits() {
local file="$1"
local lineno="$2"
if [[ ! -f "$_BASHUNIT_COVERAGE_DATA_FILE" ]]; then
echo "0"
return
fi
local count
count=$(grep -c "^${file}:${lineno}$" "$_BASHUNIT_COVERAGE_DATA_FILE" 2>/dev/null) || count=0
echo "$count"
}
# Get all line hits for a file in one pass (performance optimization)
# Output format: one "lineno:count" per line
function bashunit::coverage::get_all_line_hits() {
local file="$1"
if [[ ! -f "$_BASHUNIT_COVERAGE_DATA_FILE" ]]; then
return
fi
# Extract all lines for this file, count occurrences of each line number
grep "^${file}:" "$_BASHUNIT_COVERAGE_DATA_FILE" 2>/dev/null | \
cut -d: -f2 | sort | uniq -c | \
while read -r count lineno; do
echo "${lineno}:${count}"
done
}
# Get all test hits for a file in one pass (performance optimization)
# Output format: lineno|test_file:test_function (may have duplicates, one per hit)
function bashunit::coverage::get_all_line_tests() {
local file="$1"
if [[ ! -f "${_BASHUNIT_COVERAGE_TEST_HITS_FILE:-}" ]]; then
return
fi
# Format in file: source_file:line|test_file:test_function
# Output: lineno|test_file:test_function
grep "^${file}:" "$_BASHUNIT_COVERAGE_TEST_HITS_FILE" 2>/dev/null | \
sed "s|^${file}:||" | sort -u
}
# Extract function definitions from a bash file
# Output format: function_name:start_line:end_line (one per function)
function bashunit::coverage::extract_functions() {
local file="$1"
local lineno=0
local in_function=0
local brace_count=0
local current_fn=""
local fn_start=0
while IFS= read -r line || [[ -n "$line" ]]; do
((lineno++))
# Check for function definition patterns
# Pattern 1: function name() { or function name {
# Pattern 2: name() { or name () {
if [[ $in_function -eq 0 ]]; then
local fn_name=""
# Match: function name() or function name {
if [[ "$line" =~ ^[[:space:]]*(function[[:space:]]+)?([a-zA-Z_][a-zA-Z0-9_:]*)[[:space:]]*\(\)[[:space:]]*\{?[[:space:]]*(#.*)?$ ]]; then
fn_name="${BASH_REMATCH[2]}"
elif [[ "$line" =~ ^[[:space:]]*(function[[:space:]]+)([a-zA-Z_][a-zA-Z0-9_:]*)[[:space:]]*\{[[:space:]]*(#.*)?$ ]]; then
fn_name="${BASH_REMATCH[2]}"
fi
if [[ -n "$fn_name" ]]; then
in_function=1
current_fn="$fn_name"
fn_start=$lineno
brace_count=0
# Count opening braces on this line
local open_braces="${line//[^\{]/}"
local close_braces="${line//[^\}]/}"
brace_count=$((brace_count + ${#open_braces} - ${#close_braces}))
# Single-line function
if [[ $brace_count -eq 0 && "$line" =~ \{ && "$line" =~ \} ]]; then
echo "${current_fn}:${fn_start}:${lineno}"
in_function=0
current_fn=""
fi
continue
fi
fi
# Track braces inside function
if [[ $in_function -eq 1 ]]; then
local open_braces="${line//[^\{]/}"
local close_braces="${line//[^\}]/}"
brace_count=$((brace_count + ${#open_braces} - ${#close_braces}))
# Function ended
if [[ $brace_count -le 0 ]]; then
echo "${current_fn}:${fn_start}:${lineno}"
in_function=0
current_fn=""
brace_count=0
fi
fi
done < "$file"
# Handle unclosed function (shouldn't happen in valid code)
if [[ $in_function -eq 1 && -n "$current_fn" ]]; then
echo "${current_fn}:${fn_start}:${lineno}"
fi
}
# Calculate coverage for a specific function in a file
# Returns: hit_lines:executable_lines:percentage
function bashunit::coverage::get_function_coverage() {
local file="$1"
local fn_start="$2"
local fn_end="$3"
shift 3
# Accept hits_by_line array as nameref (Bash 4.3+) or fall back to counting
local -n _hits_ref=$1 2>/dev/null || true
local executable=0
local hit=0
local lineno
for ((lineno = fn_start; lineno <= fn_end; lineno++)); do
local line_content
line_content=$(sed -n "${lineno}p" "$file" 2>/dev/null) || continue
if bashunit::coverage::is_executable_line "$line_content" "$lineno"; then
((executable++))
local line_hits=${_hits_ref[$lineno]:-0}
if [[ $line_hits -gt 0 ]]; then
((hit++))
fi
fi
done
local pct=0
if [[ $executable -gt 0 ]]; then
pct=$((hit * 100 / executable))
fi
echo "${hit}:${executable}:${pct}"
}
function bashunit::coverage::get_percentage() {
local total_executable=0
local total_hit=0
# Check if tracked files exist
if [[ ! -f "$_BASHUNIT_COVERAGE_TRACKED_FILES" ]]; then
echo "0"
return
fi
while IFS= read -r file; do
[[ -z "$file" || ! -f "$file" ]] && continue
local executable
executable=$(bashunit::coverage::get_executable_lines "$file")
local hit
hit=$(bashunit::coverage::get_hit_lines "$file")
((total_executable += executable))
((total_hit += hit))
done < "$_BASHUNIT_COVERAGE_TRACKED_FILES"
if [[ $total_executable -eq 0 ]]; then
echo "0"
return
fi
# Calculate percentage (integer)
echo $((total_hit * 100 / total_executable))
}
function bashunit::coverage::report_text() {
if ! bashunit::env::is_coverage_enabled; then
return 0
fi
local total_executable=0
local total_hit=0
echo ""
echo "Coverage Report"
echo "---------------"
# Check if tracked files exist
if [[ ! -f "$_BASHUNIT_COVERAGE_TRACKED_FILES" ]]; then
echo "---------------"
echo "Total: 0/0 (0%)"
return 0
fi
while IFS= read -r file; do
[[ -z "$file" || ! -f "$file" ]] && continue
local executable
executable=$(bashunit::coverage::get_executable_lines "$file")
local hit
hit=$(bashunit::coverage::get_hit_lines "$file")
((total_executable += executable))
((total_hit += hit))
# Calculate percentage
local pct=0
if [[ $executable -gt 0 ]]; then
pct=$((hit * 100 / executable))
fi
# Determine color based on thresholds
local color=""
local reset=""
if [[ "${BASHUNIT_NO_COLOR:-false}" != "true" ]]; then
reset=$'\033[0m'
if [[ $pct -lt ${BASHUNIT_COVERAGE_THRESHOLD_LOW:-50} ]]; then
color=$'\033[31m' # Red
elif [[ $pct -lt ${BASHUNIT_COVERAGE_THRESHOLD_HIGH:-80} ]]; then
color=$'\033[33m' # Yellow
else
color=$'\033[32m' # Green
fi
fi
# Display relative path
local display_file
display_file="${file#"$(pwd)"/}"
printf "%s%-40s %3d/%3d lines (%3d%%)%s\n" \
"$color" "$display_file" "$hit" "$executable" "$pct" "$reset"
done < "$_BASHUNIT_COVERAGE_TRACKED_FILES"
echo "---------------"
# Total
local total_pct=0
if [[ $total_executable -gt 0 ]]; then
total_pct=$((total_hit * 100 / total_executable))
fi
local color=""
local reset=""
if [[ "${BASHUNIT_NO_COLOR:-false}" != "true" ]]; then
reset=$'\033[0m'
if [[ $total_pct -lt ${BASHUNIT_COVERAGE_THRESHOLD_LOW:-50} ]]; then
color=$'\033[31m'
elif [[ $total_pct -lt ${BASHUNIT_COVERAGE_THRESHOLD_HIGH:-80} ]]; then
color=$'\033[33m'
else
color=$'\033[32m'
fi
fi
printf "%sTotal: %d/%d (%d%%)%s\n" \
"$color" "$total_hit" "$total_executable" "$total_pct" "$reset"
# Show report location if generated
if [[ -n "$BASHUNIT_COVERAGE_REPORT" ]]; then
echo ""
echo "Coverage report written to: $BASHUNIT_COVERAGE_REPORT"
fi
}
function bashunit::coverage::report_lcov() {
local output_file="${1:-$BASHUNIT_COVERAGE_REPORT}"
if [[ -z "$output_file" ]]; then
return 0
fi
# Create output directory if needed
local output_dir
output_dir=$(dirname "$output_file")
mkdir -p "$output_dir"
# Check if tracked files exist - if not, write empty LCOV file
if [[ ! -f "$_BASHUNIT_COVERAGE_TRACKED_FILES" ]]; then
echo "TN:" > "$output_file"
return 0
fi
# Generate LCOV format
{
echo "TN:"
while IFS= read -r file; do
[[ -z "$file" || ! -f "$file" ]] && continue
echo "SF:$file"
local lineno=0
# shellcheck disable=SC2094
while IFS= read -r line || [[ -n "$line" ]]; do
((lineno++))
# Skip non-executable lines (use shared helper)
bashunit::coverage::is_executable_line "$line" "$lineno" || continue
# Get hit count for this line
local hits
hits=$(bashunit::coverage::get_line_hits "$file" "$lineno")
echo "DA:${lineno},${hits}"
done < "$file"
local executable
executable=$(bashunit::coverage::get_executable_lines "$file")
local hit
hit=$(bashunit::coverage::get_hit_lines "$file")
echo "LF:$executable"
echo "LH:$hit"
echo "end_of_record"
done < "$_BASHUNIT_COVERAGE_TRACKED_FILES"
} > "$output_file"
}
function bashunit::coverage::check_threshold() {
if [[ -z "$BASHUNIT_COVERAGE_MIN" ]]; then
return 0
fi
local pct
pct=$(bashunit::coverage::get_percentage)
if [[ $pct -lt $BASHUNIT_COVERAGE_MIN ]]; then
local color=""
local reset=""
if [[ "${BASHUNIT_NO_COLOR:-false}" != "true" ]]; then
color=$'\033[31m'
reset=$'\033[0m'
fi
printf "%sCoverage %d%% is below minimum %d%%%s\n" \
"$color" "$pct" "$BASHUNIT_COVERAGE_MIN" "$reset"
return 1
fi
return 0
}
# Escape HTML special characters
function bashunit::coverage::html_escape() {
local text="$1"
text="${text//&/&}"
text="${text//</<}"
text="${text//>/>}"
echo "$text"
}
# Convert file path to safe filename for HTML
function bashunit::coverage::path_to_filename() {
local file="$1"
local display_file="${file#"$(pwd)"/}"
# Replace / with _ and . with _
local safe_name="${display_file//\//_}"
echo "${safe_name//./_}"
}
function bashunit::coverage::report_html() {
local output_dir="${1:-coverage/html}"
if [[ -z "$output_dir" ]]; then
return 0
fi
# Check if tracked files exist
if [[ ! -f "$_BASHUNIT_COVERAGE_TRACKED_FILES" ]]; then
return 0
fi
# Create output directory structure
mkdir -p "$output_dir/files"
# Collect file data for index
local total_executable=0
local total_hit=0
local file_data=()
while IFS= read -r file; do
[[ -z "$file" || ! -f "$file" ]] && continue
local executable
executable=$(bashunit::coverage::get_executable_lines "$file")
local hit
hit=$(bashunit::coverage::get_hit_lines "$file")
((total_executable += executable))
((total_hit += hit))
local pct=0
if [[ $executable -gt 0 ]]; then
pct=$((hit * 100 / executable))
fi
local display_file="${file#"$(pwd)"/}"
local safe_filename
safe_filename=$(bashunit::coverage::path_to_filename "$file")
file_data+=("$display_file|$hit|$executable|$pct|$safe_filename")
# Generate individual file HTML
bashunit::coverage::generate_file_html "$file" "$output_dir/files/${safe_filename}.html"
done < "$_BASHUNIT_COVERAGE_TRACKED_FILES"
# Calculate total percentage
local total_pct=0
if [[ $total_executable -gt 0 ]]; then
total_pct=$((total_hit * 100 / total_executable))
fi
# Get test results
local tests_passed=$(bashunit::state::get_tests_passed)
local tests_failed=$(bashunit::state::get_tests_failed)
local tests_total=$((tests_passed + tests_failed))
# Generate index.html
bashunit::coverage::generate_index_html \
"$output_dir/index.html" "$total_hit" "$total_executable" "$total_pct" \
"$tests_total" "$tests_passed" "$tests_failed" ${file_data[@]+"${file_data[@]}"}
echo "Coverage HTML report written to: $output_dir/index.html"
}
function bashunit::coverage::generate_index_html() {
local output_file="$1"
local total_hit="$2"
local total_executable="$3"
local total_pct="$4"
local tests_total="$5"
local tests_passed="$6"
local tests_failed="$7"
shift 7
local file_data=()
[[ $# -gt 0 ]] && file_data=("$@")
# Calculate uncovered lines and file count
local total_uncovered=$((total_executable - total_hit))
local file_count=0
[[ ${#file_data[@]} -gt 0 ]] && file_count=${#file_data[@]}
# Calculate gauge stroke offset (440 is full circle circumference)
local gauge_offset=$((440 - (440 * total_pct / 100)))
# Determine coverage level and colors for gauge
local gauge_color_start gauge_color_end gauge_text_gradient
if [[ $total_pct -ge ${BASHUNIT_COVERAGE_THRESHOLD_HIGH:-80} ]]; then
# High coverage - green
gauge_color_start="#10b981"
gauge_color_end="#34d399"
gauge_text_gradient="linear-gradient(135deg, #10b981 0%, #34d399 100%)"
elif [[ $total_pct -ge ${BASHUNIT_COVERAGE_THRESHOLD_LOW:-50} ]]; then
# Medium coverage - yellow/orange
gauge_color_start="#f59e0b"
gauge_color_end="#fbbf24"
gauge_text_gradient="linear-gradient(135deg, #f59e0b 0%, #fbbf24 100%)"
else
# Low coverage - red
gauge_color_start="#ef4444"
gauge_color_end="#f87171"
gauge_text_gradient="linear-gradient(135deg, #ef4444 0%, #f87171 100%)"
fi
{
cat << 'EOF'
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Coverage Report | bashunit</title>
<style>
:root {
--primary: #6366f1; --primary-dark: #4f46e5; --primary-light: #818cf8;
--success: #10b981; --success-light: #34d399;
--warning: #f59e0b; --warning-light: #fbbf24;
--danger: #ef4444; --danger-light: #f87171;
--bg-light: #ffffff; --bg-card: #f8fafc; --bg-hover: #f1f5f9;
--text-primary: #0f172a; --text-secondary: #475569; --text-muted: #94a3b8;
--border: #e2e8f0;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; background: var(--bg-light); color: var(--text-primary); min-height: 100vh; line-height: 1.6; }
.header { background: var(--bg-card); padding: 0; position: relative; overflow: hidden; border-bottom: 1px solid var(--border); }
.header-content { position: relative; z-index: 1; max-width: 1400px; margin: 0 auto; padding: 40px 30px; }
.header-top { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; }
.logo { display: flex; align-items: center; gap: 12px; }
.logo img { width: 40px; height: 40px; }
.logo-text { font-size: 1.5rem; font-weight: 700; letter-spacing: -0.5px; color: var(--text-primary); }
.logo-text span { opacity: 0.6; font-weight: 400; }
.header-badge { background: var(--bg-hover); padding: 8px 16px; border-radius: 20px; font-size: 0.85rem; font-weight: 500; color: var(--text-secondary); }
.header-title { font-size: 2.5rem; font-weight: 800; margin-bottom: 8px; letter-spacing: -1px; color: var(--text-primary); }
.header-subtitle { font-size: 1.1rem; opacity: 0.7; color: var(--text-secondary); }
.main { max-width: 1400px; margin: 0 auto; padding: 40px 30px; }
.gauge-section { background: var(--bg-card); border-radius: 20px; padding: 40px; margin-bottom: 30px; border: 1px solid var(--border); display: flex; align-items: center; gap: 60px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
.gauge-container { position: relative; width: 200px; height: 200px; flex-shrink: 0; }
.gauge-bg { fill: none; stroke: #e5e7eb; stroke-width: 20; }
.gauge-fill { fill: none; stroke: url(#gaugeGradient); stroke-width: 20; stroke-linecap: round; transform: rotate(-90deg); transform-origin: center; animation: gaugeAnimation 1.5s ease-out forwards; }
@keyframes gaugeAnimation { from { stroke-dashoffset: 440; } }
@keyframes fadeInUp { from { opacity: 0; } to { opacity: 1 } }
.gauge-text { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; width: 100%; }
EOF
echo " .gauge-percent { font-size: 3.5rem; font-weight: 800; background: ${gauge_text_gradient}; -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; line-height: 1; margin: 0; display: block; }"
cat << 'EOF'
.gauge-label { color: var(--text-secondary); font-size: 0.9rem; text-transform: uppercase; letter-spacing: 2px; margin: 0; display: block; }
.gauge-info { flex: 1; }
.gauge-title { font-size: 1.8rem; font-weight: 700; margin-bottom: 12px; }
.gauge-description { color: var(--text-secondary); font-size: 1.05rem; margin-bottom: 24px; line-height: 1.7; }
.breakdown-item { display: flex; align-items: center; gap: 6px; white-space: nowrap; }
.breakdown-dot { width: 12px; height: 12px; border-radius: 50%; }
.breakdown-dot.total { background: #94a3b8; }
.breakdown-dot.covered { background: var(--success); }
.breakdown-dot.uncovered { background: var(--danger); }
.breakdown-dot.files { background: var(--warning); }
.breakdown-dot.tests { background: #a78bfa; }
.breakdown-dot.tests-passed { background: var(--success); }
.breakdown-dot.tests-failed { background: var(--danger); }
.breakdown-label { color: var(--text-secondary); font-size: 0.9rem; }
.breakdown-value { font-weight: 600; color: var(--text-primary); }
.compact-metrics { display: flex; flex-direction: column; gap: 10px; }
.metrics-group { background: var(--bg-hover); padding: 12px 16px; border-radius: 8px; border-left: 3px solid var(--primary); }
.metrics-group.coverage-group { border-left-color: var(--success); }
.metrics-group.test-group { border-left-color: #a78bfa; }
.metrics-group-title { font-size: 0.8rem; font-weight: 600; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 8px; }
.metrics-inline { display: flex; gap: 16px; flex-wrap: wrap; align-items: center; font-size: 0.9rem; }
.metrics-inline .breakdown-item { margin: 0; }
.section-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; flex-wrap: wrap; gap: 16px; }
.section-title { font-size: 1.5rem; font-weight: 700; display: flex; align-items: center; gap: 12px; }
.legend { display: flex; gap: 20px; background: #f1f5f9; padding: 12px 20px; border-radius: 10px; }
.legend-item { display: flex; align-items: center; gap: 8px; font-size: 0.85rem; color: var(--text-secondary); pointer-events: none; }
.legend-color { width: 16px; height: 16px; border-radius: 4px; }
.legend-color.high { background: var(--success); }
.legend-color.medium { background: var(--warning); }
.legend-color.low { background: var(--danger); }
.files-table { background: var(--bg-card); border-radius: 16px; overflow: hidden; border: 1px solid var(--border); box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
.files-table table { width: 100%; border-collapse: collapse; }
.files-table th { background: #f8fafc; padding: 16px 24px; text-align: left; font-weight: 600; color: var(--text-secondary); font-size: 0.85rem; text-transform: uppercase; letter-spacing: 1px; border-bottom: 1px solid var(--border); }
.files-table td { padding: 20px 24px; border-bottom: 1px solid var(--border); vertical-align: middle; }
.files-table tr:last-child td { border-bottom: none; }
.files-table tbody tr { transition: all 0.2s ease; animation: fadeInUp 0.5s ease-out forwards; opacity: 0; cursor: pointer; }
.files-table tbody tr:hover { background: var(--bg-hover); }
.file-info { display: flex; flex-direction: column; gap: 4px; }
.file-name { font-weight: 600; color: var(--text-primary); text-decoration: none; font-size: 1rem; transition: color 0.2s; }
.file-name:hover { color: var(--primary-light); }
.file-path { color: var(--text-muted); font-size: 0.85rem; font-family: 'SF Mono', 'Consolas', 'Liberation Mono', Menlo, monospace; }
.lines-info { text-align: center; }
.lines-covered { font-weight: 700; font-size: 1.1rem; color: var(--text-primary); }
.lines-total { color: var(--text-muted); font-size: 0.85rem; }
.coverage-cell { width: 200px; }
.coverage-bar-container { display: flex; align-items: center; gap: 16px; }
.coverage-bar { flex: 1; height: 10px; background: var(--bg-hover); border-radius: 5px; overflow: hidden; }
.coverage-bar-fill { height: 100%; border-radius: 5px; transition: width 1s ease-out; }
.coverage-bar-fill.high { background: linear-gradient(90deg, var(--success) 0%, var(--success-light) 100%); }
.coverage-bar-fill.medium { background: linear-gradient(90deg, var(--warning) 0%, var(--warning-light) 100%); }
.coverage-bar-fill.low { background: linear-gradient(90deg, var(--danger) 0%, var(--danger-light) 100%); }
.coverage-percent { font-weight: 700; font-size: 1rem; min-width: 50px; text-align: right; }
.coverage-percent.high { color: var(--success); }
.coverage-percent.medium { color: var(--warning); }
.coverage-percent.low { color: var(--danger); }
.view-btn { display: inline-flex; align-items: center; gap: 8px; padding: 10px 20px; background: var(--bg-hover); border: 1px solid var(--border); border-radius: 8px; color: var(--text-primary); text-decoration: none; font-size: 0.9rem; font-weight: 500; transition: all 0.2s; }
.view-btn:hover { background: var(--primary); border-color: var(--primary); }
.footer { max-width: 1400px; margin: 0 auto; padding: 40px 30px; text-align: center; border-top: 1px solid var(--border); }
.footer-content { display: flex; justify-content: center; align-items: center; gap: 10px; flex-wrap: wrap; }
.footer-text { color: var(--text-muted); font-size: 0.9rem; }
.footer-link { color: var(--primary-light); text-decoration: none; font-weight: 500; transition: color 0.2s; }
.footer-link:hover { color: var(--primary); }
.footer-divider { width: 4px; height: 4px; background: var(--text-muted); border-radius: 50%; }
@media (max-width: 768px) {
.header-content { padding: 30px 20px; } .header-title { font-size: 1.8rem; }
.main { padding: 30px 20px; }
.gauge-section { flex-direction: column; padding: 30px; gap: 30px; }
.gauge-container { width: 160px; height: 160px; }
.gauge-text { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 100%; }
.gauge-percent { font-size: 2.5rem; line-height: 1; margin: 0; }
.gauge-label { font-size: 0.75rem; letter-spacing: 1.5px; margin: 0; }
.metrics-inline { flex-direction: column; gap: 10px; align-items: flex-start; }
.files-table th, .files-table td { padding: 15px; }
.coverage-cell { width: auto; }
.coverage-bar-container { flex-direction: column; align-items: flex-start; gap: 8px; }
.coverage-bar { width: 100%; }
}
</style>
</head>
<body>
<header class="header">
<div class="header-content">
<div class="header-top">
<div class="logo">
<img src="https://bashunit.typeddevs.com/logo.svg" alt="bashunit">
<div class="logo-text">bashunit <span>coverage</span></div>
</div>
EOF
echo " <div class=\"header-badge\">v${BASHUNIT_VERSION:-0.0.0}</div>"
cat << 'EOF'
</div>
<h1 class="header-title">Code Coverage Report</h1>
<p class="header-subtitle">Comprehensive line-by-line coverage analysis for your bash scripts</p>
</div>
</header>
<main class="main">
<section class="gauge-section">
<div class="gauge-container">
<svg viewBox="0 0 160 160" width="200" height="200">
<defs>
<linearGradient id="gaugeGradient" x1="0%" y1="0%" x2="100%" y2="0%">
EOF
echo " <stop offset=\"0%\" style=\"stop-color:${gauge_color_start}\"/>"
echo " <stop offset=\"100%\" style=\"stop-color:${gauge_color_end}\"/>"
cat << 'EOF'
</linearGradient>
</defs>
<circle class="gauge-bg" cx="80" cy="80" r="70"/>
EOF