#!/usr/bin/env bash

# Usage:
#     ./format
#
# Run `rustfmt` on all the Rust source files in this project, modifying them in
# place. Usually, one would use `cargo fmt` for this task, but that seems to be
# broken for me at the moment.

RUSTFMT=""

function maybe_set() {
    if [[ $RUSTFMT == "" && -f "$1" ]]; then
        RUSTFMT="$1"
    fi
}

maybe_set ~/.multirust/toolchains/nightly/cargo/bin/rustfmt
maybe_set ~/.cargo/bin/rustfmt
maybe_set $(which rustfmt)

if [[ $RUSTFMT == "" ]]; then
    echo "$0: error: could not find an appropriate rustfmt binary!"
    exit 1
fi

echo "$0: using rustfmt=$RUSTFMT"

cd $(dirname $0)
RUST_FILES=$(git ls-files | grep '\.rs')

$RUSTFMT -v --write-mode replace $RUST_FILES 2>&1 \
    | xargs -I '{}' echo "rustfmt: {}"
