Skip to content

String function is not viable in environments where executable go is unavailable #18

@dmitshur

Description

@dmitshur

Consider the following (minified) example program that tries to print a value of type font.Metrics:

package main

import (
	"fmt"
	"log"

	"github.com/golang/freetype"
	"github.com/golang/freetype/truetype"
	"github.com/hexops/valast"
	"golang.org/x/image/font/gofont/gomono"
)

func main() {
	f, err := freetype.ParseFont(gomono.TTF)
	if err != nil {
		log.Fatalln(err)
	}

	face := truetype.NewFace(f, &truetype.Options{
		Size:              12,
		GlyphCacheEntries: 0,
		SubPixelsX:        1,
		SubPixelsY:        1,
	})
	fmt.Println("metrics =", valast.String(face.Metrics()))

	// Output:
	// metrics = err: go command required, not found: exec: "go": executable file not found in $PATH: stderr: 
}

(https://play.golang.org/p/6nQBdwaHo5q)

It prints:

metrics = err: go command required, not found: exec: "go": executable file not found in $PATH: stderr: 

When executed in an environment where an executable go is unavailable, such as inside a browser via WebAssembly (GOOS=js GOARCH=wasm), or inside the Go Playground.

It's possible to provide a custom PackagePathToName function via an option, such as:

fmt.Println("metrics =", valast.StringWithOptions(face.Metrics(), &valast.Options{
	PackagePathToName: func(path string) (string, error) { return pathpkg.Base(path), nil }, // TODO: Handle paths like example.com/foo/v2, where the name is 'foo' not 'v2'.
}))

Then it doesn't get the aforementioned error.

Is this intended behavior for String, or should valast know that GOOS=js GOARCH=wasm environment cannot execute a go binary and should automatically use a different PackagePathToName implementation, so that it's possible to use String?

Note that both spew.Dump(face.Metrics()) and goon.Dump(face.Metrics()) print an output without an error inside a browser.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions