aliaser

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2024 License: MIT Imports: 19 Imported by: 0

README

aliaser

Go Reference CI codecov Go Report Card

aliaser is a Go package designed to streamline the process of generating aliases for Go packages.

In Go projects, naming conflicts between imported packages and your own code can lead to verbose and cumbersome code where you have to frequently alias imported package names.

aliaser solves this problem by automatically generating Go code that provides aliases for all the exported constants, variables, functions, and types in an external package. This allows you to seamlessly integrate and extend external packages without cluttering your code with manual aliases.

Installation

You need a working Go environment.

go get github.com/marcozac/go-aliaser

Usage

To use aliaser in your project, follow these steps:

  1. Create an Aliaser: Start by creating a new aliaser.Aliaser with the target package name and the pattern of the package you want to alias.
import "github.com/marcozac/go-aliaser"

a, err := aliaser.New(&aliaser.Config{TargetPackage: "mypkg", Pattern: "github.com/example/package"})
if err != nil {
  // ...
}
  1. Generate Aliases: With the Aliaser created, you can generate the aliases writing them to a io.Writer or to directly to a file.
if err := a.Generate(io.Discard); err != nil {
  // ...
}

if err := a.GenerateFile("mypkg/alias.go"); err != nil {
  // ...
}

CLI

In addition to the library, aliaser comes with a CLI tool to simplify generating aliases directly from the command line.

After installing aliaser CLI with go install (e.g. go install github.com/marcozac/go-aliaser/cmd/aliaser@latest) or by downloading a release (available soon), you can use the aliaser command to generate aliases for a package.

aliaser generate \
  --from "github.com/example/package" \
  --package "myalias" \
  --file "path/to/output/file.go"

Examples

For simple, but more detailed examples of how to use the aliaser library and CLI, see the examples directory.

Contributing

Contributions to aliaser are welcome! Whether it's reporting bugs, discussing improvements, or contributing code, all contributions are appreciated.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	// OnDuplicateSkip is the default behavior when a duplicate object name is
	// found. It skips the object and does not generate an alias for it.
	OnDuplicateSkip = iota

	// OnDuplicateReplace replaces the old object (even if it is a different
	// kind of object) with the new one.
	OnDuplicateReplace

	// OnDuplicatePanic panics when a duplicate object name is found.
	OnDuplicatePanic
)

Variables

View Source
var (
	// ErrNilConfig is returned when the given config is nil.
	ErrNilConfig = errors.New("nil config")

	// ErrEmptyTarget is returned when the given target is empty.
	ErrEmptyTarget = errors.New("empty target")

	// ErrEmptyPattern is returned when the given pattern is empty.
	ErrEmptyPattern = errors.New("empty pattern")
)

Functions

func Generate

func Generate(target, pattern string, wr io.Writer, opts ...Option) error

Generate loads the package defined by the given pattern, generates the aliases for the target package name, and writes the result to the given writer.

Under the hood, Generate creates a new Aliaser with the given parameters and calls Aliaser.Generate with the writer.

func GenerateFile

func GenerateFile(target, pattern, name string, opts ...Option) error

GenerateFile behaves like Generate, but it writes the aliases to the file with the given name. It creates the necessary directories if they don't exist.

func NewAliasedTuple

func NewAliasedTuple(aliases []string, tuple *types.Tuple) *types.Tuple

NewAliasedTuple returns a new tuple ensuring none of its variable names is in the given aliases list. If a variable name is in the list, it is suffixed with an underscore.

Types

type Aliaser

type Aliaser struct {
	*Config
	*importer.Importer
	// contains filtered or unexported fields
}

Aliaser is the primary type of this package. It is used to generate the aliases for the loaded package.

func New

func New(c *Config, opts ...Option) (*Aliaser, error)

New returns a new Aliaser with the given configuration. The configuration is required and must have a valid target package and pattern. Otherwise, a ErrNilConfig, ErrEmptyTarget or ErrEmptyPattern will be returned. See Config for more details.

New may also return an error in these cases:

  • Package loading fails
  • The package has errors
  • More or less than one package is loaded with the given pattern
  • The loaded package has an unexpected object type

Example:

a, err := aliaser.New(&aliaser.Config{
	TargetPackage: "foo",
	Pattern: "github.com/example/package",
})
if err != nil {
	// ...
}
a.GenerateFile("mypkg/alias.go")

// mypkg/alias.go
// Code generated by aliaser. DO NOT EDIT.

package foo

import "github.com/marcozac/go-aliaser/internal/testing/pkg"

const (
	// ...
)

func (*Aliaser) AddConstants

func (a *Aliaser) AddConstants(cs ...*types.Const)

AddConstants adds the given constants to the list of the constants to generate aliases for.

NOTE: Currently, the Aliaser does not perform any check to avoid adding the same constant or any other object with the same name more than once. Adding a constant with the same name of another object will result in a non-buildable generated code.

func (*Aliaser) AddFunctions

func (a *Aliaser) AddFunctions(fns ...*types.Func)

AddFunctions adds the given functions to the list of the functions to generate aliases for.

func (*Aliaser) AddTypes

func (a *Aliaser) AddTypes(ts ...*types.TypeName)

AddTypes adds the given types to the list of the types to generate aliases for.

func (*Aliaser) AddVariables

func (a *Aliaser) AddVariables(vs ...*types.Var)

AddVariables adds the given variables to the list of the variables to generate aliases for.

func (*Aliaser) Constants

func (a *Aliaser) Constants() []*Const

Constants returns the list of the constants loaded for aliasing.

func (*Aliaser) Functions

func (a *Aliaser) Functions() []*Func

Functions returns the list of the functions loaded for aliasing.

func (*Aliaser) Generate

func (a *Aliaser) Generate(wr io.Writer) error

Generate writes the aliases to the given writer.

Generate returns an error if fails to execute the template, format the generated code, or write the result to the writer.

func (*Aliaser) GenerateFile

func (a *Aliaser) GenerateFile(name string) error

GenerateFile behaves like Aliaser.Generate, but it writes the aliases to the file with the given name creating the necessary directories. If the file already exists, it is truncated.

GenerateFile returns an error in the same cases as Aliaser.Generate and if any of the directory creation or file writing operations fail. In this case, if the file did not exist before the operation, it is removed, otherwise, its content is reset to the original state.

func (*Aliaser) Types

func (a *Aliaser) Types() []*TypeName

Types returns the list of the types loaded for aliasing.

func (*Aliaser) Variables

func (a *Aliaser) Variables() []*Var

Variables returns the list of the variables loaded for aliasing.

type Config

type Config struct {

	// [REQUIRED]
	// TargetPackage is the name of the package where the aliases will be
	// generated. For example, if the package path is
	// "github.com/marcozac/go-aliaser/pkg-that-needs-aliases/foo", the target
	// package is "foo".
	TargetPackage string

	// [REQUIRED]
	// Pattern is the package pattern in Go format to be loaded.
	//
	// Example:
	//
	//	"github.com/marcozac/go-aliaser/pkg-that-will-be-aliased"
	Pattern string

	// Header is an optional header to be written at the top of the file.
	//
	// Default: "// Code generated by aliaser. DO NOT EDIT."
	Header string

	// AssignFunctions sets whether the aliases for the functions should be
	// assigned to a variable instead of being wrapped.
	AssignFunctions bool
	// contains filtered or unexported fields
}

Config is the configuration used to define the target package.

type Const

type Const struct {
	*types.Const
	// contains filtered or unexported fields
}

Const is the type used to represent a constant in the loaded package. It contains the original constant and the resolver used to generate the aliases.

func NewConst

func NewConst(c *types.Const, imp *importer.Importer) *Const

NewConst returns a new Const with the given constant. The importer is used to add the constant package to the list of imports.

func (*Const) Generic

func (o *Const) Generic() bool

Generic returns true if the object is generic, that is, if it has type parameters that are not resolved by type arguments.

Example:

type A[T1, T2 any] struct{ Foo T1; Bar T2 } // true
type B[T1 any] A[T1, int] // false
type C A[int, string] // false

func (*Const) PackageAlias

func (o *Const) PackageAlias() string

PackageAlias returns the alias of the package as declared in the import statement.

func (*Const) TypeArgs added in v0.1.1

func (o *Const) TypeArgs() []types.Type

TypeArgs returns the type arguments of the object as a slice.

func (*Const) TypeParams

func (o *Const) TypeParams() []*TypeParam

TypeParams returns the type parameters of the object as a slice.

func (*Const) TypeString

func (o *Const) TypeString() string

TypeString returns the object type as a string, resolving the package names using the aliases declared in the import statements.

type File

type File interface {
	fs.File
	io.WriteSeeker
	Truncate(size int64) error
}

File is an interface that extends fs.File with the io.WriteSeeker and Truncate methods.

func OpenFileWithReset

func OpenFileWithReset(name string) (File, func() error, error)

OpenFileWithReset opens a file for reading and writing, creating it if it does not exist. It also returns a function to reset the file to its original state. If the file does not exist, the reset function will remove it, otherwise, it is truncate and the reset function will rewrite the original content. The reset function does not close the file, so it is the caller's responsibility to do so.

NOTE: This function does not create the parent directories of the file.

type Func

type Func struct {
	*types.Func
	// contains filtered or unexported fields
}

