#!/usr/bin/env bash # Namespacing gate (docs/rules/code-style.md): one non-private top-level type per # file. A file with more than one file-scope type declaration is a violation: # split it, or mark helper types private/fileprivate. # # Inert until Sources exists. Portable: bash 3.2 and 4+. set -u SRC="Sources" if [ ! -d "$SRC" ]; then echo "namespacing: no $SRC yet, skipping." exit 0 fi FAIL=0 while IFS= read -r f; do # Count non-private top-level types per file (docs/rules/code-style.md). Types # here are declared inside `extension ` blocks, so a column-0 grep # is blind to them. This namespace-aware scan counts a type when it is either # declared at file scope (column 0) or as a direct member (one indent) of an # `extension` whose target is a PureYAML namespace. Types nested inside another # type, declared via `extension .`, or marked # private/fileprivate are NOT counted; they MAY co-locate. count=$(awk ' BEGIN { split("PureYAML PureYAML.Model PureYAML.Parsing PureYAML.Emitting PureYAML.Decoding PureYAML.Encoding PureYAML.Validation PureYAML.Stream PureYAML.Tagged", parts, " ") for (i in parts) ns[parts[i]] = 1 } /^}/ { in_ns = 0; next } /^(public )?extension [A-Za-z0-9_.]+ \{/ { target = $0 sub(/^(public )?extension /, "", target) sub(/ \{.*/, "", target) in_ns = (target in ns) ? 1 : 0 next } /^(public |package |internal )?(indirect |final )*(actor|struct|enum|protocol|class) [A-Z]/ { count++; next } in_ns && /^ (public |package |internal )?(indirect |final )*(actor|struct|enum|protocol|class) [A-Z]/ { count++ } END { print count + 0 } ' "$f") if [ "$count" -gt 1 ]; then echo "namespacing: $count file-scope types in $f (one per file)" >&2 FAIL=1 fi public_types=$(grep -nE "^public (actor|struct|enum|protocol|class|final class) [A-Z]" "$f" || true) if [ -n "$public_types" ]; then if [ "$f" = "Sources/PureYAML.swift" ] && [ "$public_types" = "2:public enum PureYAML {" ]; then : else echo "namespacing: public file-scope type in $f (wrap it under PureYAML)" >&2 printf '%s\n' "$public_types" | sed 's/^/ /' >&2 FAIL=1 fi fi done < <(find "$SRC" -name "*.swift") if [ "$FAIL" -ne 0 ]; then echo "namespacing: gate failed. Rule: docs/rules/code-style.md" >&2 fi exit "$FAIL"