gadget

package module
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2022 License: MIT Imports: 14 Imported by: 0

README

Gadget

Documentation

Index

Examples

Constants

View Source
const (
	KIND_INTERFACE = "interface" // Used if the type is an interface with methods.
	KIND_STRUCT    = "struct"    // Used if the type is a struct with fields.
	KIND_ARRAY     = "array"     // Used for array types.
	KIND_FUNC      = "function"  // Use function types.
	KIND_CHAN      = "channel"   // Used for channel types.
	KIND_MAP       = "map"       // Used for map types.
)

Variables

This section is empty.

Functions

func AdjustSource

func AdjustSource(source string, adjustBraces bool) string

AdjustSource is a convenience function that strips the opening and closing braces of a function's ( or other things ) body and removes the first `\t` character on each remaining line.

func GetLinesFromFile

func GetLinesFromFile(path string, from, to int) []byte

GetLinesFromFile creates a byte reader for the file at the target path and returns a slice of bytes representing the file content. This slice is restricted the lines specified by the `from` and `to` arguments inclusively. This will return an empty byte if an empty file, or any error, is encountered.

func WalkGoFiles

func WalkGoFiles(path string) (files []string)

WalkGoFiles recursively moves through the directory tree specified by `path` providing a slice of files matching the `*.go` extention. Explicitly specifying a file will return that file.

Types

type Field

type Field struct {
	Name       string `json:"name"`              // The name of the field.
	IsExported bool   `json:"is_exported"`       // Determines whether the field is exported.
	IsEmbedded bool   `json:"is_embedded"`       // Determines whether the field is an embedded type.
	Line       int    `json:"line"`              // The line number this field appears on in the associated source file.
	Signature  string `json:"body"`              // The full definition of the field including name, arguments and return values.
	Comment    string `json:"comment,omitempty"` // Any inline comments associated with the field.
	Doc        string `json:"doc,omitempty"`     // The comment block directly above this field's definition.
	// contains filtered or unexported fields
}

Field represents a field used in either a struct or an interface.

func NewField

func NewField(f *ast.Field, parent *File) *Field

NewField returns a field instance and attempts to populate all associated fields with meaningful values.

func (*Field) Parse

func (f *Field) Parse() *Field

Parse is responsible for browsing through f.astField, f.parent to populate the current fields's fields. ( Chainable )

func (*Field) String

func (f *Field) String() string

String implements the Stringer struct and returns the current package's name.

type File

type File struct {
	Name          string                            `json:"name"`           // The basename of the file.
	Path          string                            `json:"path"`           // The full path to the file as specified by the caller.
	Package       string                            `json:"package"`        // The name of the golang package associated with this file.
	IsMain        bool                              `json:"is_main"`        // Determines whether this file is part of package main.
	IsTest        bool                              `json:"is_test"`        // Determines whether this file is for golang tests.
	HasTests      bool                              `json:"has_tests"`      // Determines whether this file contains golang tests.
	HasBenchmarks bool                              `json:"has_benchmarks"` // Determines whether this file contains benchmark tests.
	HasExamples   bool                              `json:"has_examples"`   // Determines whether this file contains example tests.
	Imports       []string                          `json:"imports"`        // A list of strings containing all the current file's package imports.
	Values        *collection.Collection[*Value]    `json:"values"`         // A collection of declared golang values.
	Functions     *collection.Collection[*Function] `json:"functions"`      // A collection of declared golang functions.
	Types         *collection.Collection[*Type]     `json:"types"`          // A collection of declared golang types.
	// contains filtered or unexported fields
}

File represents a single file containing golang code.

func NewFile

func NewFile(path string) (*File, error)

NewFile returns a file instance representing a file within a golang package. This function creates a new token set and parser instance representing the new file's abstract syntax tree ( AST ).

Example (Functions)
if file, err := gadget.NewFile("function.go"); err == nil {
	file.Functions.Each(func(i int, function *gadget.Function) bool {
		fmt.Printf("%s defined between lines %d and %d\n", function.Name, function.LineStart, function.LineEnd)
		return false
	})
}
Output:

