x/tools/go/analysis:如何上报相关信息

问题描述 投票:0回答:1

我只能得到以下结果,即使我像这样的代码设置相关

pass.Report(analysis.Diagnostic{
    Pos:     n.Pos(),
    Message: "",
    Related: []analysis.RelatedInformation{{
        Pos:     n.Pos(),
        Message: "related",
    }},
})

mytools -rule_name -json ./...

{
    "package_name": {
        "rule_name": [
            {
                "posn": "main.go:34:2",
                "message": ""
            }
        ]
    }
}

我怎样才能得到像这样的json结果

{
    "package_name": {
        "rule_name": [
            {
                "posn": "main.go:34:2",
                "message": "",
                "Related": [
                    {
                        "posn": "main.go:34:2",
                        "message": ""
                    }
                ]
            }
        ]
    }
}
go analysis go-toolchain
1个回答
0
投票

要在 JSON 输出中包含相关信息,您需要确保在自定义分析中正确填充相关字段。以下是如何实现此目标的示例:

package main

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

var myAnalyzer = &analysis.Analyzer{
    Name: "myanalyzer",
    Doc:  "example of a custom analyzer",
    Run:  run,
}

func run(pass *analysis.Pass) (interface{}, error) {
    // Your analysis logic here

    // Assuming 'n' is the node you are analyzing
    n := getNodeToAnalyze()

    // Report the diagnostic with related information
    diag := analysis.Diagnostic{
        Pos:     n.Pos(),
        Message: "main diagnostic message",
        Related: []analysis.RelatedInformation{
            {
                Pos:     n.Pos(),
                Message: "related information message",
            },
        },
    }
    pass.Report(diag)

    return nil, nil
}

func getNodeToAnalyze() *YourNodeType {
    // Implement your logic to get the node you want to analyze
    // For example, you can use AST traversal or other methods
    return nil
}

func main() {
    singlechecker.Main(myAnalyzer)
}

© www.soinside.com 2019 - 2024. All rights reserved.