k8s.io/kubernetes@v1.31.0-alpha.0.0.20240520171757-56147500dadc/hack/lib/verify-generated.sh (about)

     1  #!/usr/bin/env bash
     2  
     3  # Copyright 2014 The Kubernetes Authors.
     4  #
     5  # Licensed under the Apache License, Version 2.0 (the "License");
     6  # you may not use this file except in compliance with the License.
     7  # You may obtain a copy of the License at
     8  #
     9  #     http://www.apache.org/licenses/LICENSE-2.0
    10  #
    11  # Unless required by applicable law or agreed to in writing, software
    12  # distributed under the License is distributed on an "AS IS" BASIS,
    13  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14  # See the License for the specific language governing permissions and
    15  # limitations under the License.
    16  
    17  # Short-circuit if verify-generated.sh has already been sourced.
    18  [[ $(type -t kube::verify::generated::loaded) == function ]] && return 0
    19  
    20  source "${KUBE_ROOT}/hack/lib/init.sh"
    21  
    22  # This function verifies whether generated files are up-to-date. The first two
    23  # parameters are messages that get printed to stderr when changes are found,
    24  # the rest are the function or command and its parameters for generating files
    25  # in the work tree.
    26  #
    27  # Example: kube::verify::generated "Mock files are out of date" "Please run 'hack/update-mocks.sh'" hack/update-mocks.sh
    28  kube::verify::generated() {
    29    ( # a subshell prevents environment changes from leaking out of this function
    30      local failure_header=$1
    31      shift
    32      local failure_tail=$1
    33      shift
    34  
    35      kube::util::ensure_clean_working_dir
    36  
    37      # This sets up the environment, like GOCACHE, which keeps the worktree cleaner.
    38      kube::golang::setup_env
    39  
    40      _tmpdir="$(kube::realpath "$(mktemp -d -t "verify-generated-$(basename "$1").XXXXXX")")"
    41      git worktree add -f -q "${_tmpdir}" HEAD
    42      kube::util::trap_add "git worktree remove -f ${_tmpdir}" EXIT
    43      cd "${_tmpdir}"
    44  
    45      # Update generated files.
    46      "$@"
    47  
    48      # Test for diffs
    49      diffs=$(git status --porcelain | wc -l)
    50      if [[ ${diffs} -gt 0 ]]; then
    51        if [[ -n "${failure_header}" ]]; then
    52          echo "${failure_header}" >&2
    53        fi
    54        git status >&2
    55        git diff >&2
    56        if [[ -n "${failure_tail}" ]]; then
    57          echo "" >&2
    58          echo "${failure_tail}" >&2
    59        fi
    60        return 1
    61      fi
    62    )
    63  }
    64  
    65  # Marker function to indicate verify-generated.sh has been fully sourced.
    66  kube::verify::generated::loaded() {
    67    return 0
    68  }