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 clang_tidy \ 35 eslint \ 36 flake8 \ 37 isort \ 38 markdownlint \ 39 meson \ 40 prettier \ 41 shellcheck \ 42 ) 43LINTERS_DISABLED=() 44LINTERS_ENABLED=() 45declare -A LINTERS_FAILED=() 46 47eval set -- "$(getopt -o 'h' --long 'help,list-tools,no-diff,disable:,enable:,allow-missing' -n 'format-code.sh' -- "$@")" 48while true; do 49 case "$1" in 50 '-h'|'--help') 51 display_help && exit 0 52 ;; 53 54 '--list-tools') 55 echo "Available tools:" 56 for t in "${LINTERS_ALL[@]}"; do 57 echo " $t" 58 done 59 exit 0 60 ;; 61 62 '--no-diff') 63 OPTION_NO_DIFF=1 64 shift 65 ;; 66 67 '--disable') 68 LINTERS_DISABLED+=("$2") 69 shift && shift 70 ;; 71 72 '--enable') 73 LINTERS_ENABLED+=("$2") 74 shift && shift 75 ;; 76 77 '--allow-missing') 78 ALLOW_MISSING=yes 79 shift 80 ;; 81 82 '--') 83 shift 84 break 85 ;; 86 87 *) 88 echo "unknown option: $1" 89 display_help && exit 1 90 ;; 91 esac 92done 93 94# Detect tty and set nicer colors. 95if [ -t 1 ]; then 96 BLUE="\e[34m" 97 GREEN="\e[32m" 98 NORMAL="\e[0m" 99 RED="\e[31m" 100 YELLOW="\e[33m" 101else # non-tty, no escapes. 102 BLUE="" 103 GREEN="" 104 NORMAL="" 105 RED="" 106 YELLOW="" 107fi 108 109# Allow called scripts to know which clang format we are using 110export CLANG_FORMAT="clang-format" 111 112# Path to default config files for linters. 113CONFIG_PATH="$(git -C "$(dirname "${BASH_SOURCE[0]}")" rev-parse --show-toplevel)/config" 114TOOLS_PATH="$(git -C "$(dirname "${BASH_SOURCE[0]}")" rev-parse --show-toplevel)/tools" 115 116 117# Find repository root for `pwd` or $1. 118if [ -z "$1" ]; then 119 DIR="$(git rev-parse --show-toplevel || pwd)" 120else 121 DIR="$(git -C "$1" rev-parse --show-toplevel)" 122fi 123if [ ! -e "$DIR/.git" ]; then 124 echo -e "${RED}Error:${NORMAL} Directory ($DIR) does not appear to be a git repository" 125 exit 1 126fi 127 128cd "${DIR}" 129echo -e " ${BLUE}Formatting code under${NORMAL} $DIR" 130 131# Config hashes: 132# LINTER_REQUIRE - The requirements to run a linter, semi-colon separated. 133# 1. Executable. 134# 2. [optional] Configuration file. 135# 3. [optional] Global fallback configuration file. 136# 137# LINTER_IGNORE - An optional set of semi-colon separated ignore-files 138# specific to the linter. 139# 140# LINTER_TYPES - The file types supported by the linter, semi-colon separated. 141# 142# LINTER_CONFIG - The config (from LINTER_REQUIRE) chosen for the repository. 143# 144declare -A LINTER_REQUIRE=() 145declare -A LINTER_IGNORE=() 146declare -A LINTER_TYPES=() 147declare -A LINTER_CONFIG=() 148 149LINTER_REQUIRE+=([commit_spelling]="codespell") 150LINTER_TYPES+=([commit_spelling]="commit") 151 152commit_filename="$(mktemp)" 153function clean_up_file() { 154 rm "$commit_filename" 155} 156trap clean_up_file EXIT 157 158function find_codespell_dict_file() { 159 local python_codespell_dict 160 # @formatter:off 161 python_codespell_dict=$(python3 -c " 162import os.path as op 163import codespell_lib 164codespell_dir = op.dirname(codespell_lib.__file__) 165codespell_file = op.join(codespell_dir, 'data', 'dictionary.txt') 166print(codespell_file if op.isfile(codespell_file) else '', end='') 167" 2> /dev/null) 168 # @formatter:on 169 170 # Return the path if found, otherwise return an empty string 171 echo "$python_codespell_dict" 172} 173 174function do_commit_spelling() { 175 # Write the commit message to a temporary file 176 git log --format='%B' -1 > "$commit_filename" 177 178 # Some names or emails appear as false-positive misspellings, remove them 179 sed -i "s/Signed-off-by.*//" "$commit_filename" 180 181 # Get the path to the dictionary.txt file 182 local codespell_dict 183 codespell_dict=$(find_codespell_dict_file) 184 185 # Check if the dictionary file was found 186 if [[ -z "$codespell_dict" ]]; then 187 echo "Error: Could not find dictionary.txt file" 188 exit 1 189 fi 190 191 # Run the codespell with codespell dictionary on the patchset 192 echo -n "codespell-dictionary - misspelling count >> " 193 codespell -D "$codespell_dict" -d --count "$commit_filename" 194 195 # Run the codespell with builtin dictionary on the patchset 196 echo -n "generic-dictionary - misspelling count >> " 197 codespell --builtin clear,rare,en-GB_to_en-US -d --count "$commit_filename" 198} 199function do_version_commit_spelling() { 200 echo codespell: "$(codespell --version)" 201} 202 203LINTER_REQUIRE+=([commit_gitlint]="gitlint") 204LINTER_TYPES+=([commit_gitlint]="commit") 205function do_commit_gitlint() { 206 gitlint --extra-path "${CONFIG_PATH}/gitlint/" \ 207 --config "${CONFIG_PATH}/.gitlint" 208} 209function do_version_commit_gitlint() { 210 gitlint --version | awk '{ print $3 }' 211} 212 213# We need different function style for bash/zsh vs plain sh, so beautysh is 214# split into two linters. "function foo()" is not traditionally accepted 215# POSIX-shell syntax, so shellcheck barfs on it. 216LINTER_REQUIRE+=([beautysh]="beautysh") 217LINTER_IGNORE+=([beautysh]=".beautysh-ignore") 218LINTER_TYPES+=([beautysh]="bash;zsh") 219function do_beautysh() { 220 beautysh --force-function-style fnpar "$@" 221} 222function do_version_beautysh() { 223 beautysh --version 224} 225LINTER_REQUIRE+=([beautysh_sh]="beautysh") 226LINTER_IGNORE+=([beautysh_sh]=".beautysh-ignore") 227LINTER_TYPES+=([beautysh_sh]="sh") 228function do_beautysh_sh() { 229 beautysh --force-function-style paronly "$@" 230} 231function do_version_beautysh_sh() { 232 beautysh --version 233} 234 235LINTER_REQUIRE+=([black]="black") 236LINTER_TYPES+=([black]="python") 237function do_black() { 238 black -l 79 "$@" 239} 240function do_version_black() { 241 black --version | head -n1 242} 243 244LINTER_REQUIRE+=([eslint]="eslint;eslint.config.js;${CONFIG_PATH}/eslint.config.js") 245LINTER_IGNORE+=([eslint]=".eslintignore") 246LINTER_TYPES+=([eslint]="json") 247function do_eslint() { 248 eslint --no-config-lookup -c "${LINTER_CONFIG[eslint]}" \ 249 --ext .json --format=stylish \ 250 --no-error-on-unmatched-pattern "$@" 251} 252function do_version_eslint() { 253 eslint --version 254} 255 256LINTER_REQUIRE+=([flake8]="flake8") 257LINTER_IGNORE+=([flake8]=".flake8-ignore") 258LINTER_TYPES+=([flake8]="python") 259function do_flake8() { 260 flake8 --show-source --extend-ignore=E203,E501 "$@" 261 # We disable E203 and E501 because 'black' is handling these and they 262 # disagree on best practices. 263} 264function do_version_flake8() { 265 flake8 --version 266} 267 268LINTER_REQUIRE+=([isort]="isort") 269LINTER_TYPES+=([isort]="python") 270function do_isort() { 271 isort --profile black "$@" 272} 273function do_version_isort() { 274 isort --version-number 275} 276 277LINTER_REQUIRE+=([markdownlint]="markdownlint;.markdownlint.yaml;${CONFIG_PATH}/markdownlint.yaml") 278LINTER_IGNORE+=([markdownlint]=".markdownlint-ignore") 279LINTER_TYPES+=([markdownlint]="markdown") 280function do_markdownlint() { 281 markdownlint --config "${LINTER_CONFIG[markdownlint]}" -- "$@" 282} 283function do_version_markdownlint() { 284 markdownlint --version 285} 286 287LINTER_REQUIRE+=([meson]="meson;meson.build") 288LINTER_TYPES+=([meson]="meson") 289function do_meson() { 290 meson format -i "$@" 291} 292function do_version_meson() { 293 meson --version 294} 295 296LINTER_REQUIRE+=([prettier]="prettier;.prettierrc.yaml;${CONFIG_PATH}/prettierrc.yaml") 297LINTER_IGNORE+=([prettier]=".prettierignore") 298LINTER_TYPES+=([prettier]="json;markdown;yaml") 299function do_prettier() { 300 prettier --config "${LINTER_CONFIG[prettier]}" --write "$@" 301} 302function do_version_prettier() { 303 prettier --version 304} 305 306LINTER_REQUIRE+=([shellcheck]="shellcheck") 307LINTER_IGNORE+=([shellcheck]=".shellcheck-ignore") 308LINTER_TYPES+=([shellcheck]="bash;sh") 309function do_shellcheck() { 310 shellcheck --color=never -x "$@" 311} 312function do_version_shellcheck() { 313 shellcheck --version | awk '/^version/ { print $2 }' 314} 315 316LINTER_REQUIRE+=([clang_format]="clang-format;.clang-format") 317LINTER_IGNORE+=([clang_format]=".clang-ignore;.clang-format-ignore") 318LINTER_TYPES+=([clang_format]="c;cpp") 319function do_clang_format() { 320 "${CLANG_FORMAT}" -i "$@" 321} 322function do_version_clang_format() { 323 "${CLANG_FORMAT}" --version 324} 325 326LINTER_REQUIRE+=([clang_tidy]="true") 327LINTER_TYPES+=([clang_tidy]="clang-tidy-config") 328function do_clang_tidy() { 329 "${TOOLS_PATH}/config-clang-tidy" format 330} 331function do_version_clang_tidy() { 332 echo openbmc-build-scripts: "$(git rev-parse HEAD)" 333} 334 335function get_file_type() 336{ 337 case "$(basename "$1")" in 338 # First to early detect template files. 339 *.in | *.meson) echo "meson-template" && return ;; 340 *.mako | *.mako.*) echo "mako" && return ;; 341 342 *.ac) echo "autoconf" && return ;; 343 *.[ch]) echo "c" && return ;; 344 *.[ch]pp) echo "cpp" && return ;; 345 *.json) echo "json" && return ;; 346 *.md) echo "markdown" && return ;; 347 *.py) echo "python" && return ;; 348 *.tcl) echo "tcl" && return ;; 349 *.yaml | *.yml) echo "yaml" && return ;; 350 351 # Special files. 352 .git/COMMIT_EDITMSG) echo "commit" && return ;; 353 .clang-format) echo "clang-format-config" && return ;; 354 .clang-tidy) echo "clang-tidy-config" && return ;; 355 meson.build) echo "meson" && return ;; 356 meson.options) echo "meson" && return ;; 357 esac 358 359 case "$(file "$1")" in 360 *Bourne-Again\ shell*) echo "bash" && return ;; 361 *C++\ source*) echo "cpp" && return ;; 362 *C\ source*) echo "c" && return ;; 363 *JSON\ data*) echo "json" && return ;; 364 *POSIX\ shell*) echo "sh" && return ;; 365 *Python\ script*) echo "python" && return ;; 366 *python3\ script*) echo "python" && return ;; 367 *zsh\ shell*) echo "zsh" && return ;; 368 esac 369 370 echo "unknown" 371} 372 373LINTERS_AVAILABLE=() 374function check_linter() 375{ 376 TITLE="$1" 377 IFS=";" read -r -a ARGS <<< "$2" 378 379 if [[ "${LINTERS_DISABLED[*]}" =~ $1 ]]; then 380 return 381 fi 382 383 if [ 0 -ne "${#LINTERS_ENABLED[@]}" ]; then 384 if ! [[ "${LINTERS_ENABLED[*]}" =~ $1 ]]; then 385 return 386 fi 387 fi 388 389 EXE="${ARGS[0]}" 390 if [ ! -x "${EXE}" ]; then 391 if ! which "${EXE}" > /dev/null 2>&1 ; then 392 echo -e " ${YELLOW}${TITLE}:${NORMAL} cannot find ${EXE}" 393 if [ -z "$ALLOW_MISSING" ]; then 394 exit 1 395 fi 396 return 397 fi 398 fi 399 400 CONFIG="${ARGS[1]}" 401 FALLBACK="${ARGS[2]}" 402 403 if [ -n "${CONFIG}" ]; then 404 if [ -e "${CONFIG}" ]; then 405 LINTER_CONFIG+=( [${TITLE}]="${CONFIG}" ) 406 elif [ -n "${FALLBACK}" ] && [ -e "${FALLBACK}" ]; then 407 echo -e " ${YELLOW}${TITLE}:${NORMAL} cannot find ${CONFIG}; using ${FALLBACK}" 408 LINTER_CONFIG+=( [${TITLE}]="${FALLBACK}" ) 409 else 410 echo -e " ${YELLOW}${TITLE}:${NORMAL} cannot find config ${CONFIG}" 411 return 412 fi 413 fi 414 415 LINTERS_AVAILABLE+=( "${TITLE}" ) 416} 417 418# Check for a global .linter-ignore file. 419GLOBAL_IGNORE=("cat") 420if [ -e ".linter-ignore" ]; then 421 GLOBAL_IGNORE=("${CONFIG_PATH}/lib/ignore-filter" ".linter-ignore") 422fi 423 424# Find all the files in the git repository and organize by type. 425declare -A FILES=() 426FILES+=([commit]=".git") 427 428while read -r file; do 429 ftype="$(get_file_type "$file")" 430 FILES+=([$ftype]="$(echo -ne "$file;${FILES[$ftype]:-}")") 431done < <(git ls-files | xargs realpath --relative-base=. | "${GLOBAL_IGNORE[@]}") 432 433# For each linter, check if there are an applicable files and if it can 434# be enabled. 435for op in "${LINTERS_ALL[@]}"; do 436 for ftype in ${LINTER_TYPES[$op]//;/ }; do 437 if [[ -v FILES["$ftype"] ]]; then 438 check_linter "$op" "${LINTER_REQUIRE[${op}]}" 439 break 440 fi 441 done 442done 443 444# Call each linter. 445for op in "${LINTERS_AVAILABLE[@]}"; do 446 447 # Determine the linter-specific ignore file(s). 448 LOCAL_IGNORE=("${CONFIG_PATH}/lib/ignore-filter") 449 if [[ -v LINTER_IGNORE["$op"] ]]; then 450 for ignorefile in ${LINTER_IGNORE["$op"]//;/ } ; do 451 if [ -e "$ignorefile" ]; then 452 LOCAL_IGNORE+=("$ignorefile") 453 fi 454 done 455 fi 456 if [ 1 -eq ${#LOCAL_IGNORE[@]} ]; then 457 LOCAL_IGNORE=("cat") 458 fi 459 460 # Find all the files for this linter, filtering out the ignores. 461 LINTER_FILES=() 462 while read -r file ; do 463 if [ -e "$file" ]; then 464 LINTER_FILES+=("$file") 465 fi 466 done < <(for ftype in ${LINTER_TYPES[$op]//;/ }; do 467 # shellcheck disable=SC2001 468 echo "${FILES["$ftype"]:-}" | sed "s/;/\\n/g" 469 done | "${LOCAL_IGNORE[@]}") 470 471 # Call the linter now with all the files. 472 if [ 0 -ne ${#LINTER_FILES[@]} ]; then 473 echo -e " ${BLUE}Running $op${NORMAL} ($(do_version_"$op"))" 474 if ! "do_$op" "${LINTER_FILES[@]}" ; then 475 LINTERS_FAILED+=([$op]=1) 476 echo -e " ${RED}$op - FAILED${NORMAL}" 477 fi 478 else 479 echo -e " ${YELLOW}${op}:${NORMAL} all applicable files are on ignore-lists" 480 fi 481done 482 483# Check for failing linters. 484if [ 0 -ne ${#LINTERS_FAILED[@]} ]; then 485 for op in "${!LINTERS_FAILED[@]}"; do 486 echo -e "$op: ${RED}FAILED${NORMAL} (see prior failure)" 487 done 488 exit 1 489fi 490 491# Check for differences. 492if [ -z "$OPTION_NO_DIFF" ]; then 493 echo -e " ${BLUE}Result differences...${NORMAL}" 494 if ! git --no-pager diff --exit-code ; then 495 echo -e "Format: ${RED}FAILED${NORMAL}" 496 exit 1 497 else 498 echo -e "Format: ${GREEN}PASSED${NORMAL}" 499 fi 500fi 501 502# Sometimes your situation is terrible enough that you need the flexibility. 503# For example, phosphor-mboxd. 504for formatter in "format-code.sh" "format-code"; do 505 if [[ -x "${formatter}" ]]; then 506 echo -e " ${BLUE}Calling secondary formatter:${NORMAL} ${formatter}" 507 "./${formatter}" 508 if [ -z "$OPTION_NO_DIFF" ]; then 509 git --no-pager diff --exit-code 510 fi 511 fi 512done 513