NewFunction defined between lines 36 and 43
Parse defined between lines 47 and 68
parseReceiver defined between lines 71 and 95
parseOutput defined between lines 101 and 121
parseLines defined between lines 125 and 129
parseBody defined between lines 134 and 143
parseSignature defined between lines 147 and 150
String defined between lines 153 and 155
Example (Json)
var buffer strings.Builder
if file, err := gadget.NewFile("value.go"); err == nil {
	if t, ok := file.Types.AtFirst(); ok {
		encoder := json.NewEncoder(&buffer)
		if err := encoder.Encode(t.Fields.Items()); err != nil {
			fmt.Println(err)
		}
	}
}

fmt.Println(buffer.String())
Output:

[{"name":"Kind","is_exported":true,"is_embedded":false,"line":10,"body":"Kind string `json:\"kind\"`","comment":"Describes the current value's type, eg; CONST or VAR."},{"name":"Name","is_exported":true,"is_embedded":false,"line":11,"body":"Name string `json:\"name\"`","comment":"The name of the value."},{"name":"Line","is_exported":true,"is_embedded":false,"line":12,"body":"Line int `json:\"line\"`","comment":"The line number within the associated source file in which this value was originally defined."},{"name":"Body","is_exported":true,"is_embedded":false,"line":13,"body":"Body string `json:\"body\"`","comment":"The full content of the associated statement."},{"name":"astIdent","is_exported":false,"is_embedded":false,"line":14,"body":"astIdent *ast.Ident"},{"name":"parent","is_exported":false,"is_embedded":false,"line":15,"body":"parent *File"}]
Example (Structs)
if file, err := gadget.NewFile("function.go"); err == nil {
	file.Types.Each(func(i int, t *gadget.Type) bool {
		fmt.Printf("%s is a %s with %d fields:\n", t.Name, t.Kind, t.Fields.Length())
		t.Fields.Each(func(i int, f *gadget.Field) bool {
			fmt.Printf("- %s on line %d\n", f.Name, f.Line)
			return false
		})
		return false
	})
}
Output:

Function is a struct with 16 fields:
- Name on line 16
- IsTest on line 17
- IsBenchmark on line 18
- IsExample on line 19
- IsExported on line 20
- IsMethod on line 21
- Receiver on line 22
- Doc on line 23
- Output on line 24
- Body on line 25
- Signature on line 26
- LineStart on line 27
- LineEnd on line 28
- LineCount on line 29
- astFunc on line 30
- parent on line 31

func (*File) Parse

func (f *File) Parse() *File

Parse is responsible for walking through the current file's abstract syntax tree in order to populate it's fields. This includes imports, defined functions and methods, structs and interfaces and other declared values. ( Chainable )

func (*File) String

func (f *File) String() string

String implements the Stringer struct and returns the current package's name.

type Function

type Function struct {
	// Comment string `json:"comment,omitempty"`  // Any inline comments associated with the function.
	Name        string `json:"name"`               // The name of the function.
	IsTest      bool   `json:"is_test"`            // Determines whether this is a test.
	IsBenchmark bool   `json:"is_benchmark"`       // Determines whether this is a benchmark.
	IsExample   bool   `json:"is_example"`         // Determines whether this is an example.
	IsExported  bool   `json:"is_exported"`        // Determines whether this function is exported.
	IsMethod    bool   `json:"is_method"`          // Determines whether this a method. This will be true if this function has a receiver.
	Receiver    string `json:"reciever,omitempty"` // If this method has a receiver, this field will refer to the name of the associated struct.
	Doc         string `json:"doc,omitempty"`      // The comment block directly above this funciton's definition.
	Output      string `json:"output,omitempty"`   // If IsExample is true, this field should contain the comment block defining expected output.
	Body        string `json:"body"`               // The body of this function; everything contained within the opening and closing braces.
	Signature   string `json:"signature"`          // The full definition of the function including receiver, name, arguments and return values.
	LineStart   int    `json:"line_start"`         // The line number in the associated source file where this function is initially defined.
	LineEnd     int    `json:"line_end"`           // The line number in the associated source file where the definition block ends.
	LineCount   int    `json:"line_count"`         // The total number of lines, including body, the interface occupies.
	// contains filtered or unexported fields
}

