Skip to content

Instantly share code, notes, and snippets.

@Phundamentals
Last active November 23, 2023 03:03
Show Gist options
  • Save Phundamentals/46948ed1b52264bcd2900c8d430fd448 to your computer and use it in GitHub Desktop.
Save Phundamentals/46948ed1b52264bcd2900c8d430fd448 to your computer and use it in GitHub Desktop.
Publish NuGet Packages To GitHub
#!/bin/sh
#
# This script attempts to publish all *.nupkg files below a given root directory to GitHub packages.
#
# Recommended: add a nuget source replacing SOURCE_NAME (eg: github), GITHUB_USERNAME and GITHUB_API_KEY via https://github.com/settings/tokens.
# Use a classic token that only has the 'read:packages' permission. This token will provide read-only acces to your GitHub packages from
# your IDE / NuGet commandline, etc. When pushing packages with this script, provide the read/write API key when asked. This key should have
# the 'read:packages', 'write:packages', and optionally the 'delete:packages' permissions. Note that you cannot disable the automatically
# enabled 'repo:' permissions.
#
# This setup will use the read-only NuGet source by default, overriding the API key when pushing new versions of packages. It protects the
# API key that allows writing and pushing by not saving it and it does not end up visibly in your bash_history, except for the initial
# 'dotnet nuget add source' command.
#
# Either way, even if you choose to save your API key with full push permissions instead, you will have to add the nuget source first,
# or 'nuget push' might fail.
#
# dotnet nuget add source --name <SOURCE_NAME> --username <GITHUB_USERNAME> --password <GITHUB_RO_API_KEY> https://nuget.pkg.github.com/<GITHUB_USER_NAME>/index.json
#
# The same thing can be done by using the NuGet executable directly, although the arguments might be named differently.
#
# You can modify 'Build' in "${1:-Build}" below to specify another default directory to search for nuget packages. The '1:-' means: use the first
# commandline argument, if that's missing, use 'Build'.
#
echo
# Get the write/publish API key from the arguments, the environment, or the user.
if [ -n "${3}" ]; then
GITHUB_TOKEN="${3}"
fi
if [ -z "${GITHUB_TOKEN}" ]; then
read -s -p "API key: " GITHUB_TOKEN
fi
if [ -z "${GITHUB_TOKEN}" ]; then
echo -e "\n\n Please provide your GitHub API key or Personal Access Token"
exit
fi
echo
# Publish each package to GitHub.
find -P "${1:-Packages}" -type f -iname "*.nupkg" -not -iname "*.symbols.nupkg" -execdir dotnet nuget push "{}" --source ${2:-github} --api-key ${GITHUB_TOKEN} --skip-duplicate ";"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment