-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
436 lines (400 loc) · 9.42 KB
/
main.go
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
package goadapt
import (
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"runtime"
"strings"
"syscall"
"testing"
)
// Make shortcuts for common functions
var (
Spf = fmt.Sprintf
Fpf = fmt.Fprintf
)
// Allow redirecting stdio
var (
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
)
// SetStdio allows a caller to redirect stdin, stdout, and stderr.
func SetStdio(stdin io.Reader, stdout, stderr io.Writer) {
Stdin = stdin
Stdout = stdout
Stderr = stderr
}
// Pl is a shortcut for fmt.Println(), but it also allows a caller to redirect stdout
// by first setting goadapt.Stdout to the desired io.Writer.
func Pl(args ...interface{}) (n int, err error) {
if Stdout == nil {
return fmt.Println(args...)
} else {
return fmt.Fprintln(Stdout, args...)
}
}
// Pf is a shortcut for fmt.Printf(), but it also allows a caller to redirect stdout
// by first setting goadapt.Stdout to the desired io.Writer.
func Pf(format string, args ...interface{}) (n int, err error) {
if Stdout == nil {
return fmt.Printf(format, args...)
} else {
return fmt.Fprintf(Stdout, format, args...)
}
}
// XXX deprecate AdaptErr in favor of Wrap and stackTracer from https://pkg.go.dev/github.com/pkg/errors
type AdaptErr struct {
file string
line int
msg string
err error
}
func (e AdaptErr) Error() string {
var s []string
if len(e.file) > 0 {
s = append(s, fmt.Sprintf("%s:%d", e.file, e.line))
}
if len(e.msg) > 0 {
s = append(s, e.msg)
}
if e.err != nil {
s = append(s, fmt.Sprintf("%v", e.err))
}
return strings.Join(s, ": ")
}
// Msg uses UnWrap() to recurse through the err stack, concatenating
// all of the messages found in the stack and returning the result as
// a string. This function can be used instead of .Error() to get a
// shorter, cleaner message string that doesn't include file and line
// numbers.
func (e AdaptErr) Msg() string {
var parts []string
msg := e.msg
if len(msg) > 0 {
parts = append(parts, msg)
}
child := e.Unwrap()
if child != nil {
parts = append(parts, errMsg(child))
}
return strings.Join(parts, ": ")
}
func (e AdaptErr) Unwrap() error {
return e.err
}
type exitErr struct {
msg string
err error
}
func (e exitErr) Error() string {
var parts []string
msg := e.msg
if len(msg) > 0 {
parts = append(parts, msg)
}
child := e.Unwrap()
if child != nil {
parts = append(parts, errMsg(child))
}
return strings.Join(parts, ": ")
}
func (e exitErr) Unwrap() error {
return e.err
}
// errRc uses UnWrap() to iterate through the err stack looking for a
// syscall.Errno, and returns that as an int. Returns 1 if there is
// no syscall.Errno in the stack.
func errRc(err error) (rc int) {
rc = 1
e := err
for {
e = errors.Unwrap(e)
if e == nil {
return
}
errno, ok := e.(syscall.Errno)
if ok {
rc = int(errno)
return
}
}
}
// errNo uses UnWrap() to iterate through the err stack looking for a
// syscall.Errno, and returns that. Returns syscall.EPERM if there is
// no syscall.Errno in the stack.
func errNo(err error) (errno syscall.Errno) {
e := err
for {
e = errors.Unwrap(e)
if e == nil {
return
}
errno, ok := e.(syscall.Errno)
if ok {
return errno
} else {
errno = syscall.EPERM
}
}
}
// errMsg returns a short message describing all errs in stack,
// without filenames and line numbers if possible.
func errMsg(err error) (msg string) {
switch concrete := err.(type) {
case *AdaptErr:
msg = concrete.Msg()
default:
msg = concrete.Error()
}
return
}
/*
// this likely works; leaving this here in case we want it. in the
// meantime we can just use Ck()
func Raise(i int, args ...interface{}) {
err := fmt.Errorf("%w: malformed path: %s", syscall.Errno(i), args...)
if err != nil {
_, file, line, _ := runtime.Caller(1)
msg := formatArgs(args...)
e := AdaptErr{file, line, msg, err}
panic(&e)
}
}
*/
func Ck(err error, args ...interface{}) {
if err != nil {
_, file, line, _ := runtime.Caller(1)
msg := FormatArgs(args...)
e := AdaptErr{file, line, msg, err}
panic(&e)
}
}
func FormatArgs(args ...interface{}) (msg string) {
if len(args) == 1 {
msg = fmt.Sprintf("%v", args[0])
}
if len(args) > 1 {
msg = fmt.Sprintf(args[0].(string), args[1:]...)
}
return
}
/*
func errArgs(args ...interface{}) (err error) {
var stack []error
var format string
for i, arg := args {
e, ok := arg.(error)
if ok {
stack = append(stack, e)
continue
}
// first non-error arg is used as format string
if len(format) == 0 {
format = fmt.Sprintf("%v", arg)
continue
}
// remaining args are format values
e = fmt.Errorf(format, args[i:])
stack = append(stack, e)
break
}
// wrap in reverse order
for i := len(stack - 1); i >=0; i-- {
e = stack[i]
if err == nil {
err = e
} else {
err = fmt.Errorf("%w", err
}
}
}
*/
// Assert takes a bool and zero or more arguments. If the bool is
// true, then Assert returns. If the boolean is false, then Assert
// panics. The panic is of type AdaptErr. The AdaptErr contains the
// filename and line number of the caller. The first argument is used
// as a Sprintf() format string. Any remaining arguments are provided
// to the Sprintf() as values. The Sprintf() result is stored as
// AdaptErr.msg, to be used later in the AdaptErr.Error() string.
func Assert(cond bool, args ...interface{}) {
if !cond {
_, file, line, _ := runtime.Caller(1)
msg := "assertion failed"
m := FormatArgs(args...)
if len(m) > 0 {
msg += ": " + m
}
err := AdaptErr{file, line, msg, nil}
panic(&err)
}
}
// ErrnoIf takes a bool and zero or more arguments. If the bool is
// false, then ErrnoIf returns. If the boolean is true, then ErrnoIf
// panics. The panic is of type AdaptErr. The AdaptErr contains the
// filename and line number of the caller. The first argument must be
// of type syscall.Errno; the AdaptErr wraps the errno. The next
// argument is used as a Sprintf() format string. Any remaining
// arguments are provided to the Sprintf() as values. The Sprintf()
// result is stored as AdaptErr.msg, to be used later in the
// AdaptErr.Error() string.
func ErrnoIf(cond bool, errno syscall.Errno, args ...interface{}) {
if cond {
_, file, line, _ := runtime.Caller(1)
msg := FormatArgs(args...)
err := AdaptErr{file, line, msg, errno}
panic(&err)
}
}
// convert panic into returned err
// see https://github.com/lainio/err2 and https://blog.golang.org/go1.13-errors
func Return(err *error, args ...interface{}) {
r := recover()
if r == nil {
return
}
switch concrete := r.(type) {
case *AdaptErr:
msg := FormatArgs(args...)
*err = &AdaptErr{msg: msg, err: concrete}
case *exitErr:
msg := FormatArgs(args...)
e := &exitErr{msg: msg, err: concrete}
panic(e)
default:
// wasn't us -- re-raise
panic(r)
}
}
// convert panic into returned err on channel
func ReturnChan(errc chan error, args ...interface{}) {
r := recover()
if r == nil {
return
}
switch concrete := r.(type) {
case *AdaptErr:
msg := FormatArgs(args...)
err := AdaptErr{msg: msg, err: concrete}
errc <- err
case *exitErr:
msg := FormatArgs(args...)
e := &exitErr{msg: msg, err: concrete}
panic(e)
default:
// wasn't us -- re-raise
panic(r)
}
}
// convert panic into returned rc and msg
func Halt(rc *int, msg *string) {
r := recover()
if r == nil {
return
}
switch concrete := r.(type) {
case *AdaptErr:
*rc = errRc(concrete)
*msg = concrete.Error()
case *exitErr:
*rc = errRc(concrete)
*msg = errMsg(concrete)
default:
panic(r)
}
}
// Unpanic converts a panic into a syscall.Errno and a message.
func Unpanic(errno *syscall.Errno, logfunc func(msg string)) {
r := recover()
if r == nil {
return
}
var msg string
switch concrete := r.(type) {
case *syscall.Errno:
*errno = *concrete
case *AdaptErr:
*errno = errNo(concrete)
msg = concrete.Error()
default:
*errno = syscall.EPERM
msg = fmt.Sprintf("%v", concrete)
}
logfunc(msg)
}
func ExitIf(err, target error, args ...interface{}) {
if errors.Is(err, target) {
msg := FormatArgs(args...)
e := &exitErr{msg: msg, err: err}
panic(e)
}
}
func errStack(e error) (stack []error) {
stack = []error{e}
child := errors.Unwrap(e)
if child != nil {
stack = append(stack, errStack(child)...)
}
return
}
func Debug(msg interface{}, args ...interface{}) {
debug := os.Getenv("DEBUG")
if len(debug) == 0 {
return
}
_log(log.Printf, msg.(string), args...)
}
func Tassert(t *testing.T, cond bool, args ...interface{}) {
t.Helper() // cause file:line info to show caller
if !cond {
txt := FormatArgs(args...)
t.Fatal(txt)
}
}
func Info(msg interface{}, args ...interface{}) {
_log(log.Printf, msg.(string), args...)
}
func Uerr(msg interface{}, args ...interface{}) {
_log(log.Panicf, msg.(string), args...)
}
func _log(method func(string, ...interface{}), msg string, args ...interface{}) {
_, file, line, ok := runtime.Caller(2)
Assert(ok)
if len(args) > 0 {
if strings.Contains(msg, "%") {
msg = fmt.Sprintf(msg, args...)
} else {
for _, arg := range args {
msg += fmt.Sprintf(" %v", arg)
}
}
}
method("%s %d: %v", file, line, msg)
}
/*
func Debug(args ...interface{}) {
debug := os.Getenv("DEBUG")
if len(debug) == 0 {
return
}
_, file, line, _ := runtime.Caller(1)
msg := fmt.Sprintf("%s:%d", file, line)
m := formatArgs(args...)
if len(m) > 0 {
msg += ": " + m
}
fmt.Println(msg)
}
*/
func Pprint(in interface{}) {
Pl(Spprint(in))
}
func Spprint(in interface{}) string {
var buf []byte
buf, err := json.MarshalIndent(in, "", " ")
Ck(err)
return string(buf)
}