Skip to content

Instantly share code, notes, and snippets.

@yuriy-yarosh
Last active June 8, 2023 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuriy-yarosh/a8111c3e80e8a40e3751ac209f449b5a to your computer and use it in GitHub Desktop.
Save yuriy-yarosh/a8111c3e80e8a40e3751ac209f449b5a to your computer and use it in GitHub Desktop.
golang do.sh go.work helper script
#!/usr/bin/env bash
set +eux
cd "$(dirname "$0")" || exit 1
which goimports > /dev/null || go install golang.org/x/tools/cmd/goimports@latest
cmd=$1
[ "$cmd" == "gen" ] && valid_cmd=true
[ "$cmd" == "fmt" ] && valid_cmd=true
[ "$cmd" == "tidy" ] && valid_cmd=true
[ "$cmd" == "lint" ] && valid_cmd=true
[ "$cmd" == "test" ] && valid_cmd=true
[ -z "$cmd" ] && echo "Usage: do.sh [gen|fmt|test|lint|tidy]" && exit 1
[ -n "$cmd" ] && [ -z "$valid_cmd" ] && echo "use [gen|fmt|test|lint|tidy] instead of $cmd" && exit 1
mapfile -t package_dirs < <(go list -f '{{.Dir}}' -m | xargs -L1 realpath --relative-to=. | sed 's|\(.*\)|\./\1/...|')
mapfile -t dirs < <(go list -f '{{.Dir}}' -m)
[ "$cmd" == "test" ] && echo "${package_dirs[@]}" | xargs -L1 go test | grep -v -e "no test" -e "cached"
[ "$cmd" == "lint" ] && echo "${package_dirs[@]}" | xargs -L1 golangci-lint run --fix
[ "$cmd" == "tidy" ] && echo "${dirs[@]}" | sed 's| |\n|gm' | sed 's|^\(.*\)$|env --chdir=\1 -S go mod tidy|' | xargs -I '{}' bash -c "{}"
[ "$cmd" == "tidy" ] && go work sync
[ "$cmd" == "fmt" ] && echo "${dirs[@]}" | sed 's| |\n|gm' | sed 's|^\(.*\)$|env --chdir=\1 -S goimports -w .|' | xargs -I '{}' bash -c "{}"
[ "$cmd" == "fmt" ] && echo "${dirs[@]}" | sed 's| |\n|gm' | sed 's|^\(.*\)$|env --chdir=\1 -S go fmt ./...|' | xargs -I '{}' bash -c "{}"
[ "$cmd" == "gen" ] && echo "${dirs[@]}" | sed 's| |\n|gm' | sed 's|^\(.*\)$|env --chdir=\1 -S go generate ./...|' | xargs -I '{}' bash -c "{}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment