Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / search

search233 lines · 8.6 KiBRaw
1#!/usr/bin/env bash
2# Scoped string search for the Modern-Apps monorepo. Bash only, no dependencies
3# beyond rg (falls back to grep).
4#
5# Usage:
6# ./search PATTERN [-m MODULE ...] [-p PACKAGE ...] [-i] [--max N] [--files-only]
7#
8# A string (regex) search with two optional filters that compose:
9# ./search DB_NAME -m notes -p data # both: data/ package of notes/ only
10# ./search RoomRepository -m notes # module only
11# ./search TrustBundle -m web -p network # module + package combined
12# ./search "foo" -m voxels # shorthand -> games:voxels
13# ./search "bar" -m notes --files-only --max 20
14# ./search TrustBundle # no filter: repo-wide (junk dirs excluded)
15#
16# -m/--module Repeatable, comma-separated. Slash == colon
17# (games/voxels == games:voxels), shorthand (voxels -> games:voxels),
18# or 'all' (every dir with build.gradle.kts).
19# -p/--package Repeatable, comma-separated root package (ui data domain platform
20# network intents service provider widget notifications auth sync
21# telephony). Searches only <module>/src/main/{java,kotlin}/**/<pkg>/.
22# Needs -m; without it a warning is printed and it is ignored.
23# -i Case-insensitive. --max N caps output lines (default 200).
24# --files-only Print matching file paths, no contents.
25#
26# Always excluded: target/ build/ .gradle/ .kotlin/ .git/ .llms/ analysis/
27# *.log *.onnx metadata_data/photos/. Exit code is 0 on success even with no
28# matches; 1 when every -m value is unknown; 2 on bad regex.
29set -euo pipefail
30
31SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
32ROOT="$SCRIPT_DIR"
33MAX_COLS=220
34DEFAULT_MAX=200
35KNOWN_PACKAGES="ui data domain platform network intents service provider widget notifications auth sync telephony"
36
37print_help() {
38 sed -n '2,/^set -euo/p' "$SCRIPT_DIR/search" | sed 's/^# \{0,1\}//' | head -n -1
39}
40
41normalize_module() {
42 local m="$1"
43 m="$(echo "$m" | xargs)"
44 m="$(echo "$m" | sed -e 's|^[/:]*||' -e 's|[/:]*$||')"
45 m="$(echo "$m" | tr '/' ':')"
46 while echo "$m" | grep -q "::"; do m="$(echo "$m" | sed 's/::/:/g')"; done
47 echo "$m" | tr '[:upper:]' '[:lower:]'
48}
49
50all_module_dirs() {
51 grep -E 'include\(":[^"]+"\)' "$ROOT/settings.gradle.kts" 2>/dev/null \
52 | sed -E 's/.*include\(":([^"]+)"\).*/\1/' \
53 | sed -E 's/^://; s/:/\//g' \
54 | while IFS= read -r p; do
55 case "$p" in "" ) continue;; esac
56 [[ -f "$ROOT/$p/build.gradle.kts" ]] && echo "$p"
57 done | sort -u
58}
59
60HAS_RG=0
61command -v rg >/dev/null 2>&1 && HAS_RG=1
62
63run_rg() { # pattern, then dirs; prints matches, returns 0 (none) or 2 (bad regex)
64 local pat="$1"; shift
65 # NB: '//' not '/': MSYS2/git-bash expands a lone '/' to the install root.
66 # rg itself suggests this (see: rg error for --path-separator on Windows).
67 local -a args=(--no-heading --line-number --color never --hidden --path-separator=//
68 -g '!target/**' -g '!build/**' -g '!.gradle/**' -g '!.kotlin/**'
69 -g '!.git/**' -g '!.llms/**' -g '!analysis/**'
70 -g '!*.log' -g '!*.onnx' -g '!metadata_data/photos/**'
71 --max-columns "$MAX_COLS")
72 [[ "$IGNORE_CASE" -eq 1 ]] && args+=(-i)
73 local out rc=0
74 out=$(rg "${args[@]}" -e "$pat" -- "$@" 2>/dev/null) || rc=$?
75 if [[ $rc -eq 2 ]]; then echo "error: bad regex: $pat" >&2; return 2; fi
76 [[ -n "$out" ]] && printf '%s\n' "$out"
77 return 0
78}
79
80run_grep() { # pattern, then dirs (fallback when rg is missing)
81 local pat="$1"; shift
82 local -a gopts=(-rn)
83 [[ "$IGNORE_CASE" -eq 1 ]] && gopts+=(-i)
84 grep "${gopts[@]}" -e "$pat" \
85 --exclude-dir=target --exclude-dir=build --exclude-dir=.gradle \
86 --exclude-dir=.kotlin --exclude-dir=.git --exclude-dir=.llms \
87 --exclude-dir=analysis --exclude='*.log' --exclude='*.onnx' \
88 "$@" 2>/dev/null | grep -v -e '/target/' -e '/build/' -e 'metadata_data/photos/' \
89 | cut -c1-"$MAX_COLS" || true
90}
91
92pkg_dirs_for() { # mod, pkg... -> prints existing package-root dirs (deduped)
93 local mod="$1"; shift
94 local -a found=()
95 local lang base d
96 for lang in java kotlin; do
97 base="$mod/src/main/$lang"
98 [[ -d "$ROOT/$base" ]] || continue
99 for pkg in "$@"; do
100 while IFS= read -r d; do found+=("$d"); done \
101 < <(find "$base" -type d -name "$pkg" 2>/dev/null)
102 done
103 done
104 # drop dirs subsumed by another match (e.g. data/ inside data/)
105 local a b skip
106 if [[ ${#found[@]} -gt 0 ]]; then
107 for a in "${found[@]}"; do
108 skip=0
109 for b in "${found[@]}"; do
110 [[ "$a" != "$b" && "$a" == "$b"/* ]] && { skip=1; break; }
111 done
112 [[ $skip -eq 0 ]] && echo "$a"
113 done | sort -u
114 fi
115}
116
117# --- arg parsing ---
118PATTERN=""; IGNORE_CASE=0; MAX="$DEFAULT_MAX"; FILES_ONLY=0
119MODS_RAW=(); PKGS_RAW=()
120while [[ $# -gt 0 ]]; do
121 case "$1" in
122 -h|--help|help) print_help; exit 0;;
123 -m|--module) shift
124 while [[ $# -gt 0 && "$1" != -* ]]; do MODS_RAW+=("$1"); shift; done;;
125 -p|--package) shift
126 while [[ $# -gt 0 && "$1" != -* ]]; do PKGS_RAW+=("$1"); shift; done;;
127 -i|--ignore-case) IGNORE_CASE=1; shift;;
128 --max) MAX="${2:?--max needs a value}"; shift 2;;
129 --max=*) MAX="${1#--max=}"; shift;;
130 --files-only) FILES_ONLY=1; shift;;
131 --) shift; if [[ -z "$PATTERN" && $# -gt 0 ]]; then PATTERN="$1"; shift; fi;;
132 -*) echo "Error: unknown flag '$1'." >&2; exit 1;;
133 *) if [[ -z "$PATTERN" ]]; then PATTERN="$1";
134 else echo "Error: unexpected arg '$1' (pattern already set)." >&2; exit 1; fi
135 shift;;
136 esac
137done
138[[ -n "$PATTERN" ]] || { echo "Error: no pattern. Usage: ./search PATTERN [-m MODULE] [-p PACKAGE]" >&2; exit 1; }
139
140# split comma-separated filter values
141MODS_SPLIT=(); for m in ${MODS_RAW[@]:-}; do IFS=',' read -ra parts <<< "$m"; for p in "${parts[@]}"; do [[ -n "$p" ]] && MODS_SPLIT+=("$p"); done; done
142PKGS_SPLIT=(); for m in ${PKGS_RAW[@]:-}; do IFS=',' read -ra parts <<< "$m"; for p in "${parts[@]}"; do [[ -n "$p" ]] && PKGS_SPLIT+=("$(echo "$p" | tr '[:upper:]' '[:lower:]')"); done; done
143for p in ${PKGS_SPLIT[@]:-}; do
144 case " $KNOWN_PACKAGES " in *" $p "*) ;; *) echo "warning: unknown root package '$p'." >&2;; esac
145done
146
147# resolve modules
148MODS=(); ALL_EXP=0
149for raw in ${MODS_SPLIT[@]:-}; do
150 norm="$(normalize_module "$raw")"
151 if [[ "$norm" == "all" ]]; then
152 if [[ $ALL_EXP -eq 0 ]]; then
153 while IFS= read -r sm; do
154 case "$sm" in "" ) continue;; esac
155 MODS+=("$sm")
156 done < <(all_module_dirs)
157 ALL_EXP=1
158 fi
159 continue
160 fi
161 if [[ "$norm" != *":"* ]]; then
162 for pfx in games personal; do
163 [[ -f "$ROOT/$pfx/$norm/build.gradle.kts" ]] && { norm="$pfx:$norm"; break; }
164 done
165 fi
166 fs="$(echo "$norm" | tr ':' '/')"
167 if [[ ! -e "$ROOT/$fs" ]]; then echo "warning: skipping unknown module '$raw' (-> $fs/)." >&2; continue; fi
168 dup=0; for m in ${MODS[@]:-}; do [[ "$m" == "$fs" ]] && dup=1; done
169 [[ $dup -eq 0 ]] && MODS+=("$fs")
170done
171if [[ ${#MODS_RAW[@]} -gt 0 && ${#MODS[@]} -eq 0 ]]; then
172 echo "error: no valid modules (all -m values unknown)" >&2; exit 1
173fi
174
175cd "$ROOT" # rg then prints repo-relative paths
176TOTAL=0
177TMP_OUT="$(mktemp)"
178trap 'rm -f "$TMP_OUT"' EXIT
179emit_lines() { # file; applies --files-only/--max budget; prints
180 local line f
181 declare -A seen=()
182 if [[ $FILES_ONLY -eq 1 ]]; then
183 while IFS= read -r line; do
184 f="${line%%:*}"
185 [[ -n "${seen[$f]:-}" ]] && continue
186 seen[$f]=1
187 echo "$f"
188 TOTAL=$((TOTAL+1))
189 [[ $TOTAL -ge $MAX ]] && break
190 done < "$1"
191 else
192 while IFS= read -r line; do
193 echo "$line"
194 TOTAL=$((TOTAL+1))
195 [[ $TOTAL -ge $MAX ]] && break
196 done < "$1"
197 fi
198 return 0
199}
200
201search_dirs() { # prints dirs then runs backend; caller counts via emit_lines
202 if [[ $HAS_RG -eq 1 ]]; then run_rg "$PATTERN" "$@"; else run_grep "$PATTERN" "$@"; fi
203}
204
205if [[ ${#MODS[@]} -gt 0 ]]; then
206 for mod in "${MODS[@]}"; do
207 DIRS=()
208 if [[ ${#PKGS_SPLIT[@]} -gt 0 ]]; then
209 while IFS= read -r d; do DIRS+=("$d"); done < <(pkg_dirs_for "$mod" "${PKGS_SPLIT[@]}")
210 if [[ ${#DIRS[@]} -eq 0 ]]; then
211 echo "warning: $mod: no $(IFS=/; echo "${PKGS_SPLIT[*]}") package under src/main/{java,kotlin}, skipped" >&2
212 continue
213 fi
214 else
215 [[ -d "$mod/src" ]] && DIRS=("$mod/src") || DIRS=("$mod")
216 fi
217 echo "=== $mod ==="
218 RC=0
219 search_dirs "${DIRS[@]}" >"$TMP_OUT" || RC=$?
220 [[ $RC -eq 2 ]] && exit 2
221 emit_lines "$TMP_OUT"
222 [[ $TOTAL -ge $MAX ]] && break
223 done
224else
225 [[ ${#PKGS_SPLIT[@]} -gt 0 ]] && echo "warning: no -m given: -p needs a module scope, package filter ignored (repo-wide search)" >&2
226 RC=0
227 search_dirs "." >"$TMP_OUT" || RC=$?
228 [[ $RC -eq 2 ]] && exit 2
229 sed -i 's|^\./||' "$TMP_OUT"
230 emit_lines "$TMP_OUT"
231fi
232echo "--- $TOTAL match(es) ---" >&2
233exit 0