Function represents a golang function or method along with meaningful fields.

func NewFunction

func NewFunction(fn *ast.FuncDecl, parent *File) *Function

NewFunction returns a function instance and attempts to populate all associated fields with meaningful values.

func (*Function) Parse

func (f *Function) Parse() *Function

Parse is responsible for browsing through f.astFunc, f.tokenSet and f.astFile to populate the current function's fields. ( Chainable )

func (*Function) String

func (f *Function) String() string

String implements the Stringer struct and returns the current package's name.

type Package

type Package struct {
	Name  string                        `json:"name"`  // The name of the current package.
	Files *collection.Collection[*File] `json:"files"` // A collection of golang files associated with this package.
}

Package represents a golang package as well as all associated files, functions and other declarations.

func NewPackage

func NewPackage(name string) *Package

NewPackage returns a Package instance with an initialised collection used for assigning and iterating through files.

func (*Package) String

func (p *Package) String() string

String implements the Stringer struct and returns the current package's name.

type Type

type Type struct {
	Name      string                         `json:"name"`              // The name of the struct.
	Kind      string                         `json:"kind"`              // Determines the kind of type, eg; interface or struct.
	LineStart int                            `json:"line_start"`        // The line number in the associated source file where this struct is initially defined.
	LineEnd   int                            `json:"line_end"`          // The line number in the associated source file where the definition block ends.
	LineCount int                            `json:"line_count"`        // The total number of lines, including body, the struct occupies.
	Comment   string                         `json:"comment,omitempty"` // Any inline comments associated with the struct.
	Doc       string                         `json:"doc,omitempty"`     // The comment block directly above this struct's definition.
	Signature string                         `json:"signature"`         // The full definition of the struct itself.
	Body      string                         `json:"body,omitempty"`    // The full body of the struct sourced directly from the associated file; comments included.
	Fields    *collection.Collection[*Field] `json:"fields,omitempty"`  // A collection of fields and their associated metadata.
	// contains filtered or unexported fields
}

Type represents a golang type definition.

func NewType

func NewType(ts *ast.TypeSpec, parent *File) *Type

NewType returns an struct instance and attempts to populate all associated fields with meaningful values.

func (*Type) Parse

func (t *Type) Parse() *Type

Parse is responsible for browsing through f.astSpec, f.astType, f.parent to populate the current struct's fields. ( Chainable )

func (*Type) String

func (t *Type) String() string

String implements the Stringer struct and returns the current package's name.

type Value

type Value struct {
	Kind string `json:"kind"` // Describes the current value's type, eg; CONST or VAR.
	Name string `json:"name"` // The name of the value.
	Line int    `json:"line"` // The line number within the associated source file in which this value was originally defined.
	Body string `json:"body"` // The full content of the associated statement.
	// contains filtered or unexported fields
}

Value represents a declared value in go; var, const, etc...

func NewValue

func NewValue(id *ast.Ident, parent *File) *Value

NewValue returns a Value instance.

func (*Value) Parse

func (v *Value) Parse() *Value

Parse is responsible for browsing through f.astIdent and f.tokenSet to populate the current value's fields. ( Chainable )

func (*Value) String

func (v *Value) String() string

String implements the Stringer struct and returns the current package's name.

type Walker

type Walker func(ast.Node) bool

walker implements a walker interface used to traversing syntax trees.

func (Walker) Visit

func (w Walker) Visit(node ast.Node) ast.Visitor

Visit steps through each node within the specified syntax tree.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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