~ecs/hq

ref: 05e89aaebceb0242aaa43c75277e0b2cc05a11a0 hq/main.go -rw-r--r-- 3.9 KiB
05e89aaeEmber Sawady Improve multi error handling 4 months ago
                                                                                
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
package main

//go:generate goyacc -o parse.go parse.y

import (
	"errors"
	"fmt"
	"os"
	"reflect"
	"sync"
	"unsafe"

	"github.com/google/shlex"
	"golang.org/x/net/html"
)

// A Datum is a message passed through an hq pipeline. Invariant: all but one of
// the elements must be nil
type Datum struct {
	HTML *html.Node
	Text *string
	End  bool
}

// A Filter performs a permutation on a stream of `Datum`s
type Filter interface {
	Execute(args []string, ch []<-chan Datum, out chan Datum) error
}

// Filters is the list of built-in filters
var Filters map[string]Filter = make(map[string]Filter)

// Select returns the first channel which sends a value, along with the value
// sent and whether or not the channel is closed
func Select(chs []<-chan Datum) (<-chan Datum, *Datum) {
	var (
		cases []reflect.SelectCase
		d     Datum
	)
	for _, ch := range chs {
		cases = append(cases, reflect.SelectCase{
			Dir:  reflect.SelectRecv,
			Chan: reflect.ValueOf(ch),
		})
	}
	chosen, v, ok := reflect.Select(cases)
	if !ok {
		return nil, nil
	}
	d.HTML = (*html.Node)(unsafe.Pointer(v.Field(0).Pointer()))
	d.Text = (*string)(unsafe.Pointer(v.Field(1).Pointer()))
	d.End = v.Field(2).Bool()
	return chs[chosen], &d
}

// Exec executes an expression
func Exec(e Expr, ins []<-chan Datum, out chan Datum) error {
	if e.Pipe != nil {
		mid := make(chan Datum)
		errs := make(chan error)
		defer close(errs)
		go func() {
			errs <- Exec(e.Pipe.First, ins, mid)
		}()
		go func() {
			errs <- Exec(e.Pipe.Second, []<-chan Datum{mid}, out)
		}()
		if err := <-errs; err != nil {
			for range mid {
			}
			<-errs
			return err
		}
		return <-errs
	}
	if e.Multi != nil {
		var chs []chan Datum
		var mids []chan Datum
		errs := make(chan error)
		defer close(errs)
		for _, exp := range e.Multi.Cmds {
			chs = append(chs, make(chan Datum))
			mids = append(mids, make(chan Datum))
			go func(exp Expr, in <-chan Datum, out chan Datum) {
				errs <- Exec(exp, []<-chan Datum{in}, out)
			}(exp, chs[len(chs)-1], mids[len(mids)-1])
		}
		go func() {
			var wg sync.WaitGroup
			for _, d := Select(ins); d != nil; _, d = Select(ins) {
				for _, ch := range chs {
					wg.Add(1)
					go func(ch chan Datum, d *Datum) {
						ch <- *d
						wg.Done()
					}(ch, d)
				}
			}
			wg.Wait()
			for _, ch := range chs {
				close(ch)
			}
		}()
		go func() {
			// Go's type system is fucking dumb
			var ins []<-chan Datum
			for _, mid := range mids {
				ins = append(ins, mid)
			}
			err := Exec(e.Multi.Out, ins, out)
			for ch, d := Select(ins); true; ch, d = Select(ins) {
				if d != nil && !d.End {
					continue
				}
				for i, c := range ins {
					if c == ch {
						ins = append(ins[:i], ins[i+1:]...)
					}
				}
				if len(ins) == 0 {
					break
				}
			}
			errs <- err
		}()
		err := <-errs
		for range e.Multi.Cmds {
			if e := <-errs; e != nil {
				err = e
			}
		}
		return err
	}
	if len(e.Cmd) == 0 {
		close(out)
		return errors.New("no filter")
	}
	if filter, ok := Filters[e.Cmd[0]]; ok {
		return filter.Execute(e.Cmd, ins, out)
	}
	close(out)
	return errors.New(e.Cmd[0] + ": not found")
}

func main() {
	if len(os.Args) != 2 {
		fmt.Fprintln(os.Stderr, "usage: "+os.Args[0]+" <filter>")
		os.Exit(1)
	}

	cmd, err := shlex.Split(os.Args[1])
	if err != nil {
		fmt.Fprintln(os.Stderr, "shlex:", err)
		os.Exit(1)
	}

	yyParse(&yyLex{Toks: cmd, Err: os.Stderr})

	root, err := html.Parse(os.Stdin)
	if err != nil {
		fmt.Fprintln(os.Stderr, "parse:", err)
		os.Exit(1)
	}

	in := make(chan Datum)
	out := make(chan Datum)
	errs := make(chan error)

	go func() {
		errs <- Exec(Exp, []<-chan Datum{in}, out)
	}()
	go func() {
		in <- Datum{HTML: root}
		close(in)
	}()

	go func() {
		for d := range out {
			if d.HTML != nil {
				html.Render(os.Stdout, d.HTML)
				fmt.Println("")
			}
			if d.Text != nil {
				fmt.Println(*d.Text)
			}
		}
	}()
	if err := <-errs; err != nil {
		fmt.Fprintln(os.Stderr, "exec:", err)
		os.Exit(1)
	}
}