summaryrefslogtreecommitdiff
path: root/extras/formatting.sh
blob: 8e44eea81d153785ded0795cee687e7066056656 (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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
#!/usr/bin/env bash

set -e

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
source_dir="$(dirname "$script_dir")"

check_only=0
no_version_check=0
run_cpp=0
run_yaml=0
run_sh=0
run_cmake=0
run_all=1

while [[ "$#" -gt 0 ]]; do
  case $1 in
  -h | --help) help=1 ;;
  --check-only) check_only=1 ;;
  --no-version-check) no_version_check=1 ;;
  --cpp)
    run_cpp=1
    run_all=0
    ;;
  --yaml)
    run_yaml=1
    run_all=0
    ;;
  --sh)
    run_sh=1
    run_all=0
    ;;
  --cmake)
    run_cmake=1
    run_all=0
    ;;
  --source)
    source_dir="$2"
    shift
    ;;
  esac
  shift
done

if [ "$help" ]; then
  me=$(basename "$0")
  cat <<EOF
$me: Format or check formatting of files in this repo

Usage: $me [--check-only] [--no-version-check] [--source <path>] [--cpp] [--yaml] [--sh] [--cmake]

Options:
    --check-only       Check formatting without modifying files
    --no-version-check Skip version compatibility checks
    --source          Path to source directory to format (defaults to parent of script directory)
    --cpp             Format only C++ files
    --yaml            Format only YAML/JSON files
    --sh              Format only shell script files
    --cmake           Format only CMake files
EOF
  exit 0
fi

cd "$source_dir" || exit 1

require_bin() {
  local name="$1"
  local min_version="$2"
  local max_version="${3:-}"
  local version

  if ! command -v "$name" &>/dev/null; then
    echo "This script needs $name, but it isn't in \$PATH" >&2
    missing_bin=1
    return
  fi

  if [ "$no_version_check" -eq 0 ]; then
    version=$("$name" --version | grep -oP "\d+\.\d+\.?\d*" | head -n1)

    if ! printf '%s\n%s\n' "$min_version" "$version" | sort -V -C; then
      echo "$name version $version is too old. Version $min_version or newer is required." >&2
      missing_bin=1
      return
    fi

    if [ -n "$max_version" ]; then
      if ! printf '%s\n%s\n' "$version" "$max_version" | sort -V -C; then
        echo "$name version $version is too new. Version less than $max_version is required." >&2
        missing_bin=1
        return
      fi
    fi
  fi
}

require_bin "git" "1.8"
require_bin "gersemi" "0.17"
require_bin "xargs" "3"
require_bin "diff" "2"
require_bin "clang-format" "17" "18"
require_bin "prettier" "3"
require_bin "shfmt" "3"

if [ "$missing_bin" ]; then
  exit 1
fi

exit_code=0

cmake_formatting() {
  echo "Formatting CMake files..." >&2

  readarray -t files < <(git ls-files '*.cmake' 'CMakeLists.txt' '**/CMakeLists.txt')

  common_args=(
    # turn on warning when this is fixed https://github.com/BlankSpruce/gersemi/issues/39
    --no-warn-about-unknown-commands
    --definitions "${files[@]}"
  )

  if [ "$check_only" -eq 1 ]; then
    gersemi "${common_args[@]}" --diff --color "${files[@]}"
    gersemi "${common_args[@]}" --check "${files[@]}" || exit_code=1
  else
    gersemi "${common_args[@]}" --in-place "${files[@]}"
  fi
}

track_progress() {
  # Don't output the progress bar if stderr isn't a terminal, just eat all the input
  [ -t 2 ] || {
    cat >/dev/null
    return
  }

  local total=$1
  local current=0

  while IFS= read -r _; do
    ((current++)) || :
    percent=$((current * 100 / total))
    printf '\rProgress: [%-50s] %d%%' "$(printf '#%.0s' $(seq 1 $((percent / 2))))" "$percent" >&2
  done
  echo >&2
}

cpp_formatting() {
  echo "Formatting cpp files..." >&2

  readarray -t files < <(git ls-files '*.cpp' '*.hpp' '*.c' '*.h' ':!external/**')

  # The progress reporting is a bit sneaky, we use `--verbose` with xargs which
  # prints a line to stderr for each command, and we simply count these...

  if [ "$check_only" -eq 1 ]; then
    local tmpdir
    tmpdir=$(mktemp -d)
    trap 'rm -rf "$tmpdir"' EXIT

    printf '%s\n' "${files[@]}" | xargs --verbose -P "$(nproc)" -I{} bash -c "
      mkdir -p \"\$(dirname \"$tmpdir/{}\")\"
      diff -u --color=always --label \"{}\" --label \"{}\" \"{}\" <(clang-format \"{}\") > \"$tmpdir/{}\"
      :
    " |& track_progress ${#files[@]}

    for file in "${files[@]}"; do
      # Fail if any of the diffs have contents
      if [ -s "$tmpdir/$file" ]; then
        cat "$tmpdir/$file"
        exit_code=1
      fi
    done
  else
    printf '%s\n' "${files[@]}" | xargs --verbose -n1 -P "$(nproc)" clang-format -i |&
      track_progress ${#files[@]}
  fi
}

yaml_json_formatting() {
  echo "Formatting yaml and json files..." >&2

  readarray -t files < <(git ls-files "*.yaml" "*.yml" "*.json" ':!external/**')

  if [ "$check_only" -eq 1 ]; then
    for file in "${files[@]}"; do
      if ! output=$(prettier "$file" 2>/dev/null); then
        continue
      fi
      if ! diff -q "$file" <(echo "$output") >/dev/null 2>&1; then
        diff --color -u --label "$file" --label "$file" "$file" <(echo "$output")
        exit_code=1
      fi
    done
  else
    prettier --write "${files[@]}" | grep -v '(unchanged)' >&2 || :
  fi
}

sh_formatting() {
  echo "Formatting sh files..." >&2

  readarray -t files < <(git ls-files "*.sh")

  common_args=(
    # default 8 is way too wide
    --indent 2
  )

  if [ "$check_only" -eq 1 ]; then
    shfmt "${common_args[@]}" --diff "${files[@]}" || exit_code=1
  else
    shfmt "${common_args[@]}" --write "${files[@]}"
  fi
}

((run_all || run_sh)) && sh_formatting
((run_all || run_cmake)) && cmake_formatting
((run_all || run_yaml)) && yaml_json_formatting
((run_all || run_cpp)) && cpp_formatting

exit $exit_code