Debian Codegraph @

README.md

raw symbols SCIP
1 # gofumpt
2
3 [![Go Reference](https://pkg.go.dev/badge/mvdan.cc/gofumpt/format.svg)](https://pkg.go.dev/mvdan.cc/gofumpt/format)
4
5 go install mvdan.cc/gofumpt@latest
6
7 Enforce a stricter format than `gofmt`, while being backwards compatible.
8 That is, `gofumpt` is happy with a subset of the formats that `gofmt` is happy with.
9
10 The tool is a fork of `gofmt` as of Go 1.21, and requires Go 1.20 or later.
11 It can be used as a drop-in replacement to format your Go code,
12 and running `gofmt` after `gofumpt` should produce no changes.
13 For example:
14
15 gofumpt -l -w .
16
17 Some of the Go source files in this repository belong to the Go project.
18 The project includes copies of `go/printer` and `go/doc/comment` as of Go 1.21
19 to ensure consistent formatting independent of what Go version is being used.
20 The [added formatting rules](#Added-rules) are implemented in the `format` package.
21
22 `vendor` and `testdata` directories are skipped unless given as explicit arguments.
23 Similarly, the added rules do not apply to generated Go files unless they are
24 given as explicit arguments.
25
26 Finally, note that the `-r` rewrite flag is removed in favor of `gofmt -r`,
27 and the `-s` flag is hidden as it is always enabled.
28
29 ### Added rules
30
31 **No empty lines following an assignment operator**
32
33 <details><summary><i>Example</i></summary>
34
35 ```go
36 func foo() {
37 foo :=
38 "bar"
39 }
40 ```
41
42 ```go
43 func foo() {
44 foo := "bar"
45 }
46 ```
47
48 </details>
49
50 **No empty lines around function bodies**
51
52 <details><summary><i>Example</i></summary>
53
54 ```go
55 func foo() {
56
57 println("bar")
58
59 }
60 ```
61
62 ```go
63 func foo() {
64 println("bar")
65 }
66 ```
67
68 </details>
69
70 **Functions should separate `) {` where the indentation helps readability**
71
72 <details><summary><i>Example</i></summary>
73
74 ```go
75 func foo(s string,
76 i int) {
77 println("bar")
78 }
79
80 // With an empty line it's slightly better, but still not great.
81 func bar(s string,
82 i int) {
83
84 println("bar")
85 }
86 ```
87
88 ```go
89 func foo(s string,
90 i int,
91 ) {
92 println("bar")
93 }
94
95 // With an empty line it's slightly better, but still not great.
96 func bar(s string,
97 i int,
98 ) {
99 println("bar")
100 }
101 ```
102
103 </details>
104
105 **No empty lines around a lone statement (or comment) in a block**
106
107 <details><summary><i>Example</i></summary>
108
109 ```go
110 if err != nil {
111
112 return err
113 }
114 ```
115
116 ```go
117 if err != nil {
118 return err
119 }
120 ```
121
122 </details>
123
124 **No empty lines before a simple error check**
125
126 <details><summary><i>Example</i></summary>
127
128 ```go
129 foo, err := processFoo()
130
131 if err != nil {
132 return err
133 }
134 ```
135
136 ```go
137 foo, err := processFoo()
138 if err != nil {
139 return err
140 }
141 ```
142
143 </details>
144
145 **Composite literals should use newlines consistently**
146
147 <details><summary><i>Example</i></summary>
148
149 ```go
150 // A newline before or after an element requires newlines for the opening and
151 // closing braces.
152 var ints = []int{1, 2,
153 3, 4}
154
155 // A newline between consecutive elements requires a newline between all
156 // elements.
157 var matrix = [][]int{
158 {1},
159 {2}, {
160 3,
161 },
162 }
163 ```
164
165 ```go
166 var ints = []int{
167 1, 2,
168 3, 4,
169 }
170
171 var matrix = [][]int{
172 {1},
173 {2},
174 {
175 3,
176 },
177 }
178 ```
179
180 </details>
181
182 **Empty field lists should use a single line**
183
184 <details><summary><i>Example</i></summary>
185
186 ```go
187 var V interface {
188 } = 3
189
190 type T struct {
191 }
192
193 func F(
194 )
195 ```
196
197 ```go
198 var V interface{} = 3
199
200 type T struct{}
201
202 func F()
203 ```
204
205 </details>
206
207 **`std` imports must be in a separate group at the top**
208
209 <details><summary><i>Example</i></summary>
210
211 ```go
212 import (
213 "foo.com/bar"
214
215 "io"
216
217 "io/ioutil"
218 )
219 ```
220
221 ```go
222 import (
223 "io"
224 "io/ioutil"
225
226 "foo.com/bar"
227 )
228 ```
229
230 </details>
231
232 **Short case clauses should take a single line**
233
234 <details><summary><i>Example</i></summary>
235
236 ```go
237 switch c {
238 case 'a', 'b',
239 'c', 'd':
240 }
241 ```
242
243 ```go
244 switch c {
245 case 'a', 'b', 'c', 'd':
246 }
247 ```
248
249 </details>
250
251 **Multiline top-level declarations must be separated by empty lines**
252
253 <details><summary><i>Example</i></summary>
254
255 ```go
256 func foo() {
257 println("multiline foo")
258 }
259 func bar() {
260 println("multiline bar")
261 }
262 ```
263
264 ```go
265 func foo() {
266 println("multiline foo")
267 }
268
269 func bar() {
270 println("multiline bar")
271 }
272 ```
273
274 </details>
275
276 **Single var declarations should not be grouped with parentheses**
277
278 <details><summary><i>Example</i></summary>
279
280 ```go
281 var (
282 foo = "bar"
283 )
284 ```
285
286 ```go
287 var foo = "bar"
288 ```
289
290 </details>
291
292 **Contiguous top-level declarations should be grouped together**
293
294 <details><summary><i>Example</i></summary>
295
296 ```go
297 var nicer = "x"
298 var with = "y"
299 var alignment = "z"
300 ```
301
302 ```go
303 var (
304 nicer = "x"
305 with = "y"
306 alignment = "z"
307 )
308 ```
309
310 </details>
311
312 **Simple var-declaration statements should use short assignments**
313
314 <details><summary><i>Example</i></summary>
315
316 ```go
317 var s = "somestring"
318 ```
319
320 ```go
321 s := "somestring"
322 ```
323
324 </details>
325
326 **The `-s` code simplification flag is enabled by default**
327
328 <details><summary><i>Example</i></summary>
329
330 ```go
331 var _ = [][]int{[]int{1}}
332 ```
333
334 ```go
335 var _ = [][]int{{1}}
336 ```
337
338 </details>
339
340 **Octal integer literals should use the `0o` prefix on modules using Go 1.13 and later**
341
342 <details><summary><i>Example</i></summary>
343
344 ```go
345 const perm = 0755
346 ```
347
348 ```go
349 const perm = 0o755
350 ```
351
352 </details>
353
354 **Comments which aren't Go directives should start with a whitespace**
355
356 <details><summary><i>Example</i></summary>
357
358 ```go
359 //go:noinline
360
361 //Foo is awesome.
362 func Foo() {}
363 ```
364
365 ```go
366 //go:noinline
367
368 // Foo is awesome.
369 func Foo() {}
370 ```
371
372 </details>
373
374 **Composite literals should not have leading or trailing empty lines**
375
376 <details><summary><i>Example</i></summary>
377
378 ```go
379 var _ = []string{
380
381 "foo",
382
383 }
384
385 var _ = map[string]string{
386
387 "foo": "bar",
388
389 }
390 ```
391
392 ```go
393 var _ = []string{
394 "foo",
395 }
396
397 var _ = map[string]string{
398 "foo": "bar",
399 }
400 ```
401
402 </details>
403
404 **Field lists should not have leading or trailing empty lines**
405
406 <details><summary><i>Example</i></summary>
407
408 ```go
409 type Person interface {
410
411 Name() string
412
413 Age() int
414
415 }
416
417 type ZeroFields struct {
418
419 // No fields are needed here.
420
421 }
422 ```
423
424 ```go
425 type Person interface {
426 Name() string
427
428 Age() int
429 }
430
431 type ZeroFields struct {
432 // No fields are needed here.
433 }
434 ```
435
436 </details>
437
438 #### Extra rules behind `-extra`
439
440 **Adjacent parameters with the same type should be grouped together**
441
442 <details><summary><i>Example</i></summary>
443
444 ```go
445 func Foo(bar string, baz string) {}
446 ```
447
448 ```go
449 func Foo(bar, baz string) {}
450 ```
451
452 </details>
453
454 ### Installation
455
456 `gofumpt` is a replacement for `gofmt`, so you can simply `go install` it as
457 described at the top of this README and use it.
458
459 When using an IDE or editor with Go integration based on `gopls`,
460 it's best to configure the editor to use the `gofumpt` support built into `gopls`.
461
462 The instructions below show how to set up `gofumpt` for some of the
463 major editors out there.
464
465 #### Visual Studio Code
466
467 Enable the language server following [the official docs](https://github.com/golang/vscode-go#readme),
468 and then enable gopls's `gofumpt` option. Note that VS Code will complain about
469 the `gopls` settings, but they will still work.
470
471 ```json
472 "go.useLanguageServer": true,
473 "gopls": {
474 "formatting.gofumpt": true,
475 },
476 ```
477
478 #### GoLand
479
480 GoLand doesn't use `gopls` so it should be configured to use `gofumpt` directly.
481 Once `gofumpt` is installed, follow the steps below:
482
483 - Open **Settings** (File > Settings)
484 - Open the **Tools** section
485 - Find the *File Watchers* sub-section
486 - Click on the `+` on the right side to add a new file watcher
487 - Choose *Custom Template*
488
489 When a window asks for settings, you can enter the following:
490
491 * File Types: Select all .go files
492 * Scope: Project Files
493 * Program: Select your `gofumpt` executable
494 * Arguments: `-w $FilePath$`
495 * Output path to refresh: `$FilePath$`
496 * Working directory: `$ProjectFileDir$`
497 * Environment variables: `GOROOT=$GOROOT$;GOPATH=$GOPATH$;PATH=$GoBinDirs$`
498
499 To avoid unnecessary runs, you should disable all checkboxes in the *Advanced* section.
500
501 #### Vim
502
503 The configuration depends on the plugin you are using: [vim-go](https://github.com/fatih/vim-go)
504 or [govim](https://github.com/govim/govim).
505
506 ##### vim-go
507
508 To configure `gopls` to use `gofumpt`:
509
510 ```vim
511 let g:go_fmt_command="gopls"
512 let g:go_gopls_gofumpt=1
513 ```
514
515 ##### govim
516
517 To configure `gopls` to use `gofumpt`:
518
519 ```vim
520 call govim#config#Set("Gofumpt", 1)
521 ```
522
523 #### Neovim
524
525 When using [`lspconfig`](https://github.com/neovim/nvim-lspconfig), pass the `gofumpt` setting to `gopls`:
526
527 ```lua
528 require('lspconfig').gopls.setup({
529 settings = {
530 gopls = {
531 gofumpt = true
532 }
533 }
534 })
535 ```
536
537 #### Emacs
538
539 For [lsp-mode](https://emacs-lsp.github.io/lsp-mode/) users on version 8.0.0 or higher:
540
541 ```elisp
542 (setq lsp-go-use-gofumpt t)
543 ```
544
545 For users of `lsp-mode` before `8.0.0`:
546
547 ```elisp
548 (lsp-register-custom-settings
549 '(("gopls.gofumpt" t)))
550 ```
551
552 For [eglot](https://github.com/joaotavora/eglot) users:
553
554 ```elisp
555 (setq-default eglot-workspace-configuration
556 '((:gopls . ((gofumpt . t)))))
557 ```
558
559 #### Helix
560
561 When using the `gopls` language server, modify the Go settings in `~/.config/helix/languages.toml`:
562
563 ```toml
564 [language-server.gopls.config]
565 "formatting.gofumpt" = true
566 ```
567
568 #### Sublime Text
569
570 With ST4, install the Sublime Text LSP extension according to [the documentation](https://github.com/sublimelsp/LSP),
571 and enable `gopls`'s `gofumpt` option in the LSP package settings,
572 including setting `lsp_format_on_save` to `true`.
573
574 ```json
575 "lsp_format_on_save": true,
576 "clients":
577 {
578 "gopls":
579 {
580 "enabled": true,
581 "initializationOptions": {
582 "gofumpt": true,
583 }
584 }
585 }
586 ```
587
588 ### Roadmap
589
590 This tool is a place to experiment. In the long term, the features that work
591 well might be proposed for `gofmt` itself.
592
593 The tool is also compatible with `gofmt` and is aimed to be stable, so you can
594 rely on it for your code as long as you pin a version of it.
595
596 ### Frequently Asked Questions
597
598 > Why attempt to replace `gofmt` instead of building on top of it?
599
600 Our design is to build on top of `gofmt`, and we'll never add rules which
601 disagree with its formatting. So we extend `gofmt` rather than compete with it.
602
603 The tool is a modified copy of `gofmt`, for the purpose of allowing its use as a
604 drop-in replacement in editors and scripts.
605
606 > Why are my module imports being grouped with standard library imports?
607
608 Any import paths that don't start with a domain name like `foo.com` are
609 effectively [reserved by the Go toolchain](https://github.com/golang/go/issues/32819).
610 Third party modules should either start with a domain name,
611 even a local one like `foo.local`, or use [a reserved path prefix](https://github.com/golang/go/issues/37641).
612
613 For backwards compatibility with modules set up before these rules were clear,
614 `gofumpt` will treat any import path sharing a prefix with the current module
615 path as third party. For example, if the current module is `mycorp/mod1`, then
616 all import paths in `mycorp/...` will be considered third party.
617
618 > How can I use `gofumpt` if I already use `goimports` to replace `gofmt`?
619
620 Most editors have replaced the `goimports` program with the same functionality
621 provided by a language server like `gopls`. This mechanism is significantly
622 faster and more powerful, since the language server has more information that is
623 kept up to date, necessary to add missing imports.
624
625 As such, the general recommendation is to let your editor fix your imports -
626 either via `gopls`, such as VSCode or vim-go, or via their own custom
627 implementation, such as GoLand. Then follow the install instructions above to
628 enable the use of `gofumpt` instead of `gofmt`.
629
630 If you want to avoid integrating with `gopls`, and are OK with the overhead of
631 calling `goimports` from scratch on each save, you should be able to call both
632 tools; for example, `goimports file.go && gofumpt file.go`.
633
634 ### Contributing
635
636 Issues and pull requests are welcome! Please open an issue to discuss a feature
637 before sending a pull request.
638
639 We also use the `#gofumpt` channel over at the
640 [Gophers Slack](https://invite.slack.golangbridge.org/) to chat.
641
642 When reporting a formatting bug, insert a `//gofumpt:diagnose` comment.
643 The comment will be rewritten to include useful debugging information.
644 For instance:
645
646 ```
647 $ cat f.go
648 package p
649
650 //gofumpt:diagnose
651 $ gofumpt f.go
652 package p
653
654 //gofumpt:diagnose v0.1.1-0.20211103104632-bdfa3b02e50a -lang=v1.16
655 ```
656
657 ### License
658
659 Note that much of the code is copied from Go's `gofmt` command. You can tell
660 which files originate from the Go repository from their copyright headers. Their
661 license file is `LICENSE.google`.
662
663 `gofumpt`'s original source files are also under the 3-clause BSD license, with
664 the separate file `LICENSE`.