[TOOL, CLI] - Filter and examine Go type structures, interfaces and their transitive dependencies and relationships. Export structural types as TypeScript value object or bare type representations.

Overview

Build Status Coverage Status Open Issues Report Card Awesome Go

typex

Examine Go types and their transitive dependencies. Export results as TypeScript value objects (or types) declaration.

Installation

go get -u github.com/dtgorski/typex

Synopsis

The CLI command typex filters and displays Go type structures, interfaces and their relationships across package boundaries. It generates a type hierarchy tree with additional references to transitive dependencies vital for the filtered types. As an additional feature, typex exports the result tree as a TypeScript projection representing value objects or bare types.

Examples

Go type hierarchy layout

$ typex -f=Rune io/...

├── error interface {
│       Error() string
│   }
└── io
    ├── RuneReader interface {
    │       ReadRune() (r rune, size int, err error)
    │   }
    └── RuneScanner interface {
            io.RuneReader
            ReadRune() (r rune, size int, err error)
            UnreadRune() error
        }
$ typex -f=Render github.com/dtgorski/typex/...

└── github.com
    └── dtgorski
        └── typex
            └── internal
                ├── PathReplaceFunc func(string) string
                ├── go
                │   └── TypeRender struct {
                │           PathReplaceFunc internal.PathReplaceFunc
                │           IncludeUnexported bool
                │       }
                └── ts
                    └── TypeRender struct {
                            PathReplaceFunc internal.PathReplaceFunc
                            IncludeUnexported bool
                        }

TypeScript value object layout

$ typex -f=File -l=ts-class mime/multipart

export module mime {
    export module multipart {
        export class FileHeader {
            constructor(
                readonly Filename: string,
                readonly Header: net.textproto.MIMEHeader,
                readonly Size: number,
            ) {}
        }
    }
}
export module net {
    export module textproto {
        export type MIMEHeader = Record<string, string[]>
    }
}

TypeScript bare type layout

$ typex -f=File -l=ts-type mime/multipart

export module mime {
    export module multipart {
        export type FileHeader = {
            Filename: string,
            Header: net.textproto.MIMEHeader,
            Size: number,
        }
    }
}
export module net {
    export module textproto {
        export type MIMEHeader = Record<string, string[]>
    }
}

TypeScript and reserved keywords

Basically, the names of types and fields will be exported from Go without modification. Collisions with reserved keywords or standard type names in the target language may occur. To avoid conflicts, you may use the JSON tag annotation for the exported fields of a struct as described in the json.Marshal(...) documentation.

TypeScript and exportable types

Due to fundamental language differences, typex is not capable of exporting all type declarations one-to-one. Refer to the type mapping table below. Go channel, interface and function declarations will be omitted, references to these declarations will be typed with any.

TypeScript type mapping

TypeScript (resp. JavaScript aka ECMAScript) lacks a native integer number type. The numeric type provided there is inherently a 64 bit float. You should keep this in mind when working with exported numeric types - this includes byte and rune type aliases as well.

Go native type TypeScript type
bool boolean
string string
map Record<K, V>
struct (named) T
struct (anonymous) {}
array (slice) T[]
complex[64|128] any
chan, func, interface any
int[8|16|32|64] number
uint[8|16|32|64] number
byte(=uint8) number
rune(=int32) number
float[32|64] number
uintptr number

Usage

$ typex -h
Usage: typex [options] package...
Examine Go types and their transitive dependencies. Export
results as TypeScript value objects (or types) declaration.

