How to remove a Go package downloaded with "go get" command?

Viewed 29484

I want to know if there is golang way to delete or remove a go package. To be simpler, opposite to go get command.

e.g. 
$ go get <PACKAGE_NAME> 
$ go delete <PACKAGE_NAME>    (Looking for similar functionality)

Please NOTE that I am aware that we can remove the downloaded files from src and pkg directory manually by using rm command. But the problem is that system command rm is not aware of your go specific stuffs (etc. to look inside $GOPATH/pkg .. ) and this is an extra step for the user while using rm . I am looking for something which all package managers provides.. as mentioned in one comment.. (npm uninstall, pip uninstall etc..).

4 Answers

You can just delete it from you disk:

rm -r $GOPATH/src/<PACKAGE_NAME>

This will remove the package completely. Alas, there is no tool or go command for removing packages. But this should be simple enough.

But is there a simple way to delete the downloaded package (go delete PACKAGE_NAME?) ?

No there is not.

Manually rming is the way to go.

For those using Go Modules rm is not enought as your go.mod and go.sum files stays dirty. You can use go mod tidy command which works but is not so intuitive.

From https://blog.golang.org/migrating-to-go-modules:

Removing a dependency can only be done after checking all packages in a module, and all possible build tag combinations for those packages. An ordinary build command does not load this information, and so it cannot safely remove dependencies.

The go mod tidy command cleans up these unused dependencies

The first time I used it removed unused dependencies but also installed new ones. Later I discovered that it run tests to check if a dependency can be removed as described in https://github.com/golang/go/wiki/Modules#why-does-go-mod-tidy-record-indirect-and-test-dependencies-in-my-gomod.

I found an easy solution for doing this. I am using fish shell so I just added this simple function in ~/.config/fish/config.fish.

It does the job perfectly with cleaning up empty folders under $GOPATH. You might want to remove this part if you want to keep empty folders but for me, it was just annoying.

Note that your GOPATH must be declared before the function declaration or this will not work.

Make sure that you are checking for empty args because otherwise, this would remove the whole $GOPATH/src folder and you do not want that.

If you're not under Mac, you'd need to edit the 'darwin_amd64' folder and if you're not on fish, this will not work but you can simply modify it to fit your current shell.

export GOPATH=$HOME/Go

function godel
   if string length -q $argv
      rm -rf $GOPATH/src/$argv $GOPATH/pkg/darwin_amd64/$argv.a
      find $GOPATH -type d -empty -delete
   else
      echo you must send an argument
   end
end
Related