guts

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2025 License: CC0-1.0 Imports: 18 Imported by: 1

README

Go Unto Ts (guts)

Go Reference

guts is a tool to convert golang types to typescript for enabling a consistent type definition across the frontend and backend. It is intended to be called and customized as a library, rather than as a command line executable.

See the simple example for a basic usage of the library.

type SimpleType[T comparable] struct {
	FieldString     string
	FieldInt        int
	FieldComparable T
	FieldTime       time.Time
}

Gets converted into

type Comparable = string | number | boolean;

// From main/main.go
interface SimpleType<T extends Comparable> {
    FieldString: string;
    FieldInt: number;
    FieldComparable: T;
    FieldTime: string;
}

How to use it

guts is a library, not a command line utility. This is to allow configuration with code, and also helps with package resolution.

See the simple example for a basic usage of the library. A larger example can be found in the Coder repository.

// Step 1: Create a new Golang parser
golang, _ := guts.NewGolangParser()
// Step 2: Configure the parser
_ = golang.IncludeGenerate("github.com/coder/guts/example/simple")
// Step 3: Convert the Golang to the typescript AST
ts, _ := golang.ToTypescript()
// Step 4: Mutate the typescript AST
ts.ApplyMutations(
    config.ExportTypes, // add 'export' to all top level declarations
)
// Step 5: Serialize the typescript AST to a string
output, _ := ts.Serialize()
fmt.Println(output)

How it works

guts first parses a set of golang packages. The Go AST is traversed to find all the types defined in the packages.

These types are placed into a simple AST that directly maps to the typescript AST.

Using goja, these types are then serialized to typescript using the typescript compiler API.

Generator Opinions

The generator aims to do the bare minimum type conversion. An example of a common opinion, is to create enum lists.

export type Enum = "bar" | "baz" | "foo" | "qux" // <-- Golang type
export const Enums: Enum[] = ["bar", "baz", "foo", "qux"] // <-- Helpful additional generated type

These kinds of opinions can be added with:

ts.ApplyMutations(
	config.EnumLists,
)
output, _ := ts.Serialize()

Helpful notes

An incredible website to visualize the AST of typescript: https://ts-ast-viewer.com/

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func RecordReference

func RecordReference(key, value bindings.ExpressionType) *bindings.ReferenceType

RecordReference creates a reference to the 'Record' type in Typescript. The Record type takes in 2 type parameters, key and value.

Types

type GoParser

type GoParser struct {
	Pkgs      map[string]*packages.Package
	Reference map[string]bool
	Prefix    map[string]string
	// contains filtered or unexported fields
}

GoParser takes in Golang packages, and can convert them to the intermediate typescript representation. The intermediate representation is closely aligned with the typescript AST.

func NewGolangParser

func NewGolangParser() (*GoParser, error)

NewGolangParser returns a new GoParser object. This object is responsible for converting Go types into the intermediate typescript AST representation. All configuration of the GoParser should be done before calling 'ToTypescript'. For usage, see 'ExampleGeneration' in convert_test.go.

Example
package main

import (
	"fmt"

	"github.com/coder/guts"
	"github.com/coder/guts/config"
)

func main() {
	// gen will convert the golang package to the typescript AST.
	// Configure it before calling ToTypescript().
	gen, _ := guts.NewGolangParser()

	// Pass in the directory of the package you want to convert.
	// You can mark a package as 'false' to include it as a reference, but not
	// generate types for it.
	_ = gen.IncludeGenerate("github.com/coder/guts/testdata/generics")

	// Default type mappings are useful, feel free to add your own
	gen.IncludeCustomDeclaration(config.StandardMappings())
	_ = gen.IncludeCustom(map[string]string{
		// To configure a custom type for a golang type, use the full package path.
		"github.com/coder/guts/testdata/generics.ExampleType": "string",
		// You can use golang type syntax to specify a type.
		"github.com/coder/guts/testdata/generics.AnotherExampleType": "map[string]*string",
	})

	// ts is the typescript AST. It can be mutated before serializing.
	ts, _ := gen.ToTypescript()

	ts.ApplyMutations(
		// Generates a constant which lists all enum values.
		config.EnumLists,
		// Adds 'readonly' to all interface fields.
		config.ReadOnly,
		// Adds 'export' to all top level types.
		config.ExportTypes,
	)

	output, _ := ts.Serialize()
	// Output is the typescript file text
	fmt.Println(output)
}
Output:

func (*GoParser) Identifier

func (p *GoParser) Identifier(obj types.Object) bindings.Identifier

ObjectName returns the name of the object including any prefixes defined by the config.

func (*GoParser) IncludeCustom

func (p *GoParser) IncludeCustom(mappings map[GolangType]GolangType) error

IncludeCustom takes in a remapping of golang types. Both the key and value of the map should be valid golang types. The key is the type to override, and the value is the new type. Typescript will be generated with the new type.

Only named types can be overridden. Examples: "github.com/your/repo/pkg.ExampleType": "string" "time.Time": "string"

func (*GoParser) IncludeCustomDeclaration

func (p *GoParser) IncludeCustomDeclaration(mappings map[string]TypeOverride)

IncludeCustomDeclaration is an advanced form of IncludeCustom.

func (*GoParser) IncludeGenerate

func (p *GoParser) IncludeGenerate(directory string) error

IncludeGenerate parses a directory and adds the parsed package to the list of packages. These package's types will be generated.

func (*GoParser) IncludeGenerateWithPrefix

func (p *GoParser) IncludeGenerateWithPrefix(directory string, prefix string) error

IncludeGenerateWithPrefix will include a prefix to all output generated types.

func (*GoParser) IncludeReference

func (p *GoParser) IncludeReference(directory string, prefix string) error

IncludeReference only generates types if they are referenced from the generated packages. This is useful for only generating a subset of the types that are being used.

func (*GoParser) ToTypescript

func (p *GoParser) ToTypescript() (*Typescript, error)

ToTypescript translates the Go types into the intermediate typescript AST The returned typescript object can be mutated before serializing.

type GolangType

type GolangType = string

type TypeOverride

type TypeOverride func() bindings.ExpressionType

type Typescript

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

func (*Typescript) ApplyMutations

func (ts *Typescript) ApplyMutations(muts ...func(typescript *Typescript))

func (*Typescript) ForEach

func (ts *Typescript) ForEach(node func(key string, node bindings.Node))

ForEach iterates through all the nodes in the typescript AST.

func (*Typescript) Node

func (ts *Typescript) Node(key string) (bindings.Node, bool)

func (*Typescript) ReplaceNode

func (ts *Typescript) ReplaceNode(key string, node bindings.Node)

func (*Typescript) Serialize

func (ts *Typescript) Serialize() (string, error)

Serialize will serialize the typescript AST to typescript code. It sorts all types alphabetically.

func (*Typescript) SerializeInOrder

func (ts *Typescript) SerializeInOrder(sort func(nodes map[string]bindings.Node) []bindings.Node) (string, error)

func (*Typescript) SetNode

func (ts *Typescript) SetNode(key string, node bindings.Node) error

Directories

Path Synopsis
cmd
Package config provides standard configurations for the guts package.
Package config provides standard configurations for the guts package.
example

Jump to

Keyboard shortcuts

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