summaryrefslogtreecommitdiffstats
path: root/cmd/jp/main.go
blob: cc1d9b876514e0c012885c0599553ae98d5f9209 (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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package main

import (
	"encoding/csv"
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"os"
	"reflect"

	"github.com/sgreben/jp/pkg/draw"
	"github.com/sgreben/jp/pkg/terminal"

	"github.com/sgreben/jp/pkg/jsonpath"
)

type configuration struct {
	Box        draw.Box
	X          string
	Y          string
	XY         string
	PlotType   enumVar
	CanvasType enumVar
	InputType  enumVar
	HistBins   uint
}

const (
	plotTypeLine    = "line"
	plotTypeBar     = "bar"
	plotTypeScatter = "scatter"
	plotTypeHist    = "hist"
	plotTypeHist2D  = "hist2d"
)

const (
	canvasTypeFull         = "full"
	canvasTypeFullEscape   = "full-escape"
	canvasTypeFullEscapeBW = "full-bw"
	canvasTypeFullEscapeWB = "full-wb"
	canvasTypeQuarter      = "quarter"
	canvasTypeBraille      = "braille"
	canvasTypeAuto         = "auto"
)

const (
	inputTypeCSV  = "csv"
	inputTypeJSON = "json"
)

var config = configuration{
	PlotType: enumVar{
		Value: plotTypeLine,
		Choices: []string{
			plotTypeLine,
			plotTypeBar,
			plotTypeScatter,
			plotTypeHist,
			plotTypeHist2D,
		},
	},
	CanvasType: enumVar{
		Value: canvasTypeAuto,
		Choices: []string{
			canvasTypeFull,
			canvasTypeFullEscape,
			canvasTypeFullEscapeBW,
			canvasTypeFullEscapeWB,
			canvasTypeQuarter,
			canvasTypeBraille,
			canvasTypeAuto,
		},
	},
	InputType: enumVar{
		Value: inputTypeJSON,
		Choices: []string{
			inputTypeJSON,
			inputTypeCSV,
		},
	},
}

var (
	xPattern  *jsonpath.JSONPath
	yPattern  *jsonpath.JSONPath
	xyPattern *jsonpath.JSONPath
)

func init() {
	flag.Var(&config.PlotType, "type", fmt.Sprintf("Plot type. One of %v", config.PlotType.Choices))
	flag.Var(&config.CanvasType, "canvas", fmt.Sprintf("Canvas type. One of %v", config.CanvasType.Choices))
	flag.Var(&config.InputType, "input", fmt.Sprintf("Input type. One of %v", config.InputType.Choices))
	flag.StringVar(&config.X, "x", "", "x values (JSONPath expression)")
	flag.StringVar(&config.Y, "y", "", "y values (JSONPath expression)")
	flag.StringVar(&config.XY, "xy", "", "x,y value pairs (JSONPath expression). Overrides -x and -y if given.")
	flag.IntVar(&config.Box.Width, "width", 0, "Plot width (default 0 (auto))")
	flag.IntVar(&config.Box.Height, "height", 0, "Plot height (default 0 (auto))")
	flag.UintVar(&config.HistBins, "bins", 0, "Number of histogram bins (default 0 (auto))")
	flag.Parse()
	log.SetOutput(os.Stderr)
	log.SetFlags(log.LstdFlags | log.Lshortfile)

	var err error
	xPattern = jsonpath.New("x")
	xPattern.AllowMissingKeys(true)
	err = xPattern.Parse(fmt.Sprintf("{%s}", config.X))
	if err != nil {
		log.Fatal(err)
	}
	yPattern = jsonpath.New("y")
	yPattern.AllowMissingKeys(true)
	err = yPattern.Parse(fmt.Sprintf("{%s}", config.Y))
	if err != nil {
		log.Fatal(err)
	}
	if config.XY != "" || (config.X == "" && config.Y == "") {
		xyPattern = jsonpath.New("xy")
		xyPattern.AllowMissingKeys(true)
		err = xyPattern.Parse(fmt.Sprintf("{%s}", config.XY))
		if err != nil {
			log.Fatal(err)
		}
	}
	if config.Box.Width == 0 {
		config.Box.Width = terminal.Width()
	}
	if config.Box.Height == 0 {
		config.Box.Height = terminal.Height() - 1
	}
	if config.CanvasType.Value == canvasTypeAuto {
		config.CanvasType.Value = autoCanvas[config.PlotType.Value]
	}
}

func match(in interface{}, p *jsonpath.JSONPath) [][]reflect.Value {
	defer func() {
		if r := recover(); r != nil {
			log.Println("error evaluating JSONPath", p.String+":", r)
		}
	}()
	out, err := p.FindResults(in)
	if err != nil {
		log.Println(err)
	}
	return out
}

func main() {
	var in interface{}
	switch config.InputType.Value {
	case inputTypeJSON:
		dec := json.NewDecoder(os.Stdin)
		err := dec.Decode(&in)
		if err != nil {
			log.Println(inputTypeJSON, "input:", err)
		}
	case inputTypeCSV:
		r := csv.NewReader(os.Stdin)
		rows, err := r.ReadAll()
		if err != nil {
			log.Println(inputTypeCSV, "input:", err)
		}
		in = parseRows(rows)
	}
	var x, y []reflect.Value
	if xyPattern != nil {
		x, y = split(match(in, xyPattern))
	} else {
		x = flatten(match(in, xPattern))
		y = flatten(match(in, yPattern))
	}
	buffer := draw.NewBuffer(config.Box)
	var p draw.Pixels
	switch config.CanvasType.Value {
	case canvasTypeBraille:
		p = &draw.Braille{Buffer: buffer}
	case canvasTypeQuarter:
		p = &draw.Quarter{Buffer: buffer}
	case canvasTypeFull:
		p = &draw.Full{Buffer: buffer}
	case canvasTypeFullEscape, canvasTypeFullEscapeWB, canvasTypeFullEscapeBW:
		p = &draw.Full{Buffer: buffer}
	}
	p.Clear()
	c := draw.Canvas{Pixels: p}
	var out string
	switch config.PlotType.Value {
	case plotTypeLine:
		out = linePlot(x, y, c)
	case plotTypeScatter:
		out = scatterPlot(x, y, c)
	case plotTypeBar:
		out = barPlot(x, y, c)
	case plotTypeHist:
		out = histogram(x, c, config.HistBins)
	case plotTypeHist2D:
		out = hist2D(x, y, c, config.HistBins)
	}
	switch config.CanvasType.Value {
	case canvasTypeFullEscape:
		out = draw.FullEscape(out)
	case canvasTypeFullEscapeBW:
		out = draw.FullEscapeBW(out)
	case canvasTypeFullEscapeWB:
		out = draw.FullEscapeWB(out)
	}
	fmt.Println(out)
}