vim-go with coc.nvim: how to rename a package?

1.2k views Asked by At

I have a file work.go opened in vim-go. It's in package oldpackagename.

I want to refactor and rename it to newpackagename. Is there some tooling for that? The reason is, the initial assumptions for oldpackagename do not apply anymore.

I know I can do search and replace stuff, but usually either

  • GoRename resp.
  • nmap <leader>rn <Plug>(coc-rename)

work just fine on automatically renaming all occurrences.

But for the package name, I get:

vim-go: [rename] SUCCESS vim-go: cannot rename the identifier at the requested position for GoRename and:

[coc.nvim] Error on rename: The element can't be renamed. for coc.nvim.

Is package renaming different? Do I have to use search/replace or are my configs maybe corrupted?

2

There are 2 answers

0
Benjamin W. On BEST ANSWER

Under the hood, vim-go uses either gorename or gopls to run :GoRename; the default is now gopls.

Both of these don't support renaming packages:

For coc.nvim, I'm not sure, but it seems to integrate with gopls, so the same lack of support would apply.

0
VonC On

gopls should support package renaming soon (Oct. 2022).
Its integration with vim-go should take advantage of that as soon as the feature is released.

Issue 41567 mentions CL 420958

gopls/internal/lsp: add support for package renaming

Users can now rename packages by performing a rename on the package name in package declarations.

The editor will prompt user with a dialogue text field to change the package name.
This rename feature then do the following:

  • Rename all the external imports of the renaming package. In case there is renaming conflicts within a file, the feature repeatedly try fresh names constructed by appending new package name with number of try times so far until succeed.
  • Rename all the internal references to the renaming package from its files.
  • Rename the directory of the renamed package and update the imports' paths of any packages nested under the renamed directory.
  • Rename the test package with the new package name and suffix "_test" with the current test package name ends with "_test", or just the new package name otherwise.

However:

Todo:

  • Add a test for the case when the renaming package's path contains "internal" as a segment.
  • Allow edit to the whole package path not just only the last segment of the package path
  • Reject renaming if the renamed subpackages don't belong to the same module with the renaming package
  • Check the go.mod files in the workspace to see if any replace directives need to be fixed if the renaming affects the locations of any go.mod files