#!/bin/sh
# script/prettier: run prettier over this repo's canonical file set.
#
# Takes exactly one mode argument, --write or --check, and applies the
# same patterns in both modes. script/fmt and script/fmt-check both go
# through here, so the set of files that get formatted and the set that
# get verified cannot drift apart.
#
# Failures are never swallowed: a missing prettier is an error, not a
# silent skip. A formatter that quietly does nothing is worse than one
# that fails loudly.
set -eu

ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"

usage() {
    echo "usage: script/prettier --write|--check" >&2
    exit 2
}

# Prefer the version pinned by package.json/yarn.lock so that CI and
# developer machines format identically. Fall back to a prettier on PATH,
# but say so, because a different version formats differently.
find_prettier() {
    if [ -x "$ROOT/node_modules/.bin/prettier" ]; then
        printf '%s\n' "$ROOT/node_modules/.bin/prettier"
        return 0
    fi
    if command -v prettier >/dev/null 2>&1; then
        echo "prettier: node_modules/.bin/prettier is absent; using the" \
            "prettier on PATH, which may be a different version than the" \
            "one pinned in package.json. Run script/bootstrap to install" \
            "the pinned version." >&2
        command -v prettier
        return 0
    fi
    return 1
}

main() {
    [ "$#" -eq 1 ] || usage
    case "$1" in
        --write | --check) mode="$1" ;;
        *) usage ;;
    esac

    cd "$ROOT"

    if ! prettier_bin="$(find_prettier)"; then
        echo "prettier: not found." >&2
        echo "  Install it with: script/bootstrap" >&2
        echo "  (installs the version pinned in package.json/yarn.lock)" >&2
        exit 1
    fi

    # Markdown and JSON, repo-wide rather than root-only, so files in
    # subdirectories (docs/, once it exists) are covered too. Exclusions
    # live in .prettierignore; REPO_POLICIES.md is excluded there because
    # it is a verbatim copy of an upstream document.
    #
    # --no-error-on-unmatched-pattern is deliberately NOT used: both
    # patterns always match at least one tracked file (README.md,
    # package.json), so an empty match means the glob broke, and prettier
    # erroring out is exactly what we want rather than a vacuous pass.
    "$prettier_bin" "$mode" "**/*.md"
    "$prettier_bin" "$mode" "**/*.json"
}

main "$@"
