8000 GitHub - xhd2015/go-ql: AST Query Language for Go
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

xhd2015/go-ql

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Go-QL: Golang Query Language for AST Analysing

go-ql is a Go library for analyzing and extracting AST and type information from Go source code.

It uses static analysis to query AST nodes like statements and call expr, adding criterias that is intuitive, making it ideal for extract information from go code.

Features

  • Static Analysis: Extracts API route details from Go source code.
  • Flexible Queries: Supports flexible filtering in various ways.
  • Query-Based Extraction: Capture on match

Installation

go get github.com/xhd2015/go-ql@latest

Usage

Below is a minimal example demonstrating core usage by analyzing routes in a specified directory.

Example Code

package main

import (
    "fmt"
    "os"
    "path/filepath"

    "github.com/xhd2015/go-ql/engine"
    "github.com/xhd2015/go-ql/ql"
    "github.com/xhd2015/go-ql/types"
)

type MatchResult struct {
    Method  string
    API     string
    Handler string
    File    string
}

func main() {
    // Define the directory to analyze
    dir := "./test/testdata/route/basic"

    // Load Go packages
    pkgs, err := engine.LoadPackagesTypeInfo(dir, "./...")
    if err != nil {
        fmt.Printf("Failed to load packages: %v\n", err)
        os.Exit(1)
    }

    // Define the query for API routes
    // find call like:
    //   r.Any("/api/ping", handler.Gin(PingHandler))
    q := ql.Select(ql.CallStmt()).
        Where(
            ql.CallStmt().Func().Name().In("Any", "GET", "POST", "PUT", "DELETE", "PATCH").Capture("method"),
            ql.CallStmt().Func().Receiver().IsNonNil(),
            ql.CallStmt().Args(0).AsLiteral().Capture("api"),
            ql.CallStmt().Args(1).AsCall().Func().Name().Eq("Gin"),
            ql.CallStmt().Args(1).AsCall().Args(0).Capture("handler"),
            ql.CallStmt().Capture("callStmt").File().Capture("file"),
        )

    // Execute the query
    matches, err := engine.Execute(pkgs, q)
    if err != nil {
        fmt.Printf("Query failed: %v\n", err)
        os.Exit(1)
    }

    // Collect results
    var results []MatchResult
    for _, match := range matches {
        file, _ := match.Captures["file"].(*types.File)
        tokenFile := pkgs.Fset.File(file.Ast.Pos())
        results = append(results, MatchResult{
            Method:  fmt.Sprintf("%v", match.Captures["method"]),
            API:     fmt.Sprintf("%v", match.Captures["api"]),
            Handler: fmt.Sprintf("%v", match.Captures["handler"])
            File:    filepath.Base(tokenFile.Name()),
        })
    }

    // Print results
    fmt.Println("API Routes Found:")
    for _, result := range results {
        fmt.Printf("- %s %s (File: %s)\n", result.Method, result.API, result.File)
    }
}

How It Works

  1. Load Packages: The code loads Go packages from the specified directory using engine.LoadPackagesTypeInfo.
  2. Query Routes: A query is defined using ql.Select to extract API routes with HTTP methods (e.g., GET, POST) and their paths.
  3. Execute and Display: The query is executed, and results (method, API path, and file) are printed.

Example Output

API Routes Found:
- GET /api/user/profile (File: basic.go)
- POST /api/user/update (File: basic.go)

Running the Example

  1. Clone the repository:

    git clone https://github.com/xhd2015/go-ql
    cd go-ql
  2. Run the example:

    go run .

Check ./test for more details.

Contributing

Fork the repository, create a branch, make changes, and submit a pull request. Ensure code follows project standards.

License

MIT License. See LICENSE for details.

Contact

Open an issue on GitHub for questions or support.

About

AST Query Language for Go

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

0