Options:
    -f <name>
        Type name filter expression. Repeating the -f option
        is allowed, all expressions aggregate to an OR query.

        The <name> filter can be a type name, a path part or
        a regular expression. Especially in the latter case,
        <name> should be quoted or escaped correctly to avoid
        errors during shell interpolation. Filters are case
        sensitive, see examples below.

        The result tree will contain additional references to
        transitive dependencies vital for the filtered types.

    -l <layout>
        Modify the export layout. Available layouts are:
          * "go":       the default Go type dependency tree
          * "ts-type":  TypeScript type declaration projection
          * "ts-class": TypeScript value object projection

    -r <old-path>:<new-path>
        Replace matching portions of <old-path> in a fully
        qualified type name with <new-path> string. Repeating
        the -r option is allowed, substitutions will perform
        successively. <old-path> can be a regular expression.
        
        The path replacement/relocation can be used to modify
        locations of type hierarchies, e.g. prune off the
        "github.com" reference from qualified type name path
        by omitting the <new-path> part after the colon. 

    -t  Go tests (files suffixed _test.go) will be included
        in the result tree available for a filter expression

    -u  Unexported types (lowercase names) will be included
        in the result tree available for a filter expression.

    -x <name> 
        Exclude type names from export. Repeating this option
        is allowed, all expressions aggregate to an OR query.
        The exclusion filter can be a type name, a path part
        or a regular expression.

More options:
    -h  Display this usage help and exit.
    -v  Print program version and exit.

The 'package' argument denotes one or more package import path
patterns to be inspected. Patterns must be separated by space.
A pattern containing '...' specifies the active modules whose
modules paths match the pattern.

Examples:
    $ typex -u go/...
    $ typex -u -f=URL net/url
    $ typex github.com/your/repository/...
    $ typex -l=ts-type github.com/your/repository/...
    $ typex -r=github.com:a/b/c github.com/your/repository/...

This tool relies heavily on Go's package managing subsystem and
is bound to its features and environmental execution context.

Known issues

  • Occasional(?) internal error from Go's package managing subsystem has been reported on Go 1.14.6 darwin/amd64. Newer Go versions >= 1.15 seem to be not affected.

Disclaimer

The implementation and features of typex follow the YAGNI principle. There is no claim for completeness or reliability.

@dev

Try make:

$ make

 make help       Displays this list
 make clean      Removes build/test artifacts
 make build      Builds a static binary to ./bin/typex
 make debug      Starts debugger [:2345] with ./bin/typex
 make install    Compiles and installs typex in Go environment
 make test       Runs tests, reports coverage
 make tidy       Formats source files, cleans go.mod
 make sniff      Checks format and runs linter (void on success)

License

MIT - © dtg [at] lengo [dot] org

You might also like...
State observer - StateObserver used to synchronize the local(cached) state of the remote object with the real state

state observer StateObserver used to synchronize the local(cached) state of the

Notification library for gophers and their furry friends.
Notification library for gophers and their furry friends.

Shoutrrr Notification library for gophers and their furry friends. Heavily inspired by caronc/apprise. Quick Start As a package Using shoutrrr is easy

Gorsair hacks its way into remote docker containers that expose their APIs
Gorsair hacks its way into remote docker containers that expose their APIs

Gorsair Gorsair is a penetration testing tool for discovering and remotely accessing Docker APIs from vulnerable Docker containers. Once it has access

This project is an implementation of Fermat's factorization method in which multiples of prime numbers are factored into their constituent primes

This project is an implementation of Fermat's factorization method in which multiples of prime numbers are factored into their constituent primes. It is a vanity attempt to break RSA Encryption which relies on prime multiples for encryption.

Start of a project that would let people stay informed about safe running spaces in their area.

SafeRun Start of a project that would let people stay informed about safe running spaces in their area. Too many people I'm friends with feel unsafe w

GoThanks automatically stars Go's official repository and your go.mod github dependencies, providing a simple way  to say thanks to the maintainers of the modules you use and the contributors of Go itself.
GoThanks automatically stars Go's official repository and your go.mod github dependencies, providing a simple way to say thanks to the maintainers of the modules you use and the contributors of Go itself.

Give thanks (in the form of a GitHub ★) to your fellow Go modules maintainers. About GoThanks performs the following operations Sends a star to Go's r

