aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/robertkrimen/otto/dbg/dbg.go
blob: 8c27fa293ec881847f05820d2fc5eccb52e2845a (plain) (blame)
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
// This file was AUTOMATICALLY GENERATED by dbg-import (smuggol) from github.com/robertkrimen/dbg

/*
Package dbg is a println/printf/log-debugging utility library.

    import (
        Dbg "github.com/robertkrimen/dbg"
    )

    dbg, dbgf := Dbg.New()

    dbg("Emit some debug stuff", []byte{120, 121, 122, 122, 121}, math.Pi)
    # "2013/01/28 16:50:03 Emit some debug stuff [120 121 122 122 121] 3.141592653589793"

    dbgf("With a %s formatting %.2f", "little", math.Pi)
    # "2013/01/28 16:51:55 With a little formatting (3.14)"

    dbgf("%/fatal//A fatal debug statement: should not be here")
    # "A fatal debug statement: should not be here"
    # ...and then, os.Exit(1)

    dbgf("%/panic//Can also panic %s", "this")
    # "Can also panic this"
    # ...as a panic, equivalent to: panic("Can also panic this")

    dbgf("Any %s arguments without a corresponding %%", "extra", "are treated like arguments to dbg()")
    # "2013/01/28 17:14:40 Any extra arguments (without a corresponding %) are treated like arguments to dbg()"

    dbgf("%d %d", 1, 2, 3, 4, 5)
    # "2013/01/28 17:16:32 Another example: 1 2 3 4 5"

    dbgf("%@: Include the function name for a little context (via %s)", "%@")
    # "2013... github.com/robertkrimen/dbg.TestSynopsis: Include the function name for a little context (via %@)"

By default, dbg uses log (log.Println, log.Printf, log.Panic, etc.) for output.
However, you can also provide your own output destination by invoking dbg.New with
a customization function:

    import (
        "bytes"
        Dbg "github.com/robertkrimen/dbg"
        "os"
    )

    # dbg to os.Stderr
    dbg, dbgf := Dbg.New(func(dbgr *Dbgr) {
        dbgr.SetOutput(os.Stderr)
    })

    # A slightly contrived example:
    var buffer bytes.Buffer
    dbg, dbgf := New(func(dbgr *Dbgr) {
        dbgr.SetOutput(&buffer)
    })

*/
package dbg

import (
    "bytes"
    "fmt"
    "io"
    "log"
    "os"
    "regexp"
    "runtime"
    "strings"
    "unicode"
)

type _frmt struct {
    ctl          string
    format       string
    operandCount int
    panic        bool
    fatal        bool
    check        bool
}

var (
    ctlTest = regexp.MustCompile(`^\s*%/`)
    ctlScan = regexp.MustCompile(`%?/(panic|fatal|check)(?:\s|$)`)
)

func operandCount(format string) int {
    count := 0
    end := len(format)
    for at := 0; at < end; {
        for at < end && format[at] != '%' {
            at++
        }
        at++
        if at < end {
            if format[at] != '%' && format[at] != '@' {
                count++
            }
            at++
        }
    }
    return count
}

func parseFormat(format string) (frmt _frmt) {
    if ctlTest.MatchString(format) {
        format = strings.TrimLeftFunc(format, unicode.IsSpace)
        index := strings.Index(format, "//")
        if index != -1 {
            frmt.ctl = format[0:index]
            format = format[index+2:] // Skip the second slash via +2 (instead of +1)
        } else {
            frmt.ctl = format
            format = ""
        }
        for _, tmp := range ctlScan.FindAllStringSubmatch(frmt.ctl, -1) {
            for _, value := range tmp[1:] {
                switch value {
                case "panic":
                    frmt.panic = true
                case "fatal":
                    frmt.fatal = true
                case "check":
                    frmt.check = true
                }
            }
        }
    }
    frmt.format = format
    frmt.operandCount = operandCount(format)
    return
}

type Dbgr struct {
    emit _emit
}

type DbgFunction func(values ...interface{})

func NewDbgr() *Dbgr {
    self := &Dbgr{}
    return self
}

/*
New will create and return a pair of debugging functions. You can customize where
they output to by passing in an (optional) customization function:

    import (
        Dbg "github.com/robertkrimen/dbg"
        "os"
    )

    # dbg to os.Stderr
    dbg, dbgf := Dbg.New(func(dbgr *Dbgr) {
        dbgr.SetOutput(os.Stderr)
    })

*/
func New(options ...interface{}) (dbg DbgFunction, dbgf DbgFunction) {
    dbgr := NewDbgr()
    if len(options) > 0 {
        if fn, ok := options[0].(func(*Dbgr)); ok {
            fn(dbgr)
        }
    }
    return dbgr.DbgDbgf()
}

func (self Dbgr) Dbg(values ...interface{}) {
    self.getEmit().emit(_frmt{}, "", values...)
}

func (self Dbgr) Dbgf(values ...interface{}) {
    self.dbgf(values...)
}

