summaryrefslogtreecommitdiff
path: root/extras/formatting.sh
blob: a53930eafeb52b7062f3a647fb16781afc85d13a (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
#!/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

while [[ "$#" -gt 0 ]]; do
  case $1 in
  -h | --help) help=1 ;;
  --check-only) check_only=1 ;;
  --no-version-check) no_version_check=1 ;;
  --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>]

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)
EOF
  exit 0
fi

cd "$source_dir" || exit 1

require_bin() {
  local name="$1"
  local required="$2"
  local version

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

  if [ "$no_version_check" -eq 0 ]; then
    version=$("$name" --version | grep -oP "$name(?:\s+version)?\s+\K\d+\.\d+\.?\d*")
    if ! printf '%s\n%s\n' "$required" "$version" | sort -V -C; then
      echo "$name version $version is too old. Version $required or newer is required."
      missing_bin=1
    fi
  fi
}

require_bin "git" "1.8"
require_bin "gersemi" "0.17"

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

exit_code=0

cmake_formatting() {
  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
}

cmake_formatting

exit $exit_code