Socket
Socket
Sign inDemoInstall

github.com/jba/printsrc

Package Overview
Dependencies
0
Alerts
File Explorer

Install Socket

Detect and block malicious and high-risk dependencies

Install

    github.com/jba/printsrc

Package printsrc prints Go values as Go source. It strives to render legal Go source code, and returns an error when detects that it cannot. To generate code for a slice of Points in package "geo": To print the names of a type in another package, printsrc needs to know how to refer to the package. Usually, but not always, the package identifier is the last component of the package path. For example, the types in the standard library package "database/sql" are normally prefixed by "sql". But this rule doesn't hold for all packages. The actual identifier is the package name as declared in its files' package clause, which need not be the same as the last component of the import path. (A common case: import paths ending in "/v2", "/v3" and so on.) Also, an import statement can specify a different identifier. Since printsrc can't know about these special cases, you must call Printer.RegisterImport to tell it the identifier to use for a given import path. Sometimes there is no way for printsrc to discover how to print a value as valid Go source code. For example, the math/big.Int type is a struct with no exported fields, so a big.Int cannot be printed as a struct literal. (A big.Int can be constructed with the NewInt function or the SetString method.) Use Printer.RegisterPrinter to associate a type with a function that returns source code for a value of that type. A custom printer for time.Time is registered by default. It prints a time.Time by printing a call to time.Date. An error is returned if the time's location is not Local or UTC, since those are the only locations for which source expressions can be produced. This package makes an effort to sort map keys in order to generate deterministic output. But if it can't sort the keys it prints the map anyway. The output will be valid Go but the order of the keys will change from run to run. That creates noise in code review diffs. Use Printer.RegisterLess to register a function that compares two values of a type. It will be called to sort map keys of that type. This package elides the types of composite literals when it can. For example, the value will print in its simplified form, Maps with multiple NaN keys are not handled. The reflect package provides no way to distinguish a type defined inside a function from one at top level. So printsrc will print expressions containing names for those types which will not compile. Sharing relationships are not preserved. For example, if two pointers in the input point to the same value, they will point to different values in the output. Unexported fields of structs defined outside the generated package are ignored, because there is no way to set them (without using unsafe code). So important state may fail to be printed. As a safety feature, printsrc fails if it is asked to print a non-zero struct from outside the generated package with no exported fields. You must register custom printers for such structs. But that won't catch problems with types that have at least one exported field. Cycles are detected by the crude heuristic of limiting recursion depth. Cycles cause printsrc to fail. A more sophisticated approach would represent cyclical values using intermediate variables, but it doesn't seem worth it. This example shows how to use printsrc along with the text/template package to generate a file of Go code.


Version published

Readme

Source

printsrc: Printing Go Values as Source

There are many packages that print Go values so people can read them. This package prints Go values so the Go compiler can read them. It is intended for use in code generators.

Background

I wanted to provide some data to my program at startup. I could have used go:embed to store the raw data with the program and process it at startup, but I wanted to pay the processing cost beforehand and generate Go data structures into a .go file that could be linked with the rest of my code.

So I need something that printed Go values as Go source. I looked around at the many pretty-printing packages out there:

  • github.com/davecgh/go-spew/spew
  • github.com/k0kubun/pp/v3
  • github.com/kr/pretty
  • github.com/kylelemons/godebug/pretty
  • github.com/sanity-io/litter

and more. They do a great job of formatting Go values for people to read. But I couldn't find one that correctly prints values as Go source. So I wrote this package.

Issues with Printing Source

Here are a few challenges that come up when trying to print Go values in a way that the compiler can understand.

Special floating-point values

Consider the floating-point value for positive infinity. There is no Go literal for this value, but it can be obtained with math.Inf(1). Calling fmt.Sprintf("%#v", math.Inf(1)) returns +Inf, which is not valid Go.

The printsrc package prints a float64 positive infinity as math.Inf(1) and a float32 positive infinity as float32(math.Inf(1)). It handles negative infinity and NaN similarly.

Values that cannot be represented

Function and channel values cannot be written as source using information available from the reflect package. Pretty-printers do their best to render these values, as they should, but printsrc fails on them so you can discover the problem quickly.

Pointers

When faced with a pointer, printers either print the address (like Go's fmt package) or follow the pointer and print the value. Neither of those, when fed back into Go, will produce the right value. Given

i := 5
s := []*int{&i, &i}

this package will print s as

[]*int{
    func() *int { var x int = 5; return &x }(),
    func() *int { var x int = 5; return &x }(),
}

That is a valid Go expression, although it doesn't preserve the sharing relationship of the original. For simplicity, printsrc doesn't detect sharing, and fails on cycles.

Types from other packages

Say your data structure contains a time.Duration. Depending on where it occurs, such values may have to be rendered with their type, like time.Duration(100). But that code won't compile unless the time package has been imported (and imported under the name "time"). Types in the package for where the generated code lives don't have that problem; they can be generated without a qualifying package identifier.

printsrc assumes that packages it encounters have been imported using the identifier that is the last component of their import path. Most of the time that is correct, but when it isn't you can register a different identifier with an import path.

Values that need constructors

The time.Time type has unexported fields, so it can't be usably printed as a Go struct literal (unless the code is being generated in the time package itself). There are many other types that need to be constructed with a function call or in some other way. Since printsrc can't discover the constructors for these types on its own, it lets you provide custom printing functions for any type. The one for time.Time is built in and prints a call to time.Date. (You can override it if you want.)

FAQs

Last updated on 13 Dec 2021

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc