binsanity

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2023 License: BSD-3-Clause Imports: 19 Imported by: 0

README

binsanity

Asset files into golang source, with testing! Inspired by go-bindata.

GoDoc Coverage Status

You usually interact directly with the command-line application:

$ go get -u github.com/biztos/binsanity/v1/...
$ binsanity --help

For information on the Go package itself, please refer to the official documentation.

Please use version v1 or higher, earlier versions may not work with go.mod.

Using binsanity

Specify your asset directory, and binsanity will create two files for you: a source file and a test file. The test file provides 100% coverage of the source file.

$ cd src/mypkg
$ binsanity my-asset-dir
$ go test -cover .
ok      github.com/you/mypkg 0.012s  coverage: 100.0% of statements

You can pass custom values for the output file, package name, and module (imported for testing). By default the source file will be binsanity.go and the test file will binsanity_test.go; the package and module are taken from your project directory.

The generated source file defines the following functions:

  • AssetNames() []string -- return a list of all asset names.
  • Asset(name string) ([]byte,error) -- return data for an asset.
  • MustAsset(name string) []byte -- as above, but panic on errors.
  • MustAssetString(name string) string -- as above, but for strings.

Note that the design of binsanity is probably not conducive to very large asset collections. Data is compressed, but also Base64-encoded; and the lookup and caching system is fast but could potentially more than double your memory usage. If you are very worried about efficiency, you should not use binsanity. But if you are more interested in convenience and test coverage, then you probably should. :-)

Issues are welcome if they are reproducible.

Good luck, and design for testing!

Documentation

Overview

Package binsanity encodes files into Go source, with testing.

Inspired by the bindata package, binsanity aims to provide a useful subset of features while also enabiling thorough testing of the generated Go source code.

For a much more featureful, but less testable approach see:

https://pkg.go.dev/github.com/jteeuwen/go-bindata

One generally does not use this package directly, but rather the command binsanity.

This generates two Go source files: one with following functions, and one testing those functions:

Asset - return an asset's data as a []byte

MustAsset - retrieve an asset's bytes or panic if not found

MustAssetString - call MustAsset and return its result as a string

AssetNames - return a list of asset names as a []string

Assets are gzipped and base64-encoded; they are decoded and inflated only once, with the result cached.

The resulting source files introduce no dependencies outside the Go standard library.

Index

Constants

View Source
const AppDescription = `` /* 734-byte string literal not displayed */
View Source
const DummyDataString = "H4sIAAAAAAAA/8rP5gIEAAD//30OFtoDAAAA"
View Source
const DummyDataSum = "dc51b8c96c2d745df3bd5590d990230a482fd247123599548e0632fdbf97fc22"
View Source
const Version = "v1.0.0"

Variables

View Source
var Args = os.Args // used by cmd/binsanity, override...
View Source
var ErrWriter io.Writer = os.Stderr // Standard Error, override for testing
View Source
var ExitFunc = os.Exit // exit function, override for testing
View Source
var OutWriter io.Writer = os.Stdout // Standard Output, override for testing

Functions

func Asset added in v1.0.0

func Asset(name string) ([]byte, error)

Asset returns the byte content of the asset for the given name, or an error if no such asset is available.

func AssetNames added in v1.0.0

func AssetNames() []string

AssetNames returns the sorted names of the assets.

func FindImportPath added in v1.0.0

func FindImportPath(file string) (string, error)

FindImportPath attempts to figure out what module we are in, by reading the go.mod file in the target directory or a parent, and returns an import path usable by the test files, or an error if no go.mod is found.

If the go.mod is in a parent directory, we assume we are in a normal subdirectory of that, and join the paths appropriately.

The file provided is the path to the source file that will contain the package declaration when generated. Note that the package name and the import path do not need to agree.

func FindPackage added in v1.0.0

func FindPackage(path string) (string, error)

FindPackage attempts to figure out what package we are in, using a brazenly insufficient heuristic: the first package declaration in a go source file in the target directory; or the name of the directory; or "main" if that is not a valid identifier.

The path provided is to the source file that will contain the package declaration when generated.

func GoFilesBySize added in v1.0.0

func GoFilesBySize(dir string) ([]string, error)

GoFilesBySize returns a list of paths for Go source files paths in dir, sorted by file size. Test files are ignored.

func MustAsset added in v1.0.0

func MustAsset(name string) []byte

MustAsset returns the byte content of the asset for the given name, or panics if no such asset is available.

func MustAssetString added in v1.0.0

func MustAssetString(name string) string

MustAssetString returns the string content of the asset for the given name, or panics if no such asset is available. This is a convenience function for string(MustAsset(name)).

func RunApp

func RunApp(args []string)

RunApp uses the cli package to run the app with the args provided, which should be os.Args equivalent. Process is called with the parsed options.

If it encounters any error, it exits with a nonzero value though ExitFunc. Standard output and error are written to OutWriter and ErrWriter.

func ScanForPackage added in v1.0.0

func ScanForPackage(path string) (string, error)

ScanForPackage scans the Go source of the file at path and returns the package found, if any. No package found is not an error, as the file may be a work in progress.

func ValidIdent added in v1.0.0

func ValidIdent(s string) bool

ValidIdent returns true if s is a valid Go identifier according to the spec: https://go.dev/ref/spec#Identifiers

Types

type Config added in v1.0.0

type Config struct {
	Dir     string
	Package string
	File    string
	Module  string
}

Config holds the values used in Process, in order to avoid confusion.

type GenData added in v1.0.0

type GenData struct {
	CodeFile          string
	TestFile          string
	Package           string
	Module            string
	Names             []string
	DataSums          []string
	DataStrings       []string
	ExistingAssetName string
	ExistingAssetSum  string
	MissingAssetName  string
	AssetsEmpty       bool
}

GenData holds the data injected into the templates when generating files.

type Result added in v1.0.0

type Result struct {
	Files int
	Bytes int
}

Result is returned by Process and records the number of files and total bytes processed.

func Process

func Process(cfg *Config) (*Result, error)

Process converts all files in cfg.Dir into readable data in a Go file cfg.File belonging to package cfg.Package, and writes tests for the generated code. The test file imports cfg.Module.

The file defaults to "binsanity.go" and if not empty, must have ".go" as its extension.

The package and module values are guessed if not provided; a standard Go Module environment is assumed.

The test file is named "binsanity_test.go" or the equivalent for the code file, and provides full coverage of the generated functions.

If either file exists it is overwritten.

Paths are stripped of their prefixes up to the dir and converted to slash format when stored as asset names.

In the rare case of *no* assets found in the directory, a single special asset is created in order to achieve test coverage. Its name is randomized and should not conflict with any real-world data as it begins with 256 underscores.

This asset is *not* returned by the AssetNames function.

The first error encountered is returned.

func (*Result) String added in v1.0.0

func (r *Result) String() string

String returns the pretty-print version of Result.

Directories

Path Synopsis
cmd
binsanity
The binsanity program converts asset files to Go source.
The binsanity program converts asset files to Go source.

Jump to

Keyboard shortcuts

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