GCI, una herramienta que controla el orden de importación de paquetes Go y lo hace siempre determinista.
El formato de salida deseado es altamente configurable y permite un formato más personalizado que goimport
.
GCI considera un bloque de importación basado en AST de la siguiente manera:
Doc
Name Path Comment
Todos los comentarios se mantendrán como estaban, excepto los bloques de comentarios aislados.
Los bloques de comentarios aislados se ven a continuación:
import (
"fmt"
// this line is isolated comment
// those lines belong to one
// isolated comment blocks
"github.com/daixiang0/gci"
)
GCI divide todos los bloques de importación en diferentes secciones y ahora admite seis tipos de secciones:
La prioridad es estándar > predeterminada > personalizada > en blanco > punto > alias > módulo local, todas las secciones se ordenan alfabéticamente en su interior. De forma predeterminada, las secciones en blanco, de punto y de alias no se utilizan, y las líneas correspondientes terminan en los otros grupos.
Todos los bloques de importación utilizan un TAB( t
) como sangría.
Desde v0.9.0, GCI siempre coloca el bloque de importación C como el primero.
Nota :
nolint
es difícil de manejar a nivel de sección, GCI lo considerará como un comentario único.
La detección del módulo local se realiza leyendo el nombre del módulo del archivo go.mod
en el directorio donde se invoca gci
. Esto significa:
gci
desde la raíz de un módulo (es decir, el directorio que contiene go.mod
).gci
desde un directorio que contiene go.work
(aunque funcionaría si se invoca desde uno de los módulos en el espacio de trabajo) Para descargar e instalar la versión más alta disponible:
go install github.com/daixiang0/gci@latest
También puede especificar una versión específica, por ejemplo:
go install github.com/daixiang0/[email protected]
Ahora GCI proporciona dos métodos de línea de comando, principalmente por compatibilidad con versiones anteriores.
GCI admite tres modos de operación
Nota
Desde v0.10.0, los indicadores
-s
y--section
solo se pueden usar varias veces para especificar varias secciones. Por ejemplo, antes podía usar-s standard,default
, pero ahora debe usar-s standard -s default
. Este cambio importante hace posible que el proyecto admita la especificación de múltiples prefijos personalizados. (Consulte a continuación).
$ gci print -h
Print outputs the formatted file. If you want to apply the changes to a file use write instead !
Usage:
gci print path... [flags]
Aliases:
print, output
Flags:
--custom-order Enable custom order of sections
-d, --debug Enables debug output from the formatter
-h, --help help for print
-s, --section stringArray Sections define how inputs will be processed. Section names are case-insensitive and may contain parameters in (). The section order is standard > default > custom > blank > dot > alias > localmodule. The default value is [standard,default].
standard - standard section that Go provides officially, like " fmt "
Prefix(github.com/daixiang0) - custom section, groups all imports with the specified Prefix. Imports will be matched to the longest Prefix. Multiple custom prefixes may be provided, they will be rendered as distinct sections separated by newline. You can regroup multiple prefixes by separating them with comma: Prefix(github.com/daixiang0,gitlab.com/daixiang0,daixiang0)
default - default section, contains all rest imports
blank - blank section, contains all blank imports.
dot - dot section, contains all dot imports. (default [standard,default])
alias - alias section, contains all alias imports.
localmodule: localmodule section, contains all imports from local packages
--skip-generated Skip generated files
--skip-vendor Skip files inside vendor directory
$ gci write -h
Write modifies the specified files in-place
Usage:
gci write path... [flags]
Aliases:
write, overwrite
Flags:
--custom-order Enable custom order of sections
-d, --debug Enables debug output from the formatter
-h, --help help for write
-s, --section stringArray Sections define how inputs will be processed. Section names are case-insensitive and may contain parameters in (). The section order is standard > default > custom > blank > dot > alias > localmodule. The default value is [standard,default].
standard - standard section that Go provides officially, like " fmt "
Prefix(github.com/daixiang0) - custom section, groups all imports with the specified Prefix. Imports will be matched to the longest Prefix. Multiple custom prefixes may be provided, they will be rendered as distinct sections separated by newline. You can regroup multiple prefixes by separating them with comma: Prefix(github.com/daixiang0,gitlab.com/daixiang0,daixiang0)
default - default section, contains all rest imports
blank - blank section, contains all blank imports.
dot - dot section, contains all dot imports. (default [standard,default])
alias - alias section, contains all alias imports.
localmodule: localmodule section, contains all imports from local packages
--skip-generated Skip generated files
--skip-vendor Skip files inside vendor directory
$ gci list -h
Prints the filenames that need to be formatted. If you want to show the diff use diff instead, and if you want to apply the changes use write instead
Usage:
gci list path... [flags]
Flags:
--custom-order Enable custom order of sections
-d, --debug Enables debug output from the formatter
-h, --help help for list
-s, --section stringArray Sections define how inputs will be processed. Section names are case-insensitive and may contain parameters in (). The section order is standard > default > custom > blank > dot > alias > localmodule. The default value is [standard,default].
standard - standard section that Go provides officially, like " fmt "
Prefix(github.com/daixiang0) - custom section, groups all imports with the specified Prefix. Imports will be matched to the longest Prefix. Multiple custom prefixes may be provided, they will be rendered as distinct sections separated by newline. You can regroup multiple prefixes by separating them with comma: Prefix(github.com/daixiang0,gitlab.com/daixiang0,daixiang0)
default - default section, contains all rest imports
blank - blank section, contains all blank imports.
dot - dot section, contains all dot imports. (default [standard,default])
alias - alias section, contains all alias imports.
localmodule: localmodule section, contains all imports from local packages
--skip-generated Skip generated files
--skip-vendor Skip files inside vendor directory
$ gci diff -h
Diff prints a patch in the style of the diff tool that contains the required changes to the file to make it adhere to the specified formatting.
Usage:
gci diff path... [flags]
Flags:
--custom-order Enable custom order of sections
-d, --debug Enables debug output from the formatter
-h, --help help for diff
-s, --section stringArray Sections define how inputs will be processed. Section names are case-insensitive and may contain parameters in (). The section order is standard > default > custom > blank > dot > alias > localmodule. The default value is [standard,default].
standard - standard section that Go provides officially, like " fmt "
Prefix(github.com/daixiang0) - custom section, groups all imports with the specified Prefix. Imports will be matched to the longest Prefix. Multiple custom prefixes may be provided, they will be rendered as distinct sections separated by newline. You can regroup multiple prefixes by separating them with comma: Prefix(github.com/daixiang0,gitlab.com/daixiang0,daixiang0)
default - default section, contains all rest imports
blank - blank section, contains all blank imports.
dot - dot section, contains all dot imports. (default [standard,default])
alias - alias section, contains all alias imports.
localmodule: localmodule section, contains all imports from local packages
--skip-generated Skip generated files
--skip-vendor Skip files inside vendor directory
Gci enables automatic formatting of imports in a deterministic manner
If you want to integrate this as part of your CI take a look at golangci-lint.
Usage:
gci [-diff | -w rite] [--local localPackageURLs] path... [flags]
gci [command]
Available Commands:
completion Generate the autocompletion script for the specified shell
diff Prints a git style diff to STDOUT
help Help about any command
list Prints filenames that need to be formatted to STDOUT
print Outputs the formatted file to STDOUT
write Formats the specified files in-place
Flags:
-d, --diff display diffs instead of rewriting files
-h, --help help for gci
-l, --local strings put imports beginning with this string after 3rd-party packages, separate imports by comma
-v, --version version for gci
-w, --write write result to (source) file instead of stdout
Use " gci [command] --help " for more information about a command.
Nota ::
El estilo antiguo es solo para pruebas locales, quedará obsoleto, use un estilo nuevo, golangci-lint
también usa un estilo nuevo.
Ejecute gci write -s standard -s default -s "prefix(github.com/daixiang0/gci)" main.go
y manejará los siguientes casos:
package main
import (
"golang.org/x/tools"
"fmt"
"github.com/daixiang0/gci"
)
a
package main
import (
"fmt"
"golang.org/x/tools"
"github.com/daixiang0/gci"
)
package main
import (
"fmt"
go "github.com/golang"
"github.com/daixiang0/gci"
)
a
package main
import (
"fmt"
go "github.com/golang"
"github.com/daixiang0/gci"
)
package main
import (
"fmt"
go "github.com/golang"
_ "github.com/golang/blank"
. "github.com/golang/dot"
"github.com/daixiang0/gci"
_ "github.com/daixiang0/gci/blank"
. "github.com/daixiang0/gci/dot"
)
a
package main
import (
"fmt"
go "github.com/golang"
"github.com/daixiang0/gci"
_ "github.com/daixiang0/gci/blank"
_ "github.com/golang/blank"
. "github.com/daixiang0/gci/dot"
. "github.com/golang/dot"
)
package main
import (
testing "github.com/daixiang0/test"
"fmt"
g "github.com/golang"
"github.com/daixiang0/gci"
"github.com/daixiang0/gci/subtest"
)
a
package main
import (
"fmt"
"github.com/daixiang0/gci"
"github.com/daixiang0/gci/subtest"
testing "github.com/daixiang0/test"
g "github.com/golang"
)
Suponiendo que esto se ejecuta en la raíz de este repositorio (es decir, donde github.com/daixiang0/gci
es un módulo local)
package main
import (
"os"
"github.com/daixiang0/gci/cmd/gci"
)
a
package main
import (
"os"
"github.com/daixiang0/gci/cmd/gci"
)
Name
y Path
en un bloque de importaciónPath
y Comment
en un bloque de importacióngoimports
y luego use GCI)