summaryrefslogtreecommitdiff
path: root/scripts/formatthecode.sh
blob: a146f331348483a859d7b0e7727511f22efb7260 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
REPO_ROOT=$(cd "${SCRIPT_DIR}/.." && pwd)

usage() {
    cat <<'EOF'
Usage: ./scripts/formatthecode.sh [JAVA_FILE ...]

Formats Java sources with Artistic Style using the project's historical style.

Without arguments, formats all Java files under:
  - src/main/java
  - src/test/java

With arguments, formats only the provided files.

Options:
  -h, --help        Show this help text
  --check-deps      Verify required formatter dependencies are installed
EOF
}

check_deps() {
    if ! command -v astyle >/dev/null 2>&1; then
        echo "error: required formatter 'astyle' was not found in PATH" >&2
        echo "Install Artistic Style to use ./scripts/formatthecode.sh" >&2
        return 1
    fi
}

collect_default_targets() {
    find "${REPO_ROOT}/src/main/java" "${REPO_ROOT}/src/test/java" \
        -type f -name '*.java' -print0
}

main() {
    if [[ $# -gt 0 ]]; then
        case "$1" in
            -h|--help)
                usage
                return 0
                ;;
            --check-deps)
                check_deps
                return 0
                ;;
        esac
    fi

    check_deps

    if [[ $# -gt 0 ]]; then
        local target
        for target in "$@"; do
            if [[ ! -f "${target}" ]]; then
                echo "error: file not found: ${target}" >&2
                return 1
            fi
        done

        astyle --style=java --mode=java -n "$@"
        return 0
    fi

    mapfile -d '' targets < <(collect_default_targets)

    if [[ ${#targets[@]} -eq 0 ]]; then
        echo "No Java files found to format." >&2
        return 0
    fi

    astyle --style=java --mode=java -n "${targets[@]}"
}

main "$@"