Func is the type used to represent a function in the loaded package. It contains the original function and the resolver used to generate the aliases.

func NewFunc

func NewFunc(fn *types.Func, imp *importer.Importer) *Func

NewFunc returns a new Func with the given function. The importer is used to add the function package to the list of imports.

func (*Func) CallArgs

func (fn *Func) CallArgs() string

CallArgs returns the arguments of the function as a string. The arguments are joined by a comma and the variadic argument is suffixed with "...". If the function has no arguments, it returns an empty string.

Example:

func(a int, b bool, c ...string) // "a, b, c..."

func (*Func) Generic

func (o *Func) Generic() bool

Generic returns true if the object is generic, that is, if it has type parameters that are not resolved by type arguments.

Example:

type A[T1, T2 any] struct{ Foo T1; Bar T2 } // true
type B[T1 any] A[T1, int] // false
type C A[int, string] // false

func (*Func) PackageAlias

func (o *Func) PackageAlias() string

PackageAlias returns the alias of the package as declared in the import statement.

func (*Func) Returns

func (fn *Func) Returns() bool

Returns returns true if the function has results.

func (*Func) TypeArgs added in v0.1.1

func (o *Func) TypeArgs() []types.Type

TypeArgs returns the type arguments of the object as a slice.

func (*Func) TypeParams

func (o *Func) TypeParams() []*TypeParam

TypeParams returns the type parameters of the object as a slice.

func (*Func) TypeString

func (o *Func) TypeString() string

TypeString returns the object type as a string, resolving the package names using the aliases declared in the import statements.

func (*Func) WriteSignature

func (fn *Func) WriteSignature() string

WriteSignature returns the signature of the function as a string. It is a wrapper around types.WriteSignature that uses a custom types.Qualifier to resolve the package aliases. The signature is wrapped by Signature.Wrapper to replace the parameter and result names on conflict with the package aliases.

type Object

type Object interface {
	types.Object
	PackageAliaser
	TypeStringer
}

Object extends the types.Object interface with methods to get the package alias and the resolved type as a string.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is the interface implemented by all options.

func AssignFunctions

func AssignFunctions(v bool) Option

AssignFunctions sets whether the aliases for the functions should be assigned to a variable instead of being wrapped.

func ExcludeConstants

func ExcludeConstants(v bool) Option

ExcludeConstants excludes the constants from the loaded package.

func ExcludeFunctions

func ExcludeFunctions(v bool) Option

ExcludeFunctions excludes the functions from the loaded package.

func ExcludeNames

func ExcludeNames(names ...string) Option

ExcludeNames excludes the given names from the loaded package. Each name is valid for all kinds of objects (constants, variables, functions, and types).

For example, if the loaded package has a constant named "A" and a type named "B", ExcludeNames("A", "B") will exclude both "A" and "B".

func ExcludeTypes

func ExcludeTypes(v bool) Option

ExcludeTypes excludes the types from the loaded package.

func ExcludeVariables

func ExcludeVariables(v bool) Option

ExcludeVariables excludes the variables from the loaded package.

func OnDuplicate

func OnDuplicate(v int) Option

OnDuplicate sets the behavior when a duplicate object name is found.

func WithContext

func WithContext(ctx context.Context) Option

WithContext sets the context to be used when loading the package.

func WithHeader

func WithHeader(header string) Option

WithHeader sets an optional header to be written at the top of the file.

type PackageAliaser

type PackageAliaser interface {
	// PackageAlias returns the alias of the package as declared in the
	// import statement.
	PackageAlias() string
}

PackageAliaser is the interface implemented by types that can provide the alias of the package they belong to.

type PackageTyper

type PackageTyper interface {
	Pkg() *types.Package
	Type() types.Type
}

PackageTyper is a subset of the types.Object interface that provides methods to get the package and the type of the object.

type PackagesErrors

type PackagesErrors []packages.Error

PackagesErrors is a slice of packages.Error as returned by packages.Load that implements the error interface.

The error message is a concatenation of the messages of the underlying errors, separated by a semicolon and a space.

func (PackagesErrors) Error

func (e PackagesErrors) Error() string

type QualifiedType added in v0.1.1

type QualifiedType struct {
	// contains filtered or unexported fields
}

QualifiedType is the type used to represent a type in the loaded package. It contains the original type and the importer used to resolve the package aliases. It must be created using the NewQualifiedType function.

func NewQualifiedType added in v0.1.1

func NewQualifiedType(t types.Type, imp *importer.Importer) *QualifiedType

NewQualifiedType returns a new QualifiedType with the given type and importer.

func (*QualifiedType) String added in v0.1.1

func (qt *QualifiedType) String() string

