-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathubs
More file actions
executable file
·3750 lines (3512 loc) · 148 KB
/
Copy pathubs
File metadata and controls
executable file
·3750 lines (3512 loc) · 148 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
# ─────────────────────────────────────────────────────────────────────────────
# UBS Meta-Runner (v1.0)
# Unified dispatcher for Ultimate Bug Scanner across JS/TS, Python, C/C++, Rust, Go, Java, Ruby, Swift, C#, Elixir
# - Detects languages
# - Ensures modules (lazy download)
# - Runs modules concurrently
# - Merges outputs (text/json/sarif) with jq
# ─────────────────────────────────────────────────────────────────────────────
# ─────────────────────────────────────────────────────────────────────────────
# Bail early on ancient bash (macOS ships bash 3.2 which lacks associative
# arrays, `declare -A`, `readarray`, etc.). Keep this check before `set -E`
# so it works even under the stock /bin/bash.
# ─────────────────────────────────────────────────────────────────────────────
if [ "${BASH_VERSINFO[0]:-0}" -lt 4 ]; then
echo "ERROR: UBS requires bash >= 4.0 (you have ${BASH_VERSION:-unknown})." >&2
echo "" >&2
echo "macOS ships bash 3.2 due to licensing. Install a modern bash with:" >&2
echo " brew install bash" >&2
echo "" >&2
echo "Then re-run this script with: /opt/homebrew/bin/bash $0 \"\$@\"" >&2
echo "Or add /opt/homebrew/bin/bash to /etc/shells and chsh." >&2
exit 1
fi
set -Eeuo pipefail
shopt -s lastpipe || true
trap '' SIGPIPE 2>/dev/null || true
UBS_VERSION="5.3.7"
# Module / helper fetches must be checksum-stable for an installed
# release, so they pin to the tagged tree matching this script's
# UBS_VERSION. main is reserved for the self-update probe below
# (which is what advances a stale install onto a newer tag).
# Issue #43: pinning to "main" caused every installed copy to break
# the moment main moved past the release the user installed.
REPO_RAW_BASE="https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner"
REPO_RAW="${REPO_RAW_BASE}/v${UBS_VERSION}"
REPO_RAW_LATEST="${REPO_RAW_BASE}/main"
MODULE_PATH_TEMPLATE="$REPO_RAW/modules/ubs-%s.sh"
MODULE_PATH_TEMPLATE_LATEST="$REPO_RAW_LATEST/modules/ubs-%s.sh"
# Known-good module digests (sha256) for supply-chain verification.
declare -A MODULE_CHECKSUMS=(
[cpp]='f054b77189ac66e81fa5c918d4605430272ccb67d9c875f126673182fda85805'
[csharp]='aa49faa22bf85a0cb3da4a667e1ab2d2b8960473ec2f8694aac3dffe9f8861f6'
[elixir]='a231939f444a0f8dc8db97122d08898f589d8cd0dbca4e44197bb16f01b6cae9'
[golang]='a2507466d961932e821465de17ca10571f8be010909fb29db1d032e25a604f77'
[java]='9d6df2d271d7c20caa97248a82ba71d4c14970dd31fc30b0b82c7902269af4a2'
[js]='d410c8e412907be541fd748ea16234dcdaa1b7d70d8a0215beadc75c81a0587d'
[python]='5c14ebdeb0aeb3e79df8e993b83a47460fccb4a7324d896cc5d2523d09dbeb97'
[ruby]='0973251abcd905bb6892ede0448657f460aca67f821ccc97e60645be2a1c5447'
[rust]='26249823d0ddd77ef86aed424dbe587ee53cb3e30c186810a5292d0dae325740'
[swift]='abb8b2e29fa7aa735db056757e6daa4c4b6d618e3251448ed3e9855cf491e9c0'
)
# Helper assets used by some modules (AST correlation and type narrowing).
declare -A HELPER_CHECKSUMS=(
['helpers/async_task_handles_csharp.py']='a1efff32352dab3dafce18e96a39a1bd2fa4085305ba1604a799fbd3e09d3022'
['helpers/resource_lifecycle_cpp.py']='efc9f28047a23246589399309acacea675d2fe2354d011e4c667fdcaebf7dfa8'
['helpers/resource_lifecycle_csharp.py']='6a3562049d3e616781ccf941a56a8abc1925fd6b0d95d510a66a35118ee95f28'
['helpers/resource_lifecycle_go.go']='10215d2c772dd7905a7e9c60a56899a9d702f1c950e1bfd30d4eb90b190e38bd'
['helpers/resource_lifecycle_java.py']='c005da1519eaa751ccf6fa45f99f884aaa30492f91b7c1b527f7f9b782df39f1'
['helpers/resource_lifecycle_py.py']='1e884ff42c988fa6a19f9b8f8375bde2334ebcde61735bc4f10b7dc3c900483e'
['helpers/resource_lifecycle_ruby.py']='beffcd5bcac833e4dba7f49e04e296837846eff46580eab27565d1cb429b1dc2'
['helpers/resource_lifecycle_swift.py']='33a78e83acdffaf0d05b05d240bff5f408d55cd9798d0ae01bd69c36f3afbd0f'
['helpers/type_narrowing_csharp.py']='b9b0c16f67608dfc79addcb44d0638ef7e4af96840220bdd671e98ac1f5ca12c'
['helpers/type_narrowing_kotlin.py']='6f0f4482e8c349d15ac2830956baf193eedd2461d1ef836267c78da86c78ad79'
['helpers/type_narrowing_rust.py']='355ad60ce6dffb9a7c63169cb83705854612c931e2e8c3a166a81b0cb810647f'
['helpers/type_narrowing_swift.py']='f950bafa92391964e4779c77d37dcc11b0ffeab9bc351be439b4709c0f01b41a'
['helpers/type_narrowing_ts.js']='c26e30a0cc2690065bb50d1b17e5d696096dceaa6f3c87a5fcb883260ed3a32b'
)
# ─────────────────────────────────────────────────────────────────────────────
# Capabilities & helpers (must be defined before first use)
# ─────────────────────────────────────────────────────────────────────────────
need_cmd(){ command -v "$1" >/dev/null 2>&1; }
date_iso(){ if [[ "${CI_MODE:-0}" -eq 1 ]]; then date -u '+%Y-%m-%dT%H:%M:%SZ'; else date '+%Y-%m-%d %H:%M:%S'; fi; }
json_escape(){
local s="${1:-}"
s=${s//\\/\\\\}
s=${s//\"/\\\"}
s=${s//$'\n'/\\n}
s=${s//$'\r'/\\r}
s=${s//$'\t'/\\t}
printf '%s' "$s"
}
load_ignore_patterns(){
local file="$1"
[[ -f "$file" ]] || return 0
if ! need_cmd python3; then
say "${YELLOW}${WARN}${RESET} python3 is required to parse ignore file $file (skipping)"
return 0
fi
local csv
csv=$(python3 - "$file" <<'PY' 2>/dev/null
import sys, pathlib
path = pathlib.Path(sys.argv[1])
if not path.exists():
sys.exit(0)
patterns = []
seen = set()
for raw in path.read_text().splitlines():
stripped = raw.strip()
if not stripped or stripped.startswith('#'):
continue
stripped = stripped.rstrip('/')
if stripped.startswith('./'):
stripped = stripped[2:]
if not stripped or stripped in seen:
continue
seen.add(stripped)
patterns.append(stripped)
print(",".join(patterns))
PY
)
csv="${csv//$'\n'/}"
csv="${csv%,}"
if [[ -n "$csv" ]]; then
if [[ -n "$GLOBAL_EXCLUDE_PATTERNS" ]]; then
GLOBAL_EXCLUDE_PATTERNS="$GLOBAL_EXCLUDE_PATTERNS,$csv"
else
GLOBAL_EXCLUDE_PATTERNS="$csv"
fi
local human="${csv//,/ }"
say "${DIM}${INFO}${RESET} Ignoring paths from ${file} → ${human}"
fi
}
HELPER_ASSETS=(
"helpers/async_task_handles_csharp.py"
"helpers/resource_lifecycle_cpp.py"
"helpers/resource_lifecycle_csharp.py"
"helpers/resource_lifecycle_py.py"
"helpers/resource_lifecycle_go.go"
"helpers/resource_lifecycle_java.py"
"helpers/resource_lifecycle_ruby.py"
"helpers/resource_lifecycle_swift.py"
"helpers/type_narrowing_csharp.py"
"helpers/type_narrowing_ts.js"
"helpers/type_narrowing_rust.py"
"helpers/type_narrowing_kotlin.py"
"helpers/type_narrowing_swift.py"
)
HELPERS_READY=0
# Pinned ast-grep release for tool-cache auto-provisioning (JS/TS accuracy).
AST_GREP_VERSION="0.40.1"
AST_GREP_BASE_URL="https://github.com/ast-grep/ast-grep/releases/download/${AST_GREP_VERSION}"
TOOLS_DIR_DEFAULT="${XDG_DATA_HOME:-$HOME/.local/share}/ubs/tools"
TOOLS_DIR="${UBS_TOOLS_DIR:-$TOOLS_DIR_DEFAULT}"
# Known-good ast-grep asset digests (sha256) for supply-chain verification.
declare -A AST_GREP_ASSET_SHA256=(
[aarch64-apple-darwin]='d40d260d6a2c6c6963079e79d3c57e7988b2de08edca7cfa6c270b5fef591dd7'
[x86_64-apple-darwin]='1ffefbce66ceb4eabd307157ca02991d9734adfb43ac9f4b298788e935b6e04a'
[aarch64-unknown-linux-gnu]='24f7d0a99dfa45cf65c6e175e1bceaac24f04d2b84807d832c4205a17d2270ab'
[x86_64-unknown-linux-gnu]='774d6080dedbf8859a51e78d2be1cb84715454627b3995c2ff533ed755975012'
[x86_64-pc-windows-msvc]='4ac3d772c3d87aff8913708219ad3ca73cff2fff4846fd12f9967e87e55fc94e'
)
# Colors (respect NO_COLOR or non-tty)
if [[ -n "${NO_COLOR:-}" || ! -t 1 ]]; then
RED= GREEN= YELLOW= BLUE= MAGENTA= CYAN= WHITE= GRAY= BOLD= DIM= RESET=
else
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'
MAGENTA='\033[0;35m'; CYAN='\033[0;36m'; WHITE='\033[1;37m'; GRAY='\033[0;90m'
BOLD='\033[1m'; DIM='\033[2m'; RESET='\033[0m'
fi
CHECK="✓"; WARN="⚠"; INFO="ℹ"; X="✗"
say(){
if [[ "${FORMAT:-text}" == "json" || "${FORMAT:-text}" == "jsonl" || "${FORMAT:-text}" == "sarif" || "${FORMAT:-text}" == "toon" ]]; then
echo -e "$*" >&2
else
echo -e "$*"
fi
}
say_err(){ echo -e "$*" >&2; }
looks_like_toon_rust_encoder(){
local bin="${1:-}"
[[ -z "$bin" ]] && return 1
# Identify toon_rust by CONTENT, not by basename. Historically the binary was
# named `tru`, but Dicklesworthstone/toon_rust now installs it as `toon`
# (see issue #62), so a basename ban produces false negatives that silently
# fall back to JSON. The Node.js `toon` CLI and upstream toon-format's `toon`
# binary are different projects; they are rejected here because their
# --help/--version output does not carry the signatures matched below.
#
# `tru`/`toon` from toon_rust print, on `--help`:
# "TOON reference implementation in Rust (JSON <-> TOON)"
# and, on `--version`, either "tru X.Y.Z" or "toon X.Y.Z".
local help ver
help="$("$bin" --help 2>&1 | head -n 5 || true)"
if [[ "$help" == *"TOON reference implementation in Rust"* ]]; then
return 0
fi
# Fallback: match the version banner only for the Rust encoder's names.
# (The --help phrase above is the primary, spoofing-resistant signal; this
# only helps if --help is unavailable but --version still identifies it.)
ver="$("$bin" --version 2>&1 | head -n 1 || true)"
if [[ "$ver" =~ ^(tru|toon)[[:space:]][0-9] ]]; then
# A bare "toon X.Y.Z" version banner is also emitted by the unrelated
# Node.js `toon` CLI, so require the --help phrase to have matched for the
# `toon`-named case; only the `tru` name is accepted on version alone.
if [[ "$ver" =~ ^tru[[:space:]][0-9] ]]; then
return 0
fi
fi
return 1
}
print_with_permalinks(){
local file="$1"
if [[ -z "$file" || ! -s "$file" ]]; then return; fi
if [[ -z "$GIT_BLOB_BASE" ]]; then
cat "$file"
return
fi
python3 - "$SOURCE_PROJECT_DIR" "$GIT_BLOB_BASE" "$file" <<'PY' 2>/dev/null || cat "$file"
import sys, pathlib, re
root = pathlib.Path(sys.argv[1]).resolve()
blob = sys.argv[2].rstrip('/')
input_path = pathlib.Path(sys.argv[3])
pattern = re.compile(r'^(\s*)((?:[A-Za-z]:)?[^:]+?):(\d+)(?::(\d+))?')
def to_url(path_str, line):
candidate = pathlib.Path(path_str)
if not candidate.is_absolute():
candidate = root / candidate
try:
resolved = candidate.resolve(strict=True)
except Exception:
return None
if not resolved.is_file():
return None
try:
rel = resolved.relative_to(root)
except Exception:
return None
return f"{blob}/{rel.as_posix()}#L{line}"
with input_path.open('r', encoding='utf-8', errors='ignore') as fh:
for raw in fh:
m = pattern.match(raw)
if not m:
sys.stdout.write(raw)
continue
path_str = (m.group(2) or "").strip()
url = to_url(path_str, m.group(3))
if not url:
sys.stdout.write(raw)
continue
sys.stdout.write(raw.rstrip('\n') + f" ({url})\n")
PY
}
on_err(){ local ec=$? ln=${BASH_LINENO[0]:-?} cmd=${BASH_COMMAND:-?}; say "${RED}${BOLD}Error${RESET}${DIM} (exit $ec)${RESET} ${WHITE}line $ln:${RESET} $cmd"; exit $ec; }
trap on_err ERR
# ─────────────────────────────────────────────────────────────────────────────
# CLI
# ─────────────────────────────────────────────────────────────────────────────
PROJECT_DIR="."
# Format precedence: CLI > UBS_OUTPUT_FORMAT > TOON_DEFAULT_FORMAT > "text"
FORMAT="${UBS_OUTPUT_FORMAT:-${TOON_DEFAULT_FORMAT:-text}}" # text|json|jsonl|sarif|toon
# TOON encoder binary (default: tru from toon_rust; never use the Node.js `toon` CLI)
# Resolution order: TOON_TRU_BIN > TOON_BIN > tru
TOON_BIN="${TOON_TRU_BIN:-${TOON_BIN:-tru}}"
CI_MODE=0
FAIL_ON_WARNING=0
VERBOSE=0
QUIET=0
ONLY_LANGS="" # csv: js,python,cpp,rust
EXCLUDE_LANGS="" # csv
IGNORE_FILE=""
DEFAULT_IGNORES="node_modules,venv,.venv,env,.env,site-packages,dist,build,vendor,target,bin,obj,.idea,.vscode,.git,.hg,.svn,__pycache__,.mypy_cache,.pytest_cache,.ruff_cache,coverage,.gradle,DerivedData,bundler,gems,wheels"
# Safety guards: maximum directory size (MB) and whether to refuse home/root dirs
MAX_DIR_SIZE_MB="${UBS_MAX_DIR_SIZE_MB:-1000}" # 1GB default; set 0 to disable
SKIP_SIZE_CHECK="${UBS_SKIP_SIZE_CHECK:-0}"
REFUSE_HOME_ROOT="${UBS_REFUSE_HOME_ROOT:-1}" # 1 = refuse, 0 = allow
GLOBAL_EXCLUDE_PATTERNS="$DEFAULT_IGNORES"
FILTERED_PROJECT_DIR=""
MODULE_DIR_DEFAULT="${XDG_DATA_HOME:-$HOME/.local/share}/ubs/modules"
MODULE_DIR="$MODULE_DIR_DEFAULT"
UPDATE_MODULES=0
JOBS="${JOBS:-0}"
SKIP_TYPE_NARROWING=0
CSHARP_MODULE_ARGS=()
MODE="scan"
SESSION_ENTRIES=1
SESSION_RAW=0
SESSION_LOG_DIR_OVERRIDE=""
VERIFY_MODULE_ERR=""
VERIFY_HELPER_ERR=""
ALL_LANGS=(js python cpp rust golang java ruby swift csharp elixir)
# Per-language category skip lists, populated by --skip-LANG=N flags.
# Bare --skip=N continues to apply globally via UBS_SKIP_CATEGORIES (issue #52).
declare -A SKIP_BY_LANG=()
# Track whether the user passed a bare --skip=N (separate from --skip-LANG=N)
# so we can warn when it might silence different categories in different
# language modules.
BARE_SKIP_USED=0
UPDATE_ONLY=0
FORCE_SELF_UPDATE=0
CATEGORY_FILTER=""
COMPARISON_FILE=""
REPORT_JSON_PATH=""
HTML_REPORT_PATH=""
SHAREABLE_MODE=0
GIT_MODE="" # staged, diff, or empty
SCAN_FILES=() # explicit file list from --files or multiple positional args
GIT_REMOTE_URL=""
GIT_REMOTE_HTTP=""
GIT_COMMIT_SHA=""
GIT_BLOB_BASE=""
SARIF_AUTOMATION_ID=""
SHOW_VERSION=0
BEADS_JSONL_PATH=""
SUGGEST_IGNORE=0
JSONL_DETAIL=1 # 1=include findings, 0=summary only (for backward compat)
# Tool cache / JS AST engine
AST_GREP_BIN=""
AST_GREP_SOURCE=""
if [[ "${1:-}" == "doctor" ]]; then
MODE="doctor"
shift
elif [[ "${1:-}" == "sessions" || "${1:-}" == "session-log" ]]; then
MODE="sessions"
shift
fi
usage() {
cat <<USAGE >&2
Usage: ubs [options] [PROJECT_DIR]
ubs [options] FILE1 FILE2 ...
ubs --files FILE1,FILE2,... [options] [PROJECT_DIR]
ubs doctor [options]
ubs sessions [--entries N] [--raw]
Options:
--format=FMT text|json|jsonl|sarif|toon (default: text)
--version Print version and exit
--ci CI mode (stable timestamps)
--fail-on-warning Exit non-zero if warnings or critical exist
-v, --verbose Pass -v to child scanners (if supported)
-q, --quiet Reduce console output (also passes -q to scanners)
--only=CSV Restrict to languages: js,python,c,cpp,rust,golang,java,ruby,swift,csharp,cs,elixir,ex
--exclude=CSV Exclude languages
--module-dir=DIR Where to store/lookup modules (default: $MODULE_DIR_DEFAULT)
--category=CSV Focus on category packs (e.g., resource-lifecycle for AST lifecycle analyzers)
--comparison=FILE Baseline JSON to diff combined results against
--report-json=FILE Write combined summary JSON to FILE
--html-report=FILE Emit shareable HTML report to FILE
--beads-jsonl=FILE Also write combined findings to JSONL for Beads/strung
--jsonl-summary-only JSONL output: emit only summary counts, no individual findings
--suggest-ignore Print large-directory ignore suggestions (without modifying files)
--update Update the installed ubs binary and exit
--non-interactive No-op (accepted for installer/cron compatibility)
--update-modules Force re-download of modules before run
--jobs=N Parallelism hint (passed to children if supported)
--ignore-file=PATH Read additional ignore globs (default: PROJECT/.ubsignore if present)
--skip-size-check Skip directory size guard (use with care)
--skip-type-narrowing Skip JS/Rust/Kotlin/Swift/C# type narrowing checks (falls back to basic heuristics)
--skip-LANG=CSV Skip categories in ONE language only (LANG is js/python/cpp/rust/golang/java/ruby/swift/csharp/elixir;
aliases c/cs/ex accepted). Example: --skip-js=8 --skip-rust=3
Use this instead of bare --skip=N in polyglot repos: category numbers are NOT stable across
languages (e.g. JS cat 8 = Function & Scope Issues, Rust cat 8 = SECURITY FINDINGS). Issue #52.
--no-dotnet Pass through to the C# module: skip dotnet checks
--no-build Pass through to the C# module: skip dotnet build
--no-test Pass through to the C# module: skip dotnet test
--no-format Pass through to the C# module: skip dotnet format
--no-deps Pass through to the C# module: skip dotnet package checks
--dotnet-target=PATH Pass through to the C# module: select solution/project for dotnet commands
--no-auto-update Disable auto-update (even if UBS_ENABLE_AUTO_UPDATE=1)
--staged Scan only files staged for commit (git index)
--diff, --git-diff Scan only modified files (working tree vs HEAD)
--files=F1,F2,... Scan only the listed files (comma or space separated)
-h, --help Show this help
Environment Variables:
UBS_OUTPUT_FORMAT=FMT Default output format (text|json|jsonl|sarif|toon)
Overridden by --format CLI flag
TOON_DEFAULT_FORMAT=FMT Global fallback format if UBS_OUTPUT_FORMAT not set
TOON_TRU_BIN=PATH Explicit path to tru encoder (overrides TOON_BIN)
TOON_BIN=PATH TOON encoder binary (default: tru)
Set to a specific toon_rust encoder path if needed (do not use Node.js toon)
UBS_MAX_DIR_SIZE_MB=N Max directory size in MB before refusing to scan (default: 1000)
Set to 0 to disable this safety check
UBS_SKIP_SIZE_CHECK=1 Skip directory size guard entirely
UBS_REFUSE_HOME_ROOT=0|1 Whether to refuse scanning \$HOME or / (default: 1)
Set to 0 to allow scanning these directories
Examples:
ubs . # auto-detect languages and scan
ubs --staged # scan only staged files (pre-commit style)
ubs --diff # scan only modified files (quick check)
ubs --files=a.js,b.py . # scan specific files in current dir
ubs src/a.js src/b.py # multiple positional args (same effect)
ubs --format=json --ci . # machine-readable combined JSON
ubs --format=toon . # TOON format (~50% smaller than JSON)
ubs --only=js,python . # restrict language set
ubs doctor --fix # validate cached modules & redownload corrupted copies
ubs sessions --entries 1 # view the most recent installer summary
UBS_OUTPUT_FORMAT=toon ubs . # set default format via env var
UBS_MAX_DIR_SIZE_MB=0 ubs . # disable size check for large directories
USAGE
}
doctor_usage(){
cat <<DOC >&2
Usage: ubs doctor [options]
Options:
--module-dir=DIR Override the module cache directory (default: $MODULE_DIR_DEFAULT)
--fix Automatically download or refresh cached modules
-h, --help Show this help message
DOC
}
sessions_usage(){
cat <<SESS >&2
Usage: ubs sessions [options]
Options:
--entries=N Show the last N install sessions (default: 1)
--raw Print the entire session log as-is
--config-dir=DIR Override the config directory (defaults to \$XDG_CONFIG_HOME/ubs)
-h, --help Show this help message
SESS
}
show_session_history(){
local entries="$1"
local raw="$2"
local override="$3"
local base_dir
if [[ -n "$override" ]]; then
base_dir="$override"
else
base_dir="${XDG_CONFIG_HOME:-$HOME/.config}/ubs"
fi
local log_file="$base_dir/session.md"
if [[ ! -f "$log_file" ]]; then
say "${RED}$X no session history found${RESET} (expected at ${log_file})"
exit 1
fi
local entries_int=1
if [[ "$entries" =~ ^[0-9]+$ ]]; then
entries_int="$entries"
fi
if [[ "$entries_int" -lt 1 ]]; then
entries_int=1
fi
if [[ "$raw" -eq 1 ]]; then
say "${BLUE}${INFO}${RESET} Showing session log from ${log_file}"
cat "$log_file"
exit 0
fi
if ! need_cmd python3; then
say "${RED}$X python3 required${RESET} to format session history"
exit 1
fi
say "${BLUE}${INFO}${RESET} Showing last ${entries_int} session(s) from ${log_file}"
python3 - "$log_file" "$entries_int" <<'PY' 2>/dev/null
import sys, pathlib
from itertools import islice
path = pathlib.Path(sys.argv[1])
entries = max(1, int(sys.argv[2]))
text = path.read_text(encoding='utf-8', errors='ignore').strip()
if not text:
print("No session entries recorded.")
sys.exit(1)
sections = [block.strip() for block in text.split('\n---\n') if block.strip()]
if not sections:
print("No session entries recorded.")
sys.exit(1)
subset = sections[-entries:]
for idx, block in enumerate(subset):
print(block)
if idx != len(subset) - 1:
print("\n---\n")
PY
}
DOCTOR_FIX=0
if [[ "$MODE" == "doctor" ]]; then
while [[ $# -gt 0 ]]; do
case "$1" in
--module-dir=*) MODULE_DIR="${1#*=}"; shift;;
--module-dir)
if [[ $# -lt 2 ]]; then doctor_usage; exit 2; fi
shift; MODULE_DIR="$1"; shift;;
--fix) DOCTOR_FIX=1; shift;;
-h|--help) doctor_usage; exit 0;;
*)
say "${RED}$X unknown doctor option${RESET}: $1"
doctor_usage
exit 2
;;
esac
done
elif [[ "$MODE" == "sessions" ]]; then
while [[ $# -gt 0 ]]; do
case "$1" in
--entries=*) SESSION_ENTRIES="${1#*=}"; shift;;
--entries)
if [[ $# -lt 2 ]]; then sessions_usage; exit 2; fi
shift; SESSION_ENTRIES="$1"; shift;;
--raw) SESSION_RAW=1; shift;;
--config-dir=*) SESSION_LOG_DIR_OVERRIDE="${1#*=}"; shift;;
--config-dir)
if [[ $# -lt 2 ]]; then sessions_usage; exit 2; fi
shift; SESSION_LOG_DIR_OVERRIDE="$1"; shift;;
-h|--help) sessions_usage; exit 0;;
*)
say "${RED}$X unknown sessions option${RESET}: $1"
sessions_usage
exit 2
;;
esac
done
else
while [[ $# -gt 0 ]]; do
case "$1" in
--format=*) FORMAT="${1#*=}"; shift;;
--version|-V) SHOW_VERSION=1; shift;;
--ci) CI_MODE=1; shift;;
--fail-on-warning) FAIL_ON_WARNING=1; shift;;
-v|--verbose) VERBOSE=1; shift;;
-q|--quiet) QUIET=1; shift;;
--update) UPDATE_ONLY=1; FORCE_SELF_UPDATE=1; shift;;
--non-interactive) shift;;
--only=*) ONLY_LANGS="${1#*=}"; shift;;
--exclude=*) EXCLUDE_LANGS="${1#*=}"; shift;;
--category=*) CATEGORY_FILTER="${1#*=}"; shift;;
--category)
if [[ $# -lt 2 ]]; then usage; exit 2; fi
shift; CATEGORY_FILTER="$1"; shift;;
--comparison=*|--baseline=*) COMPARISON_FILE="${1#*=}"; SHAREABLE_MODE=1; SARIF_AUTOMATION_ID="ubs-comparison"; shift;;
--comparison|--baseline)
if [[ $# -lt 2 ]]; then usage; exit 2; fi
shift; COMPARISON_FILE="$1"; SHAREABLE_MODE=1; SARIF_AUTOMATION_ID="ubs-comparison"; shift;;
--report-json=*) REPORT_JSON_PATH="${1#*=}"; SHAREABLE_MODE=1; shift;;
--report-json)
if [[ $# -lt 2 ]]; then usage; exit 2; fi
shift; REPORT_JSON_PATH="$1"; SHAREABLE_MODE=1; shift;;
--html-report=*) HTML_REPORT_PATH="${1#*=}"; SHAREABLE_MODE=1; shift;;
--html-report)
if [[ $# -lt 2 ]]; then usage; exit 2; fi
shift; HTML_REPORT_PATH="$1"; SHAREABLE_MODE=1; shift;;
--beads-jsonl=*) BEADS_JSONL_PATH="${1#*=}"; shift;;
--beads-jsonl)
if [[ $# -lt 2 ]]; then usage; exit 2; fi
shift; BEADS_JSONL_PATH="$1"; shift;;
--suggest-ignore) SUGGEST_IGNORE=1; shift;;
--jsonl-summary-only) JSONL_DETAIL=0; shift;;
--ignore-file=*) IGNORE_FILE="${1#*=}"; shift;;
--skip-size-check) SKIP_SIZE_CHECK=1; shift;;
--module-dir=*) MODULE_DIR="${1#*=}"; shift;;
--module-dir)
if [[ $# -lt 2 ]]; then usage; exit 2; fi
shift; MODULE_DIR="$1"; shift;;
--update-modules) UPDATE_MODULES=1; shift;;
--jobs=*) JOBS="${1#*=}"; shift;;
--skip-type-narrowing) SKIP_TYPE_NARROWING=1; shift;;
--no-dotnet|--no-build|--no-test|--no-format|--no-deps)
CSHARP_MODULE_ARGS+=("$1")
shift;;
--dotnet-target=*)
CSHARP_MODULE_ARGS+=("$1")
shift;;
--dotnet-target)
if [[ $# -lt 2 ]]; then usage; exit 2; fi
CSHARP_MODULE_ARGS+=("$1" "$2")
shift 2;;
--no-auto-update) export UBS_NO_AUTO_UPDATE=1; shift;;
--staged) GIT_MODE="staged"; shift;;
--diff|--git-diff) GIT_MODE="diff"; shift;;
--files=*) IFS=',' read -r -a _f <<<"${1#*=}"; SCAN_FILES+=("${_f[@]}"); shift;;
--files)
if [[ $# -lt 2 ]]; then usage; exit 2; fi
shift; IFS=',' read -r -a _f <<<"$1"; SCAN_FILES+=("${_f[@]}"); shift;;
--profile=*)
export UBS_PROFILE="${1#*=}"
if [[ "$UBS_PROFILE" == "strict" ]]; then FAIL_ON_WARNING=1; fi
shift;;
--skip=*)
export UBS_SKIP_CATEGORIES="${1#*=}"
BARE_SKIP_USED=1
shift;;
--skip-*=*)
# --skip-LANG=N[,M,...] applies only to the matching language module
# (issue #52). LANG accepts the same aliases as --only / --exclude
# (e.g. --skip-c is normalized to --skip-cpp at run time, after the
# normalize_lang helper is defined). The earlier --skip-size-check /
# --skip-type-narrowing arms above shadow this glob for those flags.
_sk_lang_key="${1#--skip-}"
_sk_lang_key="${_sk_lang_key%%=*}"
_sk_lang_val="${1#*=}"
if [[ -n "${SKIP_BY_LANG[$_sk_lang_key]:-}" ]]; then
SKIP_BY_LANG["$_sk_lang_key"]="${SKIP_BY_LANG[$_sk_lang_key]},$_sk_lang_val"
else
SKIP_BY_LANG["$_sk_lang_key"]="$_sk_lang_val"
fi
unset _sk_lang_key _sk_lang_val
shift;;
-h|--help) usage; exit 0;;
*)
if [[ "$PROJECT_DIR" == "." ]]; then
# First positional arg: could be a directory OR a file
if [[ -d "$1" ]]; then
PROJECT_DIR="$1"
else
SCAN_FILES+=("$1")
fi
else
# Additional positional args: accumulate as files
SCAN_FILES+=("$1")
fi
shift;;
esac
done
if [[ "$UPDATE_ONLY" -eq 1 ]]; then
PROJECT_DIR="$(pwd -P)"
else
if [[ -d "$PROJECT_DIR" ]]; then
if ! PROJECT_DIR="$(cd "$PROJECT_DIR" 2>/dev/null && pwd -P)"; then
say "${RED}$X cannot access project directory${RESET}: $PROJECT_DIR"
exit 2
fi
elif [[ -f "$PROJECT_DIR" ]]; then
proj_dir="$(dirname "$PROJECT_DIR")"
proj_base="$(basename "$PROJECT_DIR")"
if ! proj_dir="$(cd "$proj_dir" 2>/dev/null && pwd -P)"; then
say "${RED}$X cannot access project path${RESET}: $PROJECT_DIR"
exit 2
fi
PROJECT_DIR="$proj_dir/$proj_base"
else
say "${RED}$X path not found${RESET}: $PROJECT_DIR"
exit 2
fi
fi
fi
SOURCE_PROJECT_DIR="$PROJECT_DIR"
TARGETED_SCAN_MODE=0
if [[ -n "$GIT_MODE" || ${#SCAN_FILES[@]} -gt 0 ]]; then
TARGETED_SCAN_MODE=1
fi
RUN_SCAN_GUARDS=0
if [[ "$MODE" == "scan" && "$UPDATE_ONLY" -eq 0 ]]; then
RUN_SCAN_GUARDS=1
fi
if [[ "$SHOW_VERSION" -eq 1 ]]; then
short_sha=""
if git rev-parse --short HEAD >/dev/null 2>&1; then
short_sha="$(git rev-parse --short HEAD 2>/dev/null || true)"
fi
say "UBS Meta-Runner v${UBS_VERSION}${short_sha:+ (git $short_sha)}"
exit 0
fi
# Load ignore patterns early so size checks can respect .ubsignore
if [[ "$MODE" != "doctor" && "$UPDATE_ONLY" -eq 0 ]]; then
if [[ -z "$IGNORE_FILE" && -f "$SOURCE_PROJECT_DIR/.ubsignore" ]]; then
IGNORE_FILE="$SOURCE_PROJECT_DIR/.ubsignore"
fi
if [[ -n "$IGNORE_FILE" ]]; then
load_ignore_patterns "$IGNORE_FILE"
fi
fi
# ─────────────────────────────────────────────────────────────────────────────
# Safety guards: prevent disk exhaustion when scanning large or sensitive dirs
# Fixes GitHub issue #12: UBS copies entire scan directory to /tmp
# ─────────────────────────────────────────────────────────────────────────────
# Check 1: Refuse to scan home directory or root (unless explicitly allowed)
if [[ "$RUN_SCAN_GUARDS" -eq 1 && "$TARGETED_SCAN_MODE" -eq 0 && "$REFUSE_HOME_ROOT" -eq 1 && -d "$SOURCE_PROJECT_DIR" ]]; then
resolved_dir="$(cd "$SOURCE_PROJECT_DIR" 2>/dev/null && pwd -P)"
if [[ "$resolved_dir" == "$HOME" ]]; then
say "${RED}${X}${RESET} ${BOLD}Refusing to scan home directory${RESET}"
say "${DIM}UBS copies the scan target to /tmp, which can exhaust disk space on large directories.${RESET}"
say "${DIM}If you really want to scan \$HOME, set${RESET} UBS_REFUSE_HOME_ROOT=0"
exit 2
fi
if [[ "$resolved_dir" == "/" ]]; then
say "${RED}${X}${RESET} ${BOLD}Refusing to scan root directory${RESET}"
say "${DIM}UBS copies the scan target to /tmp, which can exhaust disk space.${RESET}"
say "${DIM}If you really want to scan /, set${RESET} UBS_REFUSE_HOME_ROOT=0"
exit 2
fi
fi
dir_size_mb_filtered(){
local dir="$1"
local patterns_csv="${2:-}"
local result=""
local du_can_exclude=0
if need_cmd du; then
local -a du_args=()
if [[ -n "$patterns_csv" ]] && du --help 2>/dev/null | grep -q -- '--exclude'; then
# du --exclude matches patterns against each entry's basename, not the
# full relative path. Path-based patterns (containing '/') silently
# fail to match anything, causing the size calculation to ignore the
# exclusion entirely (GitHub issue #16). Detect this and fall through
# to the Python fallback which handles path-based patterns correctly.
local has_path_pattern=0
local -a pats=()
IFS=',' read -r -a pats <<<"$patterns_csv"
for pat in "${pats[@]}"; do
if [[ -n "$pat" ]]; then
du_args+=( "--exclude=$pat" )
[[ "$pat" == */* ]] && has_path_pattern=1
fi
done
[[ "$has_path_pattern" -eq 0 ]] && du_can_exclude=1
fi
# Only use du when no patterns are needed or du supports --exclude
# AND all patterns are simple (no path separators); otherwise fall
# through to the Python fallback which handles exclusions correctly
# on all platforms (fixes macOS/BSD du which lacks --exclude, and
# path-based patterns which du --exclude silently ignores — #16).
if [[ -z "$patterns_csv" || "$du_can_exclude" -eq 1 ]]; then
result=$(du -sm "${du_args[@]}" "$dir" 2>/dev/null | cut -f1)
if [[ "$result" =~ ^[0-9]+$ ]]; then
echo "$result"
return 0
fi
result=$(du -sk "${du_args[@]}" "$dir" 2>/dev/null | cut -f1)
if [[ "$result" =~ ^[0-9]+$ ]]; then
echo $((result / 1024))
return 0
fi
fi
fi
if need_cmd python3; then
python3 - "$dir" "$patterns_csv" <<'PY'
import fnmatch
import os
import pathlib
import sys
root = pathlib.Path(sys.argv[1]).resolve()
patterns_csv = sys.argv[2] if len(sys.argv) > 2 else ""
patterns = [p for p in patterns_csv.split(",") if p]
def excluded(rel_path, name):
for pat in patterns:
if fnmatch.fnmatch(rel_path, pat) or fnmatch.fnmatch(name, pat):
return True
for part in pathlib.Path(rel_path).parts:
if fnmatch.fnmatch(part, pat):
return True
return False
total = 0
for base, dirs, files in os.walk(root, topdown=True):
rel_root = os.path.relpath(base, root)
pruned = []
for d in dirs:
rel = os.path.join(rel_root, d) if rel_root != "." else d
if excluded(rel, d):
continue
pruned.append(d)
dirs[:] = pruned
for f in files:
rel = os.path.join(rel_root, f) if rel_root != "." else f
if excluded(rel, f):
continue
try:
total += (pathlib.Path(base) / f).stat().st_size
except OSError:
pass
print(int(total / 1024 / 1024))
PY
return 0
fi
echo "0"
}
# Check 2: Refuse directories larger than MAX_DIR_SIZE_MB (unless set to 0)
if [[ "$RUN_SCAN_GUARDS" -eq 1 && "$TARGETED_SCAN_MODE" -eq 0 && "$SKIP_SIZE_CHECK" -eq 0 && "$MAX_DIR_SIZE_MB" -gt 0 && -d "$SOURCE_PROJECT_DIR" ]]; then
dir_size_mb="$(dir_size_mb_filtered "$SOURCE_PROJECT_DIR" "$GLOBAL_EXCLUDE_PATTERNS")"
if [[ "${QUIET:-0}" -eq 0 ]]; then
say "${DIM}${INFO}${RESET} Scan size after ignores: ${dir_size_mb}MB (limit ${MAX_DIR_SIZE_MB}MB)"
fi
if [[ "$dir_size_mb" -gt "$MAX_DIR_SIZE_MB" ]]; then
say "${RED}${X}${RESET} ${BOLD}Directory too large (after ignores)${RESET}: ${dir_size_mb}MB exceeds limit of ${MAX_DIR_SIZE_MB}MB"
say "${DIM}UBS copies the scan target to /tmp before analysis, which can exhaust disk space.${RESET}"
say "${DIM}This safety check prevents accidental scans of large directories like \$HOME.${RESET}"
say ""
say "${DIM}Options:${RESET}"
say "${DIM} • Scan a smaller subdirectory instead${RESET}"
say "${DIM} • Increase the limit:${RESET} UBS_MAX_DIR_SIZE_MB=5000 ubs ..."
say "${DIM} • Disable the check:${RESET} UBS_MAX_DIR_SIZE_MB=0 ubs ..."
exit 2
fi
fi
if [[ -n "$CATEGORY_FILTER" ]]; then
CATEGORY_FILTER="${CATEGORY_FILTER,,}"
if [[ "$CATEGORY_FILTER" == "resource-lifecycle" ]]; then
SHAREABLE_MODE=$((SHAREABLE_MODE+0))
if [[ -z "$ONLY_LANGS" ]]; then
ONLY_LANGS="python,golang,java,swift,csharp"
fi
export UBS_CATEGORY_FILTER="$CATEGORY_FILTER"
else
say "${YELLOW}${WARN}${RESET} Unknown category filter: $CATEGORY_FILTER"
CATEGORY_FILTER=""
unset UBS_CATEGORY_FILTER
fi
else
unset UBS_CATEGORY_FILTER
fi
ensure_dir(){ mkdir -p "$1" 2>/dev/null || { say "${RED}$X cannot create $1${RESET}"; exit 1; }; }
script_dir(){
# Resolve the real directory of this script, following symlinks.
# Critical for macOS Homebrew where /opt/homebrew/bin/ubs is a relative
# symlink (e.g. ../Cellar/ubs/5.0.7/bin/ubs). We must resolve the
# relative target against the *symlink's* parent dir, not CWD.
#
# The set -E (errtrace) flag causes the ERR trap to fire inside
# functions. Guard every cd so a failed cd never triggers on_err
# and kills the script.
# Fast path: use realpath if available (Linux, macOS 12.3+, Homebrew coreutils)
local self="${BASH_SOURCE[0]}"
if command -v realpath >/dev/null 2>&1; then
local rp
rp="$(realpath "$self" 2>/dev/null)" || true
if [[ -n "$rp" ]]; then
dirname "$rp"
return 0
fi
fi
# Fallback: manual symlink-chase loop
local source="$self"
while [ -L "$source" ]; do
local link_dir
link_dir="$(cd -P "$(dirname "$source")" 2>/dev/null && pwd)" || link_dir=""
source="$(readlink "$source")" || true
# If readlink returned a relative path, resolve it against the
# directory that contained the symlink we just read.
if [[ "$source" != /* && -n "$link_dir" ]]; then
source="$link_dir/$source"
fi
done
# Use dirname + cd -P to canonicalize; || true prevents ERR trap on failure
local resolved
resolved="$(cd -P "$(dirname "$source")" 2>/dev/null && pwd)" || true
if [[ -n "$resolved" ]]; then
echo "$resolved"
else
# Last resort: return dirname as-is (non-canonical but usable)
dirname "$source"
fi
}
prepare_metrics_dir(){
local dir="$1"
rm -rf "$dir" 2>/dev/null || true
mkdir -p "$dir" 2>/dev/null || true
}
finalize_module_dir(){
local configured="${MODULE_DIR:-}"
if [[ -z "$configured" ]]; then
MODULE_DIR="$MODULE_DIR_DEFAULT"
else
MODULE_DIR="$configured"
while [[ "$MODULE_DIR" == */ && "$MODULE_DIR" != "/" ]]; do
MODULE_DIR="${MODULE_DIR%/}"
done
[[ -z "$MODULE_DIR" ]] && MODULE_DIR="$MODULE_DIR_DEFAULT"
fi
ensure_dir "$MODULE_DIR"
local resolved
if resolved=$(cd "$MODULE_DIR" 2>/dev/null && pwd -P); then
MODULE_DIR="$resolved"
fi
}
resolve_git_metadata(){
local root
if ! root=$(git -C "$SOURCE_PROJECT_DIR" rev-parse --show-toplevel 2>/dev/null); then
return
fi
local remote commit
remote=$(git -C "$root" config --get remote.origin.url 2>/dev/null || true)
commit=$(git -C "$root" rev-parse HEAD 2>/dev/null || true)
[[ -n "$remote" && -n "$commit" ]] || return
GIT_REMOTE_URL="$remote"
GIT_COMMIT_SHA="$commit"
GIT_REMOTE_HTTP=""
case "$remote" in
git@github.com:*)
local path_part=${remote#git@github.com:}
path_part=${path_part%.git}
GIT_REMOTE_HTTP="https://github.com/${path_part}"
GIT_BLOB_BASE="https://github.com/${path_part}/blob/${commit}"
;;
https://github.com/*)
local path_part=${remote#https://github.com/}
path_part=${path_part%.git}
GIT_REMOTE_HTTP="https://github.com/${path_part}"
GIT_BLOB_BASE="https://github.com/${path_part}/blob/${commit}"
;;
git://github.com/*)
local path_part=${remote#git://github.com/}
path_part=${path_part%.git}
GIT_REMOTE_HTTP="https://github.com/${path_part}"
GIT_BLOB_BASE="https://github.com/${path_part}/blob/${commit}"
;;
*)
GIT_BLOB_BASE=""
;;
esac
}
prepare_git_workspace(){
local mode="$1"
if ! need_cmd git; then
say "${RED}$X git not found; cannot run --$mode${RESET}"
exit 1
fi
local scan_root="$SOURCE_PROJECT_DIR"
if [[ -f "$scan_root" ]]; then
scan_root="$(dirname "$scan_root")"
fi
local repo_root
if ! repo_root="$(git -C "$scan_root" rev-parse --show-toplevel 2>/dev/null)"; then
say "${RED}$X not a git repository; cannot run --$mode${RESET}"
exit 1
fi
local scan_rel=""
if [[ "$scan_root" == "$repo_root" ]]; then
scan_rel=""
elif [[ "$scan_root" == "$repo_root/"* ]]; then
scan_rel="${scan_root#"$repo_root"/}"
else
say "${RED}$X scan path is outside git root; cannot run --$mode${RESET}"
exit 1
fi
local raw_files=()
if [[ "$mode" == "staged" ]]; then
while IFS= read -r file; do [[ -n "$file" ]] && raw_files+=("$file"); done < <(
git -C "$repo_root" diff --name-only --cached --diff-filter=ACMR
)
else
while IFS= read -r file; do [[ -n "$file" ]] && raw_files+=("$file"); done < <(
git -C "$repo_root" diff --name-only --diff-filter=ACMR HEAD
)
fi
local files=()
if [[ -n "$scan_rel" ]]; then
for file in "${raw_files[@]}"; do
if [[ "$file" == "$scan_rel/"* ]]; then
files+=("${file#"$scan_rel"/}")
fi
done
else
files=("${raw_files[@]}")
fi
# Apply .ubsignore / GLOBAL_EXCLUDE_PATTERNS filtering to the staged file list
# so that ignored paths are never copied into the shadow workspace.
if [[ -n "$GLOBAL_EXCLUDE_PATTERNS" && ${#files[@]} -gt 0 ]] && need_cmd python3; then
local filtered_csv
filtered_csv=$(printf '%s\n' "${files[@]}" | python3 -c "
import sys, fnmatch, pathlib
patterns = sys.argv[1].split(',')
for line in sys.stdin:
f = line.rstrip('\n')
if not f:
continue
name = pathlib.PurePosixPath(f).name
excluded = False