1#!/bin/bash
2set -e
3
4# This script reformats source files using various formatters and linters.
5#
6# Files are changed in-place, so make sure you don't have anything open in an
7# editor, and you may want to commit before formatting in case of awryness.
8#
9# This must be run on a clean repository to succeed
10#
11function display_help()
12{
13    echo "usage: format-code.sh [-h | --help] [--no-diff] [--list-tools]"
14    echo "                      [--disable <tool>] [--enable <tool>] [<path>]"
15    echo
16    echo "Format and lint a repository."
17    echo
18    echo "Arguments:"
19    echo "    --list-tools      Display available linters and formatters"
20    echo "    --no-diff         Don't show final diff output"
21    echo "    --disable <tool>  Disable linter"
22    echo "    --enable <tool>   Enable only specific linters"
23    echo "    --allow-missing   Run even if linters are not all present"
24    echo "    path              Path to git repository (default to pwd)"
25}
26
27LINTERS_ALL=( \
28        commit_gitlint \
29        commit_spelling \
30        beautysh \
31        beautysh_sh \
32        black \
33        clang_format \
34        eslint \
35        flake8 \
36        isort \
37        markdownlint \
38        prettier \
39        shellcheck \
40    )
41LINTERS_DISABLED=()
42LINTERS_ENABLED=()
43declare -A LINTERS_FAILED=()
44
45eval set -- "$(getopt -o 'h' --long 'help,list-tools,no-diff,disable:,enable:,allow-missing' -n 'format-code.sh' -- "$@")"
46while true; do
47    case "$1" in
48        '-h'|'--help')
49            display_help && exit 0
50            ;;
51
52        '--list-tools')
53            echo "Available tools:"
54            for t in "${LINTERS_ALL[@]}"; do
55                echo "    $t"
56            done
57            exit 0
58            ;;
59
60        '--no-diff')
61            OPTION_NO_DIFF=1
62            shift
63            ;;
64
65        '--disable')
66            LINTERS_DISABLED+=("$2")
67            shift && shift
68            ;;
69
70        '--enable')
71            LINTERS_ENABLED+=("$2")
72            shift && shift
73            ;;
74
75        '--allow-missing')
76            ALLOW_MISSING=yes
77            shift
78            ;;
79
80        '--')
81            shift
82            break
83            ;;
84
85        *)
86            echo "unknown option: $1"
87            display_help && exit 1
88            ;;
89    esac
90done
91
92# Detect tty and set nicer colors.
93if [ -t 1 ]; then
94    BLUE="\e[34m"
95    GREEN="\e[32m"
96    NORMAL="\e[0m"
97    RED="\e[31m"
98    YELLOW="\e[33m"
99else # non-tty, no escapes.
100    BLUE=""
101    GREEN=""
102    NORMAL=""
103    RED=""
104    YELLOW=""
105fi
106
107# Allow called scripts to know which clang format we are using
108export CLANG_FORMAT="clang-format"
109
110# Path to default config files for linters.
111CONFIG_PATH="$(git -C "$(dirname "${BASH_SOURCE[0]}")" rev-parse --show-toplevel)/config"
112
113# Find repository root for `pwd` or $1.
114if [ -z "$1" ]; then
115    DIR="$(git rev-parse --show-toplevel || pwd)"
116else
117    DIR="$(git -C "$1" rev-parse --show-toplevel)"
118fi
119if [ ! -e "$DIR/.git" ]; then
120    echo -e "${RED}Error:${NORMAL} Directory ($DIR) does not appear to be a git repository"
121    exit 1
122fi
123
124cd "${DIR}"
125echo -e "    ${BLUE}Formatting code under${NORMAL} $DIR"
126
127# Config hashes:
128#   LINTER_REQUIRE - The requirements to run a linter, semi-colon separated.
129#       1. Executable.
130#       2. [optional] Configuration file.
131#       3. [optional] Global fallback configuration file.
132#
133#   LINTER_IGNORE - An optional set of semi-colon separated ignore-files
134#       specific to the linter.
135#
136#   LINTER_TYPES - The file types supported by the linter, semi-colon separated.
137#
138#   LINTER_CONFIG - The config (from LINTER_REQUIRE) chosen for the repository.
139#
140declare -A LINTER_REQUIRE=()
141declare -A LINTER_IGNORE=()
142declare -A LINTER_TYPES=()
143declare -A LINTER_CONFIG=()
144
145LINTER_REQUIRE+=([commit_spelling]="codespell")
146LINTER_TYPES+=([commit_spelling]="commit")
147
148commit_filename="$(mktemp)"
149function clean_up_file() {
150    rm "$commit_filename"
151}
152trap clean_up_file EXIT
153
154function do_commit_spelling() {
155    # Write the commit message to a temporary file
156    git log --format='%B' -1 > "$commit_filename"
157
158    # Some names or emails appear as false-positive misspellings, remove them
159    sed -i "s/Signed-off-by.*//" "$commit_filename"
160
161    # Run the codespell with openbmc spcific spellings on the patchset
162    echo -n "openbmc-dictionary - misspelling count >> "
163
164    codespell -D "${CONFIG_PATH}/openbmc-spelling.txt" -d --count "$commit_filename"
165
166    # Run the codespell with generic dictionary on the patchset
167    echo -n "generic-dictionary - misspelling count >> "
168    codespell --builtin clear,rare,en-GB_to_en-US -d --count "$commit_filename"
169}
170
171LINTER_REQUIRE+=([commit_gitlint]="gitlint")
172LINTER_TYPES+=([commit_gitlint]="commit")
173function do_commit_gitlint() {
174    gitlint --extra-path "${CONFIG_PATH}/gitlint/" \
175        --config "${CONFIG_PATH}/.gitlint"
176}
177
178# We need different function style for bash/zsh vs plain sh, so beautysh is
179# split into two linters.  "function foo()" is not traditionally accepted
180# POSIX-shell syntax, so shellcheck barfs on it.
181LINTER_REQUIRE+=([beautysh]="beautysh")
182LINTER_IGNORE+=([beautysh]=".beautysh-ignore")
183LINTER_TYPES+=([beautysh]="bash;zsh")
184function do_beautysh() {
185    beautysh --force-function-style fnpar "$@"
186}
187LINTER_REQUIRE+=([beautysh_sh]="beautysh")
188LINTER_IGNORE+=([beautysh_sh]=".beautysh-ignore")
189LINTER_TYPES+=([beautysh_sh]="sh")
190function do_beautysh_sh() {
191    beautysh --force-function-style paronly "$@"
192}
193
194LINTER_REQUIRE+=([black]="black")
195LINTER_TYPES+=([black]="python")
196function do_black() {
197    black -l 79 "$@"
198}
199
200LINTER_REQUIRE+=([eslint]="eslint;.eslintrc.json;${CONFIG_PATH}/eslint-global-config.json")
201LINTER_IGNORE+=([eslint]=".eslintignore")
202LINTER_TYPES+=([eslint]="json")
203function do_eslint() {
204    eslint --no-eslintrc -c "${LINTER_CONFIG[eslint]}" \
205        --ext .json --format=stylish \
206        --resolve-plugins-relative-to /usr/local/lib/node_modules \
207        --no-error-on-unmatched-pattern "$@"
208}
209
210LINTER_REQUIRE+=([flake8]="flake8")
211LINTER_IGNORE+=([flake8]=".flake8-ignore")
212LINTER_TYPES+=([flake8]="python")
213function do_flake8() {
214    flake8 --show-source --extend-ignore=E203,E501 "$@"
215    # We disable E203 and E501 because 'black' is handling these and they
216    # disagree on best practices.
217}
218
219LINTER_REQUIRE+=([isort]="isort")
220LINTER_TYPES+=([isort]="python")
221function do_isort() {
222    isort --profile black "$@"
223}
224
225LINTER_REQUIRE+=([markdownlint]="markdownlint;.markdownlint.yaml;${CONFIG_PATH}/markdownlint.yaml")
226LINTER_IGNORE+=([markdownlint]=".markdownlint-ignore")
227LINTER_TYPES+=([markdownlint]="markdown")
228function do_markdownlint() {
229    markdownlint --config "${LINTER_CONFIG[markdownlint]}" \
230        --disable line-length -- "$@" || \
231        echo -e "    ${YELLOW}Failed markdownlint; temporarily ignoring."
232    # We disable line-length because prettier should handle prose wrap for us.
233}
234
235LINTER_REQUIRE+=([prettier]="prettier;.prettierrc.yaml;${CONFIG_PATH}/prettierrc.yaml")
236LINTER_IGNORE+=([prettier]=".prettierignore")
237LINTER_TYPES+=([prettier]="json;markdown;yaml")
238function do_prettier() {
239    prettier --config "${LINTER_CONFIG[prettier]}" --write "$@"
240}
241
242LINTER_REQUIRE+=([shellcheck]="shellcheck")
243LINTER_IGNORE+=([shellcheck]=".shellcheck-ignore")
244LINTER_TYPES+=([shellcheck]="bash;sh")
245function do_shellcheck() {
246    shellcheck --color=never -x "$@"
247}
248
249LINTER_REQUIRE+=([clang_format]="clang-format;.clang-format")
250LINTER_IGNORE+=([clang_format]=".clang-ignore;.clang-format-ignore")
251LINTER_TYPES+=([clang_format]="c;cpp")
252function do_clang_format() {
253    "${CLANG_FORMAT}" -i "$@"
254}
255
256function get_file_type()
257{
258    case "$(basename "$1")" in
259            # First to early detect template files.
260        *.in | *.meson) echo "meson-template" && return ;;
261        *.mako | *.mako.*) echo "mako" && return ;;
262
263        *.ac) echo "autoconf" && return ;;
264        *.[ch]) echo "c" && return ;;
265        *.[ch]pp) echo "cpp" &&  return ;;
266        *.json) echo "json" && return ;;
267        *.md) echo "markdown" && return ;;
268        *.py) echo "python" && return ;;
269        *.tcl) echo "tcl" && return ;;
270        *.yaml | *.yml) echo "yaml" && return ;;
271
272            # Special files.
273        .git/COMMIT_EDITMSG) echo "commit" && return ;;
274        meson.build) echo "meson" && return ;;
275    esac
276
277    case "$(file "$1")" in
278        *Bourne-Again\ shell*) echo "bash" && return ;;
279        *C++\ source*) echo "cpp" && return ;;
280        *C\ source*) echo "c" && return ;;
281        *JSON\ data*) echo "json" && return ;;
282        *POSIX\ shell*) echo "sh" && return ;;
283        *Python\ script*) echo "python" && return ;;
284        *python3\ script*) echo "python" && return ;;
285        *zsh\ shell*) echo "zsh" && return ;;
286    esac
287
288    echo "unknown"
289}
290
291LINTERS_AVAILABLE=()
292function check_linter()
293{
294    TITLE="$1"
295    IFS=";" read -r -a ARGS <<< "$2"
296
297    if [[ "${LINTERS_DISABLED[*]}" =~ $1 ]]; then
298        return
299    fi
300
301    if [ 0 -ne "${#LINTERS_ENABLED[@]}" ]; then
302        if ! [[ "${LINTERS_ENABLED[*]}" =~ $1 ]]; then
303            return
304        fi
305    fi
306
307    EXE="${ARGS[0]}"
308    if [ ! -x "${EXE}" ]; then
309        if ! which "${EXE}" > /dev/null 2>&1 ; then
310            echo -e "    ${YELLOW}${TITLE}:${NORMAL} cannot find ${EXE}"
311            if [ -z "$ALLOW_MISSING" ]; then
312                exit 1
313            fi
314            return
315        fi
316    fi
317
318    CONFIG="${ARGS[1]}"
319    FALLBACK="${ARGS[2]}"
320
321    if [ -n "${CONFIG}" ]; then
322        if [ -e "${CONFIG}" ]; then
323            LINTER_CONFIG+=( [${TITLE}]="${CONFIG}" )
324        elif [ -n "${FALLBACK}" ] && [ -e "${FALLBACK}" ]; then
325            echo -e "    ${YELLOW}${TITLE}:${NORMAL} cannot find ${CONFIG}; using ${FALLBACK}"
326            LINTER_CONFIG+=( [${TITLE}]="${FALLBACK}" )
327        else
328            echo -e "    ${YELLOW}${TITLE}:${NORMAL} cannot find config ${CONFIG}"
329            return
330        fi
331    fi
332
333    LINTERS_AVAILABLE+=( "${TITLE}" )
334}
335
336# Check for a global .linter-ignore file.
337GLOBAL_IGNORE=("cat")
338if [ -e ".linter-ignore" ]; then
339    GLOBAL_IGNORE=("${CONFIG_PATH}/lib/ignore-filter" ".linter-ignore")
340fi
341
342# Find all the files in the git repository and organize by type.
343declare -A FILES=()
344FILES+=([commit]=".git")
345
346while read -r file; do
347    ftype="$(get_file_type "$file")"
348    FILES+=([$ftype]="$(echo -ne "$file;${FILES[$ftype]:-}")")
349done < <(git ls-files | xargs realpath --relative-base=. | "${GLOBAL_IGNORE[@]}")
350
351# For each linter, check if there are an applicable files and if it can
352# be enabled.
353for op in "${LINTERS_ALL[@]}"; do
354    for ftype in ${LINTER_TYPES[$op]//;/ }; do
355        if [[ -v FILES["$ftype"] ]]; then
356            check_linter "$op" "${LINTER_REQUIRE[${op}]}"
357            break
358        fi
359    done
360done
361
362# Call each linter.
363for op in "${LINTERS_AVAILABLE[@]}"; do
364
365    # Determine the linter-specific ignore file(s).
366    LOCAL_IGNORE=("${CONFIG_PATH}/lib/ignore-filter")
367    if [[ -v LINTER_IGNORE["$op"] ]]; then
368        for ignorefile in ${LINTER_IGNORE["$op"]//;/ } ; do
369            if [ -e "$ignorefile" ]; then
370                LOCAL_IGNORE+=("$ignorefile")
371            fi
372        done
373    fi
374    if [ 1 -eq ${#LOCAL_IGNORE[@]} ]; then
375        LOCAL_IGNORE=("cat")
376    fi
377
378    # Find all the files for this linter, filtering out the ignores.
379    LINTER_FILES=()
380    while read -r file ; do
381        if [ -e "$file" ]; then
382            LINTER_FILES+=("$file")
383        fi
384        done < <(for ftype in ${LINTER_TYPES[$op]//;/ }; do
385            # shellcheck disable=SC2001
386            echo "${FILES["$ftype"]:-}" | sed "s/;/\\n/g"
387    done | "${LOCAL_IGNORE[@]}")
388
389    # Call the linter now with all the files.
390    if [ 0 -ne ${#LINTER_FILES[@]} ]; then
391        echo -e "    ${BLUE}Running $op${NORMAL}"
392        if ! "do_$op" "${LINTER_FILES[@]}" ; then
393            LINTERS_FAILED+=([$op]=1)
394        fi
395    else
396        echo -e "    ${YELLOW}${op}:${NORMAL} all applicable files are on ignore-lists"
397    fi
398done
399
400# Check for failing linters.
401if [ 0 -ne ${#LINTERS_FAILED[@]} ]; then
402    for op in "${!LINTERS_FAILED[@]}"; do
403        echo -e "$op: ${RED}FAILED${NORMAL}"
404    done
405    exit 1
406fi
407
408# Check for differences.
409if [ -z "$OPTION_NO_DIFF" ]; then
410    echo -e "    ${BLUE}Result differences...${NORMAL}"
411    if ! git --no-pager diff --exit-code ; then
412        echo -e "Format: ${RED}FAILED${NORMAL}"
413        exit 1
414    else
415        echo -e "Format: ${GREEN}PASSED${NORMAL}"
416    fi
417fi
418
419# Sometimes your situation is terrible enough that you need the flexibility.
420# For example, phosphor-mboxd.
421for formatter in "format-code.sh" "format-code"; do
422    if [[ -x "${formatter}" ]]; then
423        echo -e "    ${BLUE}Calling secondary formatter:${NORMAL} ${formatter}"
424        "./${formatter}"
425        if [ -z "$OPTION_NO_DIFF" ]; then
426            git --no-pager diff --exit-code
427        fi
428    fi
429done
430