summaryrefslogtreecommitdiff
path: root/vendor/github.com/mmcloughlin/avo/printer/printer.go
blob: b562c74ea8e974a1885b9f22658d315417b0ce9a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Package printer implements printing of avo files in various formats.
package printer

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/mmcloughlin/avo/internal/stack"
	"github.com/mmcloughlin/avo/ir"
)

// Printer can produce output for an avo File.
type Printer interface {
	Print(*ir.File) ([]byte, error)
}

// Builder can construct a printer.
type Builder func(Config) Printer

// Config represents general printing configuration.
type Config struct {
	// Command-line arguments passed to the generator. If provided, this will be
	// included in a code generation warning.
	Argv []string

	// Name of the code generator.
	Name string

	// Name of Go package the generated code will belong to.
	Pkg string
}

// NewDefaultConfig produces a config with Name "avo".
// The package name is guessed from the current directory.
func NewDefaultConfig() Config {
	return Config{
		Name: "avo",
		Pkg:  pkg(),
	}
}

// NewArgvConfig constructs a Config from os.Args.
// The package name is guessed from the current directory.
func NewArgvConfig() Config {
	return Config{
		Argv: os.Args,
		Pkg:  pkg(),
	}
}

// NewGoRunConfig produces a Config for a generator that's expected to be
// executed via "go run ...".
func NewGoRunConfig() Config {
	path := mainfile()
	if path == "" {
		return NewDefaultConfig()
	}
	argv := []string{"go", "run", filepath.Base(path)}
	if len(os.Args) > 1 {
		argv = append(argv, os.Args[1:]...)
	}
	return Config{
		Argv: argv,
		Pkg:  pkg(),
	}
}

// GeneratedBy returns a description of the code generator.
func (c Config) GeneratedBy() string {
	if c.Argv == nil {
		return c.Name
	}
	return fmt.Sprintf("command: %s", strings.Join(c.Argv, " "))
}

// GeneratedWarning returns text for a code generation warning. Conforms to https://golang.org/s/generatedcode.
func (c Config) GeneratedWarning() string {
	return fmt.Sprintf("Code generated by %s. DO NOT EDIT.", c.GeneratedBy())
}

// mainfile attempts to determine the file path of the main function by
// inspecting the stack. Returns empty string on failure.
func mainfile() string {
	if m := stack.Main(); m != nil {
		return m.File
	}
	return ""
}

// pkg guesses the name of the package from the working directory.
func pkg() string {
	if cwd, err := os.Getwd(); err == nil {
		return filepath.Base(cwd)
	}
	return ""
}