astscan

package module
v0.0.0-...-d993987 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2019 License: MIT Imports: 10 Imported by: 0

README

astscan GoDoc Build Status

astscan provides File() and Dir() functions. File() function recieves a file path and walks its AST to do check. If check is ok, it'll calls the callback. Dir() function is like File() but recieves a directory path, and walks the directory recursively.

Example

package astscan

import (
	"fmt"
	"io/ioutil"
	"os"
	"testing"
)

var (
	src = `// main 测试包

package main

import "fmt"

var (
	hello = "你好,世界"  // hello 的注释
)

func main() {
	fmt.Println(hello)
	fmt.Println("测试 2333")
}`
)

func _print(item Item) {
	fmt.Println("item:", item)
}

func TestFile(t *testing.T) {
	tmpFile, err := ioutil.TempFile("", "*.go")
	if err != nil {
		t.Fatal(err)
	}
	defer os.Remove(tmpFile.Name())
	defer tmpFile.Close()

	if _, err := tmpFile.Write([]byte(src)); err != nil {
		t.Fatal(err)
	}

	if err := File(tmpFile.Name(), CheckChinese, _print); err != nil {
		t.Fatal(err)
	}
}

func TestDir(t *testing.T) {
	tmpDir0, err := ioutil.TempDir("", "")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tmpDir0)

	tmpDir, err := ioutil.TempDir(tmpDir0, "")
	if err != nil {
		t.Fatal(err)
	}

	tmpFile, err := ioutil.TempFile(tmpDir, "*.go")
	if err != nil {
		t.Fatal(err)
	}
	defer tmpFile.Close()

	if _, err := tmpFile.Write([]byte(src)); err != nil {
		t.Fatal(err)
	}

	if err := Dir(tmpDir, CheckChinese, _print); err != nil {
		t.Fatal(err)
	}
}

Run go test -v ., you will get the output.

astscan_example_test

Documentation

Index

Constants

View Source
const (
	TypeString  = "string"
	TypeComment = "comment"
)

types for scanning

Variables

View Source
var (
	MaxDepth = 7
)

max depth for scanning dir, you can change it before running Dir

Functions

func CheckChinese

func CheckChinese(s string) bool

CheckChinese check whether s contains Chinese character

func Dir

func Dir(dir string, check Checker, callback Callback) error

Dir scans directory with deep iteration firstly, and parses every directory to check the String and Comment on ast. Dir's depth limits by MaxDepth.

func File

func File(file string, check Checker, callback Callback) error

File parses the file and checks the String and Comment on ast.

Types

type Callback

type Callback func(Item)

Callback is the scanning callbacker

type Checker

type Checker func(s string) bool

Checker is the scanning checker

type Item

type Item struct {
	Pkg, Fileline, Type, Value string
	Node                       ast.Node
}

Item for scanning callback

func (Item) String

func (i Item) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL