feat(tox): add copyright year fixer script
[csit.git] / resources / libraries / bash / entry / tox / fix_copyright_year.sh
1 # Copyright (c) 2024 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 set -exuo pipefail
15
16 # This file should be executed from tox, as the assumed working directory
17 # is different from where this file is located.
18 # This file does not have executable flag nor shebang,
19 # to dissuade non-tox callers.
20
21 # This is a fixer script, so be careful before starting it.
22 # It is recommended to always commit your recent edits before running this,
23 # and use "git diff" after running this to confirm the edits are correct.
24 # Otherwise you can lose your edits and introduce bad edits.
25
26 # This script runs a variant of "git diff" command
27 # to get the list of edited files, and few sed commands to edit the year
28 # if "20.." pattern matches in first 3 lines.
29 # No detection of "copyright", so edits can apply at surprising places.
30
31 # 3 lines were chosen, because first two lines could be shebang and empty line.
32
33 # "set -eu" handles failures from the following two lines.
34 BASH_CHECKS_DIR="$(dirname $(readlink -e "${BASH_SOURCE[0]}"))"
35 BASH_FUNCTION_DIR="$(readlink -e "${BASH_CHECKS_DIR}/../../function")"
36 source "${BASH_FUNCTION_DIR}/common.sh" || {
37     echo "Source failed." >&2
38     exit 1
39 }
40
41 year=$(date +'%Y')
42 IFS=$'\n'
43 files=($(git diff --name-only HEAD~ || true))
44 unset IFS
45 # A change can have thousands of files, supress console output for the cycle.
46 set +x
47 for fil in "${files[@]}"; do
48     if [[ -f "${fil}" ]]; then
49         sed -i "1 s/20../${year}/g" "${fil}"
50         sed -i "2 s/20../${year}/g" "${fil}"
51         sed -i "3 s/20../${year}/g" "${fil}"
52     # Else the file was actually deleted and sed would fail.
53     fi
54 done
55 set -x