Last active
August 6, 2018 11:54
-
-
Save Luzifer/ff2660f24778db4241f91c224bd5cf55 to your computer and use it in GitHub Desktop.
Shell script to list licenses of Go dependencies through the Github license API
This file contains 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 -euo pipefail | |
# Export GITHUB_TOKEN shell variable with a Github token with no special | |
# permissions assigned. Afterwards start the script with a import path | |
# prefix as first argument: | |
# | |
# go-licenses.sh github.com/Luzifer | |
replaces=( | |
# Rewrite vendors to their normal package paths | |
's@.*/vendor/@@' | |
# Rewrite wrapper packages to their Github source | |
's@google.golang.org/api@github.com/google/google-api-go-client@' | |
's@golang.org/x@github.com/golang@' | |
's@cloud.google.com/go@github.com/GoogleCloudPlatform/google-cloud-go@' | |
's@gopkg.in/([^/]+)/([^/]+).v[0-9]+@github.com/\1/\2@' | |
's@gopkg.in/([^/]+).v[0-9]+@github.com/go-\1/\1@' | |
# Shorten Github projects to have no sub-paths | |
's@^(github.com/[^/]+/[^/]+).*@\1@' | |
) | |
function get_github_license() { | |
[[ $1 =~ ^github.com.* ]] || { | |
# Script only supports querying Github for licenses | |
echo "Unknown" | |
return | |
} | |
lic=$(curl -sSfL -u "api:${GITHUB_TOKEN}" https://api.github.com/repos/${1#github.com/}/license 2>/dev/null || echo '{"license":{"spdx_id":"Unknown"}}') | |
echo "${lic}" | jq -r '.license.spdx_id' | sed 's/null/Unknown/' | |
} | |
function main() { | |
# Query imports from supplied import path | |
list=$(go list -f '{{ join .Imports "\n" }}' ${IMPORT_PATH}/...) | |
# Apply replacements | |
for repl in ${replaces[@]}; do | |
list=$(echo "${list}" | sed -E "${repl}") | |
done | |
# Iterate through imports | |
for dep in $(echo "${list}" | sort | uniq); do | |
echo -e "$(get_github_license ${dep})\t${dep} " | |
done | sort | |
} | |
IMPORT_PATH=${1:-} | |
[ -z "${IMPORT_PATH}" ] && { | |
echo "Usage: $0 <import path>" | |
exit 2 | |
} | |
[ -z "${GITHUB_TOKEN:-}" ] && { | |
echo "No GITHUB_TOKEN provided, stopping to work now" | |
exit 2 | |
} | |
main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment