File golang-src-macros.sh of Package golang-packaging
#!/bin/bash
set -xeo pipefail
export PREFIX="/usr/share/gocode/src"
get_go_source_files() {
go list -json ./...|jq -r '.ImportPath as $prefix | .GoFiles[] | "\($prefix)/\(.)"'
}
get_go_module_path() {
res=$(go list -f '{{.Module.Path}}' ./...|sort|uniq)
if [[ $(echo $res | wc -l) -gt 1 ]]; then
echo "got multiple module paths!"
exit 1
fi
echo $res
}
generate_filelist() {
rm -f go_files.lst go_files.tmp
# go files
for file in $(get_go_source_files); do
echo "$PREFIX/$file" >> go_files.tmp
done
# go.mod & go.sum
printf "$PREFIX/%s/go.mod\n$PREFIX/%s/go.sum\n" "$(get_go_module_path)" "$(get_go_module_path)" >> go_files.tmp
# PREFIX & leading directory
{ echo "%dir $PREFIX"; echo "%dir $(dirname $PREFIX)"; } >> go_files.tmp
# directories inside the source tree
for mod_name in $(go list -f '{{.ImportPath }}' ./...); do
echo "%dir $PREFIX/$mod_name" >> go_files.tmp
current="$PREFIX"
# now all directories leading to this file
for dir in $(echo "$mod_name" | tr '/' '\n'); do
current="$current/$dir"
echo "%dir $current" >> go_files.tmp
done
done
# remove all duplicates
sort < go_files.tmp | uniq > go_files.lst
rm go_files.tmp
}
go_install() {
mkdir -p "$RPM_BUILD_ROOT/$PREFIX"
srcs=()
dests=()
while IFS= read -r line; do
srcs+=("$line")
done < <(go list -json ./... | jq -r '.Dir as $dir | .GoFiles[] | "\($dir)/\(.)"')
while IFS= read -r line; do
dests+=("$line")
done < <(go list -json ./... | jq -r '.ImportPath as $imp_path | .GoFiles[] | "\($imp_path)/\(.)"')
len=${#srcs[@]}
for (( i=0; i<$len; i++ )); do
install -Dpm 0644 "${srcs[$i]}" "$RPM_BUILD_ROOT/$PREFIX/${dests[$i]}"
done
install -Dpm 0644 go.mod "$RPM_BUILD_ROOT/$PREFIX/$(get_go_module_path)/go.mod"
install -Dpm 0644 go.sum "$RPM_BUILD_ROOT/$PREFIX/$(get_go_module_path)/go.sum"
}
main() {
local action="${1}"
case "${action}" in
"--install"|"install")
go_install
;;
"--prep"|"prep")
process_prepare "${@:2}"
;;
"--build"|"build")
process_build "${@:2}"
;;
"--source"|"source")
process_source "${@:2}"
;;
"--test"|"test")
process_test "${@:2}"
;;
"--filelist"|"filelist")
generate_filelist
;;
*)
echo "Please specify a valid method: install, filelist" >&2
;;
esac
}
main "$@"