Blob Blame Raw
#!/bin/bash

usage() {
cat >&2 << EOF_USAGE
Usage: $0 -g <go import path> [-p <prefix>] [-G <go path>] [-v <version string>]
<go import path>   the Go import path of the target package
<prefix>:          an eventual prefix path such as %{buildroot}
<go path>:         the root of the Go source tree
<version string>:  tag symlinked renamings with <version string>

Example:
echo filename | $0 -g golang.org/x/net -G /usr/share/gocode
EOF_USAGE
exit 1
}

if ! options=$(getopt -n $0 -o hg:p:G:v: -l help,goipath:,prefix:,gopath:,version: -- "$@")
then
    # something went wrong, getopt will put out an error message for us
    exit 2
fi

eval set -- "$options"


prefix=''
gopath=/usr/share/gocode

while [ $# -gt 0 ] ; do
  case $1 in
    -h|--help)    usage ;;
    -g|--goipath) goipath="$2" ; shift;;
    -p|--prefix)  prefix=$(realpath -sm "$2") ; shift;;
    -G|--gopath)  gopath="$2" ; shift;;
    -v|--version) version=" = $2" ; shift;;
    (--)          shift; break;;
    (-*)          echo "$0: error - unrecognized option $1" >&2; exit 3;;
    (*)           break;;
  esac
  shift
done

[[ -z ${goipath} ]] && exit 0

root="${prefix}${gopath}"

while read dir ; do
  if [[ -L $dir ]] ; then
    targetdir=$(realpath -m "$dir")
    [[ $targetdir != ${prefix}* ]] && targetdir="${prefix}${targetdir}"
    if [[ ${targetdir}/ == ${root}/src/${goipath}/* ]] ; then
      for subdir in $(find "$targetdir" -type d) ; do
        echo "golang(${subdir#${root}/src/})${version}"
      done
    fi
  else
    if [[ -d $dir ]] ; then
      dir=$(realpath -sm "$dir")
      package="${dir#${root}/src/}"
      GOPATH=$root go list -e -f \
            '{{ join .Imports "\n" }}' "$package" |\
        while read import ; do
          GOPATH=$root go list -e -f \
            '{{if not .Standard}}{{.ImportPath | printf "golang(%s)\n"}}{{end}}' "$import"
        done
    fi
  fi
done | sort | uniq \
     | grep -v '/\([._]\)\?\(internal\|testdata\)\([/)]\)' | grep -v 'golang(C)'