hylowaker
hylowaker

Reputation: 1143

How do I refactor module name in Go?

I have a Go module named mymodule, and I'd like to rename it into github.com/hylowaker/awesome-module

Using command go mod edit -module github.com/hylowaker/awesome-module only changes module name in go.mod file, leaving go sources unchanged. I tried Refactor feature in GoLand IDE, but GoLand does not allow renaming with slash(/) characters.

So I had to find and replace every import "mymodule/..." into import "github.com/hylowaker/awesome-module/... from my source files.

Is there a better way to refactor them?

Upvotes: 27

Views: 54677

Answers (4)

freson
freson

Reputation: 96

Much better is use GoMVP tool! I just downloaded the binary from releases and put it one level above the working directory

RUN: sudo ../gomvp old/app new/app

Then you can simply delete gomvp binary file

Upvotes: 0

Matthew Trent
Matthew Trent

Reputation: 3264

Run this in your Go project directory where you set CUR to be your current name and NEW to be the new one you want it changed to.

#!/usr/bin/env sh

export CUR="CHANGE THIS" # example: github.com/user/old-lame-name
export NEW="CHANGE THIS" # example: github.com/user/new-super-cool-name
go mod edit -module ${NEW}
find . -type f -name '*.go' -exec perl -pi -e 's/$ENV{CUR}/$ENV{NEW}/g' {} \;

Source and credit here.

Upvotes: 0

hylowaker
hylowaker

Reputation: 1143

This feature is introduced in GoLand version 2021.1.

You can invoke the Rename refactoring by pressing Shift+F6 on the module name in the go.mod file.

Upvotes: 25

Moacir Schmidt
Moacir Schmidt

Reputation: 945

In GoLand just press Ctrl+Shift+R and execute "Replace in Path"

It is safe to perform that in entire project since you only need to change go.mod file and all import clauses

Upvotes: 5

Related Questions