String returns the string representation of the qualified type. It uses the types.TypeString function with the package qualifier.

func (*QualifiedType) Underlying added in v0.1.1

func (qt *QualifiedType) Underlying() types.Type

Underlying returns the underlying type of the qualified type.

type Signature

type Signature struct {
	*types.Signature
	// contains filtered or unexported fields
}

Signature is the type used to represent a function signature in the loaded package. It contains the original signature and the importer used to generate the aliases. It also contains a wrapper signature that replaces the parameter and result names on conflict with the package aliases.

func NewSignature

func NewSignature(sig *types.Signature, imp *importer.Importer) *Signature

NewSignature returns a new Signature with the given signature. The importer is used to add the signature package to the list of imports.

func (*Signature) Wrapper

func (s *Signature) Wrapper() *types.Signature

Wrapper returns a types.Signature that wraps the original one, replacing the parameter and result names on conflict with the package aliases.

Since it calls the importer.Importer.AliasedImports method for initializing the wrapper and further calls will return the same wrapper, it should be called only after the package has been fully loaded.

Example:

import "github.com/google/uuid"

func Must(uuid_ uuid.UUID, err error) uuid.UUID {
	return uuid.Must(uuid_, err)
}

type TypeName

type TypeName struct {
	*types.TypeName
	// contains filtered or unexported fields
}

TypeName is the type used to represent a type in the loaded package. It contains the original type and the resolver used to generate the aliases.

func NewTypeName

func NewTypeName(tn *types.TypeName, imp *importer.Importer) *TypeName

NewTypeName returns a new TypeName with the given type. The importer is used to add the type package to the list of imports.

func (*TypeName) Generic

func (o *TypeName) Generic() bool

Generic returns true if the object is generic, that is, if it has type parameters that are not resolved by type arguments.

Example:

type A[T1, T2 any] struct{ Foo T1; Bar T2 } // true
type B[T1 any] A[T1, int] // false
type C A[int, string] // false

func (*TypeName) PackageAlias

func (o *TypeName) PackageAlias() string

PackageAlias returns the alias of the package as declared in the import statement.

func (*TypeName) TypeArgs added in v0.1.1

func (o *TypeName) TypeArgs() []types.Type

TypeArgs returns the type arguments of the object as a slice.

func (*TypeName) TypeParams

func (o *TypeName) TypeParams() []*TypeParam

TypeParams returns the type parameters of the object as a slice.

func (*TypeName) TypeString

func (o *TypeName) TypeString() string

TypeString returns the object type as a string, resolving the package names using the aliases declared in the import statements.

type TypeParam added in v0.1.1

type TypeParam struct {
	*types.TypeParam
}

TypeParam is the type used to represent a type parameter in the loaded package. It must be created using the NewTypeParam function.

func NewTypeParam added in v0.1.1

func NewTypeParam(tp *types.TypeParam, imp *importer.Importer) *TypeParam

NewTypeParam returns a new TypeParam with the given type parameter and sets the constraint to a new QualifiedType with the given importer.

type TypeStringer

type TypeStringer interface {
	// TypeString returns the type of the implementing type as a string.
	TypeString() string
}

TypeStringer is the interface implemented by types that can return their type as a string.

type Var

type Var struct {
	*types.Var
	// contains filtered or unexported fields
}

Var is the type used to represent a variable in the loaded package. It contains the original variable and the resolver used to generate the aliases.

func NewVar

func NewVar(v *types.Var, imp *importer.Importer) *Var

NewVar returns a new Var with the given variable. The importer is used to add the variable package to the list of imports.

func (*Var) Generic

func (o *Var) Generic() bool

Generic returns true if the object is generic, that is, if it has type parameters that are not resolved by type arguments.

Example:

type A[T1, T2 any] struct{ Foo T1; Bar T2 } // true
type B[T1 any] A[T1, int] // false
type C A[int, string] // false

func (*Var) PackageAlias

func (o *Var) PackageAlias() string

PackageAlias returns the alias of the package as declared in the import statement.

func (*Var) TypeArgs added in v0.1.1

func (o *Var) TypeArgs() []types.Type

TypeArgs returns the type arguments of the object as a slice.

func (*Var) TypeParams

func (o *Var) TypeParams() []*TypeParam

TypeParams returns the type parameters of the object as a slice.

func (*Var) TypeString

func (o *Var) TypeString() string

TypeString returns the object type as a string, resolving the package names using the aliases declared in the import statements.

Directories

Path Synopsis
cmd
internal
testing/pkg/json
This package is used to simulate the import of a package that has the same name of another one.
This package is used to simulate the import of a package that has the same name of another one.
util
set

Jump to

Keyboard shortcuts

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