【问题标题】:How to define fix action for Go checker using go/analysis?如何使用 go/analysis 为 Go 检查器定义修复操作?
【发布时间】:2020-04-11 02:24:15
【问题描述】:

我最近使用 golang.org/x/tools/go/analysisgolang.org/x/tools/go/analysis/singlechecker 编写了一个 Go 检查器,并且我设法编写了自己的自定义文件操作机制(跟踪文件偏移等),但我觉得我在与系统作斗争。

https://pkg.go.dev/golang.org/x/tools/go/analysis/internal/checker 中似乎定义了一个Fix 标志,但我不知道如何使用它或挂钩到使用它的系统。

也可以定义

-fix
        apply all suggested fixes

当使用singlechecker编译检查器时:

import (
    "golang.org/x/tools/go/analysis/singlechecker"
)

var (
    Analyzer = &analysis.Analyzer{
        Name: "name",
        Run: run,
    }

    // Can't define a "fix" flag because golang.org/x/tools/go/analysis/internal/checker
    // defines it and flags cannot be redefined.
    // Fix = flag.Bool("autofix", false, "apply fixes automatically")
    Fix bool
)

func main() {
    // NOTE:
    // Don't do this at home. This should be properly integrated with
    // "golang.org/x/tools/go/analysis/internal/checker" flags (specifically -fix
    // flag) but I have no idea how to do that and the documentation is non existent.
    if len(os.Args) > 1 {
        for _, arg := range os.Args[1:] {
            if arg == "-fix" {
                Fix = true
                break
            }
        }
    }

    singlechecker.Main(Analyzer)
}

我也找不到任何关于它的文档。 在此处启用Fix 标志时应该运行的代码:https://github.com/golang/tools/blob/268ba720d32c891185aa340e8851e215f23173db/go/analysis/internal/checker/checker.go#L265

任何线索如何使用它?

【问题讨论】:

    标签: go analysis


    【解决方案1】:

    可以这样做:

        pass.Report(
        analysis.Diagnostic{
            Pos:     be.Pos(),
            Message: fmt.Sprintf("do not compare errors directly, use errors.Is() instead: %q", oldExpr),
            SuggestedFixes: []analysis.SuggestedFix{
                {
                    Message: fmt.Sprintf("should replace %q with %q", oldExpr, newExpr),
                    TextEdits: []analysis.TextEdit{
                        {
                            Pos:     be.Pos(),
                            End:     be.End(),
                            NewText: []byte(newExpr),
                        },
                    },
                },
            },
        },
    

    开始阅读的好地方是https://godoc.org/golang.org/x/tools/go/analysis#Diagnostic

    【讨论】:

      【解决方案2】:

      您可以在运行检查器时提供标志-fix=truesinglechecker 将通过运行 checker.RegisterFlags() 来注册该标志。然后,传递的标志将被解析到analysisflags.Parse()

      【讨论】:

      • 当然,这很简单,但问题是如何定义此标志将触发的操作?
      猜你喜欢
      • 2022-01-06
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      • 2014-08-14
      • 2017-06-21
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多