Skip to content

Enable `gofmt s` (simplify) flag on gopls enabled VScode

Jihoon Seo edited this page Sep 16, 2021 · 1 revision

[배경]

VScode 사용 시, Go Tools extension을 설치했다면, Go language server로 gopls가 설치되어 활용되고 있을 것입니다.

그런데, gopls가 formatting을 해 주기는 하는데, gofmt -s (simplify) flag가 적용되지 않은 formatting을 해 주고 있습니다.

이로 인해 다음과 같은 일이 있었습니다.

(As of 2021-09-16)

image


[Enable gofmt -s (simplify) flag on gopls-enabled VScode]

https://github.com/microsoft/vscode-go/issues/3230

파일 저장 시 Go language server 가 Code Action을 수행하는데, 이 때 "fixAll" 하도록 설정하려면

"[go]": {
	"editor.codeActionsOnSave": {
		"source.fixAll": true,
	},
 },

이렇게 하면 된다고 합니다.

제 환경에 적용해 보았습니다.

~/.config/Code/User/settings.json

{
    "workbench.editorAssociations": {
        "*.ipynb": "jupyter.notebook.ipynb"
    },
    "go.toolsManagement.autoUpdate": true,
    "editor.inlineSuggest.enabled": true,
    "[go]": {
        "editor.insertSpaces": false,
        "editor.formatOnSave": true,
        "editor.codeActionsOnSave": {
            "source.organizeImports": true,
+            "source.fixAll": true,
        },
        "editor.suggest.snippetsPreventQuickSuggestions": false
    }
}

그리고 나서, cb-tumblebug/src/core/common/utility.go 파일을 열고 저장하니 gofmt -s 한 효과가 났습니다! 😊


[gofmt -s 적용되는지 확인하는 방법]

package main

import (
	"strings"
)

func main() {
var final = strings.Split("a b c", " ")
var first = strings.Split("d e f", " ")
final = append(final, first[2:len(first)]...)
//gofmt -s main.go would change the previous line to
final = append(final, first[2:]...)
}

이 코드를 저장했을 때

  1. first[2:len(first)] 이 그대로 있으면, 즉
package main

import (
	"strings"
)

func main() {
	var final = strings.Split("a b c", " ")
	var first = strings.Split("d e f", " ")
	final = append(final, first[2:len(first)]...)
	//gofmt -s main.go would change the previous line to
	final = append(final, first[2:]...)
}

이렇게 저장되면, gofmt -s 적용되지 않은 것입니다.

  1. first[2:] 로 바뀌면, 즉
package main

import (
	"strings"
)

func main() {
	var final = strings.Split("a b c", " ")
	var first = strings.Split("d e f", " ")
	final = append(final, first[2:]...)
	//gofmt -s main.go would change the previous line to
	final = append(final, first[2:]...)
}

이렇게 저장되면, gofmt -s 적용된 것입니다.

(주1: 제 경우에는 "editor.formatOnSave": true, 라인은 주석처리해도 formatOnSave 동작합니다.

기본값이 true 이고, false 로 명시해야만 동작 안 하는 것일 수도 있겠네요 😊

아니면 "source.fixAll": true, 옵션이 formatOnSave 도 포함하는 것일 수도 있구요 😊)

(주2: formatting이 이전에는 formatting (by e.g. gofmt) 이라는 범주에 있었는데,

code action (by e.g. gopls) 범주로 분리되었다고 합니다. 😊)


[기타 obsolete 내용들]

VScode에서 파일 저장할 때 자동으로 되게 하려면..

https://github.com/microsoft/vscode-go/issues/444

{
    "go.formatTool": "gofmt",
    "go.formatFlags": ["-s", "-e"]
}

하면 된다고 합니다.

그런데

image

Go language server 를 쓰고 있으면 Go Format Tool 은 못 쓰네요..


[추측]

image

여기서 Go Lint Tool을 golangci-lint 등으로 바꾸고 golangci-lint 로 통합 이용할 lint tool 중 gofmt 에 -s -w flag를 pass하도록 설정하면 되려나요..

테스트 해 보지는 않았습니다.. 😊

Clone this wiki locally