buildifier_format_code.sh 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #! /bin/bash
  2. # Copyright 2019 The gRPC Authors
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. set -e
  16. BUILDIFIER_VERSION="4.2.2"
  17. TEMP_BUILDIFIER_PATH="/tmp/buildifier"
  18. EXTRA_BUILDIFIER_FLAGS="$*"
  19. function error_handling() {
  20. error=$1
  21. if [[ -x "$error" ]]; then
  22. echo "${error}"
  23. exit 1
  24. fi
  25. }
  26. function download_buildifier() {
  27. platform="$(uname -s)"
  28. case "${platform}" in
  29. Linux*) download_link="https://github.com/bazelbuild/buildtools/releases/download/${BUILDIFIER_VERSION}/buildifier";;
  30. Darwin*) download_link="https://github.com/bazelbuild/buildtools/releases/download/${BUILDIFIER_VERSION}/buildifier.mac";;
  31. *) error_handling "Unsupported platform: ${platform}";;
  32. esac
  33. if [ -x "$(command -v curl)" ]; then
  34. curl -L -o ${TEMP_BUILDIFIER_PATH} ${download_link}
  35. elif [ -x "$(command -v wget)" ]; then
  36. wget -O ${TEMP_BUILDIFIER_PATH} ${download_link}
  37. else
  38. error_handling "Download failed: curl and wget not available"
  39. fi
  40. chmod +x ${TEMP_BUILDIFIER_PATH}
  41. }
  42. # Get the correct version of buildifier
  43. if [ -x "$(command -v buildifier)" ]; then
  44. existing_buildifier_version="$(buildifier -version 2>&1 | head -n1 | cut -d" " -f3)"
  45. if [[ "${existing_buildifier_version}" != "${BUILDIFIER_VERSION}" ]]; then
  46. download_buildifier
  47. buildifier_bin="${TEMP_BUILDIFIER_PATH}"
  48. else
  49. buildifier_bin="buildifier"
  50. fi
  51. else
  52. download_buildifier
  53. buildifier_bin="${TEMP_BUILDIFIER_PATH}"
  54. fi
  55. # cd to repo root
  56. dir=$(dirname "${0}")
  57. cd "${dir}/../.."
  58. bazel_files=$(find . \( -iname 'BUILD' -o -iname '*.bzl' -o -iname '*.bazel' -o -iname 'WORKSPACE' \) -type f -not -path "./third_party/*")
  59. # shellcheck disable=SC2086,SC2068
  60. ${buildifier_bin} ${EXTRA_BUILDIFIER_FLAGS[@]} -v ${bazel_files}