Give your dependencies stars on GitHub! 🌟

Give stars to your dependencies of Go repositories and say thank you to developers!!

Track health of various dependencies - golang

Background This package helps setup health check based on status of external dependencies. The idea is to add all external dependencies like database,

Library to work with MimeHeaders and another mime types. Library support wildcards and parameters.

Mime header Motivation This library created to help people to parse media type data, like headers, and store and match it. The main features of the li

Comments
  • Add license scan report and status

    Add license scan report and status

    Your FOSSA integration was successful! Attached in this PR is a badge and license report to track scan status in your README.

    Below are docs for integrating FOSSA license checks into your CI:

    opened by fossabot 1
  • Package import errors with Go 1.14

    Package import errors with Go 1.14

    Just thought you should know; maybe put a warning in the readme? With Go 1.14, I get this:

    $ go version
    go version go1.14.6 darwin/amd64
    
    $ typex .
    2020/10/15 11:03:03 internal error: package "sync" without types was imported from "[...]"
    

    Go 1.15 works fine.

    opened by atombender 1
  • Provide more details in the README as to what this is, what it does, etc

    Provide more details in the README as to what this is, what it does, etc

    Yah.. so I would love to see a bit more detail on what this project is/does. The short bit of info is great for someone who knows it..but many of us new to Go or otherwise might not know entirely what this is and why we would use it. I have a rough idea..but still not entirely sure if I would use it, or why.. based on the brief info in the README.

    opened by goapifirst 1
Owner
Daniel T. Gorski
dtg [at] lengo [dot] org
Daniel T. Gorski
XSD (XML Schema Definition) parser and Go/C/Java/Rust/TypeScript code generator

xgen Introduction xgen is a library written in pure Go providing a set of functions that allow you to parse XSD (XML schema definition) files. This li

null 185 Sep 27, 2022
GolangChatroom - Live chatrooms built with Golang, React, and TypeScript with Webpack Hot Reloading

Go Live Chatrooms An example project demonstrating websockets and authentication

Layne Faler 0 Jan 3, 2022
Parse a shell script and output all export declarations in an easy to read format

Find Exports Parse a shell script and output all export declarations in an easy to read format. Usage Example $ findexports ~/.bashrc PATH=$PATH:/usr/

Ilia Choly 1 Jan 13, 2022
Export the private key from a Swarm json key file

exportSwarmKey Currently it is a pain in the A** to export bee key in to metamask as they are not compatible. This programe will export the private ke

Zahoor Mohamed 39 Aug 14, 2022
:runner:runs go generate recursively on a specified path or environment variable and can filter by regex

Package generate Package generate runs go generate recursively on a specified path or environment variable like $GOPATH and can filter by regex Why wo

Go Playgound 27 Jul 23, 2022
Filter out multiple strings from stdin.

minus The minus tool accepts data from stdin and filters out any arguments passed. It simplifies something like this: some_command | grep -vF thing1 |

Shawn Milochik 1 Dec 20, 2021
Our library to use the idealo interfaces in go.

Here you can find our library for idealo. We develop the API endpoints according to our demand and need. You are welcome to help us to further develop this library.

J&J Ideenschmiede GmbH 2 Mar 15, 2022
Store - Read and write data structures

Store - Read and write data structures Store provides the ability to write the data structures to a file and read from a file in the Go programming la

Andrej Giesbrecht 0 Jan 3, 2022
Gosfdc module - a collection of packages containing the data structures from the various Salesforce APIs and Tools

Gosfdc module - a collection of packages containing the data structures from the various Salesforce APIs and Tools

Rodolphe Blancho 0 Jan 21, 2022
a generic object pool for golang

Go Commons Pool The Go Commons Pool is a generic object pool for Golang, direct rewrite from Apache Commons Pool. Features Support custom PooledObject

jolestar 1.1k Sep 27, 2022