interfaces

package module
Version: v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2022 License: MIT Imports: 12 Imported by: 0

README

interfaces GoDoc Build Status Build status

Code generation tools for Go's interfaces.

Tools available in this repository:

cmd/interfacer GoDoc

Generates an interface for a named type.

Installation

~ $ go install github.com/rjeczalik/interfaces/cmd/interfacer@latest

Usage

~ $ interfacer -help
Usage of interfacer:
  -all
        Include also unexported methods.
  -as string
        Generated interface name. (default "main.Interface")
  -for string
        Type to generate an interface for.
  -o string
        Output file. (default "-")

Example

  • generate by manually
~ $ interfacer -for os.File -as mock.File
  • generate by go generate
//go:generate interfacer -for os.File -as mock.File -o file_iface.go
~ $ go generate  ./...
  • output
// Created by interfacer; DO NOT EDIT

package mock

import (
        "os"
)

// File is an interface generated for "os".File.
type File interface {
        Chdir() error
        Chmod(os.FileMode) error
        Chown(int, int) error
        Close() error
        Fd() uintptr
        Name() string
        Read([]byte) (int, error)
        ReadAt([]byte, int64) (int, error)
        Readdir(int) ([]os.FileInfo, error)
        Readdirnames(int) ([]string, error)
        Seek(int64, int) (int64, error)
        Stat() (os.FileInfo, error)
        Sync() error
        Truncate(int64) error
        Write([]byte) (int, error)
        WriteAt([]byte, int64) (int, error)
        WriteString(string) (int, error)
}
cmd/structer GoDoc

Generates a struct for a formatted file. Currently supported formats are:

  • CSV

Installation

~ $ go get github.com/rjeczalik/interfaces/cmd/structer

Usage

~ $ structer -help
Usage of structer:
  -as string
        Generated struct name. (default "main.Struct")
  -f string
        Input file. (default "-")
  -o string
        Output file. (default "-")
  -tag string
        Name for a struct tag to add to each field.
  -type string
        Type of the input, overwrites inferred from file name.

Example

~ $ head -2 aws-billing.csv         # first line is a CSV header, second - first line of values
"InvoiceID","PayerAccountId","LinkedAccountId","RecordType","RecordID","BillingPeriodStartDate","BillingPeriodEndDate","InvoiceDate"
"Estimated","123456","","PayerLineItem","5433212345","2016/01/01 00:00:00","2016/01/31 23:59:59","2016/01/21 19:19:06"
~ $ structer -f aws-billing.csv -tag json -as billing.Record
// Created by structer; DO NOT EDIT

package billing

import (
        "strconv"
        "time"
)

// Record is a struct generated from "aws-billing.csv" file.
type Record struct {
        InvoiceID              string    `json:"invoiceID"`
        PayerAccountID         int64     `json:"payerAccountID"`
        LinkedAccountID        string    `json:"linkedAccountID"`
        RecordType             string    `json:"recordType"`
        RecordID               int64     `json:"recordID"`
        BillingPeriodStartDate time.Time `json:"billingPeriodStartDate"`
        BillingPeriodEndDate   time.Time `json:"billingPeriodEndDate"`
        InvoiceDate            time.Time `json:"invoiceDate"`
}

// MarshalCSV encodes r as a single CSV record.
func (r *Record) MarshalCSV() ([]string, error) {
        records := []string{
                r.InvoiceID,
                strconv.FormatInt(r.PayerAccountID, 10),
                r.LinkedAccountID,
                r.RecordType,
                strconv.FormatInt(r.RecordID, 10),
                time.Parse("2006/01/02 15:04:05", r.BillingPeriodStartDate),
                time.Parse("2006/01/02 15:04:05", r.BillingPeriodEndDate),
                time.Parse("2006/01/02 15:04:05", r.InvoiceDate),
        }
        return records, nil
}

// UnmarshalCSV decodes a single CSV record into r.
func (r *Record) UnmarshalCSV(record []string) error {
        if len(record) != 8 {
                return fmt.Errorf("invalud number fields: want 8, got %d", len(record))
        }
        r.InvoiceID = record[0]
        if record[1] != "" {
                if val, err := strconv.ParseInt(record[1], 10, 64); err == nil {
                        r.PayerAccountID = val
                } else {
                        return err
                }
        }
        r.LinkedAccountID = record[2]
        r.RecordType = record[3]
        if record[4] != "" {
                if val, err := strconv.ParseInt(record[4], 10, 64); err == nil {
                        r.RecordID = val
                } else {
                        return err
                }
        }
        if record[5] != "" {
                if val, err := time.Parse("2006/01/02 15:04:05", record[5]); err == nil {
                        r.BillingPeriodStartDate = val
                } else {
                        return err
                }
        }
        if record[6] != "" {
                if val, err := time.Parse("2006/01/02 15:04:05", record[6]); err == nil {
                        r.BillingPeriodEndDate = val
                } else {
                        return err
                }
        }
        if record[7] != "" {
                if val, err := time.Parse("2006/01/02 15:04:05", record[7]); err == nil {
                        r.InvoiceDate = val
                } else {
                        return err
                }
        }
        return nil
}

Documentation

Overview

Package interfaces provides functionality for parsing and building interface type models for simple code generation purposes.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Field

type Field struct {
	Name string `json:"name,omitempty"`
	Type Type   `json:"type,omitempty"`
	Tags Tags   `json:"tags,omitempty"`
}

Field

func (*Field) String

func (f *Field) String() string

String

type Func

type Func struct {
	Name       string `json:"name,omitempty"` // name of the function
	Ins        []Type `json:"ins,omitempty"`  // input parameters
	Outs       []Type `json:"outs,omitempty"` // output parameters
	IsVariadic bool   // whether the function is variadic
}

Func represents an interface function.

func (Func) Deps

func (f Func) Deps() []string

Deps gives a list of packages the function depends on. E.g. if the function represents Serve(net.Listener, http.Handler) error, calling Deps() will return []string{"http", "net"}.

The packages are sorted by name.

func (Func) String

func (f Func) String() string

String gives Go code representation of the function.

Example
package main

import (
	"fmt"

	"github.com/rjeczalik/interfaces"
)

func main() {
	f := interfaces.Func{
		Name: "Close",
		Outs: []interfaces.Type{{Name: "error"}},
	}
	fmt.Println(f)
}
Output:

Close() error

type Interface

type Interface []Func

Interface represents a typed interface.

func New

func New(query string) (Interface, error)

New builds an interface definition for a type specified by the query. Supported query format is "package".Type (similar to what gorename tool accepts).

The function expects sources for the requested type to be present in current GOPATH.

Example
package main

import (
	"fmt"

	"github.com/rjeczalik/interfaces"
)

func main() {
	i, err := interfaces.New(`github.com/rjeczalik/interfaces.ExampleBaz`)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("Interface:")
	for _, fn := range i {
		fmt.Println(fn)
	}
	fmt.Println("Dependencies:")
	for _, dep := range i.Deps() {
		fmt.Println(dep)
	}
}
Output:

Interface:
A(int) int
B(*string, io.Writer, interfaces_test.ExampleFoo) (*interfaces_test.ExampleFoo, int)
C(map[string]int, *interfaces.Options, *http.Client) (chan []string, error)
D(*map[interface{}]struct{}, interface{}) (chan struct{}, []interface{})
E(*[]map[*flag.FlagSet]struct{}, [3]string)
Dependencies:
flag
github.com/rjeczalik/interfaces
github.com/rjeczalik/interfaces_test
io
net/http

func NewWithOptions

func NewWithOptions(opts *Options) (Interface, error)

NewWithOptions builds an interface definition for a type specified by the given Options.

The Options may be used to specify e.g. different GOPATH if sources for requested type are not available in the current one.

Example
package main

import (
	"fmt"

	"github.com/rjeczalik/interfaces"
)

func main() {
	opts := &interfaces.Options{
		Query: &interfaces.Query{
			Package:  "net",
			TypeName: "Interface",
		},
	}
	i, err := interfaces.NewWithOptions(opts)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("Interface:")
	for _, fn := range i {
		fmt.Println(fn)
	}
	fmt.Println("Dependencies:")
	for _, dep := range i.Deps() {
		fmt.Println(dep)
	}
}
Output:

Interface:
Addrs() ([]net.Addr, error)
MulticastAddrs() ([]net.Addr, error)
Dependencies:
net

func (Interface) Deps

func (i Interface) Deps() []string

Deps gives a list of packages the interface depends on.

type Options

type Options struct {
	Query      *Query         // a named type
	Context    *build.Context // build context; see go/build godoc for details
	Unexported bool           // whether to include unexported methods

	CSVHeader  []string
	CSVRecord  []string
	TimeFormat string
}

Options is used for altering behavior of New() function.

type Query

type Query struct {
	TypeName string `json:"name,omitempty"`
	Package  string `json:"package,omitempty"`
}

Query represents a named type request.

func ParseQuery

func ParseQuery(query string) (*Query, error)

ParseQuery gives new Query for the given query text.

type Struct

type Struct []Field

Struct

func NewStruct

func NewStruct(opts *Options) (Struct, error)

NewStruct

func (Struct) Deps

func (s Struct) Deps() []string

Deps

func (Struct) String

func (s Struct) String() string

String

type Tag

type Tag struct {
	Name  string `json:"name,omitempty"`
	Value string `json:"value,omitempty"`
}

Tag

func (Tag) String

func (t Tag) String() string

String

type Tags

type Tags []Tag

Tags

func (Tags) String

func (t Tags) String() string

String

type Type

type Type struct {
	Name        string `json:"name,omitempty"`        // type name
	Package     string `json:"package,omitempty"`     // package name the type is defined in; empty for builtin
	ImportPath  string `json:"importPath,omitempty"`  // import path of the package
	IsPointer   bool   `json:"isPointer,omitempty"`   // whether the parameter is a pointer
	IsComposite bool   `json:"isComposite,omitempty"` // whether the type is map, slice, chan or array
	IsFunc      bool   `json:"isFunc,omitempty"`      // whether the type if function
}

Type is a simple representation of a single parameter type.

func (Type) String

func (typ Type) String() (s string)

String gives Go code representation of the type.

Notes

Bugs

  • Does not work with recursive types.

  • Does not work with with more than one level of indirection (pointer to pointers).

  • Does not and will not work with struct literals.

  • May incorrectly generate dependencies for a map types which key and value are named types imported from different packages. As a workaround run goimports over the output file.

Directories

Path Synopsis
cmd
interfacer
Command interfaces
Command interfaces

Jump to

Keyboard shortcuts

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