リポジトリごとにGOPATHを切る環境でのvim-go

↓のようなリポジトリごとにその直下をGOPATHにする環境でGoを書く時、

.
├── github.com/daisuzu/bar
│     ├── bin
│     ├── pkg
│     └── src
│         └── bar
│              └── main.go
└── github.com/daisuzu/foo
       ├── bin
       ├── pkg
       └── src
           └── foo
                └── main.go

両方のリポジトリのファイルを同時に開いて行ったり来たりするのを少し楽にするためにvim-goの設定を切り替える関数を作ることにした。

function! SwitchRepo()
  let toplevel = trim(system('git rev-parse --show-toplevel'))
  if toplevel =~# '^fatal'
    return
  endif

  " GOPATHをリポジトリ直下に変更する
  execute 'GoPath ' . toplevel

  " リポジトリ名をgoimportsの'-local'フラグに渡す
  let g:go_fmt_options = { 'goimports': '-local ' . fnamemodify(toplevel, ':t') }
endfunction

*1

これで他のリポジトリのファイルを開いたらcdした後にcall SwitchRepo()すれば:GoDefでちゃんと飛べるし、
:GoImportsした時もサブパッケージを標準パッケージとは異なるグループにしてくれる。

  • Before
import (
    "bar/handler"
    "bar/model"
    "fmt"
)
  • After
import (
    "fmt"

    "bar/handler"
    "bar/model"
)

autocmdを組み合わせればもっと便利になるかもしれないけど、今のところは必要ない。

*1:普段はg:go_fmt_optionsを使っていないので都度上書き