func (self Dbgr) DbgDbgf() (dbg DbgFunction, dbgf DbgFunction) {
    dbg = func(vl ...interface{}) {
        self.Dbg(vl...)
    }
    dbgf = func(vl ...interface{}) {
        self.dbgf(vl...)
    }
    return dbg, dbgf // Redundant, but...
}

func (self Dbgr) dbgf(values ...interface{}) {

    var frmt _frmt
    if len(values) > 0 {
        tmp := fmt.Sprint(values[0])
        frmt = parseFormat(tmp)
        values = values[1:]
    }

    buffer_f := bytes.Buffer{}
    format := frmt.format
    end := len(format)
    for at := 0; at < end; {
        last := at
        for at < end && format[at] != '%' {
            at++
        }
        if at > last {
            buffer_f.WriteString(format[last:at])
        }
        if at >= end {
            break
        }
        // format[at] == '%'
        at++
        // format[at] == ?
        if format[at] == '@' {
            depth := 2
            pc, _, _, _ := runtime.Caller(depth)
            name := runtime.FuncForPC(pc).Name()
            buffer_f.WriteString(name)
        } else {
            buffer_f.WriteString(format[at-1 : at+1])
        }
        at++
    }

    //values_f := append([]interface{}{}, values[0:frmt.operandCount]...)
    values_f := values[0:frmt.operandCount]
    values_dbg := values[frmt.operandCount:]
    if len(values_dbg) > 0 {
        // Adjust frmt.format:
        // (%v instead of %s because: frmt.check)
        {
            tmp := format
            if len(tmp) > 0 {
                if unicode.IsSpace(rune(tmp[len(tmp)-1])) {
                    buffer_f.WriteString("%v")
                } else {
                    buffer_f.WriteString(" %v")
                }
            } else if frmt.check {
                // Performing a check, so no output
            } else {
                buffer_f.WriteString("%v")
            }
        }

        // Adjust values_f:
        if !frmt.check {
            tmp := []string{}
            for _, value := range values_dbg {
                tmp = append(tmp, fmt.Sprintf("%v", value))
            }
            // First, make a copy of values_f, so we avoid overwriting values_dbg when appending
            values_f = append([]interface{}{}, values_f...)
            values_f = append(values_f, strings.Join(tmp, " "))
        }
    }

    format = buffer_f.String()
    if frmt.check {
        // We do not actually emit to the log, but panic if
        // a non-nil value is detected (e.g. a non-nil error)
        for _, value := range values_dbg {
            if value != nil {
                if format == "" {
                    panic(value)
                } else {
                    panic(fmt.Sprintf(format, append(values_f, value)...))
                }
            }
        }
    } else {
        self.getEmit().emit(frmt, format, values_f...)
    }
}

// Idiot-proof &Dbgr{}, etc.
func (self *Dbgr) getEmit() _emit {
    if self.emit == nil {
        self.emit = standardEmit()
    }
    return self.emit
}

// SetOutput will accept the following as a destination for output:
//
//      *log.Logger         Print*/Panic*/Fatal* of the logger
//      io.Writer           -
//      nil                 Reset to the default output (os.Stderr)
//      "log"               Print*/Panic*/Fatal* via the "log" package
//
func (self *Dbgr) SetOutput(output interface{}) {
    if output == nil {
        self.emit = standardEmit()
        return
    }
    switch output := output.(type) {
    case *log.Logger:
        self.emit = _emitLogger{
            logger: output,
        }
        return
    case io.Writer:
        self.emit = _emitWriter{
            writer: output,
        }
        return
    case string:
        if output == "log" {
            self.emit = _emitLog{}
            return
        }
    }
    panic(output)
}

// ======== //
// = emit = //
// ======== //

func standardEmit() _emit {
    return _emitWriter{
        writer: os.Stderr,
    }
}

func ln(tmp string) string {
    length := len(tmp)
    if length > 0 && tmp[length-1] != '\n' {
        return tmp + "\n"
    }
    return tmp
}

type _emit interface {
    emit(_frmt, string, ...interface{})
}

type _emitWriter struct {
    writer io.Writer
}

func (self _emitWriter) emit(frmt _frmt, format string, values ...interface{}) {
    if format == "" {
        fmt.Fprintln(self.writer, values...)
    } else {
        if frmt.panic {
            panic(fmt.Sprintf(format, values...))
        }
        fmt.Fprintf(self.writer, ln(format), values...)
        if frmt.fatal {
            os.Exit(1)
        }
    }
}

type _emitLogger struct {
    logger *log.Logger
}

func (self _emitLogger) emit(frmt _frmt, format string, values ...interface{}) {
    if format == "" {
        self.logger.Println(values...)
    } else {
        if frmt.panic {
            self.logger.Panicf(format, values...)
        } else if frmt.fatal {
            self.logger.Fatalf(format, values...)
        } else {
            self.logger.Printf(format, values...)
        }
    }
}

type _emitLog struct {
}

func (self _emitLog) emit(frmt _frmt, format string, values ...interface{}) {
    if format == "" {
        log.Println(values...)
    } else {
        if frmt.panic {
            log.Panicf(format, values...)
        } else if frmt.fatal {
            log.Fatalf(format, values...)
        } else {
            log.Printf(format, values...)
        }
    }
}