ohnogen

command
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Jan 2, 2024 License: BSD-3-Clause Imports: 15 Imported by: 0

Documentation

Overview

ohnogen is a golang stringer based tool to automate the creation of helper methods that provide the name and description of enums(ints only). This tool also automatically ensures all your enum types will satisfy the error interface.

Installation

You can install this tool by running the command below:

go install github.com/A-0-5/ohno/cmd/ohnogen@latest

Usage

Usage of ohnogen:
	ohnogen [flags] -type T [directory]
	ohnogen [flags] -type T files... # Must be a single package

Flags

Flags:
  -formatbase int
    	format in which the enum value needs to be printed in different use cases.
    	Valid options are 2(binary), 8(octal),10(decimal), 16(hex).
    	default -formatbase=10 (default 10)
  -ohno
    	generate the OhNo method for using with ohno package
  -output string
    	output file name; default srcdir/<type>_errors.go
  -tags string
    	comma-separated list of build tags to apply
  -trimprefix prefix
    	trim the prefix from the generated constant names
  -type string
    	comma-separated list of type names; must be set
  -version
    	prints the current version information of this tool

Usage Example

Given an enum of Type T , it generates the following methods

	func (t T) String() string
	func (t T) Description() string
 	func (t T) Error() string
 	func (t T) Package() string
 	func (t T) Code() string

	// This function gets generated only if -ohno flag is set
	func (MyError) OhNo(message string, extra any, cause error,
		sourceInfoType sourceinfo.SourceInfoType, timestamp time.Time,
		timestampLayout string) (ohnoError error)

The file is created in the same package and directory as the package that defines T. It has helpful defaults designed for use with go generate.

ohnogen works best with constants that are consecutive values such as created using iota, but creates good code regardless.

For example, given this snippet,

package somepkg

type MyError int

const (
  NotFound      MyError    = iota // Requested resource was not found
  Timeout                         // Operation timed out
  AlreadyExists                   // Resource already exists
  Internal                        // An internal error occurred
  Unknown       = Internal        // An unknown error occurred
)

running this command

ohnogen -type=MyError -ohno

in the same directory will create the file myerror_errors.go, in package somepkg, containing a definition of

func (MyError) String() string
func (MyError) Description() string
func (MyError) Error() string
func (MyError) Package() string
func (MyError) Code() string

// This function gets generated only if -ohno flag is set
func (MyError) OhNo(message string, extra any, cause error,
	sourceInfoType sourceinfo.SourceInfoType, timestamp time.Time,
	timestampLayout string) (ohnoError error)

String() method

The String() method will translate the value of a MyError constant to the string representation of the respective constant name, so that the call

fmt.Print(somepkg.NotFound)

will print the string

NotFound

Description() method

The Description() method will translate the comment of a MyError constant to the string representation of the respective constant, so that the call

fmt.Print(somepkg.NotFound.Description())

will print the string

Requested resource was not found

Error() method

The Error() method is implemented to satisfy the error interface and provide a single error string containing the name and description of the respective constant, so that the call

fmt.Print(somepkg.NotFound.Error())

will print the string

NotFound: Requested resource was not found

You can also use the this as go error as this satisfies the error interface and wrap, join and compare like you would with any error.

Package() method

The Package() method gives the package name where this error constant is defined. The call

fmt.Print(somepkg.NotFound.Package())

will print the string

somepkg

Code() method

The Code() method returns the enum value as a string formatted to the base specified in formatbase argument. Assuming formatbase was 16 at the time of generation, the call

fmt.Print(somepkg.NotFound.Code())

will print the string

0x0

OhNo(...) method

The OhNo(...) method constructs an github.com/A-0-5/ohno/pkg/ohno.OhNoError from the github.com/A-0-5/ohno/pkg/ohno package and returns it. This is useful if you want to provide additional context to your error like a message and custom fields. The call

 fmt.Print(somepkg.NotFound.OhNo("not_found message", "extra_msg", nil,
		sourceinfo.ShortFileAndLineWithFunc, time.Now(), time.DateTime))

will print the string

2023-09-30 20:51:43 main.go:25 (main.main): [0x0] somepkg.NotFound: Requested resource was not found, not_found message, extra_msg

More Info

Typically this process would be run using go generate, like this:

//go:generate ohnogen -type=MyError -ohno

If multiple constants have the same value, the lexically first matching name will be used (in the example, Unknown will print as "Internal").

With no arguments, it processes the package in the current directory. Otherwise, the arguments must name a single directory holding a Go package or a set of Go source files that represent a single Go package.

The -type flag accepts a comma-separated list of types so a single run can generate methods for multiple types. The default output file is t_errors.go, where t is the lower-cased name of the first type listed. It can be overridden with the -output flag.

The `-ohno` Flag

This is a special flag which when set generates the OhNo method which allows you to add additional context to the error like source information, timestamp, custom message etc. refer the [ohno] package for more details or refer examples to see how to use them

Examples

You can use this tool in multiple ways. Checkout the examples part of this module to understand how you can use this tool and the package.

Jump to

Keyboard shortcuts

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