Skip to content

Instantly share code, notes, and snippets.

@dionysius
Last active January 7, 2020 18:00
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 dionysius/c803235e2e94353ed72be99ef208d428 to your computer and use it in GitHub Desktop.
Save dionysius/c803235e2e94353ed72be99ef208d428 to your computer and use it in GitHub Desktop.
Go add package import comment for go projects with modules
#!/bin/bash
# This script replaces the first package directive in each go file (with some excludes) and
# adds the canonical package path as import as a comment behind it
# e.g. `package foo // import "example.com/project/pkg/foo`
#
# While the package import comment is ignored with go modules I still liked it whenever I saw
# such comment, speeding up integration of that import into my sources or `go get`ting them
#
# I'm sure we could trim the script and save some commands, but at least it does the job :)
# (hopefully also for you)
set -o nounset -e
# we want to exit if current working dir is no go project (would error and thus exit with set -e)
go list -m >/dev/null
# get all go files except test files
files=$(grep -Rl --include=\*.go --exclude=\*_test.go "^package ")
while read -r file; do
reldir=$(dirname "$file")
package=$(go list -f '{{ .Name }}' ./"$reldir")
# a main package is not importable
if [[ "$package" == "main" ]]; then
continue
fi
importpath=$(go list -f '{{ .ImportPath }}' ./"$reldir")
# an internal package is not importable
if [[ "$package" =~ (^|/)"internal"(/|$) ]]; then
continue
fi
sed -i "s|^package $package.*|package $package // import \"$importpath\"|" "$file"
done <<< "$files"
Copyright 2019 dionysius
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@dionysius
Copy link
Author

dionysius commented Dec 19, 2019

If someone has a generator, formatter or linter in go, I'd like to know

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment