Last active
December 21, 2022 11:59
-
-
Save syhily/0cf83c575809154f7ac21253ff6186b7 to your computer and use it in GitHub Desktop.
A custom goimports script with better -local sorting support. Used in pre-commit hooks.
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 | |
## This shell script is used with https://github.com/TekWizely/pre-commit-golang | |
# You should add it to your .pre-commit-config.yaml file with the options like | |
# | |
# - repo: https://github.com/tekwizely/pre-commit-golang | |
# rev: v1.0.0-rc.1 | |
# hooks: | |
# - id: go-mod-tidy-repo | |
# - id: golangci-lint-mod | |
# - id: my-cmd | |
# name: goimports | |
# alias: goimports | |
# args: [ ./goimports.sh, github.com/syhily/hobbit ] | |
module="$1" | |
file="$2" | |
# Detect the running OS. | |
COMMAND="sed" | |
if [[ $OSTYPE == 'darwin'* ]]; then | |
# macOS have to use the gsed which can be installed by `brew install gsed`. | |
COMMAND="gsed" | |
fi | |
# Detect the command. | |
command -v $COMMAND >/dev/null 2>&1 || { echo >&2 "Require ${COMMAND} but it's not installed. Aborting."; exit 1; } | |
# Remove all the import spaces in staging golang files. | |
REPLACEMENT=$(cat <<-END | |
' | |
/^import (/,/)/ { | |
/^$/ d | |
} | |
' | |
END | |
) | |
bash -c "${COMMAND} -i ${REPLACEMENT} ${file}" | |
# Format the staging golang files. | |
goimports -l -d -local "${module}" -w "${file}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment