Created
September 5, 2024 12:33
-
-
Save koonix/a5be47aff2656cd4a9dc38ac0ecd4327 to your computer and use it in GitHub Desktop.
Add license headers to source files. This example adds the Apache header to Golang files.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -eu -o pipefail | |
# This script ensures source code files | |
# have copyright license headers. | |
# | |
# It modifies all source files in place | |
# and avoids adding a license header | |
# to any file that already has one. | |
header=( | |
'// Copyright 2024 Cock&Balls LLC' | |
'//' | |
'// Licensed under the Apache License, Version 2.0 (the "License");' | |
'// you may not use this file except in compliance with the License.' | |
'// You may obtain a copy of the License at' | |
'//' | |
'// http://www.apache.org/licenses/LICENSE-2.0' | |
'//' | |
'// Unless required by applicable law or agreed to in writing, software' | |
'// distributed under the License is distributed on an "AS IS" BASIS,' | |
'// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.' | |
'// See the License for the specific language governing permissions and' | |
'// limitations under the License.' | |
) | |
realpath=$(realpath -- "$0") | |
cd "${realpath%/*}" | |
checked=0 | |
updated=0 | |
shopt -s globstar | |
for file in **/*.go; do | |
checked=$((checked+1)) | |
# skip if the file contains the exact header | |
changed=0 | |
for (( i=0; i < ${#header[@]}; i++ )); do | |
IFS= read -r line | |
[[ $line != "${header[$i]}" ]] && changed=1 && break | |
done < "$file" | |
[[ $changed == 0 ]] && continue | |
# check whether the file starts with a copyright header | |
in_header=0 | |
IFS= read -r line < "$file" | |
[[ $line == '//'*'Copyright'* ]] && in_header=1 | |
# add the new copyright header, replacing the existing one, if any | |
lines=() | |
while IFS= read -r line; do | |
if [[ $in_header == 1 ]] && [[ $line != '//'* ]]; then | |
in_header=0 | |
fi | |
if [[ $in_header == 0 ]]; then | |
lines+=("$line") | |
fi | |
done < "$file" | |
printf '%s\n' "${header[@]}" '' "${lines[@]}" | gofmt > "$file" | |
echo "updated $file" | |
updated=$((updated+1)) | |
done | |
echo | |
echo "checked $checked files." | |
echo "updated $updated files." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment