Skip to content

kisunji/typecover

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

typecover

typecover is a go linter that checks if a code block is assigning to all exported fields and calling all exported methods of a struct, or calling all exported methods of an interface.

It is useful in cases where code wants to be aware of any newly added members.

Install

go get -u github.com/kisunji/typecover/cmd/typecover

Usage

Using the CLI

typecover [package/file]

Comment directives

# Local Type
// typecover:TypeName

# Imported Type
// typecover:pkg.TypeName 

# Excluding members
// typecover:TypeName -exclude Field3,Field4,Field5

typecover:YourType will check for the existence of all exported members of YourType in the comment's associated code block (for details on how comments are associated with code, see here).

Examples

Struct assignment

type MyStruct struct {
	MyField1 string
	MyField2 string
	myField3 string
}

// typecover:MyStruct
m := MyStruct{ 
    MyField1: "hello",
}
Type example.MyStruct is missing MyField2

Covering a code block

The typecover annotation can be placed at a higher level (func, if-stmt, for-loop) to cover the whole block.

// typecover:MyStruct
func example() {
    m := MyStruct{}
    m.MyField2 = "world"    
}
Type example.MyStruct is missing MyField1

Using imported types

// typecover:flag.Flag
f := flag.Flag{ 
    Name:  "test",
    Usage: "usage instructions",
    Value: nil,
}
Type flag.Flag is missing DefValue

Copying fields from exported type

//typecover:flag.Flag
func cloneFlag(f flag.Flag) MyFlag {
    return MyFlag{
        Name: f.Name,
        Usage: f.Usage,
        Value: f.Value,
    }
}
Type flag.Flag is missing DefValue

Enforcing all methods in a Builder interface

type ExampleBuilder interface {
	Option1() ExampleBuilder
	Option2() ExampleBuilder
	Build() Example
}

//typecover:ExampleBuilder
func MakeExample() Example {
	b := NewExampleBuilder().Option2()
	return b.Build()
}
Type example.ExampleBuilder is missing Option1

Exclude a member from being checked

type ExampleBuilder interface {
	Option1() ExampleBuilder
	Option2() ExampleBuilder
	Build() Example
}

//typecover:ExampleBuilder -exclude Option1
func MakeExample() Example {
	b := NewExampleBuilder().Option2()
	return b.Build()
}
(passes!)

Credits

https://github.com/mbilski/exhaustivestruct

https://github.com/reillywatson/enumcover

About

Go linter to check if a code block contains references to all exported members of a struct or interface

Resources

License

Stars

Watchers

Forks

Languages