Skip to content

Instantly share code, notes, and snippets.

@jonlabelle
Last active August 16, 2021 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jonlabelle/a0751768a220274a90d4be498da51643 to your computer and use it in GitHub Desktop.
Save jonlabelle/a0751768a220274a90d4be498da51643 to your computer and use it in GitHub Desktop.
Bash wrapper script for the .NET Format global CLI tool.
#!/usr/bin/env bash
#
# Bash wrapper script for the .NET Format global CLI tool.
#
# Author........: Jon LaBelle
# Date..........: February 4, 2021
# Snippet.......: https://jonlabelle.com/snippets/view/shell/net-format-bash-wrapper-script
# Gist..........: https://gist.github.com/jonlabelle/a0751768a220274a90d4be498da51643
# .NET Format...: https://github.com/dotnet/format
#
readonly SCRIPT_NAME=$(basename "${0}")
show_usage() {
echo "Usage: ${SCRIPT_NAME} [options]"
echo
echo "A simple wrapper script for the .NET Format global CLI tool."
echo
echo "Globs the current directory for *.sln files and passes matches"
echo "into the dotnet format tool's <workspace> argument."
echo
echo "Options:"
echo
echo " -i, --install Install the dotnet format global tool."
echo " -u, --uninstall Uninstall the dotnet format global tool."
echo " -f, --format Formats, fixes codestyle errors, and fixes 3rd party analyzer errors."
echo " -c, --check Check only. Terminates with a non-zero exit code if any files require formatting."
echo " -h, --help Show usage."
echo
}
install() {
# dotnet-format tool on net5 requires adding custom package source
dotnet tool install -g dotnet-format \
--version 5.0.* \
--add-source https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json
}
uninstall() {
dotnet tool uninstall -g dotnet-format
}
format() {
find . -name '*.sln' -type f -maxdepth 1 -print0 | xargs -0 -I % \
dotnet format --verbosity detailed % \
--fix-whitespace \
--fix-analyzers
}
check() {
local result project
for project in $(find . -name '*.sln' -type f -maxdepth 1); do
echo "> Checking project: $project"
dotnet format --verbosity diagnostic "$project" \
--fix-whitespace \
--fix-style warn \
--fix-analyzers \
--check
result=$?
if [ "$result" -gt 0 ]; then
echo
echo " Format check returned a non-zero exit code ($result)."
fi
echo
done
}
if [[ $# -eq 0 || -z "$1" ]]; then
show_usage
exit 1
fi
if [[ "$1" == "-i" || "$1" == "--install" ]]; then
install
elif [[ "$1" == "-u" || "$1" == "--uninstall" ]]; then
uninstall
elif [[ "$1" == "-f" || "$1" == "--format" ]]; then
format
elif [[ "$1" == "-c" || "$1" == "--check" ]]; then
check
elif [[ "$1" == "-h" || "$1" == "--help" ]]; then
show_usage
else
echo "'$1' is not a valid argument."
echo
show_usage
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment