#!/usr/bin/env bash # Auto-formatting for Kotlin (ktlint) and Rust (rustfmt): # ./format [...] # ktlintFormat + cargo fmt (writes changes) # ./format --check [...] # ktlintCheck + cargo fmt --check (fails on drift) # # Usage: # ./format notes backup # multi-module, one gradlew invocation # ./format voxels # shorthand -> games:voxels (same as ./install) # ./format games/voxels maps # slash == colon # ./format all # every app + library module # ./format --check games/pipes # verify only, no writes # # Module notation mirrors ./check and ./install: slash == colon, # games:/personal: shorthand, 'all' keyword, deduped. Gradle tasks run # with --continue so one broken module does not block the rest; exit # code is nonzero if anything failed. Configuration cache stays on # (repo gradle.properties), so repeat runs are cheap. # # Kotlin style lives in the root .editorconfig (indent 4, max line 120, # LF, final newline); ktlint runs its standard rule set against it. # Rust style lives in the root rustfmt.toml (max_width 100). A module # with no Rust sources simply skips the cargo step. set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ROOT="$SCRIPT_DIR" print_help() { sed -n '2,/^set -euo/p' "$SCRIPT_DIR/format" | sed 's/^# \{0,1\}//' | head -n -1 } normalize_module() { local m="$1" m="$(echo "$m" | xargs)" m="$(echo "$m" | sed -e 's|^[/:]*||' -e 's|[/:]*$||')" m="$(echo "$m" | tr '/' ':')" while echo "$m" | grep -q "::"; do m="$(echo "$m" | sed 's/::/:/g')"; done echo "$m" | tr '[:upper:]' '[:lower:]' } # Same set as ./check's 'all': app + library convention modules (the ones # that apply the ktlint convention). Pure-JVM modules are excluded here # but still accepted when named explicitly. all_module_dirs() { grep -E 'include\(":[^"]+"\)' "$ROOT/settings.gradle.kts" 2>/dev/null \ | sed -E 's/.*include\(":([^"]+)"\).*/\1/' \ | tr ':' '/' \ | while IFS= read -r p; do case "$p" in "" ) continue;; esac if [[ -f "$ROOT/$p/build.gradle.kts" ]] \ && grep -qE 'common-conventions-(app|library)' "$ROOT/$p/build.gradle.kts" 2>/dev/null; then echo "$p" fi done | sort -u } CHECK_ONLY=0 ARGS=() for arg in "$@"; do case "$arg" in --check) CHECK_ONLY=1;; --help|-h|help) print_help; exit 0;; *) ARGS+=("$arg");; esac done if [[ ${#ARGS[@]} -eq 0 ]]; then print_help; echo ""; echo "Error: no modules specified."; exit 1; fi MODS=(); ALL_EXP=0 for raw in "${ARGS[@]}"; do norm="$(normalize_module "$raw")" [[ -z "$norm" ]] && continue if [[ "$norm" == "all" ]]; then if [[ $ALL_EXP -eq 0 ]]; then while IFS= read -r sm; do case "$sm" in "" ) continue;; esac MODS+=("$sm") done < <(all_module_dirs) ALL_EXP=1 fi continue fi if [[ "$norm" != *":"* ]]; then for pfx in games personal; do [[ -f "$ROOT/$pfx/$norm/build.gradle.kts" ]] && { norm="$pfx:$norm"; break; } done fi fs="$(echo "$norm" | tr ':' '/')" if [[ ! -f "$ROOT/$fs/build.gradle.kts" ]]; then echo "Error: unknown module '$raw' (-> $fs/, no build.gradle.kts)." >&2; exit 1 fi dup=0; for m in ${MODS[@]:-}; do [[ "$m" == "$fs" ]] && dup=1; done [[ $dup -eq 0 ]] && MODS+=("$fs") done [[ ${#MODS[@]} -gt 0 ]] || { echo "Error: no valid modules." >&2; exit 1; } KT_TASK="ktlintFormat"; FMT_LABEL="cargo fmt" if [[ $CHECK_ONLY -eq 1 ]]; then KT_TASK="ktlintCheck"; FMT_LABEL="cargo fmt --check"; fi TASKS=() for mod in "${MODS[@]}"; do gmod="$(echo "$mod" | tr '/' ':')" TASKS+=(":$gmod:$KT_TASK") done echo "Modules (${#MODS[@]}): ${MODS[*]}" echo "Mode: $([[ $CHECK_ONLY -eq 1 ]] && echo check || echo format)" echo "Gradle tasks: ${TASKS[*]}" echo "" GRADLE_RC=0 "$SCRIPT_DIR/gradlew" "${TASKS[@]}" --continue --console=plain || GRADLE_RC=$? echo "" [[ $GRADLE_RC -ne 0 ]] && echo "Warning: $KT_TASK reported failures (exit $GRADLE_RC)." # --- cargo fmt (rust modules only; same crate scoping as ./check) --- # Workspace members share one root invocation via -p; standalone crates # (own [workspace] table) are handled individually in their own dir. # With `all`, the workspace-wide `--all` run also covers workspace crates # with no Gradle module (scripts/, third_party/, library/tilecodec, # library/jni-http, library/vision, communicate-dev/src/main/rust-mls), # and any standalone crate that is not a workspace member (a Cargo.toml # outside target/build/personal and outside the workspace member set) # is formatted in its own dir. standalone_crate_dirs() { python3 - "$ROOT" "$CARGO_BIN" <<'PYEOF' import json, os, pathlib, subprocess, sys root = pathlib.Path(sys.argv[1]); cargo = sys.argv[2] try: meta = json.loads(subprocess.check_output([cargo, "metadata", "--format-version", "1", "--no-deps"], cwd=root, text=True, stderr=subprocess.DEVNULL)) members = {str(pathlib.Path(p["manifest_path"]).parent) for p in meta["packages"]} except Exception: members = set() skip = {"target", "build", ".git", ".gradle", "personal"} for dirpath, dirnames, filenames in os.walk(root): dirnames[:] = sorted(d for d in dirnames if d not in skip) if "Cargo.toml" in filenames and dirpath != str(root) and dirpath not in members: print(dirpath) PYEOF } ROOT_CRATES=() STANDALONE_DIRS=() for mod in "${MODS[@]}"; do rdir="$ROOT/$mod/src/main/rust" ct="$rdir/Cargo.toml" if [[ -f "$ct" ]]; then if grep -qE '^\[workspace\][[:space:]]*$' "$ct"; then STANDALONE_DIRS+=("$rdir") echo "Rust: $mod -> standalone crate ($rdir)" else name="$(sed -nE 's/^name *= *"([^"]+)".*/\1/p' "$ct" | head -1)" [[ -n "$name" ]] && ROOT_CRATES+=("$name") && echo "Rust: $mod -> workspace crate $name" fi fi done CARGO_RC=0 if [[ ${#ROOT_CRATES[@]} -gt 0 || ${#STANDALONE_DIRS[@]} -gt 0 || $ALL_EXP -eq 1 ]]; then if command -v cargo >/dev/null 2>&1; then CARGO_BIN="cargo" else CARGO_BIN="${CARGO_HOME:-$HOME/.cargo}/bin/cargo" [[ -x "$CARGO_BIN" ]] || { echo "Error: cargo not found ($CARGO_BIN)." >&2; exit 1; } fi fi if [[ $ALL_EXP -eq 1 ]]; then echo "" if [[ $CHECK_ONLY -eq 1 ]]; then echo "Running: $FMT_LABEL --all" ( cd "$ROOT" && "$CARGO_BIN" fmt --check --all ) || CARGO_RC=$? else echo "Running: $FMT_LABEL --all" ( cd "$ROOT" && "$CARGO_BIN" fmt --all ) || CARGO_RC=$? fi [[ $CARGO_RC -ne 0 ]] && echo "Warning: $FMT_LABEL (workspace) reported failures (exit $CARGO_RC)." elif [[ ${#ROOT_CRATES[@]} -gt 0 ]]; then echo "" FMT_ARGS=() for c in "${ROOT_CRATES[@]}"; do FMT_ARGS+=(-p "$c"); done if [[ $CHECK_ONLY -eq 1 ]]; then FMT_ARGS=(--check "${FMT_ARGS[@]}"); fi echo "Running: $FMT_LABEL ${FMT_ARGS[*]}" ( cd "$ROOT" && "$CARGO_BIN" fmt "${FMT_ARGS[@]}" ) || CARGO_RC=$? [[ $CARGO_RC -ne 0 ]] && echo "Warning: $FMT_LABEL (workspace) reported failures (exit $CARGO_RC)." fi for rdir in ${STANDALONE_DIRS[@]:-}; do echo "" echo "Running: $FMT_LABEL (in $rdir)" if [[ $CHECK_ONLY -eq 1 ]]; then ( cd "$rdir" && "$CARGO_BIN" fmt --check ) || CARGO_RC=$? else ( cd "$rdir" && "$CARGO_BIN" fmt ) || CARGO_RC=$? fi [[ $CARGO_RC -ne 0 ]] && echo "Warning: $FMT_LABEL ($rdir) reported failures (exit $CARGO_RC)." done if [[ $ALL_EXP -eq 1 ]]; then while IFS= read -r rdir; do [[ -z "$rdir" ]] && continue dup=0; for m in ${STANDALONE_DIRS[@]:-}; do [[ "$m" == "$rdir" ]] && dup=1; done [[ $dup -eq 1 ]] && continue echo "" echo "Running: $FMT_LABEL (standalone in $rdir)" if [[ $CHECK_ONLY -eq 1 ]]; then ( cd "$rdir" && "$CARGO_BIN" fmt --check ) || CARGO_RC=$? else ( cd "$rdir" && "$CARGO_BIN" fmt ) || CARGO_RC=$? fi [[ $CARGO_RC -ne 0 ]] && echo "Warning: $FMT_LABEL ($rdir) reported failures (exit $CARGO_RC)." done < <(standalone_crate_dirs) fi if [[ ${#ROOT_CRATES[@]} -eq 0 && ${#STANDALONE_DIRS[@]} -eq 0 && $ALL_EXP -eq 0 ]]; then echo "No Rust crates in scope; cargo steps skipped." fi if [[ $GRADLE_RC -ne 0 || $CARGO_RC -ne 0 ]]; then exit 1; fi exit 0