- 开发工具
- 代码质量
- Lint
- 静态分析
【免费下载链接】golangci-lint
Fast linters runner for Go
golangci-lint 是一个面向 Go 的"智能、快速的 linter 运行器"(Smart, fast linters runner),其全部能力通过一组设计清晰、职责单一的 CLI 子命令暴露出来。本篇指南以官方文档 docs/content/docs/configuration/cli.md 为骨架,结合仓库内 pkg/commands 下的命令实现源码,逐一讲解run、fmt、migrate、cache、config、custom、version、completion等命令的用法、关键参数与底层行为,帮助你快速上手并从命令行层面理解 golangci-lint 的完整工作流。
命令总览与全局标志
在仓库根目录执行golangci-lint -h即可看到所有可用子命令与全局标志。从 pkg/commands/root.go 的源码可以看到,根命令注册了以下子命令:
$ golangci-lint -h Smart, fast linters runner. Usage: golangci-lint [flags] golangci-lint [command] Available Commands: cache Cache control and information. completion Generate the autocompletion script for the specified shell config Configuration file information and verification. custom Build a version of golangci-lint with custom linters. fmt Format Go source files. formatters List current formatters configuration. help Display extra help linters List current linters configuration. migrate Migrate configuration file from v1 to v2. run Lint the code. version Display the golangci-lint version. Flags: --color string Use color when printing; can be 'always', 'auto', or 'never' (default "auto") -h, --help Help for a command -v, --verbose Verbose output --version Print version全局标志对所有子命令生效,其处理逻辑位于 pkg/commands/root.go:
--color:控制彩色输出,取值always、auto、never,默认auto;非法取值会直接报错退出。-v, --verbose:开启详细输出,便于排查配置加载与 linter 执行细节。-h, --help:查看任意子命令的帮助,例如golangci-lint run -h。--version:在根命令级别打印版本号并退出(与version子命令等价)。
需要特别说明的是,-c/--config与--no-config两个标志并非全局标志,而是各子命令自行注册的"配置加载标志"(见 pkg/commands/run.go 中的setupConfigFileFlagSet),因此run、fmt、linters、formatters、migrate、config都各自携带它们。
run:执行 lint 分析(核心命令)
run是 golangci-lint 的核心命令,负责加载配置、构建分析上下文、并行执行启用的 linters,并输出结果。运行golangci-lint run -h可查看其完整参数:
$ golangci-lint run -h Lint the code. Usage: golangci-lint run [flags] Flags: -c, --config PATH Read config from file path PATH --no-config Don't read config file --default string Default set of linters to enable (default "standard") -D, --disable strings Disable specific linter -E, --enable strings Enable specific linter --enable-only strings Override linters configuration section to only run the specific linter(s) --fast-only Filter enabled linters to run only fast linters -j, --concurrency int Number of CPUs to use (Default: Automatically set to match Linux container CPU quota and fall back to the number of logical CPUs in the machine) --modules-download-mode string Modules download mode. If not empty, passed as -mod=<mode> to go tools --issues-exit-code int Exit code when issues were found (default 1) --build-tags strings Build tags --timeout duration Timeout for total work. Disabled by default --tests Analyze tests (*_test.go) (default true) --allow-parallel-runners Allow multiple parallel golangci-lint instances running. If false (default) - golangci-lint acquires file lock on start. --allow-serial-runners Allow multiple golangci-lint instances running, but serialize them around a lock. If false (default) - golangci-lint exits with an error if it fails to acquire file lock on start. --path-prefix string Path prefix to add to output --path-mode string Path mode to use (empty, or 'abs') --show-stats Show statistics per linter (default true) --output.text.path stdout Output path can be either stdout, `stderr` or path to the file to write to. --output.text.print-linter-name Print linter name in the end of issue text. (default true) --output.text.print-issued-lines Print lines of code with issue. (default true) --output.text.colors Use colors. (default true) --output.json.path stdout Output path can be either stdout, `stderr` or path to the file to write to. --output.tab.path stdout Output path can be either stdout, `stderr` or path to the file to write to. --output.tab.print-linter-name Print linter name in the end of issue text. (default true) --output.tab.colors Use colors. (default true) --output.html.path stdout Output path can be either stdout, `stderr` or path to the file to write to. --output.checkstyle.path stdout Output path can be either stdout, `stderr` or path to the file to write to. --output.code-climate.path stdout Output path can be either stdout, `stderr` or path to the file to write to. --output.junit-xml.path stdout Output path can be either stdout, `stderr` or path to the file to write to. --output.junit-xml.extended Support extra JUnit XML fields. --output.teamcity.path stdout Output path can be either stdout, `stderr` or path to the file to write to. --output.sarif.path stdout Output path can be either stdout, `stderr` or path to the file to write to. --max-issues-per-linter int Maximum issues count per one linter. Set to 0 to disable (default 50) --max-same-issues int Maximum count of issues with the same text. Set to 0 to disable (default 3) --uniq-by-line Make issues output unique by line (default true) -n, --new Show only new issues: if there are unstaged changes or untracked files, only those changes are analyzed, else only changes in HEAD~ are analyzed. It's a super-useful option for integration of golangci-lint into existing large codebase. It's not practical to fix all existing issues at the moment of integration: much better to not allow issues in new code. For CI setups, prefer --new-from-rev=HEAD~, as --new can skip linting the current patch if any scripts generate unstaged files before golangci-lint runs. --new-from-rev REV Show only new issues created after git revision REV --new-from-patch PATH Show only new issues created in git patch with file path PATH --new-from-merge-base string Show only new issues created after the best common ancestor (merge-base against HEAD) --whole-files Show issues in any part of update files (requires new-from-rev or new-from-patch) --fix Apply the fixes detected by the linters and formatters (if it's supported by the linter) --cpu-profile-path string Path to CPU profile output file --mem-profile-path string Path to memory profile output file --trace-path string Path to trace output filerun与 formatters 的关系
官方文档特别强调了一点:run命令只执行启用的 linters 和formatters配置段中定义的 formatters,但不会真正格式化代码。formatters 不能在linters配置段内启用/禁用,也不能通过run的-E/--enable、-D/--disable标志控制。
- 只想格式化代码:使用
golangci-lint fmt。 - 想同时应用 linter 修复与格式化:使用
golangci-lint run --fix。 - formatters 的启用/禁用:在配置文件 formatters 配置段 中定义,或通过
golangci-lint fmt的-E/--enable、-D/--disable标志控制。
[!NOTE] 这一设计将"检查/修复"(run)与"格式化"(fmt)两条链路明确分离,避免 formatter 与 linter 的启停规则互相干扰。
linter 选择与过滤参数
--default:指定默认启用的 linter 集合,默认standard。-E/--enable、-D/--disable:按名称启用或禁用特定 linter,可重复传入。--enable-only:完全覆盖linters配置段,只运行指定的 linter(s),适合快速聚焦排查单个 linter。--fast-only:过滤掉非快速 linter,只运行标记为 fast 的 linter(run的帮助中即显示ineffassign ... [fast]之类的标注)。- 默认启用的 linter 集合(来自
--default standard)包括:errcheck(检查未处理的错误)、govet(go vet的分析 passes,支持自动修复)、ineffassign(检测对已有变量的无效赋值,fast)、staticcheck(staticcheck 规则集,支持自动修复)、unused(检查未使用的常量、变量、函数与类型)。
分析范围与"仅新问题"模式
--build-tags:指定构建标签,会透传给分析过程。--tests:是否分析*_test.go测试文件,默认true。--new(-n):只显示新问题——若存在未暂存改动或未跟踪文件则只分析这些改动,否则只分析相对HEAD~的改动。官方文档明确建议:CI 场景优先使用--new-from-rev=HEAD~,因为--new可能在某些脚本于 golangci-lint 运行前生成未暂存文件时跳过对当前补丁的检查。--new-from-rev REV:只显示 git 修订版本REV之后产生的新问题。--new-from-patch PATH:只显示 git 补丁文件PATH中产生的新问题。--new-from-merge-base:只显示基于与HEAD的最佳公共祖先(merge-base)之后产生的新问题。--whole-files:显示更新文件任意部分的问题(需配合--new-from-rev或--new-from-patch使用)。
输出、格式化与退出码
--output.<format>.path:为每种输出格式(text、json、tab、html、checkstyle、code-climate、junit-xml、teamcity、sarif)指定输出位置,可选stdout、stderr或文件路径;同时支持--output.text.print-linter-name、--output.text.print-issued-lines、--output.text.colors等细粒度控制项,以及--output.junit-xml.extended扩展 JUnit XML 字段。--path-prefix/--path-mode:为输出路径添加前缀或切换为绝对路径模式(abs)。--max-issues-per-linter:单个 linter 最多报告的问题数,默认 50,设 0 关闭。--max-same-issues:相同文本问题最多报告数,默认 3,设 0 关闭。--uniq-by-line:按行去重问题输出,默认true。--show-stats:输出每个 linter 的统计信息,默认true。统计逻辑见 pkg/commands/run.go:无问题时打印0 issues.,否则打印N issues:及按 linter 分组的计数。--issues-exit-code:发现问题时的退出码,默认 1。运行结束后,若存在 issue,setExitCodeIfIssuesFound会将退出码设为此值(见 pkg/commands/run.go)。
并发、超时与文件锁
-j, --concurrency:使用的 CPU 数;默认自动适配 Linux 容器 CPU 配额,回退到机器逻辑 CPU 数。若在配置中显式设置run.concurrency,persistentPreRunE会调用runtime.GOMAXPROCS生效(见 pkg/commands/run.go)。--timeout:总工作超时,默认禁用。超时后会以exitcodes.Timeout退出并提示 "Timeout exceeded: try increasing it by passing --timeout option"(见 pkg/commands/run.go)。--allow-parallel-runners:允许多个 golangci-lint 实例并行运行;默认为 false,此时启动时获取文件锁(默认锁文件位于系统临时目录下的golangci-lint.lock,获取逻辑见 pkg/commands/run.go)。--allow-serial-runners:允许多个实例运行但在锁上串行等待;默认为 false,此时若 5 秒内未能获取锁会直接报错 "parallel golangci-lint is running"。
自动修复与性能剖析
--fix:应用 linter(以及 formatters)检测到的、其自身支持的修复。--cpu-profile-path/--mem-profile-path:写入 CPU / 内存剖析数据,格式与 pprof),CPU profile 在startTracing中通过pprof.StartCPUProfile开启并在结束后停止;内存 profile 通过pprof.WriteHeapProfile写出,且支持GL_MEM_PROFILE_RATE环境变量覆盖runtime.MemProfileRate。--trace-path:写入运行时追踪数据,格式与go tool trace命令及可视化工具兼容,通过标准库runtime/trace实现(见 pkg/commands/run.go)。
fmt:格式化 Go 源码
fmt命令独立负责格式化,是 v2 中与 lint 分离的"格式化专用入口":
$ golangci-lint fmt -h Format Go source files. Usage: golangci-lint fmt [flags] Flags: -c, --config PATH Read config from file path PATH --no-config Don't read config file -E, --enable strings Enable specific formatter -d, --diff Display diffs instead of rewriting files --diff-colored Display diffs instead of rewriting files (with colors) --stdin Use standard input for piping source files Global Flags: --color string Use color when printing; can be 'always', 'auto', or 'never' (default "auto") -h, --help Help for a command -v, --verbose Verbose output-E/--enable:启用特定 formatter(可在 formatters 配置段 之外直接通过命令行指定)。-d, --diff:仅显示差异而不改写文件。--diff-colored:带颜色显示差异。--stdin:从标准输入读取源码进行格式化(适合管道场景)。
从实现看,fmt命令通过 pkg/goformat/runner.go 与 pkg/goformatters/meta_formatter.go 构建"元 formatter"链式执行 gofmt、goimports、gci、gofumpt、golines、swaggo 等内置 formatter,并可通过processors.NewGeneratedFileMatcher跳过生成文件(见 pkg/commands/fmt.go)。无参数时默认处理当前目录(.),路径参数中的...通配会被展开清理(见 pkg/commands/fmt.go)。
migrate:配置文件 v1 到 v2 迁移
v2 的配置格式与 v1 差异较大,migrate子命令用于将 v1 配置文件迁移到 v2:
$ golangci-lint migrate -h Migrate configuration file from v1 to v2. Usage: golangci-lint migrate [flags] Flags: -c, --config PATH Read config from file path PATH --no-config Don't read config file --format string Output file format. By default, the format of the input configuration file is used. It can be 'yml', 'yaml', 'toml', or 'json'. --skip-validation Skip validation of the configuration file against the JSON Schema for v1. Global Flags: --color string Use color when printing; can be 'always', 'auto', or 'never' (default "auto") -h, --help Help for a command -v, --verbose Verbose output关键行为(见 pkg/commands/migrate.go):
- 默认输出格式与输入文件一致;可通过
--format显式指定yml、yaml、toml或json,非法值会在preRunE中报错。 - 迁移前会先对 v1 配置执行 JSON Schema 校验(除非传入
--skip-validation),校验失败会输出详细错误并中止(见 pkg/commands/migrate.go)。 - 迁移过程会自动为原文件生成
*.bck.*备份(如golangci-lint.yml→golangci-lint.bck.yml,见backupConfigurationFile),随后写出新格式文件;若输出格式与输入格式不同,原文件会被删除。 - 注意:配置中的注释不会被迁移;若 v1 配置设置了
run.timeout,迁移时会提示该设置在 v2 中默认被忽略(v2 默认不设超时)。 - 迁移实现位于 pkg/commands/internal/migrate,仓库内置了 326 个
.yml迁移用例用于验证各类配置的转换结果。
formatters:查看 formatter 配置
$ golangci-lint formatters -h List current formatters configuration. Usage: golangci-lint formatters [flags] Flags: -c, --config PATH Read config from file path PATH --no-config Don't read config file -E, --enable strings Enable specific formatter --json Display as JSON Global Flags: --color string Use color when printing; can be 'always', 'auto', or 'never' (default "auto") -h, --help Help for a command -v, --verbose Verbose outputformatters命令列出当前配置下生效的 formatters(与linters命令对称),-E可临时启用指定 formatter,--json输出 JSON 便于脚本解析。它读取的是 formatters 配置段,而不是linters配置段。
help:附加帮助
$ golangci-lint help -h Display extra help Usage: golangci-lint help [flags] golangci-lint help [command] Available Commands: formatters Display help for formatters. linters Display help for linters. Global Flags: --color string Use color when printing; can be 'always', 'auto', or 'never' (default "auto") -h, --help Help for a command -v, --verbose Verbose outputhelp子命令由根命令通过rootCmd.SetHelpCommand(newHelpCommand(log).cmd)注册(见 pkg/commands/root.go),提供针对formatters与linters两个主题的补充帮助页。
linters:查看 linter 配置
$ golangci-lint linters -h List current linters configuration. Usage: golangci-lint linters [flags] Flags: -c, --config PATH Read config from file path PATH --no-config Don't read config file --default string Default set of linters to enable (default "standard") -D, --disable strings Disable specific linter -E, --enable strings Enable specific linter --enable-only strings Override linters configuration section to only run the specific linter(s) --fast-only Filter enabled linters to run only fast linters --json Display as JSON Global Flags: --color string Use color when printing; can be 'always', 'auto', or 'never' (default "auto") -h, --help Help for a command -v, --verbose Verbose outputlinters列出当前配置下启用与禁用的 linters,并标注是否为 formatter 或 fast linter;--json输出包含Enabled/Disabled两部分的 JSON 结构(见 pkg/commands/linters.go)。可结合 linters 概览文档 与 linter 配置文档 使用。在 CI 或脚本中,golangci-lint linters --json常用于断言期望的 linter 集合是否生效。
cache:缓存控制与信息
golangci-lint 将缓存存放在默认用户缓存目录(os.UserCacheDir)下的golangci-lint子目录中;缓存仅由golangci-lint run(linters)使用,fmt命令不涉及。
可通过环境变量GOLANGCI_LINT_CACHE覆盖默认缓存目录,路径必须是绝对路径(该环境变量在 internal/cache/cache_test.go 的测试中亦有使用)。
$ golangci-lint cache -h Cache control and information. Usage: golangci-lint cache [flags] golangci-lint cache [command] Available Commands: clean Clean cache status Show cache status Global Flags: --color string Use color when printing; can be 'always', 'auto', or 'never' (default "auto") -h, --help Help for a command -v, --verbose Verbose outputcache status:打印缓存目录路径(Dir: ...)与总大小(Size: ...),见 pkg/commands/cache.go。cache clean:删除整个缓存目录,见 pkg/commands/cache.go。
缓存的正确性依赖"盐值"(salt)机制:run命令在启动时会计算二进制版本、配置(linters.settings与run.build-tags)以及go.mod内容的哈希共同组成缓存盐,任何一方变化都会使缓存失效重建,详见 pkg/commands/run.go。
config:配置文件信息与校验
$ golangci-lint config -h Configuration file information and verification. Usage: golangci-lint config [flags] golangci-lint config [command] Available Commands: path Print used configuration path. verify Verify configuration against JSON schema. Flags: -c, --config PATH Read config from file path PATH --no-config Don't read config file Global Flags: --color string Use color when printing; can be 'always', 'auto', or 'never' (default "auto") -h, --help Help for a command -v, --verbose Verbose outputconfig path:打印当前实际使用的配置文件路径;--json输出path与absolutePath两个字段(见 pkg/commands/config.go)。未检测到配置文件时退出码为非 0 并提示 "No config file detected"。config verify:对照 JSON Schema 校验当前配置。仓库的 jsonschema 目录内置了从 v1.57 到 v2.x 各版本的golangci.vX.Y.jsonschema.json,以及golangci.jsonschema.json、golangci.next.jsonschema.json等,校验正是基于这些 Schema 进行的。
custom:构建带自定义 linter 的版本
$ golangci-lint custom -h Build a version of golangci-lint with custom linters. Usage: golangci-lint custom [flags] Flags: --destination string The directory path used to store the custom binary --name string The name of the custom binary --version string The golangci-lint version used to build the custom binary Global Flags: --color string Use color when printing; can be 'always', 'auto', or 'never' (default "auto") -h, --help Help for a command -v, --verbose Verbose outputcustom命令用于将自定义 linter 编译进 golangci-lint 可执行文件:--version指定构建所用的 golangci-lint 版本,--name指定生成二进制名称,--destination指定输出目录。构建过程中会读取配置文件中的自定义插件配置并校验(见 pkg/commands/custom.go),构建在临时目录中进行,完成后清理;可通过环境变量CUSTOM_GCL_KEEP_TEMP_FILES保留临时文件用于调试(见 pkg/commands/custom.go)。更详细的使用方式可参考 plugins 文档。
version:版本信息
$ golangci-lint version -h Display the golangci-lint version. Usage: golangci-lint version [flags] Flags: --debug Add build information --json Display as JSON --short Display only the version number Global Flags: --color string Use color when printing; can be 'always', 'auto', or 'never' (default "auto") -h, --help Help for a command -v, --verbose Verbose output- 默认输出形如
golangci-lint has version X built with goX.Y from <commit> on <date>的一行信息(见 pkg/commands/version.go)。 --short:只输出版本号,适合脚本比对版本。--json:输出 JSON 结构,包含goVersion、version、commit、date字段。--debug:额外附加go version -m风格的构建信息(通过debug.ReadBuildInfo()读取,见 pkg/commands/version.go)。
completion:Shell 自动补全
$ golangci-lint completion -h Generate the autocompletion script for golangci-lint for the specified shell. See each sub-command's help for details on how to use the generated script. Usage: golangci-lint completion [command] Available Commands: bash Generate the autocompletion script for bash fish Generate the autocompletion script for fish powershell Generate the autocompletion script for powershell zsh Generate the autocompletion script for zsh Global Flags: --color string Use color when printing; can be 'always', 'auto', or 'never' (default "auto") -h, --help Help for a command -v, --verbose Verbose outputcompletion为 bash、fish、powershell、zsh 四种 shell 生成自动补全脚本。典型用法是将输出 source 进 shell 配置,例如 bash 下source <(golangci-lint completion bash)。
实战组合建议
结合上文,几个高频实战场景可以这样组织:
- CI 中只检查新代码:
golangci-lint run --new-from-rev=HEAD~ --out-format=...(官方建议优先--new-from-rev而非--new)。 - 一次性修复可自动修复的问题并格式化:
golangci-lint run --fix(同时应用 linter 修复与 formatter)。 - 只格式化:
golangci-lint fmt,先golangci-lint fmt -d预览差异,确认无误再真正改写;管道场景用--stdin。 - 排查性能瓶颈:
golangci-lint run --cpu-profile-path cpu.out --mem-profile-path mem.out --trace-path trace.out,随后分别用 pprof 工具与go tool trace分析。 - 多实例串行执行(如 monorepo 多包并行 CI job):设置
--allow-serial-runners让实例排队,或--allow-parallel-runners彻底并行(自行承担缓存竞争风险)。 - v1 配置升级 v2:
golangci-lint migrate,迁移前会自动校验并生成.bck备份。
每个命令都可随时通过golangci-lint <command> -h获取与本文一致的权威帮助输出,也可以直接阅读仓库 pkg/commands 目录下的对应实现(如 run.go、fmt.go、migrate.go、cache.go 等)深入了解其内部行为。
- 开发工具
- 代码质量
- Lint
- 静态分析
【免费下载链接】golangci-lint
Fast linters runner for Go
相关推荐
golangci-lint 配置完全指南:配置文件与命令行参数详解
golangci lint 配置完全指南:配置文件与命令行参数详解 本文围绕 golangci lint(当前仓库为 v2 系列)的配置体系展开,系统讲解配置文
开发工具代码质量Lint静态分析DLSS版本管理工具:解锁游戏画质优化的终极方案
DLSS版本管理工具:解锁游戏画质优化的终极方案 你是否曾在游戏中遇到这样的困扰?明明显卡性能足够,却因为游戏自带的DLSS版本过旧,导致画质损失严重或帧率不稳
搜索引擎可观测性日志分析链路追踪后端全文检索Delve(dlv)命令行完全指南:根命令、全局选项与全部调试子命令详解
Delve(dlv)命令行完全指南:根命令、全局选项与全部调试子命令详解 Delve 是 Go 编程语言的调试器,其命令行入口统一由 dlv 根命令承载。本文以
开发工具
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考