mirror of https://github.com/schollz/croc.git
Vendoring
This commit is contained in:
parent
c3956b059e
commit
0b9eaa1e1e
|
@ -0,0 +1,63 @@
|
|||
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
|
||||
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/gosuri/uilive"
|
||||
packages = ["."]
|
||||
revision = "ac356e6e42cd31fcef8e6aec13ae9ed6fe87713e"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/gosuri/uiprogress"
|
||||
packages = [".","util/strutil"]
|
||||
revision = "d0567a9d84a1c40dd7568115ea66f4887bf57b33"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/mattn/go-isatty"
|
||||
packages = ["."]
|
||||
revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39"
|
||||
version = "v0.0.3"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/pkg/errors"
|
||||
packages = ["."]
|
||||
revision = "645ef00459ed84a119197bfb8d8205042c6df63d"
|
||||
version = "v0.8.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "github.com/schollz/mnemonicode"
|
||||
packages = ["."]
|
||||
revision = "15c9654387fad6d257aa28f9be57b9f124101955"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/sirupsen/logrus"
|
||||
packages = ["."]
|
||||
revision = "f006c2ac4710855cf0f916dd6b77acf6b048dc6e"
|
||||
version = "v1.0.3"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/crypto"
|
||||
packages = ["ssh/terminal"]
|
||||
revision = "9419663f5a44be8b34ca85f08abc5fe1be11f8a3"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/sys"
|
||||
packages = ["unix","windows"]
|
||||
revision = "8dbc5d05d6edcc104950cc299a1ce6641235bc86"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/text"
|
||||
packages = ["transform"]
|
||||
revision = "c01e4764d870b77f8abe5096ee19ad20d80e8075"
|
||||
|
||||
[solve-meta]
|
||||
analyzer-name = "dep"
|
||||
analyzer-version = 1
|
||||
inputs-digest = "b5f57442f43856cf17500cec2a357c4ea34e5f9eae4298954f62765111b0d5a9"
|
||||
solver-name = "gps-cdcl"
|
||||
solver-version = 1
|
|
@ -0,0 +1,38 @@
|
|||
|
||||
# Gopkg.toml example
|
||||
#
|
||||
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
|
||||
# for detailed Gopkg.toml documentation.
|
||||
#
|
||||
# required = ["github.com/user/thing/cmd/thing"]
|
||||
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
|
||||
#
|
||||
# [[constraint]]
|
||||
# name = "github.com/user/project"
|
||||
# version = "1.0.0"
|
||||
#
|
||||
# [[constraint]]
|
||||
# name = "github.com/user/project2"
|
||||
# branch = "dev"
|
||||
# source = "github.com/myfork/project2"
|
||||
#
|
||||
# [[override]]
|
||||
# name = "github.com/x/y"
|
||||
# version = "2.4.0"
|
||||
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/gosuri/uiprogress"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/pkg/errors"
|
||||
version = "0.8.0"
|
||||
|
||||
[[constraint]]
|
||||
branch = "master"
|
||||
name = "github.com/schollz/mnemonicode"
|
||||
|
||||
[[constraint]]
|
||||
name = "github.com/sirupsen/logrus"
|
||||
version = "1.0.3"
|
19
main.go
19
main.go
|
@ -1,6 +1,7 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
|
@ -24,7 +25,6 @@ func main() {
|
|||
flag.StringVar(&serverAddress, "server", "", "(run as client) server address to connect to")
|
||||
flag.StringVar(&fileName, "file", "", "(run as server) file to serve")
|
||||
flag.StringVar(&codePhraseFlag, "code", "", "(run as server) file to serve")
|
||||
flag.StringVar(&connectionTypeFlag, "type", "", "(run as server) file to serve")
|
||||
flag.Parse()
|
||||
// Check build flags too, which take precedent
|
||||
if server != "" {
|
||||
|
@ -40,6 +40,16 @@ func main() {
|
|||
log.Fatal(err)
|
||||
return
|
||||
}
|
||||
connectionTypeFlag = "s" // sender
|
||||
if len(codePhraseFlag) == 0 {
|
||||
codePhraseFlag = GetRandomName()
|
||||
getInput("Your code phrase is '" + GetRandomName() + "' (press okay)")
|
||||
}
|
||||
} else {
|
||||
connectionTypeFlag = "r" //receiver
|
||||
if len(codePhraseFlag) == 0 {
|
||||
codePhraseFlag = getInput("What is your code phrase? ")
|
||||
}
|
||||
}
|
||||
|
||||
log.SetFormatter(&log.TextFormatter{})
|
||||
|
@ -57,3 +67,10 @@ func main() {
|
|||
fmt.Println("You must specify either -file (for running as a server) or -server (for running as a client)")
|
||||
}
|
||||
}
|
||||
|
||||
func getInput(prompt string) string {
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
fmt.Print(prompt)
|
||||
text, _ := reader.ReadString('\n')
|
||||
return text
|
||||
}
|
||||
|
|
|
@ -0,0 +1,22 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"math/rand"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/schollz/mnemonicode"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rand.Seed(time.Now().UTC().UnixNano())
|
||||
}
|
||||
|
||||
func GetRandomName() string {
|
||||
result := []string{}
|
||||
bs := make([]byte, 4)
|
||||
binary.LittleEndian.PutUint32(bs, rand.Uint32())
|
||||
result = mnemonicode.EncodeWordList(result, bs)
|
||||
return strings.Join(result, "-")
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
language: go
|
||||
sudo: false
|
||||
install:
|
||||
- go get ./...
|
||||
go:
|
||||
- 1.4
|
||||
- tip
|
|
@ -0,0 +1,10 @@
|
|||
MIT License
|
||||
===========
|
||||
|
||||
Copyright (c) 2015, Greg Osuri
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@ -0,0 +1,31 @@
|
|||
# uilive [![GoDoc](https://godoc.org/github.com/gosuri/uilive?status.svg)](https://godoc.org/github.com/gosuri/uilive) [![Build Status](https://travis-ci.org/gosuri/uilive.svg?branch=master)](https://travis-ci.org/gosuri/uilive)
|
||||
|
||||
uilive is a go library for updating terminal output in realtime. It provides a buffered [io.Writer](https://golang.org/pkg/io/#Writer) that is flushed at a timed interval. uilive powers [uiprogress](https://github.com/gosuri/uiprogress).
|
||||
|
||||
## Usage Example
|
||||
|
||||
Calling `uilive.New()` will create a new writer. To start rendering, simply call `writer.Start()` and update the ui by writing to the `writer`. Full source for the below example is in [example/main.go](example/main.go).
|
||||
|
||||
```go
|
||||
writer := uilive.New()
|
||||
// start listening for updates and render
|
||||
writer.Start()
|
||||
|
||||
for i := 0; i <= 100; i++ {
|
||||
fmt.Fprintf(writer, "Downloading.. (%d/%d) GB\n", i, 100)
|
||||
time.Sleep(time.Millisecond * 5)
|
||||
}
|
||||
|
||||
fmt.Fprintln(writer, "Finished: Downloaded 100GB")
|
||||
writer.Stop() // flush and stop rendering
|
||||
```
|
||||
|
||||
The above will render
|
||||
|
||||
![example](doc/example.gif)
|
||||
|
||||
## Installation
|
||||
|
||||
```sh
|
||||
$ go get -v github.com/gosuri/uilive
|
||||
```
|
|
@ -0,0 +1,2 @@
|
|||
// Package uilive provides a writer that live updates the terminal. It provides a buffered io.Writer that is flushed at a timed interval.
|
||||
package uilive
|
Binary file not shown.
After Width: | Height: | Size: 156 KiB |
|
@ -0,0 +1,26 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/gosuri/uilive"
|
||||
)
|
||||
|
||||
func main() {
|
||||
writer := uilive.New()
|
||||
|
||||
// start listening for updates and render
|
||||
writer.Start()
|
||||
|
||||
for _, f := range []string{"Foo.zip", "Bar.iso"} {
|
||||
for i := 0; i <= 50; i++ {
|
||||
fmt.Fprintf(writer, "Downloading %s.. (%d/%d) GB\n", f, i, 50)
|
||||
time.Sleep(time.Millisecond * 25)
|
||||
}
|
||||
fmt.Fprintf(writer.Bypass(), "Downloaded %s\n", f)
|
||||
}
|
||||
|
||||
fmt.Fprintln(writer, "Finished: Downloaded 100GB")
|
||||
writer.Stop() // flush and stop rendering
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package uilive_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/gosuri/uilive"
|
||||
)
|
||||
|
||||
func Example() {
|
||||
writer := uilive.New()
|
||||
|
||||
// start listening to updates and render
|
||||
writer.Start()
|
||||
|
||||
for i := 0; i <= 100; i++ {
|
||||
fmt.Fprintf(writer, "Downloading.. (%d/%d) GB\n", i, 100)
|
||||
time.Sleep(time.Millisecond * 5)
|
||||
}
|
||||
|
||||
fmt.Fprintln(writer, "Finished: Downloaded 100GB")
|
||||
writer.Stop() // flush and stop rendering
|
||||
}
|
|
@ -0,0 +1,138 @@
|
|||
package uilive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ESC is the ASCII code for escape character
|
||||
const ESC = 27
|
||||
|
||||
// RefreshInterval is the default refresh interval to update the ui
|
||||
var RefreshInterval = time.Millisecond
|
||||
|
||||
// Out is the default output writer for the Writer
|
||||
var Out = os.Stdout
|
||||
|
||||
// ErrClosedPipe is the error returned when trying to writer is not listening
|
||||
var ErrClosedPipe = errors.New("uilive: read/write on closed pipe")
|
||||
|
||||
// FdWriter is a writer with a file descriptor.
|
||||
type FdWriter interface {
|
||||
io.Writer
|
||||
Fd() uintptr
|
||||
}
|
||||
|
||||
// Writer is a buffered the writer that updates the terminal. The contents of writer will be flushed on a timed interval or when Flush is called.
|
||||
type Writer struct {
|
||||
// Out is the writer to write to
|
||||
Out io.Writer
|
||||
|
||||
// RefreshInterval is the time the UI sould refresh
|
||||
RefreshInterval time.Duration
|
||||
|
||||
ticker *time.Ticker
|
||||
tdone chan bool
|
||||
|
||||
buf bytes.Buffer
|
||||
mtx *sync.Mutex
|
||||
lineCount int
|
||||
}
|
||||
|
||||
type bypass struct {
|
||||
writer *Writer
|
||||
}
|
||||
|
||||
// New returns a new Writer with defaults
|
||||
func New() *Writer {
|
||||
return &Writer{
|
||||
Out: Out,
|
||||
RefreshInterval: RefreshInterval,
|
||||
|
||||
mtx: &sync.Mutex{},
|
||||
}
|
||||
}
|
||||
|
||||
// Flush writes to the out and resets the buffer. It should be called after the last call to Write to ensure that any data buffered in the Writer is written to output.
|
||||
// Any incomplete escape sequence at the end is considered complete for formatting purposes.
|
||||
// An error is returned if the contents of the buffer cannot be written to the underlying output stream
|
||||
func (w *Writer) Flush() error {
|
||||
w.mtx.Lock()
|
||||
defer w.mtx.Unlock()
|
||||
|
||||
// do nothing is buffer is empty
|
||||
if len(w.buf.Bytes()) == 0 {
|
||||
return nil
|
||||
}
|
||||
w.clearLines()
|
||||
|
||||
lines := 0
|
||||
for _, b := range w.buf.Bytes() {
|
||||
if b == '\n' {
|
||||
lines++
|
||||
}
|
||||
}
|
||||
w.lineCount = lines
|
||||
_, err := w.Out.Write(w.buf.Bytes())
|
||||
w.buf.Reset()
|
||||
return err
|
||||
}
|
||||
|
||||
// Start starts the listener in a non-blocking manner
|
||||
func (w *Writer) Start() {
|
||||
if w.ticker == nil {
|
||||
w.ticker = time.NewTicker(w.RefreshInterval)
|
||||
w.tdone = make(chan bool, 1)
|
||||
}
|
||||
|
||||
go w.Listen()
|
||||
}
|
||||
|
||||
// Stop stops the listener that updates the terminal
|
||||
func (w *Writer) Stop() {
|
||||
w.Flush()
|
||||
close(w.tdone)
|
||||
}
|
||||
|
||||
// Listen listens for updates to the writer's buffer and flushes to the out provided. It blocks the runtime.
|
||||
func (w *Writer) Listen() {
|
||||
for {
|
||||
select {
|
||||
case <-w.ticker.C:
|
||||
if w.ticker != nil {
|
||||
w.Flush()
|
||||
}
|
||||
case <-w.tdone:
|
||||
w.mtx.Lock()
|
||||
w.ticker.Stop()
|
||||
w.ticker = nil
|
||||
w.mtx.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Write save the contents of b to its buffers. The only errors returned are ones encountered while writing to the underlying buffer.
|
||||
func (w *Writer) Write(b []byte) (n int, err error) {
|
||||
w.mtx.Lock()
|
||||
defer w.mtx.Unlock()
|
||||
return w.buf.Write(b)
|
||||
}
|
||||
|
||||
// Bypass creates an io.Writer which allows non-buffered output to be written to the underlying output
|
||||
func (w *Writer) Bypass() io.Writer {
|
||||
return &bypass{writer: w}
|
||||
}
|
||||
|
||||
func (b *bypass) Write(p []byte) (n int, err error) {
|
||||
b.writer.mtx.Lock()
|
||||
defer b.writer.mtx.Unlock()
|
||||
|
||||
b.writer.clearLines()
|
||||
b.writer.lineCount = 0
|
||||
return b.writer.Out.Write(p)
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
// +build !windows
|
||||
|
||||
package uilive
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func (w *Writer) clearLines() {
|
||||
for i := 0; i < w.lineCount; i++ {
|
||||
fmt.Fprintf(w.Out, "%c[2K", ESC) // clear the line
|
||||
fmt.Fprintf(w.Out, "%c[%dA", ESC, 1) // move the cursor up
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package uilive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWriter(t *testing.T) {
|
||||
w := New()
|
||||
b := &bytes.Buffer{}
|
||||
w.Out = b
|
||||
w.Start()
|
||||
for i := 0; i < 2; i++ {
|
||||
fmt.Fprintln(w, "foo")
|
||||
}
|
||||
w.Stop()
|
||||
fmt.Fprintln(b, "bar")
|
||||
|
||||
want := "foo\nfoo\nbar\n"
|
||||
if b.String() != want {
|
||||
t.Fatalf("want %q, got %q", want, b.String())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,74 @@
|
|||
// +build windows
|
||||
|
||||
package uilive
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/mattn/go-isatty"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var kernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
|
||||
var (
|
||||
procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo")
|
||||
procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition")
|
||||
procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW")
|
||||
procFillConsoleOutputAttribute = kernel32.NewProc("FillConsoleOutputAttribute")
|
||||
)
|
||||
|
||||
type short int16
|
||||
type dword uint32
|
||||
type word uint16
|
||||
|
||||
type coord struct {
|
||||
x short
|
||||
y short
|
||||
}
|
||||
|
||||
type smallRect struct {
|
||||
left short
|
||||
top short
|
||||
right short
|
||||
bottom short
|
||||
}
|
||||
|
||||
type consoleScreenBufferInfo struct {
|
||||
size coord
|
||||
cursorPosition coord
|
||||
attributes word
|
||||
window smallRect
|
||||
maximumWindowSize coord
|
||||
}
|
||||
|
||||
func (w *Writer) clearLines() {
|
||||
f, ok := w.Out.(FdWriter)
|
||||
if ok && !isatty.IsTerminal(f.Fd()) {
|
||||
ok = false
|
||||
}
|
||||
if !ok {
|
||||
for i := 0; i < w.lineCount; i++ {
|
||||
fmt.Fprintf(w.Out, "%c[%dA", ESC, 0) // move the cursor up
|
||||
fmt.Fprintf(w.Out, "%c[2K\r", ESC) // clear the line
|
||||
}
|
||||
return
|
||||
}
|
||||
fd := f.Fd()
|
||||
var csbi consoleScreenBufferInfo
|
||||
procGetConsoleScreenBufferInfo.Call(fd, uintptr(unsafe.Pointer(&csbi)))
|
||||
|
||||
for i := 0; i < w.lineCount; i++ {
|
||||
// move the cursor up
|
||||
csbi.cursorPosition.y--
|
||||
procSetConsoleCursorPosition.Call(fd, uintptr(*(*int32)(unsafe.Pointer(&csbi.cursorPosition))))
|
||||
// clear the line
|
||||
cursor := coord{
|
||||
x: csbi.window.left,
|
||||
y: csbi.window.top + csbi.cursorPosition.y,
|
||||
}
|
||||
var count, w dword
|
||||
count = dword(csbi.size.x)
|
||||
procFillConsoleOutputCharacter.Call(fd, uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&w)))
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
language: go
|
||||
sudo: false
|
||||
install:
|
||||
- go get ./...
|
||||
go:
|
||||
- 1.4
|
||||
- tip
|
|
@ -0,0 +1,10 @@
|
|||
MIT License
|
||||
===========
|
||||
|
||||
Copyright (c) 2015, Greg Osuri
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@ -0,0 +1,11 @@
|
|||
test:
|
||||
@go test -race .
|
||||
@go test -race ./util/strutil
|
||||
|
||||
examples:
|
||||
go run -race example/full/full.go
|
||||
go run -race example/incr/incr.go
|
||||
go run -race example/multi/multi.go
|
||||
go run -race example/simple/simple.go
|
||||
|
||||
.PHONY: test examples
|
|
@ -0,0 +1,146 @@
|
|||
# uiprogress [![GoDoc](https://godoc.org/github.com/gosuri/uiprogress?status.svg)](https://godoc.org/github.com/gosuri/uiprogress) [![Build Status](https://travis-ci.org/gosuri/uiprogress.svg?branch=master)](https://travis-ci.org/gosuri/uiprogress)
|
||||
|
||||
A Go library to render progress bars in terminal applications. It provides a set of flexible features with a customizable API.
|
||||
|
||||
![example](doc/example_full.gif)
|
||||
|
||||
Progress bars improve readability for terminal applications with long outputs by providing a concise feedback loop.
|
||||
|
||||
## Features
|
||||
|
||||
* __Multiple Bars__: uiprogress can render multiple progress bars that can be tracked concurrently
|
||||
* __Dynamic Addition__: Add additional progress bars any time, even after the progress tracking has started
|
||||
* __Prepend and Append Functions__: Append or prepend completion percent and time elapsed to the progress bars
|
||||
* __Custom Decorator Functions__: Add custom functions around the bar along with helper functions
|
||||
|
||||
## Usage
|
||||
|
||||
To start listening for progress bars, call `uiprogress.Start()` and add a progress bar using `uiprogress.AddBar(total int)`. Update the progress using `bar.Incr()` or `bar.Set(n int)`. Full source code for the below example is available at [example/simple/simple.go](example/simple/simple.go)
|
||||
|
||||
```go
|
||||
uiprogress.Start() // start rendering
|
||||
bar := uiprogress.AddBar(100) // Add a new bar
|
||||
|
||||
// optionally, append and prepend completion and elapsed time
|
||||
bar.AppendCompleted()
|
||||
bar.PrependElapsed()
|
||||
|
||||
for bar.Incr() {
|
||||
time.Sleep(time.Millisecond * 20)
|
||||
}
|
||||
```
|
||||
|
||||
This will render the below in the terminal
|
||||
|
||||
![example](doc/example_simple.gif)
|
||||
|
||||
### Using Custom Decorators
|
||||
|
||||
You can also add a custom decorator function in addition to default `bar.AppendCompleted()` and `bar.PrependElapsed()` decorators. The below example tracks the current step for an application deploy progress. Source code for the below example is available at [example/full/full.go](example/full/full.go)
|
||||
|
||||
```go
|
||||
var steps = []string{"downloading source", "installing deps", "compiling", "packaging", "seeding database", "deploying", "staring servers"}
|
||||
bar := uiprogress.AddBar(len(steps))
|
||||
|
||||
// prepend the current step to the bar
|
||||
bar.PrependFunc(func(b *uiprogress.Bar) string {
|
||||
return "app: " + steps[b.Current()-1]
|
||||
})
|
||||
|
||||
for bar.Incr() {
|
||||
time.Sleep(time.Millisecond * 10)
|
||||
}
|
||||
```
|
||||
|
||||
### Rendering Multiple bars
|
||||
|
||||
You can add multiple bars using `uiprogress.AddBar(n)`. The below example demonstrates updating multiple bars concurrently and adding a new bar later in the pipeline. Source for this example is available at [example/multi/multi.go](example/multi/multi.go)
|
||||
|
||||
```go
|
||||
waitTime := time.Millisecond * 100
|
||||
uiprogress.Start()
|
||||
|
||||
// start the progress bars in go routines
|
||||
var wg sync.WaitGroup
|
||||
|
||||
bar1 := uiprogress.AddBar(20).AppendCompleted().PrependElapsed()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for bar1.Incr() {
|
||||
time.Sleep(waitTime)
|
||||
}
|
||||
}()
|
||||
|
||||
bar2 := uiprogress.AddBar(40).AppendCompleted().PrependElapsed()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for bar2.Incr() {
|
||||
time.Sleep(waitTime)
|
||||
}
|
||||
}()
|
||||
|
||||
time.Sleep(time.Second)
|
||||
bar3 := uiprogress.AddBar(20).PrependElapsed().AppendCompleted()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 1; i <= bar3.Total; i++ {
|
||||
bar3.Set(i)
|
||||
time.Sleep(waitTime)
|
||||
}
|
||||
}()
|
||||
|
||||
// wait for all the go routines to finish
|
||||
wg.Wait()
|
||||
```
|
||||
|
||||
This will produce
|
||||
|
||||
![example](doc/example_multi.gif)
|
||||
|
||||
### `Incr` counter
|
||||
|
||||
[Bar.Incr()](https://godoc.org/github.com/gosuri/uiprogress#Bar.Incr) is an atomic counter and can be used as a general tracker, making it ideal for tracking progress of work fanned out to a lots of go routines. The source code for the below example is available at [example/incr/incr.go](example/incr/incr.go)
|
||||
|
||||
```go
|
||||
runtime.GOMAXPROCS(runtime.NumCPU()) // use all available cpu cores
|
||||
|
||||
// create a new bar and prepend the task progress to the bar and fanout into 1k go routines
|
||||
count := 1000
|
||||
bar := uiprogress.AddBar(count).AppendCompleted().PrependElapsed()
|
||||
bar.PrependFunc(func(b *uiprogress.Bar) string {
|
||||
return fmt.Sprintf("Task (%d/%d)", b.Current(), count)
|
||||
})
|
||||
|
||||
uiprogress.Start()
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// fanout into go routines
|
||||
for i := 0; i < count; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
time.Sleep(time.Millisecond * time.Duration(rand.Intn(500)))
|
||||
bar.Incr()
|
||||
}()
|
||||
}
|
||||
time.Sleep(time.Second) // wait for a second for all the go routines to finish
|
||||
wg.Wait()
|
||||
uiprogress.Stop()
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
```sh
|
||||
$ go get -v github.com/gosuri/uiprogress
|
||||
```
|
||||
## Todos
|
||||
|
||||
- [ ] Resize bars and decorators by auto detecting window's dimensions
|
||||
- [ ] Handle more progress bars than vertical screen allows
|
||||
|
||||
## License
|
||||
|
||||
uiprogress is released under the MIT License. See [LICENSE](https://github.com/gosuri/uiprogress/blob/master/LICENSE).
|
|
@ -0,0 +1,237 @@
|
|||
package uiprogress
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gosuri/uiprogress/util/strutil"
|
||||
)
|
||||
|
||||
var (
|
||||
// Fill is the default character representing completed progress
|
||||
Fill byte = '='
|
||||
|
||||
// Head is the default character that moves when progress is updated
|
||||
Head byte = '>'
|
||||
|
||||
// Empty is the default character that represents the empty progress
|
||||
Empty byte = '-'
|
||||
|
||||
// LeftEnd is the default character in the left most part of the progress indicator
|
||||
LeftEnd byte = '['
|
||||
|
||||
// RightEnd is the default character in the right most part of the progress indicator
|
||||
RightEnd byte = ']'
|
||||
|
||||
// Width is the default width of the progress bar
|
||||
Width = 70
|
||||
|
||||
// ErrMaxCurrentReached is error when trying to set current value that exceeds the total value
|
||||
ErrMaxCurrentReached = errors.New("errors: current value is greater total value")
|
||||
)
|
||||
|
||||
// Bar represents a progress bar
|
||||
type Bar struct {
|
||||
// Total of the total for the progress bar
|
||||
Total int
|
||||
|
||||
// LeftEnd is character in the left most part of the progress indicator. Defaults to '['
|
||||
LeftEnd byte
|
||||
|
||||
// RightEnd is character in the right most part of the progress indicator. Defaults to ']'
|
||||
RightEnd byte
|
||||
|
||||
// Fill is the character representing completed progress. Defaults to '='
|
||||
Fill byte
|
||||
|
||||
// Head is the character that moves when progress is updated. Defaults to '>'
|
||||
Head byte
|
||||
|
||||
// Empty is the character that represents the empty progress. Default is '-'
|
||||
Empty byte
|
||||
|
||||
// TimeStated is time progress began
|
||||
TimeStarted time.Time
|
||||
|
||||
// Width is the width of the progress bar
|
||||
Width int
|
||||
|
||||
// timeElased is the time elapsed for the progress
|
||||
timeElapsed time.Duration
|
||||
current int
|
||||
|
||||
mtx *sync.RWMutex
|
||||
|
||||
appendFuncs []DecoratorFunc
|
||||
prependFuncs []DecoratorFunc
|
||||
}
|
||||
|
||||
// DecoratorFunc is a function that can be prepended and appended to the progress bar
|
||||
type DecoratorFunc func(b *Bar) string
|
||||
|
||||
// NewBar returns a new progress bar
|
||||
func NewBar(total int) *Bar {
|
||||
return &Bar{
|
||||
Total: total,
|
||||
Width: Width,
|
||||
LeftEnd: LeftEnd,
|
||||
RightEnd: RightEnd,
|
||||
Head: Head,
|
||||
Fill: Fill,
|
||||
Empty: Empty,
|
||||
|
||||
mtx: &sync.RWMutex{},
|
||||
}
|
||||
}
|
||||
|
||||
// Set the current count of the bar. It returns ErrMaxCurrentReached when trying n exceeds the total value. This is atomic operation and concurancy safe.
|
||||
func (b *Bar) Set(n int) error {
|
||||
b.mtx.Lock()
|
||||
defer b.mtx.Unlock()
|
||||
|
||||
if n > b.Total {
|
||||
return ErrMaxCurrentReached
|
||||
}
|
||||
b.current = n
|
||||
return nil
|
||||
}
|
||||
|
||||
// Incr increments the current value by 1, time elapsed to current time and returns true. It returns false if the cursor has reached or exceeds total value.
|
||||
func (b *Bar) Incr() bool {
|
||||
b.mtx.Lock()
|
||||
defer b.mtx.Unlock()
|
||||
|
||||
n := b.current + 1
|
||||
if n > b.Total {
|
||||
return false
|
||||
}
|
||||
var t time.Time
|
||||
if b.TimeStarted == t {
|
||||
b.TimeStarted = time.Now()
|
||||
}
|
||||
b.timeElapsed = time.Since(b.TimeStarted)
|
||||
b.current = n
|
||||
return true
|
||||
}
|
||||
|
||||
// Current returns the current progress of the bar
|
||||
func (b *Bar) Current() int {
|
||||
b.mtx.RLock()
|
||||
defer b.mtx.RUnlock()
|
||||
return b.current
|
||||
}
|
||||
|
||||
// AppendFunc runs the decorator function and renders the output on the right of the progress bar
|
||||
func (b *Bar) AppendFunc(f DecoratorFunc) *Bar {
|
||||
b.mtx.Lock()
|
||||
defer b.mtx.Unlock()
|
||||
b.appendFuncs = append(b.appendFuncs, f)
|
||||
return b
|
||||
}
|
||||
|
||||
// AppendCompleted appends the completion percent to the progress bar
|
||||
func (b *Bar) AppendCompleted() *Bar {
|
||||
b.AppendFunc(func(b *Bar) string {
|
||||
return b.CompletedPercentString()
|
||||
})
|
||||
return b
|
||||
}
|
||||
|
||||
// AppendElapsed appends the time elapsed the be progress bar
|
||||
func (b *Bar) AppendElapsed() *Bar {
|
||||
b.AppendFunc(func(b *Bar) string {
|
||||
return strutil.PadLeft(b.TimeElapsedString(), 5, ' ')
|
||||
})
|
||||
return b
|
||||
}
|
||||
|
||||
// PrependFunc runs decorator function and render the output left the progress bar
|
||||
func (b *Bar) PrependFunc(f DecoratorFunc) *Bar {
|
||||
b.mtx.Lock()
|
||||
defer b.mtx.Unlock()
|
||||
b.prependFuncs = append(b.prependFuncs, f)
|
||||
return b
|
||||
}
|
||||
|
||||
// PrependCompleted prepends the precent completed to the progress bar
|
||||
func (b *Bar) PrependCompleted() *Bar {
|
||||
b.PrependFunc(func(b *Bar) string {
|
||||
return b.CompletedPercentString()
|
||||
})
|
||||
return b
|
||||
}
|
||||
|
||||
// PrependElapsed prepends the time elapsed to the begining of the bar
|
||||
func (b *Bar) PrependElapsed() *Bar {
|
||||
b.PrependFunc(func(b *Bar) string {
|
||||
return strutil.PadLeft(b.TimeElapsedString(), 5, ' ')
|
||||
})
|
||||
return b
|
||||
}
|
||||
|
||||
// Bytes returns the byte presentation of the progress bar
|
||||
func (b *Bar) Bytes() []byte {
|
||||
completedWidth := int(float64(b.Width) * (b.CompletedPercent() / 100.00))
|
||||
|
||||
// add fill and empty bits
|
||||
var buf bytes.Buffer
|
||||
for i := 0; i < completedWidth; i++ {
|
||||
buf.WriteByte(b.Fill)
|
||||
}
|
||||
for i := 0; i < b.Width-completedWidth; i++ {
|
||||
buf.WriteByte(b.Empty)
|
||||
}
|
||||
|
||||
// set head bit
|
||||
pb := buf.Bytes()
|
||||
if completedWidth > 0 && completedWidth < b.Width {
|
||||
pb[completedWidth-1] = b.Head
|
||||
}
|
||||
|
||||
// set left and right ends bits
|
||||
pb[0], pb[len(pb)-1] = b.LeftEnd, b.RightEnd
|
||||
|
||||
// render append functions to the right of the bar
|
||||
for _, f := range b.appendFuncs {
|
||||
pb = append(pb, ' ')
|
||||
pb = append(pb, []byte(f(b))...)
|
||||
}
|
||||
|
||||
// render prepend functions to the left of the bar
|
||||
for _, f := range b.prependFuncs {
|
||||
args := []byte(f(b))
|
||||
args = append(args, ' ')
|
||||
pb = append(args, pb...)
|
||||
}
|
||||
return pb
|
||||
}
|
||||
|
||||
// String returns the string representation of the bar
|
||||
func (b *Bar) String() string {
|
||||
return string(b.Bytes())
|
||||
}
|
||||
|
||||
// CompletedPercent return the percent completed
|
||||
func (b *Bar) CompletedPercent() float64 {
|
||||
return (float64(b.Current()) / float64(b.Total)) * 100.00
|
||||
}
|
||||
|
||||
// CompletedPercentString returns the formatted string representation of the completed percent
|
||||
func (b *Bar) CompletedPercentString() string {
|
||||
return fmt.Sprintf("%3.f%%", b.CompletedPercent())
|
||||
}
|
||||
|
||||
// TimeElapsed returns the time elapsed
|
||||
func (b *Bar) TimeElapsed() time.Duration {
|
||||
b.mtx.RLock()
|
||||
defer b.mtx.RUnlock()
|
||||
return b.timeElapsed
|
||||
}
|
||||
|
||||
// TimeElapsedString returns the formatted string represenation of the time elapsed
|
||||
func (b *Bar) TimeElapsedString() string {
|
||||
return strutil.PrettyTime(b.TimeElapsed())
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package uiprogress
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestBarPrepend(t *testing.T) {
|
||||
b := NewBar(100)
|
||||
b.PrependCompleted()
|
||||
b.Set(50)
|
||||
if !strings.Contains(b.String(), "50") {
|
||||
t.Fatal("want", "50%", "in", b.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBarIncr(t *testing.T) {
|
||||
b := NewBar(10000)
|
||||
runtime.GOMAXPROCS(runtime.NumCPU())
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 10000; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
b.Incr()
|
||||
time.Sleep(time.Millisecond * time.Duration(rand.Intn(10)))
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if b.Current() != 10000 {
|
||||
t.Fatal("need", 10000, "got", b.Current())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
// Package uiprogress is a library to render progress bars in terminal applications
|
||||
package uiprogress
|
Binary file not shown.
After Width: | Height: | Size: 674 KiB |
Binary file not shown.
After Width: | Height: | Size: 784 KiB |
Binary file not shown.
After Width: | Height: | Size: 230 KiB |
|
@ -0,0 +1,50 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gosuri/uiprogress"
|
||||
)
|
||||
|
||||
func main() {
|
||||
waitTime := time.Millisecond * 200
|
||||
p := uiprogress.New()
|
||||
p.Start()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
bar1 := p.AddBar(20).AppendCompleted().PrependElapsed()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for bar1.Incr() {
|
||||
time.Sleep(waitTime)
|
||||
}
|
||||
fmt.Fprintln(p.Bypass(), "Bar1 finished")
|
||||
}()
|
||||
|
||||
bar2 := p.AddBar(40).AppendCompleted().PrependElapsed()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for bar2.Incr() {
|
||||
time.Sleep(waitTime)
|
||||
}
|
||||
fmt.Fprintln(p.Bypass(), "Bar2 finished")
|
||||
}()
|
||||
|
||||
time.Sleep(time.Second)
|
||||
bar3 := p.AddBar(20).PrependElapsed().AppendCompleted()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for bar3.Incr() {
|
||||
time.Sleep(waitTime)
|
||||
}
|
||||
fmt.Fprintln(p.Bypass(), "Bar3 finished")
|
||||
}()
|
||||
|
||||
wg.Wait()
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gosuri/uiprogress"
|
||||
"github.com/gosuri/uiprogress/util/strutil"
|
||||
)
|
||||
|
||||
var steps = []string{
|
||||
"downloading source",
|
||||
"installing deps",
|
||||
"compiling",
|
||||
"packaging",
|
||||
"seeding database",
|
||||
"deploying",
|
||||
"staring servers",
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println("apps: deployment started: app1, app2")
|
||||
uiprogress.Start()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go deploy("app1", &wg)
|
||||
wg.Add(1)
|
||||
go deploy("app2", &wg)
|
||||
wg.Wait()
|
||||
|
||||
fmt.Println("apps: successfully deployed: app1, app2")
|
||||
}
|
||||
|
||||
func deploy(app string, wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
bar := uiprogress.AddBar(len(steps)).AppendCompleted().PrependElapsed()
|
||||
bar.Width = 50
|
||||
|
||||
// prepend the deploy step to the bar
|
||||
bar.PrependFunc(func(b *uiprogress.Bar) string {
|
||||
return strutil.Resize(app+": "+steps[b.Current()-1], 22)
|
||||
})
|
||||
|
||||
rand.Seed(500)
|
||||
for bar.Incr() {
|
||||
time.Sleep(time.Millisecond * time.Duration(rand.Intn(2000)))
|
||||
}
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gosuri/uiprogress"
|
||||
)
|
||||
|
||||
func main() {
|
||||
runtime.GOMAXPROCS(runtime.NumCPU()) // use all available cpu cores
|
||||
|
||||
// create a new bar and prepend the task progress to the bar and fanout into 1k go routines
|
||||
count := 1000
|
||||
bar := uiprogress.AddBar(count).AppendCompleted().PrependElapsed()
|
||||
bar.PrependFunc(func(b *uiprogress.Bar) string {
|
||||
return fmt.Sprintf("Task (%d/%d)", b.Current(), count)
|
||||
})
|
||||
|
||||
uiprogress.Start()
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// fanout into 1k go routines
|
||||
for i := 0; i < count; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
time.Sleep(time.Millisecond * time.Duration(rand.Intn(500)))
|
||||
bar.Incr()
|
||||
}()
|
||||
}
|
||||
time.Sleep(time.Second) // wait for a second for all the go routines to finish
|
||||
wg.Wait()
|
||||
uiprogress.Stop()
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gosuri/uiprogress"
|
||||
)
|
||||
|
||||
func main() {
|
||||
waitTime := time.Millisecond * 100
|
||||
uiprogress.Start()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
bar1 := uiprogress.AddBar(20).AppendCompleted().PrependElapsed()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for bar1.Incr() {
|
||||
time.Sleep(waitTime)
|
||||
}
|
||||
}()
|
||||
|
||||
bar2 := uiprogress.AddBar(40).AppendCompleted().PrependElapsed()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for bar2.Incr() {
|
||||
time.Sleep(waitTime)
|
||||
}
|
||||
}()
|
||||
|
||||
time.Sleep(time.Second)
|
||||
bar3 := uiprogress.AddBar(20).PrependElapsed().AppendCompleted()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for bar3.Incr() {
|
||||
time.Sleep(waitTime)
|
||||
}
|
||||
}()
|
||||
|
||||
wg.Wait()
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/gosuri/uiprogress"
|
||||
)
|
||||
|
||||
func main() {
|
||||
uiprogress.Start() // start rendering
|
||||
bar := uiprogress.AddBar(100) // Add a new bar
|
||||
|
||||
// optionally, append and prepend completion and elapsed time
|
||||
bar.AppendCompleted()
|
||||
bar.PrependElapsed()
|
||||
|
||||
for bar.Incr() {
|
||||
time.Sleep(time.Millisecond * 20)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,103 @@
|
|||
package uiprogress_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gosuri/uiprogress"
|
||||
)
|
||||
|
||||
func Example() {
|
||||
uiprogress.Start() // start rendering
|
||||
bar := uiprogress.AddBar(100) // Add a new bar
|
||||
|
||||
// optionally, append and prepend completion and elapsed time
|
||||
bar.AppendCompleted()
|
||||
bar.PrependElapsed()
|
||||
|
||||
for bar.Incr() {
|
||||
time.Sleep(time.Millisecond * 20)
|
||||
}
|
||||
}
|
||||
|
||||
func ExampleProgress_AddBar() {
|
||||
waitTime := time.Millisecond * 100
|
||||
uiprogress.Start()
|
||||
// start the progress bars in go routines
|
||||
var wg sync.WaitGroup
|
||||
|
||||
bar1 := uiprogress.AddBar(20).AppendCompleted().PrependElapsed()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for bar1.Incr() {
|
||||
time.Sleep(waitTime)
|
||||
}
|
||||
}()
|
||||
|
||||
bar2 := uiprogress.AddBar(40).AppendCompleted().PrependElapsed()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for bar2.Incr() {
|
||||
time.Sleep(waitTime)
|
||||
}
|
||||
}()
|
||||
|
||||
time.Sleep(time.Second)
|
||||
bar3 := uiprogress.AddBar(20).PrependElapsed().AppendCompleted()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 1; i <= bar3.Total; i++ {
|
||||
bar3.Set(i)
|
||||
time.Sleep(waitTime)
|
||||
}
|
||||
}()
|
||||
// wait for all the go routines to finish
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func ExampleDecoratorFunc() {
|
||||
var steps = []string{"downloading source", "installing deps", "compiling", "packaging", "seeding database", "deploying", "staring servers"}
|
||||
bar := uiprogress.AddBar(len(steps))
|
||||
|
||||
// prepend the current step to the bar
|
||||
bar.PrependFunc(func(b *uiprogress.Bar) string {
|
||||
return "app: " + steps[b.Current()-1]
|
||||
})
|
||||
|
||||
for bar.Incr() {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func ExampleBar_Incr() {
|
||||
runtime.GOMAXPROCS(runtime.NumCPU()) // use all available cpu cores
|
||||
|
||||
// create a new bar and prepend the task progress to the bar
|
||||
count := 1000
|
||||
bar := uiprogress.AddBar(count).AppendCompleted().PrependElapsed()
|
||||
bar.PrependFunc(func(b *uiprogress.Bar) string {
|
||||
return fmt.Sprintf("Task (%d/%d)", b.Current(), count)
|
||||
})
|
||||
|
||||
uiprogress.Start()
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// fanout into 1k go routines
|
||||
for i := 0; i < count; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
time.Sleep(time.Millisecond * time.Duration(rand.Intn(500)))
|
||||
bar.Incr()
|
||||
}()
|
||||
}
|
||||
time.Sleep(time.Second) // wait for a second for all the go routines to finish
|
||||
wg.Wait()
|
||||
uiprogress.Stop()
|
||||
}
|
|
@ -0,0 +1,146 @@
|
|||
package uiprogress
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gosuri/uilive"
|
||||
)
|
||||
|
||||
// Out is the default writer to render progress bars to
|
||||
var Out = os.Stdout
|
||||
|
||||
// RefreshInterval in the default time duration to wait for refreshing the output
|
||||
var RefreshInterval = time.Millisecond * 10
|
||||
|
||||
// defaultProgress is the default progress
|
||||
var defaultProgress = New()
|
||||
|
||||
// Progress represents the container that renders progress bars
|
||||
type Progress struct {
|
||||
// Out is the writer to render progress bars to
|
||||
Out io.Writer
|
||||
|
||||
// Width is the width of the progress bars
|
||||
Width int
|
||||
|
||||
// Bars is the collection of progress bars
|
||||
Bars []*Bar
|
||||
|
||||
// RefreshInterval in the time duration to wait for refreshing the output
|
||||
RefreshInterval time.Duration
|
||||
|
||||
lw *uilive.Writer
|
||||
ticker *time.Ticker
|
||||
tdone chan bool
|
||||
mtx *sync.RWMutex
|
||||
}
|
||||
|
||||
// New returns a new progress bar with defaults
|
||||
func New() *Progress {
|
||||
lw := uilive.New()
|
||||
lw.Out = Out
|
||||
|
||||
return &Progress{
|
||||
Width: Width,
|
||||
Out: Out,
|
||||
Bars: make([]*Bar, 0),
|
||||
RefreshInterval: RefreshInterval,
|
||||
|
||||
tdone: make(chan bool),
|
||||
lw: uilive.New(),
|
||||
mtx: &sync.RWMutex{},
|
||||
}
|
||||
}
|
||||
|
||||
// AddBar creates a new progress bar and adds it to the default progress container
|
||||
func AddBar(total int) *Bar {
|
||||
return defaultProgress.AddBar(total)
|
||||
}
|
||||
|
||||
// Start starts the rendering the progress of progress bars using the DefaultProgress. It listens for updates using `bar.Set(n)` and new bars when added using `AddBar`
|
||||
func Start() {
|
||||
defaultProgress.Start()
|
||||
}
|
||||
|
||||
// Stop stops listening
|
||||
func Stop() {
|
||||
defaultProgress.Stop()
|
||||
}
|
||||
|
||||
// Listen listens for updates and renders the progress bars
|
||||
func Listen() {
|
||||
defaultProgress.Listen()
|
||||
}
|
||||
|
||||
func (p *Progress) SetOut(o io.Writer) {
|
||||
p.mtx.Lock()
|
||||
defer p.mtx.Unlock()
|
||||
|
||||
p.Out = o
|
||||
p.lw.Out = o
|
||||
}
|
||||
|
||||
func (p *Progress) SetRefreshInterval(interval time.Duration) {
|
||||
p.mtx.Lock()
|
||||
defer p.mtx.Unlock()
|
||||
p.RefreshInterval = interval
|
||||
}
|
||||
|
||||
// AddBar creates a new progress bar and adds to the container
|
||||
func (p *Progress) AddBar(total int) *Bar {
|
||||
p.mtx.Lock()
|
||||
defer p.mtx.Unlock()
|
||||
|
||||
bar := NewBar(total)
|
||||
bar.Width = p.Width
|
||||
p.Bars = append(p.Bars, bar)
|
||||
return bar
|
||||
}
|
||||
|
||||
// Listen listens for updates and renders the progress bars
|
||||
func (p *Progress) Listen() {
|
||||
for {
|
||||
|
||||
p.mtx.Lock()
|
||||
interval := p.RefreshInterval
|
||||
p.mtx.Unlock()
|
||||
|
||||
select {
|
||||
case <-time.After(interval):
|
||||
p.print()
|
||||
case <-p.tdone:
|
||||
p.print()
|
||||
close(p.tdone)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Progress) print() {
|
||||
p.mtx.Lock()
|
||||
defer p.mtx.Unlock()
|
||||
for _, bar := range p.Bars {
|
||||
fmt.Fprintln(p.lw, bar.String())
|
||||
}
|
||||
p.lw.Flush()
|
||||
}
|
||||
|
||||
// Start starts the rendering the progress of progress bars. It listens for updates using `bar.Set(n)` and new bars when added using `AddBar`
|
||||
func (p *Progress) Start() {
|
||||
go p.Listen()
|
||||
}
|
||||
|
||||
// Stop stops listening
|
||||
func (p *Progress) Stop() {
|
||||
p.tdone <- true
|
||||
<-p.tdone
|
||||
}
|
||||
|
||||
// Bypass returns a writer which allows non-buffered data to be written to the underlying output
|
||||
func (p *Progress) Bypass() io.Writer {
|
||||
return p.lw.Bypass()
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package uiprogress
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestStoppingPrintout(t *testing.T) {
|
||||
progress := New()
|
||||
progress.SetRefreshInterval(time.Millisecond * 10)
|
||||
|
||||
var buffer = &bytes.Buffer{}
|
||||
progress.SetOut(buffer)
|
||||
|
||||
bar := progress.AddBar(100)
|
||||
progress.Start()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
wg.Add(1)
|
||||
|
||||
go func() {
|
||||
for i := 0; i <= 80; i = i + 10 {
|
||||
bar.Set(i)
|
||||
time.Sleep(time.Millisecond * 5)
|
||||
}
|
||||
|
||||
wg.Done()
|
||||
}()
|
||||
|
||||
wg.Wait()
|
||||
|
||||
progress.Stop()
|
||||
fmt.Fprintf(buffer, "foo")
|
||||
|
||||
var wantSuffix = "[======================================================>-------------]\nfoo"
|
||||
|
||||
if !strings.HasSuffix(buffer.String(), wantSuffix) {
|
||||
t.Errorf("Content that should be printed after stop not appearing on buffer.")
|
||||
}
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
// Package strutil provides various utilities for manipulating strings
|
||||
package strutil
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PadRight returns a new string of a specified length in which the end of the current string is padded with spaces or with a specified Unicode character.
|
||||
func PadRight(str string, length int, pad byte) string {
|
||||
if len(str) >= length {
|
||||
return str
|
||||
}
|
||||
buf := bytes.NewBufferString(str)
|
||||
for i := 0; i < length-len(str); i++ {
|
||||
buf.WriteByte(pad)
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// PadLeft returns a new string of a specified length in which the beginning of the current string is padded with spaces or with a specified Unicode character.
|
||||
func PadLeft(str string, length int, pad byte) string {
|
||||
if len(str) >= length {
|
||||
return str
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
for i := 0; i < length-len(str); i++ {
|
||||
buf.WriteByte(pad)
|
||||
}
|
||||
buf.WriteString(str)
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// Resize resizes the string with the given length. It ellipses with '...' when the string's length exceeds
|
||||
// the desired length or pads spaces to the right of the string when length is smaller than desired
|
||||
func Resize(s string, length uint) string {
|
||||
n := int(length)
|
||||
if len(s) == n {
|
||||
return s
|
||||
}
|
||||
// Pads only when length of the string smaller than len needed
|
||||
s = PadRight(s, n, ' ')
|
||||
if len(s) > n {
|
||||
b := []byte(s)
|
||||
var buf bytes.Buffer
|
||||
for i := 0; i < n-3; i++ {
|
||||
buf.WriteByte(b[i])
|
||||
}
|
||||
buf.WriteString("...")
|
||||
s = buf.String()
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// PrettyTime returns the string representation of the duration. It rounds the time duration to a second and returns a "---" when duration is 0
|
||||
func PrettyTime(t time.Duration) string {
|
||||
if t == 0 {
|
||||
return "---"
|
||||
}
|
||||
return (t - (t % time.Second)).String()
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package strutil
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestResize(t *testing.T) {
|
||||
s := "foo"
|
||||
got := Resize(s, 5)
|
||||
if len(got) != 5 {
|
||||
t.Fatal("want", 5, "got", len(got))
|
||||
}
|
||||
s = "foobar"
|
||||
got = Resize(s, 5)
|
||||
|
||||
if got != "fo..." {
|
||||
t.Fatal("want", "fo...", "got", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPadRight(t *testing.T) {
|
||||
got := PadRight("foo", 5, '-')
|
||||
if got != "foo--" {
|
||||
t.Fatal("want", "foo--", "got", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPadLeft(t *testing.T) {
|
||||
got := PadLeft("foo", 5, '-')
|
||||
if got != "--foo" {
|
||||
t.Fatal("want", "--foo", "got", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrettyTime(t *testing.T) {
|
||||
d, _ := time.ParseDuration("")
|
||||
got := PrettyTime(d)
|
||||
if got != "---" {
|
||||
t.Fatal("want", "---", "got", got)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
language: go
|
||||
go:
|
||||
- tip
|
||||
|
||||
before_install:
|
||||
- go get github.com/mattn/goveralls
|
||||
- go get golang.org/x/tools/cmd/cover
|
||||
script:
|
||||
- $HOME/gopath/bin/goveralls -repotoken 3gHdORO5k5ziZcWMBxnd9LrMZaJs8m9x5
|
|
@ -0,0 +1,9 @@
|
|||
Copyright (c) Yasuhiro MATSUMOTO <mattn.jp@gmail.com>
|
||||
|
||||
MIT License (Expat)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@ -0,0 +1,50 @@
|
|||
# go-isatty
|
||||
|
||||
[![Godoc Reference](https://godoc.org/github.com/mattn/go-isatty?status.svg)](http://godoc.org/github.com/mattn/go-isatty)
|
||||
[![Build Status](https://travis-ci.org/mattn/go-isatty.svg?branch=master)](https://travis-ci.org/mattn/go-isatty)
|
||||
[![Coverage Status](https://coveralls.io/repos/github/mattn/go-isatty/badge.svg?branch=master)](https://coveralls.io/github/mattn/go-isatty?branch=master)
|
||||
[![Go Report Card](https://goreportcard.com/badge/mattn/go-isatty)](https://goreportcard.com/report/mattn/go-isatty)
|
||||
|
||||
isatty for golang
|
||||
|
||||
## Usage
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/mattn/go-isatty"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if isatty.IsTerminal(os.Stdout.Fd()) {
|
||||
fmt.Println("Is Terminal")
|
||||
} else if isatty.IsCygwinTerminal(os.Stdout.Fd()) {
|
||||
fmt.Println("Is Cygwin/MSYS2 Terminal")
|
||||
} else {
|
||||
fmt.Println("Is Not Terminal")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
```
|
||||
$ go get github.com/mattn/go-isatty
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
|
||||
## Author
|
||||
|
||||
Yasuhiro Matsumoto (a.k.a mattn)
|
||||
|
||||
## Thanks
|
||||
|
||||
* k-takata: base idea for IsCygwinTerminal
|
||||
|
||||
https://github.com/k-takata/go-iscygpty
|
|
@ -0,0 +1,2 @@
|
|||
// Package isatty implements interface to isatty
|
||||
package isatty
|
|
@ -0,0 +1,18 @@
|
|||
package isatty_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/mattn/go-isatty"
|
||||
)
|
||||
|
||||
func Example() {
|
||||
if isatty.IsTerminal(os.Stdout.Fd()) {
|
||||
fmt.Println("Is Terminal")
|
||||
} else if isatty.IsCygwinTerminal(os.Stdout.Fd()) {
|
||||
fmt.Println("Is Cygwin/MSYS2 Terminal")
|
||||
} else {
|
||||
fmt.Println("Is Not Terminal")
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
// +build appengine
|
||||
|
||||
package isatty
|
||||
|
||||
// IsTerminal returns true if the file descriptor is terminal which
|
||||
// is always false on on appengine classic which is a sandboxed PaaS.
|
||||
func IsTerminal(fd uintptr) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2
|
||||
// terminal. This is also always false on this environment.
|
||||
func IsCygwinTerminal(fd uintptr) bool {
|
||||
return false
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
// +build darwin freebsd openbsd netbsd dragonfly
|
||||
// +build !appengine
|
||||
|
||||
package isatty
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const ioctlReadTermios = syscall.TIOCGETA
|
||||
|
||||
// IsTerminal return true if the file descriptor is terminal.
|
||||
func IsTerminal(fd uintptr) bool {
|
||||
var termios syscall.Termios
|
||||
_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
|
||||
return err == 0
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
// +build linux
|
||||
// +build !appengine,!ppc64,!ppc64le
|
||||
|
||||
package isatty
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const ioctlReadTermios = syscall.TCGETS
|
||||
|
||||
// IsTerminal return true if the file descriptor is terminal.
|
||||
func IsTerminal(fd uintptr) bool {
|
||||
var termios syscall.Termios
|
||||
_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
|
||||
return err == 0
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
// +build linux
|
||||
// +build ppc64 ppc64le
|
||||
|
||||
package isatty
|
||||
|
||||
import (
|
||||
"unsafe"
|
||||
|
||||
syscall "golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
const ioctlReadTermios = syscall.TCGETS
|
||||
|
||||
// IsTerminal return true if the file descriptor is terminal.
|
||||
func IsTerminal(fd uintptr) bool {
|
||||
var termios syscall.Termios
|
||||
_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
|
||||
return err == 0
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
// +build !windows
|
||||
// +build !appengine
|
||||
|
||||
package isatty
|
||||
|
||||
// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2
|
||||
// terminal. This is also always false on this environment.
|
||||
func IsCygwinTerminal(fd uintptr) bool {
|
||||
return false
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
// +build !windows
|
||||
|
||||
package isatty
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTerminal(t *testing.T) {
|
||||
// test for non-panic
|
||||
IsTerminal(os.Stdout.Fd())
|
||||
}
|
||||
|
||||
func TestCygwinPipeName(t *testing.T) {
|
||||
if IsCygwinTerminal(os.Stdout.Fd()) {
|
||||
t.Fatal("should be false always")
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
// +build solaris
|
||||
// +build !appengine
|
||||
|
||||
package isatty
|
||||
|
||||
import (
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// IsTerminal returns true if the given file descriptor is a terminal.
|
||||
// see: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libbc/libc/gen/common/isatty.c
|
||||
func IsTerminal(fd uintptr) bool {
|
||||
var termio unix.Termio
|
||||
err := unix.IoctlSetTermio(int(fd), unix.TCGETA, &termio)
|
||||
return err == nil
|
||||
}
|
|
@ -0,0 +1,94 @@
|
|||
// +build windows
|
||||
// +build !appengine
|
||||
|
||||
package isatty
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"syscall"
|
||||
"unicode/utf16"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
fileNameInfo uintptr = 2
|
||||
fileTypePipe = 3
|
||||
)
|
||||
|
||||
var (
|
||||
kernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
procGetConsoleMode = kernel32.NewProc("GetConsoleMode")
|
||||
procGetFileInformationByHandleEx = kernel32.NewProc("GetFileInformationByHandleEx")
|
||||
procGetFileType = kernel32.NewProc("GetFileType")
|
||||
)
|
||||
|
||||
func init() {
|
||||
// Check if GetFileInformationByHandleEx is available.
|
||||
if procGetFileInformationByHandleEx.Find() != nil {
|
||||
procGetFileInformationByHandleEx = nil
|
||||
}
|
||||
}
|
||||
|
||||
// IsTerminal return true if the file descriptor is terminal.
|
||||
func IsTerminal(fd uintptr) bool {
|
||||
var st uint32
|
||||
r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0)
|
||||
return r != 0 && e == 0
|
||||
}
|
||||
|
||||
// Check pipe name is used for cygwin/msys2 pty.
|
||||
// Cygwin/MSYS2 PTY has a name like:
|
||||
// \{cygwin,msys}-XXXXXXXXXXXXXXXX-ptyN-{from,to}-master
|
||||
func isCygwinPipeName(name string) bool {
|
||||
token := strings.Split(name, "-")
|
||||
if len(token) < 5 {
|
||||
return false
|
||||
}
|
||||
|
||||
if token[0] != `\msys` && token[0] != `\cygwin` {
|
||||
return false
|
||||
}
|
||||
|
||||
if token[1] == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(token[2], "pty") {
|
||||
return false
|
||||
}
|
||||
|
||||
if token[3] != `from` && token[3] != `to` {
|
||||
return false
|
||||
}
|
||||
|
||||
if token[4] != "master" {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2
|
||||
// terminal.
|
||||
func IsCygwinTerminal(fd uintptr) bool {
|
||||
if procGetFileInformationByHandleEx == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
// Cygwin/msys's pty is a pipe.
|
||||
ft, _, e := syscall.Syscall(procGetFileType.Addr(), 1, fd, 0, 0)
|
||||
if ft != fileTypePipe || e != 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
var buf [2 + syscall.MAX_PATH]uint16
|
||||
r, _, e := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(),
|
||||
4, fd, fileNameInfo, uintptr(unsafe.Pointer(&buf)),
|
||||
uintptr(len(buf)*2), 0, 0)
|
||||
if r == 0 || e != 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
l := *(*uint32)(unsafe.Pointer(&buf))
|
||||
return isCygwinPipeName(string(utf16.Decode(buf[2 : 2+l/2])))
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
// +build windows
|
||||
|
||||
package isatty
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCygwinPipeName(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
result bool
|
||||
}{
|
||||
{``, false},
|
||||
{`\msys-`, false},
|
||||
{`\cygwin-----`, false},
|
||||
{`\msys-x-PTY5-pty1-from-master`, false},
|
||||
{`\cygwin-x-PTY5-from-master`, false},
|
||||
{`\cygwin-x-pty2-from-toaster`, false},
|
||||
{`\cygwin--pty2-from-master`, false},
|
||||
{`\\cygwin-x-pty2-from-master`, false},
|
||||
{`\cygwin-x-pty2-from-master-`, true}, // for the feature
|
||||
{`\cygwin-e022582115c10879-pty4-from-master`, true},
|
||||
{`\msys-e022582115c10879-pty4-to-master`, true},
|
||||
{`\cygwin-e022582115c10879-pty4-to-master`, true},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
want := test.result
|
||||
got := isCygwinPipeName(test.name)
|
||||
if want != got {
|
||||
t.Fatalf("isatty(%q): got %v, want %v:", test.name, got, want)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
*.test
|
||||
*.prof
|
|
@ -0,0 +1,11 @@
|
|||
language: go
|
||||
go_import_path: github.com/pkg/errors
|
||||
go:
|
||||
- 1.4.3
|
||||
- 1.5.4
|
||||
- 1.6.2
|
||||
- 1.7.1
|
||||
- tip
|
||||
|
||||
script:
|
||||
- go test -v ./...
|
|
@ -0,0 +1,23 @@
|
|||
Copyright (c) 2015, Dave Cheney <dave@cheney.net>
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@ -0,0 +1,52 @@
|
|||
# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors)
|
||||
|
||||
Package errors provides simple error handling primitives.
|
||||
|
||||
`go get github.com/pkg/errors`
|
||||
|
||||
The traditional error handling idiom in Go is roughly akin to
|
||||
```go
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
```
|
||||
which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error.
|
||||
|
||||
## Adding context to an error
|
||||
|
||||
The errors.Wrap function returns a new error that adds context to the original error. For example
|
||||
```go
|
||||
_, err := ioutil.ReadAll(r)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "read failed")
|
||||
}
|
||||
```
|
||||
## Retrieving the cause of an error
|
||||
|
||||
Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`.
|
||||
```go
|
||||
type causer interface {
|
||||
Cause() error
|
||||
}
|
||||
```
|
||||
`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example:
|
||||
```go
|
||||
switch err := errors.Cause(err).(type) {
|
||||
case *MyError:
|
||||
// handle specifically
|
||||
default:
|
||||
// unknown error
|
||||
}
|
||||
```
|
||||
|
||||
[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors).
|
||||
|
||||
## Contributing
|
||||
|
||||
We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high.
|
||||
|
||||
Before proposing a change, please discuss your change by raising an issue.
|
||||
|
||||
## Licence
|
||||
|
||||
BSD-2-Clause
|
|
@ -0,0 +1,32 @@
|
|||
version: build-{build}.{branch}
|
||||
|
||||
clone_folder: C:\gopath\src\github.com\pkg\errors
|
||||
shallow_clone: true # for startup speed
|
||||
|
||||
environment:
|
||||
GOPATH: C:\gopath
|
||||
|
||||
platform:
|
||||
- x64
|
||||
|
||||
# http://www.appveyor.com/docs/installed-software
|
||||
install:
|
||||
# some helpful output for debugging builds
|
||||
- go version
|
||||
- go env
|
||||
# pre-installed MinGW at C:\MinGW is 32bit only
|
||||
# but MSYS2 at C:\msys64 has mingw64
|
||||
- set PATH=C:\msys64\mingw64\bin;%PATH%
|
||||
- gcc --version
|
||||
- g++ --version
|
||||
|
||||
build_script:
|
||||
- go install -v ./...
|
||||
|
||||
test_script:
|
||||
- set PATH=C:\gopath\bin;%PATH%
|
||||
- go test -v ./...
|
||||
|
||||
#artifacts:
|
||||
# - path: '%GOPATH%\bin\*.exe'
|
||||
deploy: off
|
|
@ -0,0 +1,59 @@
|
|||
// +build go1.7
|
||||
|
||||
package errors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
stderrors "errors"
|
||||
)
|
||||
|
||||
func noErrors(at, depth int) error {
|
||||
if at >= depth {
|
||||
return stderrors.New("no error")
|
||||
}
|
||||
return noErrors(at+1, depth)
|
||||
}
|
||||
func yesErrors(at, depth int) error {
|
||||
if at >= depth {
|
||||
return New("ye error")
|
||||
}
|
||||
return yesErrors(at+1, depth)
|
||||
}
|
||||
|
||||
func BenchmarkErrors(b *testing.B) {
|
||||
var toperr error
|
||||
type run struct {
|
||||
stack int
|
||||
std bool
|
||||
}
|
||||
runs := []run{
|
||||
{10, false},
|
||||
{10, true},
|
||||
{100, false},
|
||||
{100, true},
|
||||
{1000, false},
|
||||
{1000, true},
|
||||
}
|
||||
for _, r := range runs {
|
||||
part := "pkg/errors"
|
||||
if r.std {
|
||||
part = "errors"
|
||||
}
|
||||
name := fmt.Sprintf("%s-stack-%d", part, r.stack)
|
||||
b.Run(name, func(b *testing.B) {
|
||||
var err error
|
||||
f := yesErrors
|
||||
if r.std {
|
||||
f = noErrors
|
||||
}
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
err = f(0, r.stack)
|
||||
}
|
||||
b.StopTimer()
|
||||
toperr = err
|
||||
})
|
||||
}
|
||||
}
|
|
@ -0,0 +1,269 @@
|
|||
// Package errors provides simple error handling primitives.
|
||||
//
|
||||
// The traditional error handling idiom in Go is roughly akin to
|
||||
//
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
//
|
||||
// which applied recursively up the call stack results in error reports
|
||||
// without context or debugging information. The errors package allows
|
||||
// programmers to add context to the failure path in their code in a way
|
||||
// that does not destroy the original value of the error.
|
||||
//
|
||||
// Adding context to an error
|
||||
//
|
||||
// The errors.Wrap function returns a new error that adds context to the
|
||||
// original error by recording a stack trace at the point Wrap is called,
|
||||
// and the supplied message. For example
|
||||
//
|
||||
// _, err := ioutil.ReadAll(r)
|
||||
// if err != nil {
|
||||
// return errors.Wrap(err, "read failed")
|
||||
// }
|
||||
//
|
||||
// If additional control is required the errors.WithStack and errors.WithMessage
|
||||
// functions destructure errors.Wrap into its component operations of annotating
|
||||
// an error with a stack trace and an a message, respectively.
|
||||
//
|
||||
// Retrieving the cause of an error
|
||||
//
|
||||
// Using errors.Wrap constructs a stack of errors, adding context to the
|
||||
// preceding error. Depending on the nature of the error it may be necessary
|
||||
// to reverse the operation of errors.Wrap to retrieve the original error
|
||||
// for inspection. Any error value which implements this interface
|
||||
//
|
||||
// type causer interface {
|
||||
// Cause() error
|
||||
// }
|
||||
//
|
||||
// can be inspected by errors.Cause. errors.Cause will recursively retrieve
|
||||
// the topmost error which does not implement causer, which is assumed to be
|
||||
// the original cause. For example:
|
||||
//
|
||||
// switch err := errors.Cause(err).(type) {
|
||||
// case *MyError:
|
||||
// // handle specifically
|
||||
// default:
|
||||
// // unknown error
|
||||
// }
|
||||
//
|
||||
// causer interface is not exported by this package, but is considered a part
|
||||
// of stable public API.
|
||||
//
|
||||
// Formatted printing of errors
|
||||
//
|
||||
// All error values returned from this package implement fmt.Formatter and can
|
||||
// be formatted by the fmt package. The following verbs are supported
|
||||
//
|
||||
// %s print the error. If the error has a Cause it will be
|
||||
// printed recursively
|
||||
// %v see %s
|
||||
// %+v extended format. Each Frame of the error's StackTrace will
|
||||
// be printed in detail.
|
||||
//
|
||||
// Retrieving the stack trace of an error or wrapper
|
||||
//
|
||||
// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are
|
||||
// invoked. This information can be retrieved with the following interface.
|
||||
//
|
||||
// type stackTracer interface {
|
||||
// StackTrace() errors.StackTrace
|
||||
// }
|
||||
//
|
||||
// Where errors.StackTrace is defined as
|
||||
//
|
||||
// type StackTrace []Frame
|
||||
//
|
||||
// The Frame type represents a call site in the stack trace. Frame supports
|
||||
// the fmt.Formatter interface that can be used for printing information about
|
||||
// the stack trace of this error. For example:
|
||||
//
|
||||
// if err, ok := err.(stackTracer); ok {
|
||||
// for _, f := range err.StackTrace() {
|
||||
// fmt.Printf("%+s:%d", f)
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// stackTracer interface is not exported by this package, but is considered a part
|
||||
// of stable public API.
|
||||
//
|
||||
// See the documentation for Frame.Format for more details.
|
||||
package errors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// New returns an error with the supplied message.
|
||||
// New also records the stack trace at the point it was called.
|
||||
func New(message string) error {
|
||||
return &fundamental{
|
||||
msg: message,
|
||||
stack: callers(),
|
||||
}
|
||||
}
|
||||
|
||||
// Errorf formats according to a format specifier and returns the string
|
||||
// as a value that satisfies error.
|
||||
// Errorf also records the stack trace at the point it was called.
|
||||
func Errorf(format string, args ...interface{}) error {
|
||||
return &fundamental{
|
||||
msg: fmt.Sprintf(format, args...),
|
||||
stack: callers(),
|
||||
}
|
||||
}
|
||||
|
||||
// fundamental is an error that has a message and a stack, but no caller.
|
||||
type fundamental struct {
|
||||
msg string
|
||||
*stack
|
||||
}
|
||||
|
||||
func (f *fundamental) Error() string { return f.msg }
|
||||
|
||||
func (f *fundamental) Format(s fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 'v':
|
||||
if s.Flag('+') {
|
||||
io.WriteString(s, f.msg)
|
||||
f.stack.Format(s, verb)
|
||||
return
|
||||
}
|
||||
fallthrough
|
||||
case 's':
|
||||
io.WriteString(s, f.msg)
|
||||
case 'q':
|
||||
fmt.Fprintf(s, "%q", f.msg)
|
||||
}
|
||||
}
|
||||
|
||||
// WithStack annotates err with a stack trace at the point WithStack was called.
|
||||
// If err is nil, WithStack returns nil.
|
||||
func WithStack(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return &withStack{
|
||||
err,
|
||||
callers(),
|
||||
}
|
||||
}
|
||||
|
||||
type withStack struct {
|
||||
error
|
||||
*stack
|
||||
}
|
||||
|
||||
func (w *withStack) Cause() error { return w.error }
|
||||
|
||||
func (w *withStack) Format(s fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 'v':
|
||||
if s.Flag('+') {
|
||||
fmt.Fprintf(s, "%+v", w.Cause())
|
||||
w.stack.Format(s, verb)
|
||||
return
|
||||
}
|
||||
fallthrough
|
||||
case 's':
|
||||
io.WriteString(s, w.Error())
|
||||
case 'q':
|
||||
fmt.Fprintf(s, "%q", w.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// Wrap returns an error annotating err with a stack trace
|
||||
// at the point Wrap is called, and the supplied message.
|
||||
// If err is nil, Wrap returns nil.
|
||||
func Wrap(err error, message string) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
err = &withMessage{
|
||||
cause: err,
|
||||
msg: message,
|
||||
}
|
||||
return &withStack{
|
||||
err,
|
||||
callers(),
|
||||
}
|
||||
}
|
||||
|
||||
// Wrapf returns an error annotating err with a stack trace
|
||||
// at the point Wrapf is call, and the format specifier.
|
||||
// If err is nil, Wrapf returns nil.
|
||||
func Wrapf(err error, format string, args ...interface{}) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
err = &withMessage{
|
||||
cause: err,
|
||||
msg: fmt.Sprintf(format, args...),
|
||||
}
|
||||
return &withStack{
|
||||
err,
|
||||
callers(),
|
||||
}
|
||||
}
|
||||
|
||||
// WithMessage annotates err with a new message.
|
||||
// If err is nil, WithMessage returns nil.
|
||||
func WithMessage(err error, message string) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return &withMessage{
|
||||
cause: err,
|
||||
msg: message,
|
||||
}
|
||||
}
|
||||
|
||||
type withMessage struct {
|
||||
cause error
|
||||
msg string
|
||||
}
|
||||
|
||||
func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() }
|
||||
func (w *withMessage) Cause() error { return w.cause }
|
||||
|
||||
func (w *withMessage) Format(s fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 'v':
|
||||
if s.Flag('+') {
|
||||
fmt.Fprintf(s, "%+v\n", w.Cause())
|
||||
io.WriteString(s, w.msg)
|
||||
return
|
||||
}
|
||||
fallthrough
|
||||
case 's', 'q':
|
||||
io.WriteString(s, w.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// Cause returns the underlying cause of the error, if possible.
|
||||
// An error value has a cause if it implements the following
|
||||
// interface:
|
||||
//
|
||||
// type causer interface {
|
||||
// Cause() error
|
||||
// }
|
||||
//
|
||||
// If the error does not implement Cause, the original error will
|
||||
// be returned. If the error is nil, nil will be returned without further
|
||||
// investigation.
|
||||
func Cause(err error) error {
|
||||
type causer interface {
|
||||
Cause() error
|
||||
}
|
||||
|
||||
for err != nil {
|
||||
cause, ok := err.(causer)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
err = cause.Cause()
|
||||
}
|
||||
return err
|
||||
}
|
|
@ -0,0 +1,226 @@
|
|||
package errors
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
tests := []struct {
|
||||
err string
|
||||
want error
|
||||
}{
|
||||
{"", fmt.Errorf("")},
|
||||
{"foo", fmt.Errorf("foo")},
|
||||
{"foo", New("foo")},
|
||||
{"string with format specifiers: %v", errors.New("string with format specifiers: %v")},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := New(tt.err)
|
||||
if got.Error() != tt.want.Error() {
|
||||
t.Errorf("New.Error(): got: %q, want %q", got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrapNil(t *testing.T) {
|
||||
got := Wrap(nil, "no error")
|
||||
if got != nil {
|
||||
t.Errorf("Wrap(nil, \"no error\"): got %#v, expected nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrap(t *testing.T) {
|
||||
tests := []struct {
|
||||
err error
|
||||
message string
|
||||
want string
|
||||
}{
|
||||
{io.EOF, "read error", "read error: EOF"},
|
||||
{Wrap(io.EOF, "read error"), "client error", "client error: read error: EOF"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := Wrap(tt.err, tt.message).Error()
|
||||
if got != tt.want {
|
||||
t.Errorf("Wrap(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type nilError struct{}
|
||||
|
||||
func (nilError) Error() string { return "nil error" }
|
||||
|
||||
func TestCause(t *testing.T) {
|
||||
x := New("error")
|
||||
tests := []struct {
|
||||
err error
|
||||
want error
|
||||
}{{
|
||||
// nil error is nil
|
||||
err: nil,
|
||||
want: nil,
|
||||
}, {
|
||||
// explicit nil error is nil
|
||||
err: (error)(nil),
|
||||
want: nil,
|
||||
}, {
|
||||
// typed nil is nil
|
||||
err: (*nilError)(nil),
|
||||
want: (*nilError)(nil),
|
||||
}, {
|
||||
// uncaused error is unaffected
|
||||
err: io.EOF,
|
||||
want: io.EOF,
|
||||
}, {
|
||||
// caused error returns cause
|
||||
err: Wrap(io.EOF, "ignored"),
|
||||
want: io.EOF,
|
||||
}, {
|
||||
err: x, // return from errors.New
|
||||
want: x,
|
||||
}, {
|
||||
WithMessage(nil, "whoops"),
|
||||
nil,
|
||||
}, {
|
||||
WithMessage(io.EOF, "whoops"),
|
||||
io.EOF,
|
||||
}, {
|
||||
WithStack(nil),
|
||||
nil,
|
||||
}, {
|
||||
WithStack(io.EOF),
|
||||
io.EOF,
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
got := Cause(tt.err)
|
||||
if !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("test %d: got %#v, want %#v", i+1, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrapfNil(t *testing.T) {
|
||||
got := Wrapf(nil, "no error")
|
||||
if got != nil {
|
||||
t.Errorf("Wrapf(nil, \"no error\"): got %#v, expected nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrapf(t *testing.T) {
|
||||
tests := []struct {
|
||||
err error
|
||||
message string
|
||||
want string
|
||||
}{
|
||||
{io.EOF, "read error", "read error: EOF"},
|
||||
{Wrapf(io.EOF, "read error without format specifiers"), "client error", "client error: read error without format specifiers: EOF"},
|
||||
{Wrapf(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := Wrapf(tt.err, tt.message).Error()
|
||||
if got != tt.want {
|
||||
t.Errorf("Wrapf(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorf(t *testing.T) {
|
||||
tests := []struct {
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
{Errorf("read error without format specifiers"), "read error without format specifiers"},
|
||||
{Errorf("read error with %d format specifier", 1), "read error with 1 format specifier"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := tt.err.Error()
|
||||
if got != tt.want {
|
||||
t.Errorf("Errorf(%v): got: %q, want %q", tt.err, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithStackNil(t *testing.T) {
|
||||
got := WithStack(nil)
|
||||
if got != nil {
|
||||
t.Errorf("WithStack(nil): got %#v, expected nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithStack(t *testing.T) {
|
||||
tests := []struct {
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
{io.EOF, "EOF"},
|
||||
{WithStack(io.EOF), "EOF"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := WithStack(tt.err).Error()
|
||||
if got != tt.want {
|
||||
t.Errorf("WithStack(%v): got: %v, want %v", tt.err, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithMessageNil(t *testing.T) {
|
||||
got := WithMessage(nil, "no error")
|
||||
if got != nil {
|
||||
t.Errorf("WithMessage(nil, \"no error\"): got %#v, expected nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithMessage(t *testing.T) {
|
||||
tests := []struct {
|
||||
err error
|
||||
message string
|
||||
want string
|
||||
}{
|
||||
{io.EOF, "read error", "read error: EOF"},
|
||||
{WithMessage(io.EOF, "read error"), "client error", "client error: read error: EOF"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := WithMessage(tt.err, tt.message).Error()
|
||||
if got != tt.want {
|
||||
t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// errors.New, etc values are not expected to be compared by value
|
||||
// but the change in errors#27 made them incomparable. Assert that
|
||||
// various kinds of errors have a functional equality operator, even
|
||||
// if the result of that equality is always false.
|
||||
func TestErrorEquality(t *testing.T) {
|
||||
vals := []error{
|
||||
nil,
|
||||
io.EOF,
|
||||
errors.New("EOF"),
|
||||
New("EOF"),
|
||||
Errorf("EOF"),
|
||||
Wrap(io.EOF, "EOF"),
|
||||
Wrapf(io.EOF, "EOF%d", 2),
|
||||
WithMessage(nil, "whoops"),
|
||||
WithMessage(io.EOF, "whoops"),
|
||||
WithStack(io.EOF),
|
||||
WithStack(nil),
|
||||
}
|
||||
|
||||
for i := range vals {
|
||||
for j := range vals {
|
||||
_ = vals[i] == vals[j] // mustn't panic
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,205 @@
|
|||
package errors_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func ExampleNew() {
|
||||
err := errors.New("whoops")
|
||||
fmt.Println(err)
|
||||
|
||||
// Output: whoops
|
||||
}
|
||||
|
||||
func ExampleNew_printf() {
|
||||
err := errors.New("whoops")
|
||||
fmt.Printf("%+v", err)
|
||||
|
||||
// Example output:
|
||||
// whoops
|
||||
// github.com/pkg/errors_test.ExampleNew_printf
|
||||
// /home/dfc/src/github.com/pkg/errors/example_test.go:17
|
||||
// testing.runExample
|
||||
// /home/dfc/go/src/testing/example.go:114
|
||||
// testing.RunExamples
|
||||
// /home/dfc/go/src/testing/example.go:38
|
||||
// testing.(*M).Run
|
||||
// /home/dfc/go/src/testing/testing.go:744
|
||||
// main.main
|
||||
// /github.com/pkg/errors/_test/_testmain.go:106
|
||||
// runtime.main
|
||||
// /home/dfc/go/src/runtime/proc.go:183
|
||||
// runtime.goexit
|
||||
// /home/dfc/go/src/runtime/asm_amd64.s:2059
|
||||
}
|
||||
|
||||
func ExampleWithMessage() {
|
||||
cause := errors.New("whoops")
|
||||
err := errors.WithMessage(cause, "oh noes")
|
||||
fmt.Println(err)
|
||||
|
||||
// Output: oh noes: whoops
|
||||
}
|
||||
|
||||
func ExampleWithStack() {
|
||||
cause := errors.New("whoops")
|
||||
err := errors.WithStack(cause)
|
||||
fmt.Println(err)
|
||||
|
||||
// Output: whoops
|
||||
}
|
||||
|
||||
func ExampleWithStack_printf() {
|
||||
cause := errors.New("whoops")
|
||||
err := errors.WithStack(cause)
|
||||
fmt.Printf("%+v", err)
|
||||
|
||||
// Example Output:
|
||||
// whoops
|
||||
// github.com/pkg/errors_test.ExampleWithStack_printf
|
||||
// /home/fabstu/go/src/github.com/pkg/errors/example_test.go:55
|
||||
// testing.runExample
|
||||
// /usr/lib/go/src/testing/example.go:114
|
||||
// testing.RunExamples
|
||||
// /usr/lib/go/src/testing/example.go:38
|
||||
// testing.(*M).Run
|
||||
// /usr/lib/go/src/testing/testing.go:744
|
||||
// main.main
|
||||
// github.com/pkg/errors/_test/_testmain.go:106
|
||||
// runtime.main
|
||||
// /usr/lib/go/src/runtime/proc.go:183
|
||||
// runtime.goexit
|
||||
// /usr/lib/go/src/runtime/asm_amd64.s:2086
|
||||
// github.com/pkg/errors_test.ExampleWithStack_printf
|
||||
// /home/fabstu/go/src/github.com/pkg/errors/example_test.go:56
|
||||
// testing.runExample
|
||||
// /usr/lib/go/src/testing/example.go:114
|
||||
// testing.RunExamples
|
||||
// /usr/lib/go/src/testing/example.go:38
|
||||
// testing.(*M).Run
|
||||
// /usr/lib/go/src/testing/testing.go:744
|
||||
// main.main
|
||||
// github.com/pkg/errors/_test/_testmain.go:106
|
||||
// runtime.main
|
||||
// /usr/lib/go/src/runtime/proc.go:183
|
||||
// runtime.goexit
|
||||
// /usr/lib/go/src/runtime/asm_amd64.s:2086
|
||||
}
|
||||
|
||||
func ExampleWrap() {
|
||||
cause := errors.New("whoops")
|
||||
err := errors.Wrap(cause, "oh noes")
|
||||
fmt.Println(err)
|
||||
|
||||
// Output: oh noes: whoops
|
||||
}
|
||||
|
||||
func fn() error {
|
||||
e1 := errors.New("error")
|
||||
e2 := errors.Wrap(e1, "inner")
|
||||
e3 := errors.Wrap(e2, "middle")
|
||||
return errors.Wrap(e3, "outer")
|
||||
}
|
||||
|
||||
func ExampleCause() {
|
||||
err := fn()
|
||||
fmt.Println(err)
|
||||
fmt.Println(errors.Cause(err))
|
||||
|
||||
// Output: outer: middle: inner: error
|
||||
// error
|
||||
}
|
||||
|
||||
func ExampleWrap_extended() {
|
||||
err := fn()
|
||||
fmt.Printf("%+v\n", err)
|
||||
|
||||
// Example output:
|
||||
// error
|
||||
// github.com/pkg/errors_test.fn
|
||||
// /home/dfc/src/github.com/pkg/errors/example_test.go:47
|
||||
// github.com/pkg/errors_test.ExampleCause_printf
|
||||
// /home/dfc/src/github.com/pkg/errors/example_test.go:63
|
||||
// testing.runExample
|
||||
// /home/dfc/go/src/testing/example.go:114
|
||||
// testing.RunExamples
|
||||
// /home/dfc/go/src/testing/example.go:38
|
||||
// testing.(*M).Run
|
||||
// /home/dfc/go/src/testing/testing.go:744
|
||||
// main.main
|
||||
// /github.com/pkg/errors/_test/_testmain.go:104
|
||||
// runtime.main
|
||||
// /home/dfc/go/src/runtime/proc.go:183
|
||||
// runtime.goexit
|
||||
// /home/dfc/go/src/runtime/asm_amd64.s:2059
|
||||
// github.com/pkg/errors_test.fn
|
||||
// /home/dfc/src/github.com/pkg/errors/example_test.go:48: inner
|
||||
// github.com/pkg/errors_test.fn
|
||||
// /home/dfc/src/github.com/pkg/errors/example_test.go:49: middle
|
||||
// github.com/pkg/errors_test.fn
|
||||
// /home/dfc/src/github.com/pkg/errors/example_test.go:50: outer
|
||||
}
|
||||
|
||||
func ExampleWrapf() {
|
||||
cause := errors.New("whoops")
|
||||
err := errors.Wrapf(cause, "oh noes #%d", 2)
|
||||
fmt.Println(err)
|
||||
|
||||
// Output: oh noes #2: whoops
|
||||
}
|
||||
|
||||
func ExampleErrorf_extended() {
|
||||
err := errors.Errorf("whoops: %s", "foo")
|
||||
fmt.Printf("%+v", err)
|
||||
|
||||
// Example output:
|
||||
// whoops: foo
|
||||
// github.com/pkg/errors_test.ExampleErrorf
|
||||
// /home/dfc/src/github.com/pkg/errors/example_test.go:101
|
||||
// testing.runExample
|
||||
// /home/dfc/go/src/testing/example.go:114
|
||||
// testing.RunExamples
|
||||
// /home/dfc/go/src/testing/example.go:38
|
||||
// testing.(*M).Run
|
||||
// /home/dfc/go/src/testing/testing.go:744
|
||||
// main.main
|
||||
// /github.com/pkg/errors/_test/_testmain.go:102
|
||||
// runtime.main
|
||||
// /home/dfc/go/src/runtime/proc.go:183
|
||||
// runtime.goexit
|
||||
// /home/dfc/go/src/runtime/asm_amd64.s:2059
|
||||
}
|
||||
|
||||
func Example_stackTrace() {
|
||||
type stackTracer interface {
|
||||
StackTrace() errors.StackTrace
|
||||
}
|
||||
|
||||
err, ok := errors.Cause(fn()).(stackTracer)
|
||||
if !ok {
|
||||
panic("oops, err does not implement stackTracer")
|
||||
}
|
||||
|
||||
st := err.StackTrace()
|
||||
fmt.Printf("%+v", st[0:2]) // top two frames
|
||||
|
||||
// Example output:
|
||||
// github.com/pkg/errors_test.fn
|
||||
// /home/dfc/src/github.com/pkg/errors/example_test.go:47
|
||||
// github.com/pkg/errors_test.Example_stackTrace
|
||||
// /home/dfc/src/github.com/pkg/errors/example_test.go:127
|
||||
}
|
||||
|
||||
func ExampleCause_printf() {
|
||||
err := errors.Wrap(func() error {
|
||||
return func() error {
|
||||
return errors.Errorf("hello %s", fmt.Sprintf("world"))
|
||||
}()
|
||||
}(), "failed")
|
||||
|
||||
fmt.Printf("%v", err)
|
||||
|
||||
// Output: failed: hello world
|
||||
}
|
|
@ -0,0 +1,535 @@
|
|||
package errors
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFormatNew(t *testing.T) {
|
||||
tests := []struct {
|
||||
error
|
||||
format string
|
||||
want string
|
||||
}{{
|
||||
New("error"),
|
||||
"%s",
|
||||
"error",
|
||||
}, {
|
||||
New("error"),
|
||||
"%v",
|
||||
"error",
|
||||
}, {
|
||||
New("error"),
|
||||
"%+v",
|
||||
"error\n" +
|
||||
"github.com/pkg/errors.TestFormatNew\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:26",
|
||||
}, {
|
||||
New("error"),
|
||||
"%q",
|
||||
`"error"`,
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatErrorf(t *testing.T) {
|
||||
tests := []struct {
|
||||
error
|
||||
format string
|
||||
want string
|
||||
}{{
|
||||
Errorf("%s", "error"),
|
||||
"%s",
|
||||
"error",
|
||||
}, {
|
||||
Errorf("%s", "error"),
|
||||
"%v",
|
||||
"error",
|
||||
}, {
|
||||
Errorf("%s", "error"),
|
||||
"%+v",
|
||||
"error\n" +
|
||||
"github.com/pkg/errors.TestFormatErrorf\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:56",
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatWrap(t *testing.T) {
|
||||
tests := []struct {
|
||||
error
|
||||
format string
|
||||
want string
|
||||
}{{
|
||||
Wrap(New("error"), "error2"),
|
||||
"%s",
|
||||
"error2: error",
|
||||
}, {
|
||||
Wrap(New("error"), "error2"),
|
||||
"%v",
|
||||
"error2: error",
|
||||
}, {
|
||||
Wrap(New("error"), "error2"),
|
||||
"%+v",
|
||||
"error\n" +
|
||||
"github.com/pkg/errors.TestFormatWrap\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:82",
|
||||
}, {
|
||||
Wrap(io.EOF, "error"),
|
||||
"%s",
|
||||
"error: EOF",
|
||||
}, {
|
||||
Wrap(io.EOF, "error"),
|
||||
"%v",
|
||||
"error: EOF",
|
||||
}, {
|
||||
Wrap(io.EOF, "error"),
|
||||
"%+v",
|
||||
"EOF\n" +
|
||||
"error\n" +
|
||||
"github.com/pkg/errors.TestFormatWrap\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:96",
|
||||
}, {
|
||||
Wrap(Wrap(io.EOF, "error1"), "error2"),
|
||||
"%+v",
|
||||
"EOF\n" +
|
||||
"error1\n" +
|
||||
"github.com/pkg/errors.TestFormatWrap\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:103\n",
|
||||
}, {
|
||||
Wrap(New("error with space"), "context"),
|
||||
"%q",
|
||||
`"context: error with space"`,
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatWrapf(t *testing.T) {
|
||||
tests := []struct {
|
||||
error
|
||||
format string
|
||||
want string
|
||||
}{{
|
||||
Wrapf(io.EOF, "error%d", 2),
|
||||
"%s",
|
||||
"error2: EOF",
|
||||
}, {
|
||||
Wrapf(io.EOF, "error%d", 2),
|
||||
"%v",
|
||||
"error2: EOF",
|
||||
}, {
|
||||
Wrapf(io.EOF, "error%d", 2),
|
||||
"%+v",
|
||||
"EOF\n" +
|
||||
"error2\n" +
|
||||
"github.com/pkg/errors.TestFormatWrapf\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:134",
|
||||
}, {
|
||||
Wrapf(New("error"), "error%d", 2),
|
||||
"%s",
|
||||
"error2: error",
|
||||
}, {
|
||||
Wrapf(New("error"), "error%d", 2),
|
||||
"%v",
|
||||
"error2: error",
|
||||
}, {
|
||||
Wrapf(New("error"), "error%d", 2),
|
||||
"%+v",
|
||||
"error\n" +
|
||||
"github.com/pkg/errors.TestFormatWrapf\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:149",
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatWithStack(t *testing.T) {
|
||||
tests := []struct {
|
||||
error
|
||||
format string
|
||||
want []string
|
||||
}{{
|
||||
WithStack(io.EOF),
|
||||
"%s",
|
||||
[]string{"EOF"},
|
||||
}, {
|
||||
WithStack(io.EOF),
|
||||
"%v",
|
||||
[]string{"EOF"},
|
||||
}, {
|
||||
WithStack(io.EOF),
|
||||
"%+v",
|
||||
[]string{"EOF",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:175"},
|
||||
}, {
|
||||
WithStack(New("error")),
|
||||
"%s",
|
||||
[]string{"error"},
|
||||
}, {
|
||||
WithStack(New("error")),
|
||||
"%v",
|
||||
[]string{"error"},
|
||||
}, {
|
||||
WithStack(New("error")),
|
||||
"%+v",
|
||||
[]string{"error",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:189",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:189"},
|
||||
}, {
|
||||
WithStack(WithStack(io.EOF)),
|
||||
"%+v",
|
||||
[]string{"EOF",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:197",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:197"},
|
||||
}, {
|
||||
WithStack(WithStack(Wrapf(io.EOF, "message"))),
|
||||
"%+v",
|
||||
[]string{"EOF",
|
||||
"message",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:205",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:205",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:205"},
|
||||
}, {
|
||||
WithStack(Errorf("error%d", 1)),
|
||||
"%+v",
|
||||
[]string{"error1",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:216",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:216"},
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatWithMessage(t *testing.T) {
|
||||
tests := []struct {
|
||||
error
|
||||
format string
|
||||
want []string
|
||||
}{{
|
||||
WithMessage(New("error"), "error2"),
|
||||
"%s",
|
||||
[]string{"error2: error"},
|
||||
}, {
|
||||
WithMessage(New("error"), "error2"),
|
||||
"%v",
|
||||
[]string{"error2: error"},
|
||||
}, {
|
||||
WithMessage(New("error"), "error2"),
|
||||
"%+v",
|
||||
[]string{
|
||||
"error",
|
||||
"github.com/pkg/errors.TestFormatWithMessage\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:244",
|
||||
"error2"},
|
||||
}, {
|
||||
WithMessage(io.EOF, "addition1"),
|
||||
"%s",
|
||||
[]string{"addition1: EOF"},
|
||||
}, {
|
||||
WithMessage(io.EOF, "addition1"),
|
||||
"%v",
|
||||
[]string{"addition1: EOF"},
|
||||
}, {
|
||||
WithMessage(io.EOF, "addition1"),
|
||||
"%+v",
|
||||
[]string{"EOF", "addition1"},
|
||||
}, {
|
||||
WithMessage(WithMessage(io.EOF, "addition1"), "addition2"),
|
||||
"%v",
|
||||
[]string{"addition2: addition1: EOF"},
|
||||
}, {
|
||||
WithMessage(WithMessage(io.EOF, "addition1"), "addition2"),
|
||||
"%+v",
|
||||
[]string{"EOF", "addition1", "addition2"},
|
||||
}, {
|
||||
Wrap(WithMessage(io.EOF, "error1"), "error2"),
|
||||
"%+v",
|
||||
[]string{"EOF", "error1", "error2",
|
||||
"github.com/pkg/errors.TestFormatWithMessage\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:272"},
|
||||
}, {
|
||||
WithMessage(Errorf("error%d", 1), "error2"),
|
||||
"%+v",
|
||||
[]string{"error1",
|
||||
"github.com/pkg/errors.TestFormatWithMessage\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:278",
|
||||
"error2"},
|
||||
}, {
|
||||
WithMessage(WithStack(io.EOF), "error"),
|
||||
"%+v",
|
||||
[]string{
|
||||
"EOF",
|
||||
"github.com/pkg/errors.TestFormatWithMessage\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:285",
|
||||
"error"},
|
||||
}, {
|
||||
WithMessage(Wrap(WithStack(io.EOF), "inside-error"), "outside-error"),
|
||||
"%+v",
|
||||
[]string{
|
||||
"EOF",
|
||||
"github.com/pkg/errors.TestFormatWithMessage\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:293",
|
||||
"inside-error",
|
||||
"github.com/pkg/errors.TestFormatWithMessage\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:293",
|
||||
"outside-error"},
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatGeneric(t *testing.T) {
|
||||
starts := []struct {
|
||||
err error
|
||||
want []string
|
||||
}{
|
||||
{New("new-error"), []string{
|
||||
"new-error",
|
||||
"github.com/pkg/errors.TestFormatGeneric\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:315"},
|
||||
}, {Errorf("errorf-error"), []string{
|
||||
"errorf-error",
|
||||
"github.com/pkg/errors.TestFormatGeneric\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:319"},
|
||||
}, {errors.New("errors-new-error"), []string{
|
||||
"errors-new-error"},
|
||||
},
|
||||
}
|
||||
|
||||
wrappers := []wrapper{
|
||||
{
|
||||
func(err error) error { return WithMessage(err, "with-message") },
|
||||
[]string{"with-message"},
|
||||
}, {
|
||||
func(err error) error { return WithStack(err) },
|
||||
[]string{
|
||||
"github.com/pkg/errors.(func·002|TestFormatGeneric.func2)\n\t" +
|
||||
".+/github.com/pkg/errors/format_test.go:333",
|
||||
},
|
||||
}, {
|
||||
func(err error) error { return Wrap(err, "wrap-error") },
|
||||
[]string{
|
||||
"wrap-error",
|
||||
"github.com/pkg/errors.(func·003|TestFormatGeneric.func3)\n\t" +
|
||||
".+/github.com/pkg/errors/format_test.go:339",
|
||||
},
|
||||
}, {
|
||||
func(err error) error { return Wrapf(err, "wrapf-error%d", 1) },
|
||||
[]string{
|
||||
"wrapf-error1",
|
||||
"github.com/pkg/errors.(func·004|TestFormatGeneric.func4)\n\t" +
|
||||
".+/github.com/pkg/errors/format_test.go:346",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for s := range starts {
|
||||
err := starts[s].err
|
||||
want := starts[s].want
|
||||
testFormatCompleteCompare(t, s, err, "%+v", want, false)
|
||||
testGenericRecursive(t, err, want, wrappers, 3)
|
||||
}
|
||||
}
|
||||
|
||||
func testFormatRegexp(t *testing.T, n int, arg interface{}, format, want string) {
|
||||
got := fmt.Sprintf(format, arg)
|
||||
gotLines := strings.SplitN(got, "\n", -1)
|
||||
wantLines := strings.SplitN(want, "\n", -1)
|
||||
|
||||
if len(wantLines) > len(gotLines) {
|
||||
t.Errorf("test %d: wantLines(%d) > gotLines(%d):\n got: %q\nwant: %q", n+1, len(wantLines), len(gotLines), got, want)
|
||||
return
|
||||
}
|
||||
|
||||
for i, w := range wantLines {
|
||||
match, err := regexp.MatchString(w, gotLines[i])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !match {
|
||||
t.Errorf("test %d: line %d: fmt.Sprintf(%q, err):\n got: %q\nwant: %q", n+1, i+1, format, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var stackLineR = regexp.MustCompile(`\.`)
|
||||
|
||||
// parseBlocks parses input into a slice, where:
|
||||
// - incase entry contains a newline, its a stacktrace
|
||||
// - incase entry contains no newline, its a solo line.
|
||||
//
|
||||
// Detecting stack boundaries only works incase the WithStack-calls are
|
||||
// to be found on the same line, thats why it is optionally here.
|
||||
//
|
||||
// Example use:
|
||||
//
|
||||
// for _, e := range blocks {
|
||||
// if strings.ContainsAny(e, "\n") {
|
||||
// // Match as stack
|
||||
// } else {
|
||||
// // Match as line
|
||||
// }
|
||||
// }
|
||||
//
|
||||
func parseBlocks(input string, detectStackboundaries bool) ([]string, error) {
|
||||
var blocks []string
|
||||
|
||||
stack := ""
|
||||
wasStack := false
|
||||
lines := map[string]bool{} // already found lines
|
||||
|
||||
for _, l := range strings.Split(input, "\n") {
|
||||
isStackLine := stackLineR.MatchString(l)
|
||||
|
||||
switch {
|
||||
case !isStackLine && wasStack:
|
||||
blocks = append(blocks, stack, l)
|
||||
stack = ""
|
||||
lines = map[string]bool{}
|
||||
case isStackLine:
|
||||
if wasStack {
|
||||
// Detecting two stacks after another, possible cause lines match in
|
||||
// our tests due to WithStack(WithStack(io.EOF)) on same line.
|
||||
if detectStackboundaries {
|
||||
if lines[l] {
|
||||
if len(stack) == 0 {
|
||||
return nil, errors.New("len of block must not be zero here")
|
||||
}
|
||||
|
||||
blocks = append(blocks, stack)
|
||||
stack = l
|
||||
lines = map[string]bool{l: true}
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
stack = stack + "\n" + l
|
||||
} else {
|
||||
stack = l
|
||||
}
|
||||
lines[l] = true
|
||||
case !isStackLine && !wasStack:
|
||||
blocks = append(blocks, l)
|
||||
default:
|
||||
return nil, errors.New("must not happen")
|
||||
}
|
||||
|
||||
wasStack = isStackLine
|
||||
}
|
||||
|
||||
// Use up stack
|
||||
if stack != "" {
|
||||
blocks = append(blocks, stack)
|
||||
}
|
||||
return blocks, nil
|
||||
}
|
||||
|
||||
func testFormatCompleteCompare(t *testing.T, n int, arg interface{}, format string, want []string, detectStackBoundaries bool) {
|
||||
gotStr := fmt.Sprintf(format, arg)
|
||||
|
||||
got, err := parseBlocks(gotStr, detectStackBoundaries)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("test %d: fmt.Sprintf(%s, err) -> wrong number of blocks: got(%d) want(%d)\n got: %s\nwant: %s\ngotStr: %q",
|
||||
n+1, format, len(got), len(want), prettyBlocks(got), prettyBlocks(want), gotStr)
|
||||
}
|
||||
|
||||
for i := range got {
|
||||
if strings.ContainsAny(want[i], "\n") {
|
||||
// Match as stack
|
||||
match, err := regexp.MatchString(want[i], got[i])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !match {
|
||||
t.Fatalf("test %d: block %d: fmt.Sprintf(%q, err):\ngot:\n%q\nwant:\n%q\nall-got:\n%s\nall-want:\n%s\n",
|
||||
n+1, i+1, format, got[i], want[i], prettyBlocks(got), prettyBlocks(want))
|
||||
}
|
||||
} else {
|
||||
// Match as message
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("test %d: fmt.Sprintf(%s, err) at block %d got != want:\n got: %q\nwant: %q", n+1, format, i+1, got[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type wrapper struct {
|
||||
wrap func(err error) error
|
||||
want []string
|
||||
}
|
||||
|
||||
func prettyBlocks(blocks []string, prefix ...string) string {
|
||||
var out []string
|
||||
|
||||
for _, b := range blocks {
|
||||
out = append(out, fmt.Sprintf("%v", b))
|
||||
}
|
||||
|
||||
return " " + strings.Join(out, "\n ")
|
||||
}
|
||||
|
||||
func testGenericRecursive(t *testing.T, beforeErr error, beforeWant []string, list []wrapper, maxDepth int) {
|
||||
if len(beforeWant) == 0 {
|
||||
panic("beforeWant must not be empty")
|
||||
}
|
||||
for _, w := range list {
|
||||
if len(w.want) == 0 {
|
||||
panic("want must not be empty")
|
||||
}
|
||||
|
||||
err := w.wrap(beforeErr)
|
||||
|
||||
// Copy required cause append(beforeWant, ..) modified beforeWant subtly.
|
||||
beforeCopy := make([]string, len(beforeWant))
|
||||
copy(beforeCopy, beforeWant)
|
||||
|
||||
beforeWant := beforeCopy
|
||||
last := len(beforeWant) - 1
|
||||
var want []string
|
||||
|
||||
// Merge two stacks behind each other.
|
||||
if strings.ContainsAny(beforeWant[last], "\n") && strings.ContainsAny(w.want[0], "\n") {
|
||||
want = append(beforeWant[:last], append([]string{beforeWant[last] + "((?s).*)" + w.want[0]}, w.want[1:]...)...)
|
||||
} else {
|
||||
want = append(beforeWant, w.want...)
|
||||
}
|
||||
|
||||
testFormatCompleteCompare(t, maxDepth, err, "%+v", want, false)
|
||||
if maxDepth > 0 {
|
||||
testGenericRecursive(t, err, want, list, maxDepth-1)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,178 @@
|
|||
package errors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"path"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Frame represents a program counter inside a stack frame.
|
||||
type Frame uintptr
|
||||
|
||||
// pc returns the program counter for this frame;
|
||||
// multiple frames may have the same PC value.
|
||||
func (f Frame) pc() uintptr { return uintptr(f) - 1 }
|
||||
|
||||
// file returns the full path to the file that contains the
|
||||
// function for this Frame's pc.
|
||||
func (f Frame) file() string {
|
||||
fn := runtime.FuncForPC(f.pc())
|
||||
if fn == nil {
|
||||
return "unknown"
|
||||
}
|
||||
file, _ := fn.FileLine(f.pc())
|
||||
return file
|
||||
}
|
||||
|
||||
// line returns the line number of source code of the
|
||||
// function for this Frame's pc.
|
||||
func (f Frame) line() int {
|
||||
fn := runtime.FuncForPC(f.pc())
|
||||
if fn == nil {
|
||||
return 0
|
||||
}
|
||||
_, line := fn.FileLine(f.pc())
|
||||
return line
|
||||
}
|
||||
|
||||
// Format formats the frame according to the fmt.Formatter interface.
|
||||
//
|
||||
// %s source file
|
||||
// %d source line
|
||||
// %n function name
|
||||
// %v equivalent to %s:%d
|
||||
//
|
||||
// Format accepts flags that alter the printing of some verbs, as follows:
|
||||
//
|
||||
// %+s path of source file relative to the compile time GOPATH
|
||||
// %+v equivalent to %+s:%d
|
||||
func (f Frame) Format(s fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 's':
|
||||
switch {
|
||||
case s.Flag('+'):
|
||||
pc := f.pc()
|
||||
fn := runtime.FuncForPC(pc)
|
||||
if fn == nil {
|
||||
io.WriteString(s, "unknown")
|
||||
} else {
|
||||
file, _ := fn.FileLine(pc)
|
||||
fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file)
|
||||
}
|
||||
default:
|
||||
io.WriteString(s, path.Base(f.file()))
|
||||
}
|
||||
case 'd':
|
||||
fmt.Fprintf(s, "%d", f.line())
|
||||
case 'n':
|
||||
name := runtime.FuncForPC(f.pc()).Name()
|
||||
io.WriteString(s, funcname(name))
|
||||
case 'v':
|
||||
f.Format(s, 's')
|
||||
io.WriteString(s, ":")
|
||||
f.Format(s, 'd')
|
||||
}
|
||||
}
|
||||
|
||||
// StackTrace is stack of Frames from innermost (newest) to outermost (oldest).
|
||||
type StackTrace []Frame
|
||||
|
||||
func (st StackTrace) Format(s fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 'v':
|
||||
switch {
|
||||
case s.Flag('+'):
|
||||
for _, f := range st {
|
||||
fmt.Fprintf(s, "\n%+v", f)
|
||||
}
|
||||
case s.Flag('#'):
|
||||
fmt.Fprintf(s, "%#v", []Frame(st))
|
||||
default:
|
||||
fmt.Fprintf(s, "%v", []Frame(st))
|
||||
}
|
||||
case 's':
|
||||
fmt.Fprintf(s, "%s", []Frame(st))
|
||||
}
|
||||
}
|
||||
|
||||
// stack represents a stack of program counters.
|
||||
type stack []uintptr
|
||||
|
||||
func (s *stack) Format(st fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 'v':
|
||||
switch {
|
||||
case st.Flag('+'):
|
||||
for _, pc := range *s {
|
||||
f := Frame(pc)
|
||||
fmt.Fprintf(st, "\n%+v", f)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stack) StackTrace() StackTrace {
|
||||
f := make([]Frame, len(*s))
|
||||
for i := 0; i < len(f); i++ {
|
||||
f[i] = Frame((*s)[i])
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func callers() *stack {
|
||||
const depth = 32
|
||||
var pcs [depth]uintptr
|
||||
n := runtime.Callers(3, pcs[:])
|
||||
var st stack = pcs[0:n]
|
||||
return &st
|
||||
}
|
||||
|
||||
// funcname removes the path prefix component of a function's name reported by func.Name().
|
||||
func funcname(name string) string {
|
||||
i := strings.LastIndex(name, "/")
|
||||
name = name[i+1:]
|
||||
i = strings.Index(name, ".")
|
||||
return name[i+1:]
|
||||
}
|
||||
|
||||
func trimGOPATH(name, file string) string {
|
||||
// Here we want to get the source file path relative to the compile time
|
||||
// GOPATH. As of Go 1.6.x there is no direct way to know the compiled
|
||||
// GOPATH at runtime, but we can infer the number of path segments in the
|
||||
// GOPATH. We note that fn.Name() returns the function name qualified by
|
||||
// the import path, which does not include the GOPATH. Thus we can trim
|
||||
// segments from the beginning of the file path until the number of path
|
||||
// separators remaining is one more than the number of path separators in
|
||||
// the function name. For example, given:
|
||||
//
|
||||
// GOPATH /home/user
|
||||
// file /home/user/src/pkg/sub/file.go
|
||||
// fn.Name() pkg/sub.Type.Method
|
||||
//
|
||||
// We want to produce:
|
||||
//
|
||||
// pkg/sub/file.go
|
||||
//
|
||||
// From this we can easily see that fn.Name() has one less path separator
|
||||
// than our desired output. We count separators from the end of the file
|
||||
// path until it finds two more than in the function name and then move
|
||||
// one character forward to preserve the initial path segment without a
|
||||
// leading separator.
|
||||
const sep = "/"
|
||||
goal := strings.Count(name, sep) + 2
|
||||
i := len(file)
|
||||
for n := 0; n < goal; n++ {
|
||||
i = strings.LastIndex(file[:i], sep)
|
||||
if i == -1 {
|
||||
// not enough separators found, set i so that the slice expression
|
||||
// below leaves file unmodified
|
||||
i = -len(sep)
|
||||
break
|
||||
}
|
||||
}
|
||||
// get back to 0 or trim the leading separator
|
||||
file = file[i+len(sep):]
|
||||
return file
|
||||
}
|
|
@ -0,0 +1,292 @@
|
|||
package errors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var initpc, _, _, _ = runtime.Caller(0)
|
||||
|
||||
func TestFrameLine(t *testing.T) {
|
||||
var tests = []struct {
|
||||
Frame
|
||||
want int
|
||||
}{{
|
||||
Frame(initpc),
|
||||
9,
|
||||
}, {
|
||||
func() Frame {
|
||||
var pc, _, _, _ = runtime.Caller(0)
|
||||
return Frame(pc)
|
||||
}(),
|
||||
20,
|
||||
}, {
|
||||
func() Frame {
|
||||
var pc, _, _, _ = runtime.Caller(1)
|
||||
return Frame(pc)
|
||||
}(),
|
||||
28,
|
||||
}, {
|
||||
Frame(0), // invalid PC
|
||||
0,
|
||||
}}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := tt.Frame.line()
|
||||
want := tt.want
|
||||
if want != got {
|
||||
t.Errorf("Frame(%v): want: %v, got: %v", uintptr(tt.Frame), want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type X struct{}
|
||||
|
||||
func (x X) val() Frame {
|
||||
var pc, _, _, _ = runtime.Caller(0)
|
||||
return Frame(pc)
|
||||
}
|
||||
|
||||
func (x *X) ptr() Frame {
|
||||
var pc, _, _, _ = runtime.Caller(0)
|
||||
return Frame(pc)
|
||||
}
|
||||
|
||||
func TestFrameFormat(t *testing.T) {
|
||||
var tests = []struct {
|
||||
Frame
|
||||
format string
|
||||
want string
|
||||
}{{
|
||||
Frame(initpc),
|
||||
"%s",
|
||||
"stack_test.go",
|
||||
}, {
|
||||
Frame(initpc),
|
||||
"%+s",
|
||||
"github.com/pkg/errors.init\n" +
|
||||
"\t.+/github.com/pkg/errors/stack_test.go",
|
||||
}, {
|
||||
Frame(0),
|
||||
"%s",
|
||||
"unknown",
|
||||
}, {
|
||||
Frame(0),
|
||||
"%+s",
|
||||
"unknown",
|
||||
}, {
|
||||
Frame(initpc),
|
||||
"%d",
|
||||
"9",
|
||||
}, {
|
||||
Frame(0),
|
||||
"%d",
|
||||
"0",
|
||||
}, {
|
||||
Frame(initpc),
|
||||
"%n",
|
||||
"init",
|
||||
}, {
|
||||
func() Frame {
|
||||
var x X
|
||||
return x.ptr()
|
||||
}(),
|
||||
"%n",
|
||||
`\(\*X\).ptr`,
|
||||
}, {
|
||||
func() Frame {
|
||||
var x X
|
||||
return x.val()
|
||||
}(),
|
||||
"%n",
|
||||
"X.val",
|
||||
}, {
|
||||
Frame(0),
|
||||
"%n",
|
||||
"",
|
||||
}, {
|
||||
Frame(initpc),
|
||||
"%v",
|
||||
"stack_test.go:9",
|
||||
}, {
|
||||
Frame(initpc),
|
||||
"%+v",
|
||||
"github.com/pkg/errors.init\n" +
|
||||
"\t.+/github.com/pkg/errors/stack_test.go:9",
|
||||
}, {
|
||||
Frame(0),
|
||||
"%v",
|
||||
"unknown:0",
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
testFormatRegexp(t, i, tt.Frame, tt.format, tt.want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFuncname(t *testing.T) {
|
||||
tests := []struct {
|
||||
name, want string
|
||||
}{
|
||||
{"", ""},
|
||||
{"runtime.main", "main"},
|
||||
{"github.com/pkg/errors.funcname", "funcname"},
|
||||
{"funcname", "funcname"},
|
||||
{"io.copyBuffer", "copyBuffer"},
|
||||
{"main.(*R).Write", "(*R).Write"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := funcname(tt.name)
|
||||
want := tt.want
|
||||
if got != want {
|
||||
t.Errorf("funcname(%q): want: %q, got %q", tt.name, want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrimGOPATH(t *testing.T) {
|
||||
var tests = []struct {
|
||||
Frame
|
||||
want string
|
||||
}{{
|
||||
Frame(initpc),
|
||||
"github.com/pkg/errors/stack_test.go",
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
pc := tt.Frame.pc()
|
||||
fn := runtime.FuncForPC(pc)
|
||||
file, _ := fn.FileLine(pc)
|
||||
got := trimGOPATH(fn.Name(), file)
|
||||
testFormatRegexp(t, i, got, "%s", tt.want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStackTrace(t *testing.T) {
|
||||
tests := []struct {
|
||||
err error
|
||||
want []string
|
||||
}{{
|
||||
New("ooh"), []string{
|
||||
"github.com/pkg/errors.TestStackTrace\n" +
|
||||
"\t.+/github.com/pkg/errors/stack_test.go:172",
|
||||
},
|
||||
}, {
|
||||
Wrap(New("ooh"), "ahh"), []string{
|
||||
"github.com/pkg/errors.TestStackTrace\n" +
|
||||
"\t.+/github.com/pkg/errors/stack_test.go:177", // this is the stack of Wrap, not New
|
||||
},
|
||||
}, {
|
||||
Cause(Wrap(New("ooh"), "ahh")), []string{
|
||||
"github.com/pkg/errors.TestStackTrace\n" +
|
||||
"\t.+/github.com/pkg/errors/stack_test.go:182", // this is the stack of New
|
||||
},
|
||||
}, {
|
||||
func() error { return New("ooh") }(), []string{
|
||||
`github.com/pkg/errors.(func·009|TestStackTrace.func1)` +
|
||||
"\n\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New
|
||||
"github.com/pkg/errors.TestStackTrace\n" +
|
||||
"\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New's caller
|
||||
},
|
||||
}, {
|
||||
Cause(func() error {
|
||||
return func() error {
|
||||
return Errorf("hello %s", fmt.Sprintf("world"))
|
||||
}()
|
||||
}()), []string{
|
||||
`github.com/pkg/errors.(func·010|TestStackTrace.func2.1)` +
|
||||
"\n\t.+/github.com/pkg/errors/stack_test.go:196", // this is the stack of Errorf
|
||||
`github.com/pkg/errors.(func·011|TestStackTrace.func2)` +
|
||||
"\n\t.+/github.com/pkg/errors/stack_test.go:197", // this is the stack of Errorf's caller
|
||||
"github.com/pkg/errors.TestStackTrace\n" +
|
||||
"\t.+/github.com/pkg/errors/stack_test.go:198", // this is the stack of Errorf's caller's caller
|
||||
},
|
||||
}}
|
||||
for i, tt := range tests {
|
||||
x, ok := tt.err.(interface {
|
||||
StackTrace() StackTrace
|
||||
})
|
||||
if !ok {
|
||||
t.Errorf("expected %#v to implement StackTrace() StackTrace", tt.err)
|
||||
continue
|
||||
}
|
||||
st := x.StackTrace()
|
||||
for j, want := range tt.want {
|
||||
testFormatRegexp(t, i, st[j], "%+v", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func stackTrace() StackTrace {
|
||||
const depth = 8
|
||||
var pcs [depth]uintptr
|
||||
n := runtime.Callers(1, pcs[:])
|
||||
var st stack = pcs[0:n]
|
||||
return st.StackTrace()
|
||||
}
|
||||
|
||||
func TestStackTraceFormat(t *testing.T) {
|
||||
tests := []struct {
|
||||
StackTrace
|
||||
format string
|
||||
want string
|
||||
}{{
|
||||
nil,
|
||||
"%s",
|
||||
`\[\]`,
|
||||
}, {
|
||||
nil,
|
||||
"%v",
|
||||
`\[\]`,
|
||||
}, {
|
||||
nil,
|
||||
"%+v",
|
||||
"",
|
||||
}, {
|
||||
nil,
|
||||
"%#v",
|
||||
`\[\]errors.Frame\(nil\)`,
|
||||
}, {
|
||||
make(StackTrace, 0),
|
||||
"%s",
|
||||
`\[\]`,
|
||||
}, {
|
||||
make(StackTrace, 0),
|
||||
"%v",
|
||||
`\[\]`,
|
||||
}, {
|
||||
make(StackTrace, 0),
|
||||
"%+v",
|
||||
"",
|
||||
}, {
|
||||
make(StackTrace, 0),
|
||||
"%#v",
|
||||
`\[\]errors.Frame{}`,
|
||||
}, {
|
||||
stackTrace()[:2],
|
||||
"%s",
|
||||
`\[stack_test.go stack_test.go\]`,
|
||||
}, {
|
||||
stackTrace()[:2],
|
||||
"%v",
|
||||
`\[stack_test.go:225 stack_test.go:272\]`,
|
||||
}, {
|
||||
stackTrace()[:2],
|
||||
"%+v",
|
||||
"\n" +
|
||||
"github.com/pkg/errors.stackTrace\n" +
|
||||
"\t.+/github.com/pkg/errors/stack_test.go:225\n" +
|
||||
"github.com/pkg/errors.TestStackTraceFormat\n" +
|
||||
"\t.+/github.com/pkg/errors/stack_test.go:276",
|
||||
}, {
|
||||
stackTrace()[:2],
|
||||
"%#v",
|
||||
`\[\]errors.Frame{stack_test.go:225, stack_test.go:284}`,
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
testFormatRegexp(t, i, tt.StackTrace, tt.format, tt.want)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
// From GitHub version/fork maintained by Stephen Paul Weber available at:
|
||||
// https://github.com/singpolyma/mnemonicode
|
||||
//
|
||||
// Originally from:
|
||||
// http://web.archive.org/web/20101031205747/http://www.tothink.com/mnemonic/
|
||||
|
||||
/*
|
||||
Copyright (c) 2000 Oren Tirosh <oren@hishome.net>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
|
@ -0,0 +1,118 @@
|
|||
Mnemonicode
|
||||
===========
|
||||
|
||||
Mnemonicode is a method for encoding binary data into a sequence
|
||||
of words which can be spoken over the phone, for example, and converted
|
||||
back to data on the other side.
|
||||
|
||||
[![GoDoc](https://godoc.org/bitbucket.org/dchapes/mnemonicode?status.png)](https://godoc.org/bitbucket.org/dchapes/mnemonicode)
|
||||
|
||||
Online package documentation is available via
|
||||
[https://godoc.org/bitbucket.org/dchapes/mnemonicode](https://godoc.org/bitbucket.org/dchapes/mnemonicode).
|
||||
|
||||
To install the package:
|
||||
|
||||
go get bitbucket.org/dchapes/mnemonicode
|
||||
|
||||
or the command line programs:
|
||||
|
||||
go get bitbucket.org/dchapes/mnemonicode/cmd/...
|
||||
|
||||
or `go build` any Go code that imports it:
|
||||
|
||||
import "bitbucket.org/dchapes/mnemonicode"
|
||||
|
||||
For more information see
|
||||
<https://github.com/singpolyma/mnemonicode>
|
||||
or
|
||||
<http://web.archive.org/web/20101031205747/http://www.tothink.com/mnemonic/>
|
||||
|
||||
From the README there:
|
||||
|
||||
There are some other somewhat similar systems that seem less satisfactory:
|
||||
|
||||
- OTP was designed for easy typing, and for minimizing length, but as
|
||||
a consequence the word list contains words that are similar ("AD"
|
||||
and "ADD") that are poor for dictating over the phone
|
||||
|
||||
- PGPfone has optimized "maximum phonetic distance" between words,
|
||||
which resolves the above problem but has some other drawbacks:
|
||||
|
||||
- Low efficiency, as it encodes a little less than 1 bit per
|
||||
character;
|
||||
|
||||
- Word quality issues, as some words are somewhat obscure to
|
||||
non-native speakers of English, or are awkward to use or type.
|
||||
|
||||
Mnemonic tries to do better by being more selective about its word
|
||||
list. Its criteria are thus:
|
||||
|
||||
Mandatory Criteria:
|
||||
|
||||
- The wordlist contains 1626 words.
|
||||
|
||||
- All words are between 4 and 7 letters long.
|
||||
|
||||
- No word in the list is a prefix of another word (e.g. visit,
|
||||
visitor).
|
||||
|
||||
- Five letter prefixes of words are sufficient to be unique.
|
||||
|
||||
Less Strict Criteria:
|
||||
|
||||
- The words should be usable by people all over the world. The list
|
||||
is far from perfect in that respect. It is heavily biased towards
|
||||
western culture and English in particular. The international
|
||||
vocabulary is simply not big enough. One can argue that even words
|
||||
like "hotel" or "radio" are not truly international. You will find
|
||||
many English words in the list but I have tried to limit them to
|
||||
words that are part of a beginner's vocabulary or words that have
|
||||
close relatives in other european languages. In some cases a word
|
||||
has a different meaning in another language or is pronounced very
|
||||
differently but for the purpose of the encoding it is still ok - I
|
||||
assume that when the encoding is used for spoken communication
|
||||
both sides speak the same language.
|
||||
|
||||
- The words should have more than one syllable. This makes them
|
||||
easier to recognize when spoken, especially over a phone
|
||||
line. Again, you will find many exceptions. For one syllable words
|
||||
I have tried to use words with 3 or more consonants or words with
|
||||
diphthongs, making for a longer and more distinct
|
||||
pronounciation. As a result of this requirement the average word
|
||||
length has increased. I do not consider this to be a problem since
|
||||
my goal in limiting the word length was not to reduce the average
|
||||
length of encoded data but to limit the maximum length to fit in
|
||||
fixed-size fields or a terminal line width.
|
||||
|
||||
- No two words on the list should sound too much alike. Soundalikes
|
||||
such as "sweet" and "suite" are ruled out. One of the two is
|
||||
chosen and the other should be accepted by the decoder's
|
||||
soundalike matching code or using explicit aliases for some words.
|
||||
|
||||
- No offensive words. The rule was to avoid words that I would not
|
||||
like to be printed on my business card. I have extended this to
|
||||
words that by themselves are not offensive but are too likely to
|
||||
create combinations that someone may find embarrassing or
|
||||
offensive. This includes words dealing with religion such as
|
||||
"church" or "jewish" and some words with negative meanings like
|
||||
"problem" or "fiasco". I am sure that a creative mind (or a random
|
||||
number generator) can find plenty of embarrasing or offensive word
|
||||
combinations using only words in the list but I have tried to
|
||||
avoid the more obvious ones. One of my tools for this was simply a
|
||||
generator of random word combinations - the problematic ones stick
|
||||
out like a sore thumb.
|
||||
|
||||
- Avoid words with tricky spelling or pronounciation. Even if the
|
||||
receiver of the message can probably spell the word close enough
|
||||
for the soundalike matcher to recognize it correctly I prefer
|
||||
avoiding such words. I believe this will help users feel more
|
||||
comfortable using the system, increase the level of confidence and
|
||||
decrease the overall error rate. Most words in the list can be
|
||||
spelled more or less correctly from hearing, even without knowing
|
||||
the word.
|
||||
|
||||
- The word should feel right for the job. I know, this one is very
|
||||
subjective but some words would meet all the criteria and still
|
||||
not feel right for the purpose of mnemonic encoding. The word
|
||||
should feel like one of the words in the radio phonetic alphabets
|
||||
(alpha, bravo, charlie, delta etc).
|
|
@ -0,0 +1,38 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"io"
|
||||
)
|
||||
|
||||
const bufsize = 256
|
||||
|
||||
type hexdump struct {
|
||||
w io.Writer
|
||||
buf [bufsize]byte
|
||||
}
|
||||
|
||||
func hexoutput(w io.Writer) io.WriteCloser {
|
||||
return &hexdump{w: w}
|
||||
}
|
||||
|
||||
func (h *hexdump) Write(data []byte) (n int, err error) {
|
||||
for n < len(data) {
|
||||
amt := len(data) - n
|
||||
if hex.EncodedLen(amt) > bufsize {
|
||||
amt = hex.DecodedLen(bufsize)
|
||||
}
|
||||
nn := hex.Encode(h.buf[:], data[n:n+amt])
|
||||
_, err := h.w.Write(h.buf[:nn])
|
||||
n += amt
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (h *hexdump) Close() error {
|
||||
_, err := h.w.Write([]byte{'\n'})
|
||||
return err
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path"
|
||||
|
||||
"bitbucket.org/dchapes/mnemonicode"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log.SetFlags(0)
|
||||
log.SetPrefix(path.Base(os.Args[0]) + ": ")
|
||||
hexFlag := flag.Bool("x", false, "hex output")
|
||||
verboseFlag := flag.Bool("v", false, "verbose")
|
||||
flag.Parse()
|
||||
if flag.NArg() > 0 {
|
||||
flag.Usage()
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
output := io.WriteCloser(os.Stdout)
|
||||
if *hexFlag {
|
||||
output = hexoutput(output)
|
||||
}
|
||||
|
||||
var n int64
|
||||
var err error
|
||||
if true {
|
||||
dec := mnemonicode.NewDecoder(os.Stdin)
|
||||
n, err = io.Copy(output, dec)
|
||||
} else {
|
||||
w := mnemonicode.NewDecodeWriter(output)
|
||||
n, err = io.Copy(w, os.Stdin)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
err = w.Close()
|
||||
}
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if *verboseFlag {
|
||||
log.Println("bytes decoded:", n)
|
||||
}
|
||||
if err = output.Close(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/text/transform"
|
||||
)
|
||||
|
||||
type hexinput bool
|
||||
|
||||
func (h *hexinput) Reset() {
|
||||
*h = false
|
||||
}
|
||||
|
||||
func (h *hexinput) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
|
||||
for r, sz := rune(0), 0; len(src) > 0; src = src[sz:] {
|
||||
if r = rune(src[0]); r < utf8.RuneSelf {
|
||||
sz = 1
|
||||
} else {
|
||||
r, sz = utf8.DecodeRune(src)
|
||||
if sz == 1 {
|
||||
// Invalid rune.
|
||||
if !atEOF && !utf8.FullRune(src) {
|
||||
err = transform.ErrShortSrc
|
||||
break
|
||||
}
|
||||
// Just ignore it
|
||||
nSrc++
|
||||
continue
|
||||
}
|
||||
}
|
||||
if unicode.IsSpace(r) {
|
||||
nSrc += sz
|
||||
continue
|
||||
}
|
||||
if sz > 1 {
|
||||
err = hex.InvalidByteError(src[0]) // XXX
|
||||
break
|
||||
}
|
||||
if len(src) < 2 {
|
||||
err = transform.ErrShortSrc
|
||||
break
|
||||
}
|
||||
if nDst+1 > len(dst) {
|
||||
err = transform.ErrShortDst
|
||||
break
|
||||
}
|
||||
|
||||
sz = 2
|
||||
nSrc += 2
|
||||
if !*h {
|
||||
*h = true
|
||||
if r == '0' && (src[1] == 'x' || src[1] == 'X') {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if _, err = hex.Decode(dst[nDst:], src[:2]); err != nil {
|
||||
break
|
||||
}
|
||||
nDst++
|
||||
}
|
||||
return
|
||||
}
|
|
@ -0,0 +1,118 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
|
||||
"golang.org/x/text/transform"
|
||||
|
||||
"bitbucket.org/dchapes/mnemonicode"
|
||||
)
|
||||
|
||||
type quoted string
|
||||
|
||||
func (q quoted) Get() interface{} { return string(q) }
|
||||
func (q quoted) String() string { return strconv.Quote(string(q)) }
|
||||
func (q *quoted) Set(s string) (err error) {
|
||||
if s, err = strconv.Unquote(`"` + s + `"`); err == nil {
|
||||
*q = quoted(s)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type quotedRune rune
|
||||
|
||||
func (qr quotedRune) Get() interface{} { return rune(qr) }
|
||||
func (qr quotedRune) String() string { return strconv.QuoteRune(rune(qr)) }
|
||||
func (qr *quotedRune) Set(s string) error {
|
||||
r, _, x, err := strconv.UnquoteChar(s, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if x != "" {
|
||||
return fmt.Errorf("more than a single rune")
|
||||
}
|
||||
*qr = quotedRune(r)
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
log.SetFlags(0)
|
||||
log.SetPrefix(path.Base(os.Args[0]) + ": ")
|
||||
vlog := log.New(os.Stderr, log.Prefix(), log.Flags())
|
||||
|
||||
config := mnemonicode.NewDefaultConfig()
|
||||
prefix := quoted(config.LinePrefix)
|
||||
suffix := quoted(config.LineSuffix)
|
||||
wordsep := quoted(config.WordSeparator)
|
||||
groupsep := quoted(config.GroupSeparator)
|
||||
pad := quotedRune(config.WordPadding)
|
||||
|
||||
flag.Var(&prefix, "prefix", "prefix each line with `string`")
|
||||
flag.Var(&suffix, "suffix", "suffix each line with `string`")
|
||||
flag.Var(&wordsep, "word", "separate each word with `wsep`")
|
||||
flag.Var(&groupsep, "group", "separate each word group with `gsep`")
|
||||
words := flag.Uint("words", config.WordsPerGroup, "words per group")
|
||||
groups := flag.Uint("groups", config.GroupsPerLine, "groups per line")
|
||||
nopad := flag.Bool("nopad", false, "do not pad words")
|
||||
flag.Var(&pad, "pad", "pad shorter words with `rune`")
|
||||
hexin := flag.Bool("x", false, "hex input")
|
||||
verbose := flag.Bool("v", false, "verbose")
|
||||
|
||||
flag.Parse()
|
||||
if flag.NArg() > 0 {
|
||||
flag.Usage()
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
if !*verbose {
|
||||
vlog.SetOutput(ioutil.Discard)
|
||||
}
|
||||
|
||||
config.LinePrefix = prefix.Get().(string)
|
||||
config.LineSuffix = suffix.Get().(string)
|
||||
config.GroupSeparator = groupsep.Get().(string)
|
||||
config.WordSeparator = wordsep.Get().(string)
|
||||
config.WordPadding = pad.Get().(rune)
|
||||
if *words > 0 {
|
||||
config.WordsPerGroup = *words
|
||||
}
|
||||
if *groups > 0 {
|
||||
config.GroupsPerLine = *groups
|
||||
}
|
||||
if *nopad {
|
||||
config.WordPadding = 0
|
||||
}
|
||||
|
||||
vlog.Println("Wordlist ver", mnemonicode.WordListVersion)
|
||||
|
||||
input := io.Reader(os.Stdin)
|
||||
if *hexin {
|
||||
input = transform.NewReader(input, new(hexinput))
|
||||
}
|
||||
|
||||
var n int64
|
||||
var err error
|
||||
if true {
|
||||
enc := mnemonicode.NewEncoder(os.Stdout, config)
|
||||
n, err = io.Copy(enc, input)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
err = enc.Close()
|
||||
} else {
|
||||
r := mnemonicode.NewEncodeReader(input, config)
|
||||
n, err = io.Copy(os.Stdout, r)
|
||||
}
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Println()
|
||||
vlog.Println("bytes encoded:", n)
|
||||
}
|
|
@ -0,0 +1,70 @@
|
|||
// For use with go-fuzz, "github.com/dvyukov/go-fuzz"
|
||||
//
|
||||
// +build gofuzz
|
||||
|
||||
package mnemonicode
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
|
||||
"golang.org/x/text/transform"
|
||||
)
|
||||
|
||||
var (
|
||||
tenc = NewEncodeTransformer(nil)
|
||||
tdec = NewDecodeTransformer()
|
||||
tencdec = transform.Chain(tenc, tdec)
|
||||
)
|
||||
|
||||
//go:generate go-fuzz-build bitbucket.org/dchapes/mnemonicode
|
||||
// Then:
|
||||
// go-fuzz -bin=mnemonicode-fuzz.zip -workdir=fuzz
|
||||
|
||||
// Fuzz is for use with go-fuzz, "github.com/dvyukov/go-fuzz"
|
||||
func Fuzz(data []byte) int {
|
||||
words := EncodeWordList(nil, data)
|
||||
if len(words) != WordsRequired(len(data)) {
|
||||
panic("bad WordsRequired result")
|
||||
}
|
||||
data2, err := DecodeWordList(nil, words)
|
||||
if err != nil {
|
||||
fmt.Println("words:", words)
|
||||
panic(err)
|
||||
}
|
||||
if !bytes.Equal(data, data2) {
|
||||
fmt.Println("words:", words)
|
||||
panic("data != data2")
|
||||
}
|
||||
|
||||
data3, _, err := transform.Bytes(tencdec, data)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if !bytes.Equal(data, data3) {
|
||||
fmt.Println("words:", words)
|
||||
panic("data != data3")
|
||||
}
|
||||
|
||||
if len(data) == 0 {
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
//go:generate go-fuzz-build -func Fuzz2 -o mnemonicode-fuzz2.zip bitbucket.org/dchapes/mnemonicode
|
||||
// Then:
|
||||
// go-fuzz -bin=mnemonicode-fuzz2.zip -workdir=fuzz2
|
||||
|
||||
// Fuzz2 is another fuzz tester, this time with words as input rather than binary data.
|
||||
func Fuzz2(data []byte) int {
|
||||
_, _, err := transform.Bytes(tdec, data)
|
||||
if err != nil {
|
||||
if _, ok := err.(WordError); !ok {
|
||||
return 0
|
||||
}
|
||||
fmt.Println("Unexpected error")
|
||||
panic(err)
|
||||
}
|
||||
return 1
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package mnemonicode_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"bitbucket.org/dchapes/mnemonicode"
|
||||
)
|
||||
|
||||
func TestIssue002(t *testing.T) {
|
||||
buf := &bytes.Buffer{}
|
||||
// Code from:
|
||||
const issue = `https://bitbucket.org/dchapes/mnemonicode/issues/2`
|
||||
|
||||
config := mnemonicode.NewDefaultConfig()
|
||||
config.GroupsPerLine = 1
|
||||
config.LineSuffix = "\n"
|
||||
config.GroupSeparator = "\n"
|
||||
config.WordPadding = 0
|
||||
config.WordsPerGroup = 1
|
||||
config.WordSeparator = "\n"
|
||||
src := strings.NewReader("abcdefgh")
|
||||
r := mnemonicode.NewEncodeReader(src, config)
|
||||
//io.Copy(os.Stdout, r)
|
||||
io.Copy(buf, r)
|
||||
|
||||
// Note, in the issue the expected trailing newline is missing.
|
||||
const expected = ` bogart
|
||||
atlas
|
||||
safari
|
||||
airport
|
||||
cabaret
|
||||
shock
|
||||
`
|
||||
if s := buf.String(); s != expected {
|
||||
t.Errorf("%v\n\tgave %q\n\twant%q", issue, s, expected)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,557 @@
|
|||
// Package mnemonicode …
|
||||
package mnemonicode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/text/transform"
|
||||
)
|
||||
|
||||
// WordsRequired returns the number of words required to encode input
|
||||
// data of length bytes using mnomonic encoding.
|
||||
//
|
||||
// Every four bytes of input is encoded into three words. If there
|
||||
// is an extra one or two bytes they get an extra one or two words
|
||||
// respectively. If there is an extra three bytes, they will be encoded
|
||||
// into three words with the last word being one of a small set of very
|
||||
// short words (only needed to encode the last 3 bits).
|
||||
func WordsRequired(length int) int {
|
||||
return ((length + 1) * 3) / 4
|
||||
}
|
||||
|
||||
// A Config structure contains options for mneomonic encoding.
|
||||
//
|
||||
// {PREFIX}word{wsep}word{gsep}word{wsep}word{SUFFIX}
|
||||
type Config struct {
|
||||
LinePrefix string
|
||||
LineSuffix string
|
||||
WordSeparator string
|
||||
GroupSeparator string
|
||||
WordsPerGroup uint
|
||||
GroupsPerLine uint
|
||||
WordPadding rune
|
||||
}
|
||||
|
||||
var defaultConfig = Config{
|
||||
LinePrefix: "",
|
||||
LineSuffix: "\n",
|
||||
WordSeparator: " ",
|
||||
GroupSeparator: " - ",
|
||||
WordsPerGroup: 3,
|
||||
GroupsPerLine: 3,
|
||||
WordPadding: ' ',
|
||||
}
|
||||
|
||||
// NewDefaultConfig returns a newly allocated Config initialised with default values.
|
||||
func NewDefaultConfig() *Config {
|
||||
r := new(Config)
|
||||
*r = defaultConfig
|
||||
return r
|
||||
}
|
||||
|
||||
// NewEncodeReader returns a new io.Reader that will return a
|
||||
// formatted list of mnemonic words representing the bytes in r.
|
||||
//
|
||||
// The configuration of the word formatting is controlled
|
||||
// by c, which can be nil for default formatting.
|
||||
func NewEncodeReader(r io.Reader, c *Config) io.Reader {
|
||||
t := NewEncodeTransformer(c)
|
||||
return transform.NewReader(r, t)
|
||||
}
|
||||
|
||||
// NewEncoder returns a new io.WriteCloser that will write a formatted
|
||||
// list of mnemonic words representing the bytes written to w. The user
|
||||
// needs to call Close to flush unwritten bytes that may be buffered.
|
||||
//
|
||||
// The configuration of the word formatting is controlled
|
||||
// by c, which can be nil for default formatting.
|
||||
func NewEncoder(w io.Writer, c *Config) io.WriteCloser {
|
||||
t := NewEncodeTransformer(c)
|
||||
return transform.NewWriter(w, t)
|
||||
}
|
||||
|
||||
// NewEncodeTransformer returns a new transformer
|
||||
// that encodes bytes into mnemonic words.
|
||||
//
|
||||
// The configuration of the word formatting is controlled
|
||||
// by c, which can be nil for default formatting.
|
||||
func NewEncodeTransformer(c *Config) transform.Transformer {
|
||||
if c == nil {
|
||||
c = &defaultConfig
|
||||
}
|
||||
return &enctrans{
|
||||
c: *c,
|
||||
state: needPrefix,
|
||||
}
|
||||
}
|
||||
|
||||
type enctrans struct {
|
||||
c Config
|
||||
state encTransState
|
||||
wordCnt uint
|
||||
groupCnt uint
|
||||
wordidx [3]int
|
||||
wordidxcnt int // remaining indexes in wordidx; wordidx[3-wordidxcnt:]
|
||||
}
|
||||
|
||||
func (t *enctrans) Reset() {
|
||||
t.state = needPrefix
|
||||
t.wordCnt = 0
|
||||
t.groupCnt = 0
|
||||
t.wordidxcnt = 0
|
||||
}
|
||||
|
||||
type encTransState uint8
|
||||
|
||||
const (
|
||||
needNothing = iota
|
||||
needPrefix
|
||||
needWordSep
|
||||
needGroupSep
|
||||
needSuffix
|
||||
)
|
||||
|
||||
func (t *enctrans) strState() (str string, nextState encTransState) {
|
||||
switch t.state {
|
||||
case needPrefix:
|
||||
str = t.c.LinePrefix
|
||||
case needWordSep:
|
||||
str = t.c.WordSeparator
|
||||
case needGroupSep:
|
||||
str = t.c.GroupSeparator
|
||||
case needSuffix:
|
||||
str = t.c.LineSuffix
|
||||
nextState = needPrefix
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (t *enctrans) advState() {
|
||||
t.wordCnt++
|
||||
if t.wordCnt < t.c.WordsPerGroup {
|
||||
t.state = needWordSep
|
||||
} else {
|
||||
t.wordCnt = 0
|
||||
t.groupCnt++
|
||||
if t.groupCnt < t.c.GroupsPerLine {
|
||||
t.state = needGroupSep
|
||||
} else {
|
||||
t.groupCnt = 0
|
||||
t.state = needSuffix
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// transformWords consumes words from wordidx copying the words with
|
||||
// formatting into dst.
|
||||
// On return, if err==nil, all words were consumed (wordidxcnt==0).
|
||||
func (t *enctrans) transformWords(dst []byte) (nDst int, err error) {
|
||||
//log.Println("transformWords: len(dst)=",len(dst),"wordidxcnt=",t.wordidxcnt)
|
||||
for t.wordidxcnt > 0 {
|
||||
for t.state != needNothing {
|
||||
str, nextState := t.strState()
|
||||
if len(dst) < len(str) {
|
||||
return nDst, transform.ErrShortDst
|
||||
}
|
||||
n := copy(dst, str)
|
||||
dst = dst[n:]
|
||||
nDst += n
|
||||
t.state = nextState
|
||||
}
|
||||
word := wordList[t.wordidx[3-t.wordidxcnt]]
|
||||
n := len(word)
|
||||
if n < longestWord {
|
||||
if rlen := utf8.RuneLen(t.c.WordPadding); rlen > 0 {
|
||||
n += (longestWord - n) * rlen
|
||||
}
|
||||
}
|
||||
if len(dst) < n {
|
||||
return nDst, transform.ErrShortDst
|
||||
}
|
||||
n = copy(dst, word)
|
||||
t.wordidxcnt--
|
||||
dst = dst[n:]
|
||||
nDst += n
|
||||
if t.c.WordPadding != 0 {
|
||||
for i := n; i < longestWord; i++ {
|
||||
n = utf8.EncodeRune(dst, t.c.WordPadding)
|
||||
dst = dst[n:]
|
||||
nDst += n
|
||||
}
|
||||
}
|
||||
t.advState()
|
||||
}
|
||||
return nDst, nil
|
||||
}
|
||||
|
||||
// Transform implements the transform.Transformer interface.
|
||||
func (t *enctrans) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
|
||||
//log.Printf("Transform(%d,%d,%t)\n", len(dst), len(src), atEOF)
|
||||
var n int
|
||||
for {
|
||||
if t.wordidxcnt > 0 {
|
||||
n, err = t.transformWords(dst)
|
||||
dst = dst[n:]
|
||||
nDst += n
|
||||
if err != nil {
|
||||
//log.Printf("\t\t\tRet1: (%d) %d, %d, %v\n", t.wordidxcnt, nDst, nSrc, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
var x uint32
|
||||
switch {
|
||||
case len(src) >= 4:
|
||||
x = uint32(src[0])
|
||||
x |= uint32(src[1]) << 8
|
||||
x |= uint32(src[2]) << 16
|
||||
x |= uint32(src[3]) << 24
|
||||
src = src[4:]
|
||||
nSrc += 4
|
||||
|
||||
t.wordidx[0] = int(x % base)
|
||||
t.wordidx[1] = int(x/base) % base
|
||||
t.wordidx[2] = int(x/base/base) % base
|
||||
t.wordidxcnt = 3
|
||||
//log.Printf("\t\tConsumed 4 bytes (%d, %d)", nDst, nSrc)
|
||||
//continue
|
||||
case len(src) == 0:
|
||||
//log.Printf("\t\t\tRet2: (%d) %d, %d, %v\n", t.wordidxcnt, nDst, nSrc, err)
|
||||
return
|
||||
case !atEOF:
|
||||
//log.Printf("\t\t!atEOF (%d, %d)", nDst, nSrc)
|
||||
err = transform.ErrShortSrc
|
||||
return
|
||||
default:
|
||||
x = 0
|
||||
n = len(src)
|
||||
for i := n - 1; i >= 0; i-- {
|
||||
x <<= 8
|
||||
x |= uint32(src[i])
|
||||
}
|
||||
t.wordidx[3-n] = int(x % base)
|
||||
if n >= 2 {
|
||||
t.wordidx[4-n] = int(x/base) % base
|
||||
}
|
||||
if n == 3 {
|
||||
t.wordidx[2] = base + int(x/base/base)%7
|
||||
}
|
||||
src = src[n:]
|
||||
nSrc += n
|
||||
t.wordidxcnt = n
|
||||
//log.Printf("\t\tatEOF (%d) (%d, %d)", t.wordidxcnt, nDst, nSrc)
|
||||
//continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
// NewDecoder returns a new io.Reader that will return the
|
||||
// decoded bytes from mnemonic words in r. Unrecognized
|
||||
// words in r will cause reads to return an error.
|
||||
func NewDecoder(r io.Reader) io.Reader {
|
||||
t := NewDecodeTransformer()
|
||||
return transform.NewReader(r, t)
|
||||
}
|
||||
|
||||
// NewDecodeWriter returns a new io.WriteCloser that will
|
||||
// write decoded bytes from mnemonic words written to it.
|
||||
// Unrecognized words will cause a write error. The user needs
|
||||
// to call Close to flush unwritten bytes that may be buffered.
|
||||
func NewDecodeWriter(w io.Writer) io.WriteCloser {
|
||||
t := NewDecodeTransformer()
|
||||
return transform.NewWriter(w, t)
|
||||
}
|
||||
|
||||
// NewDecodeTransformer returns a new transform
|
||||
// that decodes mnemonic words into the represented
|
||||
// bytes. Unrecognized words will trigger an error.
|
||||
func NewDecodeTransformer() transform.Transformer {
|
||||
return &dectrans{wordidx: make([]int, 0, 3)}
|
||||
}
|
||||
|
||||
type dectrans struct {
|
||||
wordidx []int
|
||||
short bool // last word in wordidx is/was short
|
||||
}
|
||||
|
||||
func (t *dectrans) Reset() {
|
||||
t.wordidx = nil
|
||||
t.short = false
|
||||
}
|
||||
|
||||
func (t *dectrans) transformWords(dst []byte) (int, error) {
|
||||
//log.Println("transformWords: len(dst)=",len(dst),"len(t.wordidx)=", len(t.wordidx))
|
||||
n := len(t.wordidx)
|
||||
if n == 3 && !t.short {
|
||||
n = 4
|
||||
}
|
||||
if len(dst) < n {
|
||||
return 0, transform.ErrShortDst
|
||||
}
|
||||
for len(t.wordidx) < 3 {
|
||||
t.wordidx = append(t.wordidx, 0)
|
||||
}
|
||||
x := uint32(t.wordidx[2])
|
||||
x *= base
|
||||
x += uint32(t.wordidx[1])
|
||||
x *= base
|
||||
x += uint32(t.wordidx[0])
|
||||
for i := 0; i < n; i++ {
|
||||
dst[i] = byte(x)
|
||||
x >>= 8
|
||||
}
|
||||
t.wordidx = t.wordidx[:0]
|
||||
return n, nil
|
||||
}
|
||||
|
||||
type WordError interface {
|
||||
error
|
||||
Word() string
|
||||
}
|
||||
|
||||
type UnexpectedWordError string
|
||||
type UnexpectedEndWordError string
|
||||
type UnknownWordError string
|
||||
|
||||
func (e UnexpectedWordError) Word() string { return string(e) }
|
||||
func (e UnexpectedEndWordError) Word() string { return string(e) }
|
||||
func (e UnknownWordError) Word() string { return string(e) }
|
||||
func (e UnexpectedWordError) Error() string {
|
||||
return fmt.Sprintf("mnemonicode: unexpected word after short word: %q", string(e))
|
||||
}
|
||||
func (e UnexpectedEndWordError) Error() string {
|
||||
return fmt.Sprintf("mnemonicode: unexpected end word: %q", string(e))
|
||||
}
|
||||
func (e UnknownWordError) Error() string {
|
||||
return fmt.Sprintf("mnemonicode: unknown word: %q", string(e))
|
||||
}
|
||||
|
||||
// Transform implements the transform.Transformer interface.
|
||||
func (t *dectrans) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
|
||||
//log.Printf("Transform(%d,%d,%t)\n", len(dst), len(src), atEOF)
|
||||
var n int
|
||||
for len(t.wordidx) > 0 || len(src) > 0 {
|
||||
for len(t.wordidx) < 3 {
|
||||
var word []byte
|
||||
var idx int
|
||||
//n, word, err = bufio.ScanWords(src, atEOF)
|
||||
n, word, err = scanWords(src, atEOF)
|
||||
src = src[n:]
|
||||
nSrc += n
|
||||
if err != nil {
|
||||
//log.Print("ScanWords error:", err)
|
||||
return
|
||||
}
|
||||
if word == nil {
|
||||
if atEOF {
|
||||
//log.Printf("atEOF (%d, %d) %d, %d", nDst, nSrc, n, len(src))
|
||||
n = len(src)
|
||||
src = src[n:]
|
||||
nSrc += n
|
||||
break
|
||||
}
|
||||
//log.Printf("\t\t!atEOF (%d, %d)", nDst, nSrc)
|
||||
err = transform.ErrShortSrc
|
||||
return
|
||||
}
|
||||
if t.short {
|
||||
err = UnexpectedWordError(word)
|
||||
//log.Print("short error:", err)
|
||||
return
|
||||
}
|
||||
idx, _, t.short, err = closestWordIdx(string(word), len(t.wordidx) == 2)
|
||||
if err != nil {
|
||||
//log.Print("closestWordIdx error:", err)
|
||||
return
|
||||
}
|
||||
t.wordidx = append(t.wordidx, idx)
|
||||
}
|
||||
if len(t.wordidx) > 0 {
|
||||
n, err = t.transformWords(dst)
|
||||
dst = dst[n:]
|
||||
nDst += n
|
||||
if n != 4 {
|
||||
//log.Println("transformWords returned:", n, err)
|
||||
//log.Println("len(t.wordidx):", len(t.wordidx), len(src))
|
||||
}
|
||||
if err != nil {
|
||||
//log.Printf("\t\t\tRet1: (%d) %d, %d, %v\n", len(t.wordidx), nDst, nSrc, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
const base = 1626
|
||||
|
||||
// EncodeWordList encodes src into mnemomic words which are appended to dst.
|
||||
// The final wordlist is returned.
|
||||
// There will be WordsRequired(len(src)) words appeneded.
|
||||
func EncodeWordList(dst []string, src []byte) (result []string) {
|
||||
if n := len(dst) + WordsRequired(len(src)); cap(dst) < n {
|
||||
result = make([]string, len(dst), n)
|
||||
copy(result, dst)
|
||||
} else {
|
||||
result = dst
|
||||
}
|
||||
|
||||
var x uint32
|
||||
for len(src) >= 4 {
|
||||
x = uint32(src[0])
|
||||
x |= uint32(src[1]) << 8
|
||||
x |= uint32(src[2]) << 16
|
||||
x |= uint32(src[3]) << 24
|
||||
src = src[4:]
|
||||
|
||||
i0 := int(x % base)
|
||||
i1 := int(x/base) % base
|
||||
i2 := int(x/base/base) % base
|
||||
result = append(result, wordList[i0], wordList[i1], wordList[i2])
|
||||
}
|
||||
if len(src) > 0 {
|
||||
x = 0
|
||||
for i := len(src) - 1; i >= 0; i-- {
|
||||
x <<= 8
|
||||
x |= uint32(src[i])
|
||||
}
|
||||
i := int(x % base)
|
||||
result = append(result, wordList[i])
|
||||
if len(src) >= 2 {
|
||||
i = int(x/base) % base
|
||||
result = append(result, wordList[i])
|
||||
}
|
||||
if len(src) == 3 {
|
||||
i = base + int(x/base/base)%7
|
||||
result = append(result, wordList[i])
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func closestWordIdx(word string, shortok bool) (idx int, exact, short bool, err error) {
|
||||
word = strings.ToLower(word)
|
||||
if idx, exact = wordMap[word]; !exact {
|
||||
// TODO(dchapes): normalize unicode, remove accents, etc
|
||||
// TODO(dchapes): phonetic algorithm or other closest match
|
||||
err = UnknownWordError(word)
|
||||
return
|
||||
}
|
||||
if short = (idx >= base); short {
|
||||
idx -= base
|
||||
if !shortok {
|
||||
err = UnexpectedEndWordError(word)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// DecodeWordList decodes the mnemonic words in src into bytes which are
|
||||
// appended to dst.
|
||||
func DecodeWordList(dst []byte, src []string) (result []byte, err error) {
|
||||
if n := (len(src)+2)/3*4 + len(dst); cap(dst) < n {
|
||||
result = make([]byte, len(dst), n)
|
||||
copy(result, dst)
|
||||
} else {
|
||||
result = dst
|
||||
}
|
||||
|
||||
var idx [3]int
|
||||
for len(src) > 3 {
|
||||
if idx[0], _, _, err = closestWordIdx(src[0], false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if idx[1], _, _, err = closestWordIdx(src[1], false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if idx[2], _, _, err = closestWordIdx(src[2], false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
src = src[3:]
|
||||
x := uint32(idx[2])
|
||||
x *= base
|
||||
x += uint32(idx[1])
|
||||
x *= base
|
||||
x += uint32(idx[0])
|
||||
result = append(result, byte(x), byte(x>>8), byte(x>>16), byte(x>>24))
|
||||
}
|
||||
|
||||
if len(src) > 0 {
|
||||
var short bool
|
||||
idx[1] = 0
|
||||
idx[2] = 0
|
||||
n := len(src)
|
||||
for i := 0; i < n; i++ {
|
||||
idx[i], _, short, err = closestWordIdx(src[i], i == 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
x := uint32(idx[2])
|
||||
x *= base
|
||||
x += uint32(idx[1])
|
||||
x *= base
|
||||
x += uint32(idx[0])
|
||||
result = append(result, byte(x))
|
||||
if n > 1 {
|
||||
result = append(result, byte(x>>8))
|
||||
}
|
||||
if n > 2 {
|
||||
result = append(result, byte(x>>16))
|
||||
if !short {
|
||||
result = append(result, byte(x>>24))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
for len(src) > 0 {
|
||||
short := false
|
||||
n := len(src)
|
||||
if n > 3 {
|
||||
n = 3
|
||||
}
|
||||
for i := 0; i < n; i++ {
|
||||
idx[i], _, err = closestWordIdx(src[i])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if idx[i] >= base {
|
||||
if i != 2 || len(src) != 3 {
|
||||
return nil, UnexpectedEndWord(src[i])
|
||||
}
|
||||
short = true
|
||||
idx[i] -= base
|
||||
}
|
||||
}
|
||||
for i := n; i < 3; i++ {
|
||||
idx[i] = 0
|
||||
}
|
||||
src = src[n:]
|
||||
x := uint32(idx[2])
|
||||
x *= base
|
||||
x += uint32(idx[1])
|
||||
x *= base
|
||||
x += uint32(idx[0])
|
||||
result = append(result, byte(x))
|
||||
if n > 1 {
|
||||
result = append(result, byte(x>>8))
|
||||
}
|
||||
if n > 2 {
|
||||
result = append(result, byte(x>>16))
|
||||
if !short {
|
||||
result = append(result, byte(x>>24))
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
return result, nil
|
||||
}
|
|
@ -0,0 +1,238 @@
|
|||
package mnemonicode
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/text/transform"
|
||||
)
|
||||
|
||||
func TestWordsReq(t *testing.T) {
|
||||
for i, n := range []int{0, 1, 2, 3, 3, 4, 5, 6, 6, 7, 8, 9, 9, 10} {
|
||||
r := WordsRequired(i)
|
||||
if r != n {
|
||||
t.Errorf("WordsRequired(%d) returned %d, expected %d", i, r, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var testData = []struct {
|
||||
hex string
|
||||
words []string
|
||||
}{
|
||||
{"01", []string{"acrobat"}},
|
||||
{"0102", []string{"opera", "academy"}},
|
||||
{"010203", []string{"kayak", "cement", "ego"}},
|
||||
{"01020304", []string{"papa", "twist", "alpine"}},
|
||||
{"0102030405", []string{"papa", "twist", "alpine", "admiral"}},
|
||||
{"010203040506", []string{"papa", "twist", "alpine", "shine", "academy"}},
|
||||
{"01020304050607", []string{"papa", "twist", "alpine", "chess", "flute", "ego"}},
|
||||
{"0102030405060708", []string{"papa", "twist", "alpine", "content", "sailor", "athena"}},
|
||||
{"00", []string{"academy"}},
|
||||
{"5A06", []string{"academy", "acrobat"}},
|
||||
{"FE5D28", []string{"academy", "acrobat", "fax"}},
|
||||
{"A2B55000", []string{"academy", "acrobat", "active"}},
|
||||
{"A2B5500003", []string{"academy", "acrobat", "active", "actor"}},
|
||||
{"A2B550006B19", []string{"academy", "acrobat", "active", "actor", "adam"}},
|
||||
{"A2B550000F7128", []string{"academy", "acrobat", "active", "actor", "adam", "fax"}},
|
||||
{"A2B550009FCFC900", []string{"academy", "acrobat", "active", "actor", "adam", "admiral"}},
|
||||
{"FF", []string{"exact"}},
|
||||
{"FFFF", []string{"nevada", "archive"}},
|
||||
{"FFFFFF", []string{"claudia", "photo", "yes"}},
|
||||
{"FFFFFFFF", []string{"natural", "analyze", "verbal"}},
|
||||
{"123456789ABCDEF123456789ABCDEF012345", []string{
|
||||
"plastic", "roger", "vincent", "pilgrim", "flame", "secure", "apropos", "polka", "earth", "radio", "modern", "aladdin", "marion", "airline"}},
|
||||
}
|
||||
|
||||
func compareWordList(tb testing.TB, expected, got []string, args ...interface{}) {
|
||||
fail := false
|
||||
if len(expected) != len(got) {
|
||||
fail = true
|
||||
}
|
||||
for i := 0; !fail && i < len(expected); i++ {
|
||||
fail = expected[i] != got[i]
|
||||
}
|
||||
if fail {
|
||||
prefix := ""
|
||||
if len(args) > 0 {
|
||||
prefix += fmt.Sprintln(args...)
|
||||
prefix = prefix[:len(prefix)-1] + ": "
|
||||
}
|
||||
tb.Errorf("%vexpected %v, got %v", prefix, expected, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncodeWordList(t *testing.T) {
|
||||
var result []string
|
||||
for i, d := range testData {
|
||||
raw, err := hex.DecodeString(d.hex)
|
||||
if err != nil {
|
||||
t.Fatal("bad test data:", i, err)
|
||||
}
|
||||
result = EncodeWordList(result, raw)
|
||||
compareWordList(t, d.words, result, i, d.hex)
|
||||
result = result[:0]
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeWordList(t *testing.T) {
|
||||
var result []byte
|
||||
var err error
|
||||
for i, d := range testData {
|
||||
raw, _ := hex.DecodeString(d.hex)
|
||||
result, err = DecodeWordList(result, d.words)
|
||||
if err != nil {
|
||||
t.Errorf("%2d %v failed: %v", i, d.words, err)
|
||||
continue
|
||||
}
|
||||
if !bytes.Equal(raw, result) {
|
||||
t.Errorf("%2d %v expected %v got %v", i, d.words, raw, result)
|
||||
}
|
||||
result = result[:0]
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncodeTransformer(t *testing.T) {
|
||||
cfg := NewDefaultConfig()
|
||||
cfg.GroupSeparator = " "
|
||||
enc := NewEncodeTransformer(cfg)
|
||||
for i, d := range testData {
|
||||
raw, err := hex.DecodeString(d.hex)
|
||||
if err != nil {
|
||||
t.Fatal("bad test data:", i, err)
|
||||
}
|
||||
result, _, err := transform.Bytes(enc, raw)
|
||||
if err != nil {
|
||||
t.Errorf("%2d %v failed: %v", i, d.words, err)
|
||||
continue
|
||||
}
|
||||
//t.Logf("%q", result)
|
||||
words := strings.Fields(string(result))
|
||||
compareWordList(t, d.words, words, i, d.hex)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestDecodeTransformer(t *testing.T) {
|
||||
dec := NewDecodeTransformer()
|
||||
for i, d := range testData {
|
||||
raw, _ := hex.DecodeString(d.hex)
|
||||
words := strings.Join(d.words, " ")
|
||||
result, _, err := transform.Bytes(dec, []byte(words))
|
||||
if err != nil {
|
||||
t.Errorf("%2d %v failed: %v", i, d.words, err)
|
||||
continue
|
||||
}
|
||||
if !bytes.Equal(raw, result) {
|
||||
t.Errorf("%2d %v expected %v got %v", i, d.words, raw, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncodeFormatting(t *testing.T) {
|
||||
raw, _ := hex.DecodeString(testData[20].hex)
|
||||
input := string(raw)
|
||||
//words := testData[20].words
|
||||
tests := []struct {
|
||||
cfg *Config
|
||||
formatted string
|
||||
}{
|
||||
{nil, "plastic roger vincent - pilgrim flame secure - apropos polka earth \nradio modern aladdin - marion airline"},
|
||||
{&Config{
|
||||
LinePrefix: "{P}",
|
||||
LineSuffix: "{S}\n",
|
||||
WordSeparator: "{w}",
|
||||
GroupSeparator: "{g}",
|
||||
WordsPerGroup: 2,
|
||||
GroupsPerLine: 2,
|
||||
WordPadding: '·',
|
||||
},
|
||||
`{P}plastic{w}roger··{g}vincent{w}pilgrim{S}
|
||||
{P}flame··{w}secure·{g}apropos{w}polka··{S}
|
||||
{P}earth··{w}radio··{g}modern·{w}aladdin{S}
|
||||
{P}marion·{w}airline`},
|
||||
}
|
||||
for i, d := range tests {
|
||||
enc := NewEncodeTransformer(d.cfg)
|
||||
result, _, err := transform.String(enc, input)
|
||||
if err != nil {
|
||||
t.Errorf("%2d transform failed: %v", i, err)
|
||||
continue
|
||||
}
|
||||
if result != d.formatted {
|
||||
t.Errorf("%2d expected:\n%q\ngot:\n%q", i, d.formatted, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkEncodeWordList(b *testing.B) {
|
||||
// the list of all known words (except the short end words)
|
||||
data, err := DecodeWordList(nil, wordList[:base])
|
||||
if err != nil {
|
||||
b.Fatal("DecodeWordList failed:", err)
|
||||
}
|
||||
b.SetBytes(int64(len(data)))
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
var words []string
|
||||
for i := 0; i < b.N; i++ {
|
||||
words = EncodeWordList(words[:0], data)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkDencodeWordList(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
var buf []byte
|
||||
var err error
|
||||
// decode the list of all known words (except the short end words)
|
||||
for i := 0; i < b.N; i++ {
|
||||
buf, err = DecodeWordList(buf[:0], wordList[:base])
|
||||
if err != nil {
|
||||
b.Fatal("DecodeWordList failed:", err)
|
||||
}
|
||||
}
|
||||
b.SetBytes(int64(len(buf)))
|
||||
}
|
||||
|
||||
func BenchmarkEncodeTransformer(b *testing.B) {
|
||||
// the list of all known words (except the short end words)
|
||||
data, err := DecodeWordList(nil, wordList[:base])
|
||||
if err != nil {
|
||||
b.Fatal("DecodeWordList failed:", err)
|
||||
}
|
||||
enc := NewEncodeTransformer(nil)
|
||||
b.SetBytes(int64(len(data)))
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _, err := transform.Bytes(enc, data)
|
||||
if err != nil {
|
||||
b.Fatal("encode transformer error:", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkDecodeTransformer(b *testing.B) {
|
||||
data, err := DecodeWordList(nil, wordList[:base])
|
||||
if err != nil {
|
||||
b.Fatal("DecodeWordList failed:", err)
|
||||
}
|
||||
enc := NewEncodeTransformer(nil)
|
||||
words, _, err := transform.Bytes(enc, data)
|
||||
if err != nil {
|
||||
b.Fatal("encode transformer error:", err)
|
||||
}
|
||||
b.SetBytes(int64(len(data)))
|
||||
dec := NewDecodeTransformer()
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _, err := transform.Bytes(dec, words)
|
||||
if err != nil {
|
||||
b.Fatal("decode transformer error:", err)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package mnemonicode
|
||||
|
||||
import (
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// modified version of bufio.ScanWords from bufio/scan.go
|
||||
|
||||
// scanWords is a split function for a Scanner that returns
|
||||
// each non-letter separated word of text, with surrounding
|
||||
// non-leters deleted. It will never return an empty string.
|
||||
// The definition of letter is set by unicode.IsLetter.
|
||||
func scanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
|
||||
// Skip leading non-letters.
|
||||
start := 0
|
||||
for width := 0; start < len(data); start += width {
|
||||
var r rune
|
||||
r, width = utf8.DecodeRune(data[start:])
|
||||
if unicode.IsLetter(r) {
|
||||
break
|
||||
}
|
||||
}
|
||||
if atEOF && len(data) == 0 {
|
||||
return 0, nil, nil
|
||||
}
|
||||
// Scan until non-letter, marking end of word.
|
||||
for width, i := 0, start; i < len(data); i += width {
|
||||
var r rune
|
||||
r, width = utf8.DecodeRune(data[i:])
|
||||
if !unicode.IsLetter(r) {
|
||||
return i + width, data[start:i], nil
|
||||
}
|
||||
}
|
||||
// If we're at EOF, we have a final, non-empty, non-terminated word. Return it.
|
||||
if atEOF && len(data) > start {
|
||||
return len(data), data[start:], nil
|
||||
}
|
||||
// Request more data.
|
||||
return 0, nil, nil
|
||||
}
|
|
@ -0,0 +1,290 @@
|
|||
package mnemonicode
|
||||
|
||||
// WordListVersion is the version of compiled in word list.
|
||||
const WordListVersion = "0.7"
|
||||
|
||||
var wordMap = make(map[string]int, len(wordList))
|
||||
|
||||
func init() {
|
||||
for i, w := range wordList {
|
||||
wordMap[w] = i
|
||||
}
|
||||
}
|
||||
|
||||
const longestWord = 7
|
||||
|
||||
var wordList = []string{
|
||||
"academy", "acrobat", "active", "actor", "adam", "admiral",
|
||||
"adrian", "africa", "agenda", "agent", "airline", "airport",
|
||||
"aladdin", "alarm", "alaska", "albert", "albino", "album",
|
||||
"alcohol", "alex", "algebra", "alibi", "alice", "alien",
|
||||
"alpha", "alpine", "amadeus", "amanda", "amazon", "amber",
|
||||
"america", "amigo", "analog", "anatomy", "angel", "animal",
|
||||
"antenna", "antonio", "apollo", "april", "archive", "arctic",
|
||||
"arizona", "arnold", "aroma", "arthur", "artist", "asia",
|
||||
"aspect", "aspirin", "athena", "athlete", "atlas", "audio",
|
||||
"august", "austria", "axiom", "aztec", "balance", "ballad",
|
||||
"banana", "bandit", "banjo", "barcode", "baron", "basic",
|
||||
"battery", "belgium", "berlin", "bermuda", "bernard", "bikini",
|
||||
"binary", "bingo", "biology", "block", "blonde", "bonus",
|
||||
"boris", "boston", "boxer", "brandy", "bravo", "brazil",
|
||||
"bronze", "brown", "bruce", "bruno", "burger", "burma",
|
||||
"cabinet", "cactus", "cafe", "cairo", "cake", "calypso",
|
||||
"camel", "camera", "campus", "canada", "canal", "cannon",
|
||||
"canoe", "cantina", "canvas", "canyon", "capital", "caramel",
|
||||
"caravan", "carbon", "cargo", "carlo", "carol", "carpet",
|
||||
"cartel", "casino", "castle", "castro", "catalog", "caviar",
|
||||
"cecilia", "cement", "center", "century", "ceramic", "chamber",
|
||||
"chance", "change", "chaos", "charlie", "charm", "charter",
|
||||
"chef", "chemist", "cherry", "chess", "chicago", "chicken",
|
||||
"chief", "china", "cigar", "cinema", "circus", "citizen",
|
||||
"city", "clara", "classic", "claudia", "clean", "client",
|
||||
"climax", "clinic", "clock", "club", "cobra", "coconut",
|
||||
"cola", "collect", "colombo", "colony", "color", "combat",
|
||||
"comedy", "comet", "command", "compact", "company", "complex",
|
||||
"concept", "concert", "connect", "consul", "contact", "context",
|
||||
"contour", "control", "convert", "copy", "corner", "corona",
|
||||
"correct", "cosmos", "couple", "courage", "cowboy", "craft",
|
||||
"crash", "credit", "cricket", "critic", "crown", "crystal",
|
||||
"cuba", "culture", "dallas", "dance", "daniel", "david",
|
||||
"decade", "decimal", "deliver", "delta", "deluxe", "demand",
|
||||
"demo", "denmark", "derby", "design", "detect", "develop",
|
||||
"diagram", "dialog", "diamond", "diana", "diego", "diesel",
|
||||
"diet", "digital", "dilemma", "diploma", "direct", "disco",
|
||||
"disney", "distant", "doctor", "dollar", "dominic", "domino",
|
||||
"donald", "dragon", "drama", "dublin", "duet", "dynamic",
|
||||
"east", "ecology", "economy", "edgar", "egypt", "elastic",
|
||||
"elegant", "element", "elite", "elvis", "email", "energy",
|
||||
"engine", "english", "episode", "equator", "escort", "ethnic",
|
||||
"europe", "everest", "evident", "exact", "example", "exit",
|
||||
"exotic", "export", "express", "extra", "fabric", "factor",
|
||||
"falcon", "family", "fantasy", "fashion", "fiber", "fiction",
|
||||
"fidel", "fiesta", "figure", "film", "filter", "final",
|
||||
"finance", "finish", "finland", "flash", "florida", "flower",
|
||||
"fluid", "flute", "focus", "ford", "forest", "formal",
|
||||
"format", "formula", "fortune", "forum", "fragile", "france",
|
||||
"frank", "friend", "frozen", "future", "gabriel", "galaxy",
|
||||
"gallery", "gamma", "garage", "garden", "garlic", "gemini",
|
||||
"general", "genetic", "genius", "germany", "global", "gloria",
|
||||
"golf", "gondola", "gong", "good", "gordon", "gorilla",
|
||||
"grand", "granite", "graph", "green", "group", "guide",
|
||||
"guitar", "guru", "hand", "happy", "harbor", "harmony",
|
||||
"harvard", "havana", "hawaii", "helena", "hello", "henry",
|
||||
"hilton", "history", "horizon", "hotel", "human", "humor",
|
||||
"icon", "idea", "igloo", "igor", "image", "impact",
|
||||
"import", "index", "india", "indigo", "input", "insect",
|
||||
"instant", "iris", "italian", "jacket", "jacob", "jaguar",
|
||||
"janet", "japan", "jargon", "jazz", "jeep", "john",
|
||||
"joker", "jordan", "jumbo", "june", "jungle", "junior",
|
||||
"jupiter", "karate", "karma", "kayak", "kermit", "kilo",
|
||||
"king", "koala", "korea", "labor", "lady", "lagoon",
|
||||
"laptop", "laser", "latin", "lava", "lecture", "left",
|
||||
"legal", "lemon", "level", "lexicon", "liberal", "libra",
|
||||
"limbo", "limit", "linda", "linear", "lion", "liquid",
|
||||
"liter", "little", "llama", "lobby", "lobster", "local",
|
||||
"logic", "logo", "lola", "london", "lotus", "lucas",
|
||||
"lunar", "machine", "macro", "madam", "madonna", "madrid",
|
||||
"maestro", "magic", "magnet", "magnum", "major", "mama",
|
||||
"mambo", "manager", "mango", "manila", "marco", "marina",
|
||||
"market", "mars", "martin", "marvin", "master", "matrix",
|
||||
"maximum", "media", "medical", "mega", "melody", "melon",
|
||||
"memo", "mental", "mentor", "menu", "mercury", "message",
|
||||
"metal", "meteor", "meter", "method", "metro", "mexico",
|
||||
"miami", "micro", "million", "mineral", "minimum", "minus",
|
||||
"minute", "miracle", "mirage", "miranda", "mister", "mixer",
|
||||
"mobile", "model", "modem", "modern", "modular", "moment",
|
||||
"monaco", "monica", "monitor", "mono", "monster", "montana",
|
||||
"morgan", "motel", "motif", "motor", "mozart", "multi",
|
||||
"museum", "music", "mustang", "natural", "neon", "nepal",
|
||||
"neptune", "nerve", "neutral", "nevada", "news", "ninja",
|
||||
"nirvana", "normal", "nova", "novel", "nuclear", "numeric",
|
||||
"nylon", "oasis", "object", "observe", "ocean", "octopus",
|
||||
"olivia", "olympic", "omega", "opera", "optic", "optimal",
|
||||
"orange", "orbit", "organic", "orient", "origin", "orlando",
|
||||
"oscar", "oxford", "oxygen", "ozone", "pablo", "pacific",
|
||||
"pagoda", "palace", "pamela", "panama", "panda", "panel",
|
||||
"panic", "paradox", "pardon", "paris", "parker", "parking",
|
||||
"parody", "partner", "passage", "passive", "pasta", "pastel",
|
||||
"patent", "patriot", "patrol", "patron", "pegasus", "pelican",
|
||||
"penguin", "pepper", "percent", "perfect", "perfume", "period",
|
||||
"permit", "person", "peru", "phone", "photo", "piano",
|
||||
"picasso", "picnic", "picture", "pigment", "pilgrim", "pilot",
|
||||
"pirate", "pixel", "pizza", "planet", "plasma", "plaster",
|
||||
"plastic", "plaza", "pocket", "poem", "poetic", "poker",
|
||||
"polaris", "police", "politic", "polo", "polygon", "pony",
|
||||
"popcorn", "popular", "postage", "postal", "precise", "prefix",
|
||||
"premium", "present", "price", "prince", "printer", "prism",
|
||||
"private", "product", "profile", "program", "project", "protect",
|
||||
"proton", "public", "pulse", "puma", "pyramid", "queen",
|
||||
"radar", "radio", "random", "rapid", "rebel", "record",
|
||||
"recycle", "reflex", "reform", "regard", "regular", "relax",
|
||||
"report", "reptile", "reverse", "ricardo", "ringo", "ritual",
|
||||
"robert", "robot", "rocket", "rodeo", "romeo", "royal",
|
||||
"russian", "safari", "salad", "salami", "salmon", "salon",
|
||||
"salute", "samba", "sandra", "santana", "sardine", "school",
|
||||
"screen", "script", "second", "secret", "section", "segment",
|
||||
"select", "seminar", "senator", "senior", "sensor", "serial",
|
||||
"service", "sheriff", "shock", "sierra", "signal", "silicon",
|
||||
"silver", "similar", "simon", "single", "siren", "slogan",
|
||||
"social", "soda", "solar", "solid", "solo", "sonic",
|
||||
"soviet", "special", "speed", "spiral", "spirit", "sport",
|
||||
"static", "station", "status", "stereo", "stone", "stop",
|
||||
"street", "strong", "student", "studio", "style", "subject",
|
||||
"sultan", "super", "susan", "sushi", "suzuki", "switch",
|
||||
"symbol", "system", "tactic", "tahiti", "talent", "tango",
|
||||
"tarzan", "taxi", "telex", "tempo", "tennis", "texas",
|
||||
"textile", "theory", "thermos", "tiger", "titanic", "tokyo",
|
||||
"tomato", "topic", "tornado", "toronto", "torpedo", "total",
|
||||
"totem", "tourist", "tractor", "traffic", "transit", "trapeze",
|
||||
"travel", "tribal", "trick", "trident", "trilogy", "tripod",
|
||||
"tropic", "trumpet", "tulip", "tuna", "turbo", "twist",
|
||||
"ultra", "uniform", "union", "uranium", "vacuum", "valid",
|
||||
"vampire", "vanilla", "vatican", "velvet", "ventura", "venus",
|
||||
"vertigo", "veteran", "victor", "video", "vienna", "viking",
|
||||
"village", "vincent", "violet", "violin", "virtual", "virus",
|
||||
"visa", "vision", "visitor", "visual", "vitamin", "viva",
|
||||
"vocal", "vodka", "volcano", "voltage", "volume", "voyage",
|
||||
"water", "weekend", "welcome", "western", "window", "winter",
|
||||
"wizard", "wolf", "world", "xray", "yankee", "yoga",
|
||||
"yogurt", "yoyo", "zebra", "zero", "zigzag", "zipper",
|
||||
"zodiac", "zoom", "abraham", "action", "address", "alabama",
|
||||
"alfred", "almond", "ammonia", "analyze", "annual", "answer",
|
||||
"apple", "arena", "armada", "arsenal", "atlanta", "atomic",
|
||||
"avenue", "average", "bagel", "baker", "ballet", "bambino",
|
||||
"bamboo", "barbara", "basket", "bazaar", "benefit", "bicycle",
|
||||
"bishop", "blitz", "bonjour", "bottle", "bridge", "british",
|
||||
"brother", "brush", "budget", "cabaret", "cadet", "candle",
|
||||
"capitan", "capsule", "career", "cartoon", "channel", "chapter",
|
||||
"cheese", "circle", "cobalt", "cockpit", "college", "compass",
|
||||
"comrade", "condor", "crimson", "cyclone", "darwin", "declare",
|
||||
"degree", "delete", "delphi", "denver", "desert", "divide",
|
||||
"dolby", "domain", "domingo", "double", "drink", "driver",
|
||||
"eagle", "earth", "echo", "eclipse", "editor", "educate",
|
||||
"edward", "effect", "electra", "emerald", "emotion", "empire",
|
||||
"empty", "escape", "eternal", "evening", "exhibit", "expand",
|
||||
"explore", "extreme", "ferrari", "first", "flag", "folio",
|
||||
"forget", "forward", "freedom", "fresh", "friday", "fuji",
|
||||
"galileo", "garcia", "genesis", "gold", "gravity", "habitat",
|
||||
"hamlet", "harlem", "helium", "holiday", "house", "hunter",
|
||||
"ibiza", "iceberg", "imagine", "infant", "isotope", "jackson",
|
||||
"jamaica", "jasmine", "java", "jessica", "judo", "kitchen",
|
||||
"lazarus", "letter", "license", "lithium", "loyal", "lucky",
|
||||
"magenta", "mailbox", "manual", "marble", "mary", "maxwell",
|
||||
"mayor", "milk", "monarch", "monday", "money", "morning",
|
||||
"mother", "mystery", "native", "nectar", "nelson", "network",
|
||||
"next", "nikita", "nobel", "nobody", "nominal", "norway",
|
||||
"nothing", "number", "october", "office", "oliver", "opinion",
|
||||
"option", "order", "outside", "package", "pancake", "pandora",
|
||||
"panther", "papa", "patient", "pattern", "pedro", "pencil",
|
||||
"people", "phantom", "philips", "pioneer", "pluto", "podium",
|
||||
"portal", "potato", "prize", "process", "protein", "proxy",
|
||||
"pump", "pupil", "python", "quality", "quarter", "quiet",
|
||||
"rabbit", "radical", "radius", "rainbow", "ralph", "ramirez",
|
||||
"ravioli", "raymond", "respect", "respond", "result", "resume",
|
||||
"retro", "richard", "right", "risk", "river", "roger",
|
||||
"roman", "rondo", "sabrina", "salary", "salsa", "sample",
|
||||
"samuel", "saturn", "savage", "scarlet", "scoop", "scorpio",
|
||||
"scratch", "scroll", "sector", "serpent", "shadow", "shampoo",
|
||||
"sharon", "sharp", "short", "shrink", "silence", "silk",
|
||||
"simple", "slang", "smart", "smoke", "snake", "society",
|
||||
"sonar", "sonata", "soprano", "source", "sparta", "sphere",
|
||||
"spider", "sponsor", "spring", "acid", "adios", "agatha",
|
||||
"alamo", "alert", "almanac", "aloha", "andrea", "anita",
|
||||
"arcade", "aurora", "avalon", "baby", "baggage", "balloon",
|
||||
"bank", "basil", "begin", "biscuit", "blue", "bombay",
|
||||
"brain", "brenda", "brigade", "cable", "carmen", "cello",
|
||||
"celtic", "chariot", "chrome", "citrus", "civil", "cloud",
|
||||
"common", "compare", "cool", "copper", "coral", "crater",
|
||||
"cubic", "cupid", "cycle", "depend", "door", "dream",
|
||||
"dynasty", "edison", "edition", "enigma", "equal", "eric",
|
||||
"event", "evita", "exodus", "extend", "famous", "farmer",
|
||||
"food", "fossil", "frog", "fruit", "geneva", "gentle",
|
||||
"george", "giant", "gilbert", "gossip", "gram", "greek",
|
||||
"grille", "hammer", "harvest", "hazard", "heaven", "herbert",
|
||||
"heroic", "hexagon", "husband", "immune", "inca", "inch",
|
||||
"initial", "isabel", "ivory", "jason", "jerome", "joel",
|
||||
"joshua", "journal", "judge", "juliet", "jump", "justice",
|
||||
"kimono", "kinetic", "leonid", "lima", "maze", "medusa",
|
||||
"member", "memphis", "michael", "miguel", "milan", "mile",
|
||||
"miller", "mimic", "mimosa", "mission", "monkey", "moral",
|
||||
"moses", "mouse", "nancy", "natasha", "nebula", "nickel",
|
||||
"nina", "noise", "orchid", "oregano", "origami", "orinoco",
|
||||
"orion", "othello", "paper", "paprika", "prelude", "prepare",
|
||||
"pretend", "profit", "promise", "provide", "puzzle", "remote",
|
||||
"repair", "reply", "rival", "riviera", "robin", "rose",
|
||||
"rover", "rudolf", "saga", "sahara", "scholar", "shelter",
|
||||
"ship", "shoe", "sigma", "sister", "sleep", "smile",
|
||||
"spain", "spark", "split", "spray", "square", "stadium",
|
||||
"star", "storm", "story", "strange", "stretch", "stuart",
|
||||
"subway", "sugar", "sulfur", "summer", "survive", "sweet",
|
||||
"swim", "table", "taboo", "target", "teacher", "telecom",
|
||||
"temple", "tibet", "ticket", "tina", "today", "toga",
|
||||
"tommy", "tower", "trivial", "tunnel", "turtle", "twin",
|
||||
"uncle", "unicorn", "unique", "update", "valery", "vega",
|
||||
"version", "voodoo", "warning", "william", "wonder", "year",
|
||||
"yellow", "young", "absent", "absorb", "accent", "alfonso",
|
||||
"alias", "ambient", "andy", "anvil", "appear", "apropos",
|
||||
"archer", "ariel", "armor", "arrow", "austin", "avatar",
|
||||
"axis", "baboon", "bahama", "bali", "balsa", "bazooka",
|
||||
"beach", "beast", "beatles", "beauty", "before", "benny",
|
||||
"betty", "between", "beyond", "billy", "bison", "blast",
|
||||
"bless", "bogart", "bonanza", "book", "border", "brave",
|
||||
"bread", "break", "broken", "bucket", "buenos", "buffalo",
|
||||
"bundle", "button", "buzzer", "byte", "caesar", "camilla",
|
||||
"canary", "candid", "carrot", "cave", "chant", "child",
|
||||
"choice", "chris", "cipher", "clarion", "clark", "clever",
|
||||
"cliff", "clone", "conan", "conduct", "congo", "content",
|
||||
"costume", "cotton", "cover", "crack", "current", "danube",
|
||||
"data", "decide", "desire", "detail", "dexter", "dinner",
|
||||
"dispute", "donor", "druid", "drum", "easy", "eddie",
|
||||
"enjoy", "enrico", "epoxy", "erosion", "except", "exile",
|
||||
"explain", "fame", "fast", "father", "felix", "field",
|
||||
"fiona", "fire", "fish", "flame", "flex", "flipper",
|
||||
"float", "flood", "floor", "forbid", "forever", "fractal",
|
||||
"frame", "freddie", "front", "fuel", "gallop", "game",
|
||||
"garbo", "gate", "gibson", "ginger", "giraffe", "gizmo",
|
||||
"glass", "goblin", "gopher", "grace", "gray", "gregory",
|
||||
"grid", "griffin", "ground", "guest", "gustav", "gyro",
|
||||
"hair", "halt", "harris", "heart", "heavy", "herman",
|
||||
"hippie", "hobby", "honey", "hope", "horse", "hostel",
|
||||
"hydro", "imitate", "info", "ingrid", "inside", "invent",
|
||||
"invest", "invite", "iron", "ivan", "james", "jester",
|
||||
"jimmy", "join", "joseph", "juice", "julius", "july",
|
||||
"justin", "kansas", "karl", "kevin", "kiwi", "ladder",
|
||||
"lake", "laura", "learn", "legacy", "legend", "lesson",
|
||||
"life", "light", "list", "locate", "lopez", "lorenzo",
|
||||
"love", "lunch", "malta", "mammal", "margo", "marion",
|
||||
"mask", "match", "mayday", "meaning", "mercy", "middle",
|
||||
"mike", "mirror", "modest", "morph", "morris", "nadia",
|
||||
"nato", "navy", "needle", "neuron", "never", "newton",
|
||||
"nice", "night", "nissan", "nitro", "nixon", "north",
|
||||
"oberon", "octavia", "ohio", "olga", "open", "opus",
|
||||
"orca", "oval", "owner", "page", "paint", "palma",
|
||||
"parade", "parent", "parole", "paul", "peace", "pearl",
|
||||
"perform", "phoenix", "phrase", "pierre", "pinball", "place",
|
||||
"plate", "plato", "plume", "pogo", "point", "polite",
|
||||
"polka", "poncho", "powder", "prague", "press", "presto",
|
||||
"pretty", "prime", "promo", "quasi", "quest", "quick",
|
||||
"quiz", "quota", "race", "rachel", "raja", "ranger",
|
||||
"region", "remark", "rent", "reward", "rhino", "ribbon",
|
||||
"rider", "road", "rodent", "round", "rubber", "ruby",
|
||||
"rufus", "sabine", "saddle", "sailor", "saint", "salt",
|
||||
"satire", "scale", "scuba", "season", "secure", "shake",
|
||||
"shallow", "shannon", "shave", "shelf", "sherman", "shine",
|
||||
"shirt", "side", "sinatra", "sincere", "size", "slalom",
|
||||
"slow", "small", "snow", "sofia", "song", "sound",
|
||||
"south", "speech", "spell", "spend", "spoon", "stage",
|
||||
"stamp", "stand", "state", "stella", "stick", "sting",
|
||||
"stock", "store", "sunday", "sunset", "support", "sweden",
|
||||
"swing", "tape", "think", "thomas", "tictac", "time",
|
||||
"toast", "tobacco", "tonight", "torch", "torso", "touch",
|
||||
"toyota", "trade", "tribune", "trinity", "triton", "truck",
|
||||
"trust", "type", "under", "unit", "urban", "urgent",
|
||||
"user", "value", "vendor", "venice", "verona", "vibrate",
|
||||
"virgo", "visible", "vista", "vital", "voice", "vortex",
|
||||
"waiter", "watch", "wave", "weather", "wedding", "wheel",
|
||||
"whiskey", "wisdom", "deal", "null", "nurse", "quebec",
|
||||
"reserve", "reunion", "roof", "singer", "verbal", "amen",
|
||||
"ego", "fax", "jet", "job", "rio", "ski",
|
||||
"yes",
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
logrus
|
|
@ -0,0 +1,15 @@
|
|||
language: go
|
||||
go:
|
||||
- 1.6.x
|
||||
- 1.7.x
|
||||
- 1.8.x
|
||||
- tip
|
||||
env:
|
||||
- GOMAXPROCS=4 GORACE=halt_on_error=1
|
||||
install:
|
||||
- go get github.com/stretchr/testify/assert
|
||||
- go get gopkg.in/gemnasium/logrus-airbrake-hook.v2
|
||||
- go get golang.org/x/sys/unix
|
||||
- go get golang.org/x/sys/windows
|
||||
script:
|
||||
- go test -race -v ./...
|
|
@ -0,0 +1,113 @@
|
|||
# 1.0.3
|
||||
|
||||
* Replace example files with testable examples
|
||||
|
||||
# 1.0.2
|
||||
|
||||
* bug: quote non-string values in text formatter (#583)
|
||||
* Make (*Logger) SetLevel a public method
|
||||
|
||||
# 1.0.1
|
||||
|
||||
* bug: fix escaping in text formatter (#575)
|
||||
|
||||
# 1.0.0
|
||||
|
||||
* Officially changed name to lower-case
|
||||
* bug: colors on Windows 10 (#541)
|
||||
* bug: fix race in accessing level (#512)
|
||||
|
||||
# 0.11.5
|
||||
|
||||
* feature: add writer and writerlevel to entry (#372)
|
||||
|
||||
# 0.11.4
|
||||
|
||||
* bug: fix undefined variable on solaris (#493)
|
||||
|
||||
# 0.11.3
|
||||
|
||||
* formatter: configure quoting of empty values (#484)
|
||||
* formatter: configure quoting character (default is `"`) (#484)
|
||||
* bug: fix not importing io correctly in non-linux environments (#481)
|
||||
|
||||
# 0.11.2
|
||||
|
||||
* bug: fix windows terminal detection (#476)
|
||||
|
||||
# 0.11.1
|
||||
|
||||
* bug: fix tty detection with custom out (#471)
|
||||
|
||||
# 0.11.0
|
||||
|
||||
* performance: Use bufferpool to allocate (#370)
|
||||
* terminal: terminal detection for app-engine (#343)
|
||||
* feature: exit handler (#375)
|
||||
|
||||
# 0.10.0
|
||||
|
||||
* feature: Add a test hook (#180)
|
||||
* feature: `ParseLevel` is now case-insensitive (#326)
|
||||
* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308)
|
||||
* performance: avoid re-allocations on `WithFields` (#335)
|
||||
|
||||
# 0.9.0
|
||||
|
||||
* logrus/text_formatter: don't emit empty msg
|
||||
* logrus/hooks/airbrake: move out of main repository
|
||||
* logrus/hooks/sentry: move out of main repository
|
||||
* logrus/hooks/papertrail: move out of main repository
|
||||
* logrus/hooks/bugsnag: move out of main repository
|
||||
* logrus/core: run tests with `-race`
|
||||
* logrus/core: detect TTY based on `stderr`
|
||||
* logrus/core: support `WithError` on logger
|
||||
* logrus/core: Solaris support
|
||||
|
||||
# 0.8.7
|
||||
|
||||
* logrus/core: fix possible race (#216)
|
||||
* logrus/doc: small typo fixes and doc improvements
|
||||
|
||||
|
||||
# 0.8.6
|
||||
|
||||
* hooks/raven: allow passing an initialized client
|
||||
|
||||
# 0.8.5
|
||||
|
||||
* logrus/core: revert #208
|
||||
|
||||
# 0.8.4
|
||||
|
||||
* formatter/text: fix data race (#218)
|
||||
|
||||
# 0.8.3
|
||||
|
||||
* logrus/core: fix entry log level (#208)
|
||||
* logrus/core: improve performance of text formatter by 40%
|
||||
* logrus/core: expose `LevelHooks` type
|
||||
* logrus/core: add support for DragonflyBSD and NetBSD
|
||||
* formatter/text: print structs more verbosely
|
||||
|
||||
# 0.8.2
|
||||
|
||||
* logrus: fix more Fatal family functions
|
||||
|
||||
# 0.8.1
|
||||
|
||||
* logrus: fix not exiting on `Fatalf` and `Fatalln`
|
||||
|
||||
# 0.8.0
|
||||
|
||||
* logrus: defaults to stderr instead of stdout
|
||||
* hooks/sentry: add special field for `*http.Request`
|
||||
* formatter/text: ignore Windows for colors
|
||||
|
||||
# 0.7.3
|
||||
|
||||
* formatter/\*: allow configuration of timestamp layout
|
||||
|
||||
# 0.7.2
|
||||
|
||||
* formatter/text: Add configuration option for time format (#158)
|
|
@ -0,0 +1,21 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Simon Eskildsen
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
|
@ -0,0 +1,505 @@
|
|||
# Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/> [![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus) [![GoDoc](https://godoc.org/github.com/sirupsen/logrus?status.svg)](https://godoc.org/github.com/sirupsen/logrus)
|
||||
|
||||
Logrus is a structured logger for Go (golang), completely API compatible with
|
||||
the standard library logger.
|
||||
|
||||
**Seeing weird case-sensitive problems?** It's in the past been possible to
|
||||
import Logrus as both upper- and lower-case. Due to the Go package environment,
|
||||
this caused issues in the community and we needed a standard. Some environments
|
||||
experienced problems with the upper-case variant, so the lower-case was decided.
|
||||
Everything using `logrus` will need to use the lower-case:
|
||||
`github.com/sirupsen/logrus`. Any package that isn't, should be changed.
|
||||
|
||||
To fix Glide, see [these
|
||||
comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437).
|
||||
For an in-depth explanation of the casing issue, see [this
|
||||
comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276).
|
||||
|
||||
**Are you interested in assisting in maintaining Logrus?** Currently I have a
|
||||
lot of obligations, and I am unable to provide Logrus with the maintainership it
|
||||
needs. If you'd like to help, please reach out to me at `simon at author's
|
||||
username dot com`.
|
||||
|
||||
Nicely color-coded in development (when a TTY is attached, otherwise just
|
||||
plain text):
|
||||
|
||||
![Colored](http://i.imgur.com/PY7qMwd.png)
|
||||
|
||||
With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash
|
||||
or Splunk:
|
||||
|
||||
```json
|
||||
{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the
|
||||
ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"}
|
||||
|
||||
{"level":"warning","msg":"The group's number increased tremendously!",
|
||||
"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"}
|
||||
|
||||
{"animal":"walrus","level":"info","msg":"A giant walrus appears!",
|
||||
"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"}
|
||||
|
||||
{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.",
|
||||
"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"}
|
||||
|
||||
{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true,
|
||||
"time":"2014-03-10 19:57:38.562543128 -0400 EDT"}
|
||||
```
|
||||
|
||||
With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not
|
||||
attached, the output is compatible with the
|
||||
[logfmt](http://godoc.org/github.com/kr/logfmt) format:
|
||||
|
||||
```text
|
||||
time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8
|
||||
time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
|
||||
time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true
|
||||
time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4
|
||||
time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009
|
||||
time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true
|
||||
exit status 1
|
||||
```
|
||||
|
||||
#### Case-sensitivity
|
||||
|
||||
The organization's name was changed to lower-case--and this will not be changed
|
||||
back. If you are getting import conflicts due to case sensitivity, please use
|
||||
the lower-case import: `github.com/sirupsen/logrus`.
|
||||
|
||||
#### Example
|
||||
|
||||
The simplest way to use Logrus is simply the package-level exported logger:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log.WithFields(log.Fields{
|
||||
"animal": "walrus",
|
||||
}).Info("A walrus appears")
|
||||
}
|
||||
```
|
||||
|
||||
Note that it's completely api-compatible with the stdlib logger, so you can
|
||||
replace your `log` imports everywhere with `log "github.com/sirupsen/logrus"`
|
||||
and you'll now have the flexibility of Logrus. You can customize it all you
|
||||
want:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func init() {
|
||||
// Log as JSON instead of the default ASCII formatter.
|
||||
log.SetFormatter(&log.JSONFormatter{})
|
||||
|
||||
// Output to stdout instead of the default stderr
|
||||
// Can be any io.Writer, see below for File example
|
||||
log.SetOutput(os.Stdout)
|
||||
|
||||
// Only log the warning severity or above.
|
||||
log.SetLevel(log.WarnLevel)
|
||||
}
|
||||
|
||||
func main() {
|
||||
log.WithFields(log.Fields{
|
||||
"animal": "walrus",
|
||||
"size": 10,
|
||||
}).Info("A group of walrus emerges from the ocean")
|
||||
|
||||
log.WithFields(log.Fields{
|
||||
"omg": true,
|
||||
"number": 122,
|
||||
}).Warn("The group's number increased tremendously!")
|
||||
|
||||
log.WithFields(log.Fields{
|
||||
"omg": true,
|
||||
"number": 100,
|
||||
}).Fatal("The ice breaks!")
|
||||
|
||||
// A common pattern is to re-use fields between logging statements by re-using
|
||||
// the logrus.Entry returned from WithFields()
|
||||
contextLogger := log.WithFields(log.Fields{
|
||||
"common": "this is a common field",
|
||||
"other": "I also should be logged always",
|
||||
})
|
||||
|
||||
contextLogger.Info("I'll be logged with common and other field")
|
||||
contextLogger.Info("Me too")
|
||||
}
|
||||
```
|
||||
|
||||
For more advanced usage such as logging to multiple locations from the same
|
||||
application, you can also create an instance of the `logrus` Logger:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Create a new instance of the logger. You can have any number of instances.
|
||||
var log = logrus.New()
|
||||
|
||||
func main() {
|
||||
// The API for setting attributes is a little different than the package level
|
||||
// exported logger. See Godoc.
|
||||
log.Out = os.Stdout
|
||||
|
||||
// You could set this to any `io.Writer` such as a file
|
||||
// file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666)
|
||||
// if err == nil {
|
||||
// log.Out = file
|
||||
// } else {
|
||||
// log.Info("Failed to log to file, using default stderr")
|
||||
// }
|
||||
|
||||
log.WithFields(logrus.Fields{
|
||||
"animal": "walrus",
|
||||
"size": 10,
|
||||
}).Info("A group of walrus emerges from the ocean")
|
||||
}
|
||||
```
|
||||
|
||||
#### Fields
|
||||
|
||||
Logrus encourages careful, structured logging through logging fields instead of
|
||||
long, unparseable error messages. For example, instead of: `log.Fatalf("Failed
|
||||
to send event %s to topic %s with key %d")`, you should log the much more
|
||||
discoverable:
|
||||
|
||||
```go
|
||||
log.WithFields(log.Fields{
|
||||
"event": event,
|
||||
"topic": topic,
|
||||
"key": key,
|
||||
}).Fatal("Failed to send event")
|
||||
```
|
||||
|
||||
We've found this API forces you to think about logging in a way that produces
|
||||
much more useful logging messages. We've been in countless situations where just
|
||||
a single added field to a log statement that was already there would've saved us
|
||||
hours. The `WithFields` call is optional.
|
||||
|
||||
In general, with Logrus using any of the `printf`-family functions should be
|
||||
seen as a hint you should add a field, however, you can still use the
|
||||
`printf`-family functions with Logrus.
|
||||
|
||||
#### Default Fields
|
||||
|
||||
Often it's helpful to have fields _always_ attached to log statements in an
|
||||
application or parts of one. For example, you may want to always log the
|
||||
`request_id` and `user_ip` in the context of a request. Instead of writing
|
||||
`log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on
|
||||
every line, you can create a `logrus.Entry` to pass around instead:
|
||||
|
||||
```go
|
||||
requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})
|
||||
requestLogger.Info("something happened on that request") # will log request_id and user_ip
|
||||
requestLogger.Warn("something not great happened")
|
||||
```
|
||||
|
||||
#### Hooks
|
||||
|
||||
You can add hooks for logging levels. For example to send errors to an exception
|
||||
tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to
|
||||
multiple places simultaneously, e.g. syslog.
|
||||
|
||||
Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in
|
||||
`init`:
|
||||
|
||||
```go
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "aibrake"
|
||||
logrus_syslog "github.com/sirupsen/logrus/hooks/syslog"
|
||||
"log/syslog"
|
||||
)
|
||||
|
||||
func init() {
|
||||
|
||||
// Use the Airbrake hook to report errors that have Error severity or above to
|
||||
// an exception tracker. You can create custom hooks, see the Hooks section.
|
||||
log.AddHook(airbrake.NewHook(123, "xyz", "production"))
|
||||
|
||||
hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
|
||||
if err != nil {
|
||||
log.Error("Unable to connect to local syslog daemon")
|
||||
} else {
|
||||
log.AddHook(hook)
|
||||
}
|
||||
}
|
||||
```
|
||||
Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md).
|
||||
|
||||
| Hook | Description |
|
||||
| ----- | ----------- |
|
||||
| [Airbrake "legacy"](https://github.com/gemnasium/logrus-airbrake-legacy-hook) | Send errors to an exception tracking service compatible with the Airbrake API V2. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. |
|
||||
| [Airbrake](https://github.com/gemnasium/logrus-airbrake-hook) | Send errors to the Airbrake API V3. Uses the official [`gobrake`](https://github.com/airbrake/gobrake) behind the scenes. |
|
||||
| [Amazon Kinesis](https://github.com/evalphobia/logrus_kinesis) | Hook for logging to [Amazon Kinesis](https://aws.amazon.com/kinesis/) |
|
||||
| [Amqp-Hook](https://github.com/vladoatanasov/logrus_amqp) | Hook for logging to Amqp broker (Like RabbitMQ) |
|
||||
| [Bugsnag](https://github.com/Shopify/logrus-bugsnag/blob/master/bugsnag.go) | Send errors to the Bugsnag exception tracking service. |
|
||||
| [DeferPanic](https://github.com/deferpanic/dp-logrus) | Hook for logging to DeferPanic |
|
||||
| [Discordrus](https://github.com/kz/discordrus) | Hook for logging to [Discord](https://discordapp.com/) |
|
||||
| [ElasticSearch](https://github.com/sohlich/elogrus) | Hook for logging to ElasticSearch|
|
||||
| [Firehose](https://github.com/beaubrewer/logrus_firehose) | Hook for logging to [Amazon Firehose](https://aws.amazon.com/kinesis/firehose/)
|
||||
| [Fluentd](https://github.com/evalphobia/logrus_fluent) | Hook for logging to fluentd |
|
||||
| [Go-Slack](https://github.com/multiplay/go-slack) | Hook for logging to [Slack](https://slack.com) |
|
||||
| [Graylog](https://github.com/gemnasium/logrus-graylog-hook) | Hook for logging to [Graylog](http://graylog2.org/) |
|
||||
| [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. |
|
||||
| [Honeybadger](https://github.com/agonzalezro/logrus_honeybadger) | Hook for sending exceptions to Honeybadger |
|
||||
| [InfluxDB](https://github.com/Abramovic/logrus_influxdb) | Hook for logging to influxdb |
|
||||
| [Influxus](http://github.com/vlad-doru/influxus) | Hook for concurrently logging to [InfluxDB](http://influxdata.com/) |
|
||||
| [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` |
|
||||
| [KafkaLogrus](https://github.com/goibibo/KafkaLogrus) | Hook for logging to kafka |
|
||||
| [LFShook](https://github.com/rifflock/lfshook) | Hook for logging to the local filesystem |
|
||||
| [Logentries](https://github.com/jcftang/logentriesrus) | Hook for logging to [Logentries](https://logentries.com/) |
|
||||
| [Logentrus](https://github.com/puddingfactory/logentrus) | Hook for logging to [Logentries](https://logentries.com/) |
|
||||
| [Logmatic.io](https://github.com/logmatic/logmatic-go) | Hook for logging to [Logmatic.io](http://logmatic.io/) |
|
||||
| [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) |
|
||||
| [Logstash](https://github.com/bshuster-repo/logrus-logstash-hook) | Hook for logging to [Logstash](https://www.elastic.co/products/logstash) |
|
||||
| [Mail](https://github.com/zbindenren/logrus_mail) | Hook for sending exceptions via mail |
|
||||
| [Mattermost](https://github.com/shuLhan/mattermost-integration/tree/master/hooks/logrus) | Hook for logging to [Mattermost](https://mattermost.com/) |
|
||||
| [Mongodb](https://github.com/weekface/mgorus) | Hook for logging to mongodb |
|
||||
| [NATS-Hook](https://github.com/rybit/nats_logrus_hook) | Hook for logging to [NATS](https://nats.io) |
|
||||
| [Octokit](https://github.com/dorajistyle/logrus-octokit-hook) | Hook for logging to github via octokit |
|
||||
| [Papertrail](https://github.com/polds/logrus-papertrail-hook) | Send errors to the [Papertrail](https://papertrailapp.com) hosted logging service via UDP. |
|
||||
| [PostgreSQL](https://github.com/gemnasium/logrus-postgresql-hook) | Send logs to [PostgreSQL](http://postgresql.org) |
|
||||
| [Pushover](https://github.com/toorop/logrus_pushover) | Send error via [Pushover](https://pushover.net) |
|
||||
| [Raygun](https://github.com/squirkle/logrus-raygun-hook) | Hook for logging to [Raygun.io](http://raygun.io/) |
|
||||
| [Redis-Hook](https://github.com/rogierlommers/logrus-redis-hook) | Hook for logging to a ELK stack (through Redis) |
|
||||
| [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar |
|
||||
| [Scribe](https://github.com/sagar8192/logrus-scribe-hook) | Hook for logging to [Scribe](https://github.com/facebookarchive/scribe)|
|
||||
| [Sentry](https://github.com/evalphobia/logrus_sentry) | Send errors to the Sentry error logging and aggregation service. |
|
||||
| [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. |
|
||||
| [Stackdriver](https://github.com/knq/sdhook) | Hook for logging to [Google Stackdriver](https://cloud.google.com/logging/) |
|
||||
| [Sumorus](https://github.com/doublefree/sumorus) | Hook for logging to [SumoLogic](https://www.sumologic.com/)|
|
||||
| [Syslog](https://github.com/sirupsen/logrus/blob/master/hooks/syslog/syslog.go) | Send errors to remote syslog server. Uses standard library `log/syslog` behind the scenes. |
|
||||
| [Syslog TLS](https://github.com/shinji62/logrus-syslog-ng) | Send errors to remote syslog server with TLS support. |
|
||||
| [TraceView](https://github.com/evalphobia/logrus_appneta) | Hook for logging to [AppNeta TraceView](https://www.appneta.com/products/traceview/) |
|
||||
| [Typetalk](https://github.com/dragon3/logrus-typetalk-hook) | Hook for logging to [Typetalk](https://www.typetalk.in/) |
|
||||
| [logz.io](https://github.com/ripcurld00d/logrus-logzio-hook) | Hook for logging to [logz.io](https://logz.io), a Log as a Service using Logstash |
|
||||
| [SQS-Hook](https://github.com/tsarpaul/logrus_sqs) | Hook for logging to [Amazon Simple Queue Service (SQS)](https://aws.amazon.com/sqs/) |
|
||||
|
||||
#### Level logging
|
||||
|
||||
Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic.
|
||||
|
||||
```go
|
||||
log.Debug("Useful debugging information.")
|
||||
log.Info("Something noteworthy happened!")
|
||||
log.Warn("You should probably take a look at this.")
|
||||
log.Error("Something failed but I'm not quitting.")
|
||||
// Calls os.Exit(1) after logging
|
||||
log.Fatal("Bye.")
|
||||
// Calls panic() after logging
|
||||
log.Panic("I'm bailing.")
|
||||
```
|
||||
|
||||
You can set the logging level on a `Logger`, then it will only log entries with
|
||||
that severity or anything above it:
|
||||
|
||||
```go
|
||||
// Will log anything that is info or above (warn, error, fatal, panic). Default.
|
||||
log.SetLevel(log.InfoLevel)
|
||||
```
|
||||
|
||||
It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose
|
||||
environment if your application has that.
|
||||
|
||||
#### Entries
|
||||
|
||||
Besides the fields added with `WithField` or `WithFields` some fields are
|
||||
automatically added to all logging events:
|
||||
|
||||
1. `time`. The timestamp when the entry was created.
|
||||
2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after
|
||||
the `AddFields` call. E.g. `Failed to send event.`
|
||||
3. `level`. The logging level. E.g. `info`.
|
||||
|
||||
#### Environments
|
||||
|
||||
Logrus has no notion of environment.
|
||||
|
||||
If you wish for hooks and formatters to only be used in specific environments,
|
||||
you should handle that yourself. For example, if your application has a global
|
||||
variable `Environment`, which is a string representation of the environment you
|
||||
could do:
|
||||
|
||||
```go
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
init() {
|
||||
// do something here to set environment depending on an environment variable
|
||||
// or command-line flag
|
||||
if Environment == "production" {
|
||||
log.SetFormatter(&log.JSONFormatter{})
|
||||
} else {
|
||||
// The TextFormatter is default, you don't actually have to do this.
|
||||
log.SetFormatter(&log.TextFormatter{})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This configuration is how `logrus` was intended to be used, but JSON in
|
||||
production is mostly only useful if you do log aggregation with tools like
|
||||
Splunk or Logstash.
|
||||
|
||||
#### Formatters
|
||||
|
||||
The built-in logging formatters are:
|
||||
|
||||
* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise
|
||||
without colors.
|
||||
* *Note:* to force colored output when there is no TTY, set the `ForceColors`
|
||||
field to `true`. To force no colored output even if there is a TTY set the
|
||||
`DisableColors` field to `true`. For Windows, see
|
||||
[github.com/mattn/go-colorable](https://github.com/mattn/go-colorable).
|
||||
* All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter).
|
||||
* `logrus.JSONFormatter`. Logs fields as JSON.
|
||||
* All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter).
|
||||
|
||||
Third party logging formatters:
|
||||
|
||||
* [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can by parsed by Kubernetes and Google Container Engine.
|
||||
* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events.
|
||||
* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout.
|
||||
* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦.
|
||||
|
||||
You can define your formatter by implementing the `Formatter` interface,
|
||||
requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a
|
||||
`Fields` type (`map[string]interface{}`) with all your fields as well as the
|
||||
default ones (see Entries section above):
|
||||
|
||||
```go
|
||||
type MyJSONFormatter struct {
|
||||
}
|
||||
|
||||
log.SetFormatter(new(MyJSONFormatter))
|
||||
|
||||
func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
|
||||
// Note this doesn't include Time, Level and Message which are available on
|
||||
// the Entry. Consult `godoc` on information about those fields or read the
|
||||
// source of the official loggers.
|
||||
serialized, err := json.Marshal(entry.Data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
|
||||
}
|
||||
return append(serialized, '\n'), nil
|
||||
}
|
||||
```
|
||||
|
||||
#### Logger as an `io.Writer`
|
||||
|
||||
Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it.
|
||||
|
||||
```go
|
||||
w := logger.Writer()
|
||||
defer w.Close()
|
||||
|
||||
srv := http.Server{
|
||||
// create a stdlib log.Logger that writes to
|
||||
// logrus.Logger.
|
||||
ErrorLog: log.New(w, "", 0),
|
||||
}
|
||||
```
|
||||
|
||||
Each line written to that writer will be printed the usual way, using formatters
|
||||
and hooks. The level for those entries is `info`.
|
||||
|
||||
This means that we can override the standard library logger easily:
|
||||
|
||||
```go
|
||||
logger := logrus.New()
|
||||
logger.Formatter = &logrus.JSONFormatter{}
|
||||
|
||||
// Use logrus for standard log output
|
||||
// Note that `log` here references stdlib's log
|
||||
// Not logrus imported under the name `log`.
|
||||
log.SetOutput(logger.Writer())
|
||||
```
|
||||
|
||||
#### Rotation
|
||||
|
||||
Log rotation is not provided with Logrus. Log rotation should be done by an
|
||||
external program (like `logrotate(8)`) that can compress and delete old log
|
||||
entries. It should not be a feature of the application-level logger.
|
||||
|
||||
#### Tools
|
||||
|
||||
| Tool | Description |
|
||||
| ---- | ----------- |
|
||||
|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.|
|
||||
|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) |
|
||||
|
||||
#### Testing
|
||||
|
||||
Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides:
|
||||
|
||||
* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook
|
||||
* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any):
|
||||
|
||||
```go
|
||||
import(
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/sirupsen/logrus/hooks/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSomething(t*testing.T){
|
||||
logger, hook := test.NewNullLogger()
|
||||
logger.Error("Helloerror")
|
||||
|
||||
assert.Equal(t, 1, len(hook.Entries))
|
||||
assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level)
|
||||
assert.Equal(t, "Helloerror", hook.LastEntry().Message)
|
||||
|
||||
hook.Reset()
|
||||
assert.Nil(t, hook.LastEntry())
|
||||
}
|
||||
```
|
||||
|
||||
#### Fatal handlers
|
||||
|
||||
Logrus can register one or more functions that will be called when any `fatal`
|
||||
level message is logged. The registered handlers will be executed before
|
||||
logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need
|
||||
to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted.
|
||||
|
||||
```
|
||||
...
|
||||
handler := func() {
|
||||
// gracefully shutdown something...
|
||||
}
|
||||
logrus.RegisterExitHandler(handler)
|
||||
...
|
||||
```
|
||||
|
||||
#### Thread safety
|
||||
|
||||
By default Logger is protected by mutex for concurrent writes, this mutex is invoked when calling hooks and writing logs.
|
||||
If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking.
|
||||
|
||||
Situation when locking is not needed includes:
|
||||
|
||||
* You have no hooks registered, or hooks calling is already thread-safe.
|
||||
|
||||
* Writing to logger.Out is already thread-safe, for example:
|
||||
|
||||
1) logger.Out is protected by locks.
|
||||
|
||||
2) logger.Out is a os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allow multi-thread/multi-process writing)
|
||||
|
||||
(Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/)
|
|
@ -0,0 +1,64 @@
|
|||
package logrus
|
||||
|
||||
// The following code was sourced and modified from the
|
||||
// https://github.com/tebeka/atexit package governed by the following license:
|
||||
//
|
||||
// Copyright (c) 2012 Miki Tebeka <miki.tebeka@gmail.com>.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
// this software and associated documentation files (the "Software"), to deal in
|
||||
// the Software without restriction, including without limitation the rights to
|
||||
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
// the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
// subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
var handlers = []func(){}
|
||||
|
||||
func runHandler(handler func()) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err)
|
||||
}
|
||||
}()
|
||||
|
||||
handler()
|
||||
}
|
||||
|
||||
func runHandlers() {
|
||||
for _, handler := range handlers {
|
||||
runHandler(handler)
|
||||
}
|
||||
}
|
||||
|
||||
// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code)
|
||||
func Exit(code int) {
|
||||
runHandlers()
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
// RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke
|
||||
// all handlers. The handlers will also be invoked when any Fatal log entry is
|
||||
// made.
|
||||
//
|
||||
// This method is useful when a caller wishes to use logrus to log a fatal
|
||||
// message but also needs to gracefully shutdown. An example usecase could be
|
||||
// closing database connections, or sending a alert that the application is
|
||||
// closing.
|
||||
func RegisterExitHandler(handler func()) {
|
||||
handlers = append(handlers, handler)
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
package logrus
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRegister(t *testing.T) {
|
||||
current := len(handlers)
|
||||
RegisterExitHandler(func() {})
|
||||
if len(handlers) != current+1 {
|
||||
t.Fatalf("expected %d handlers, got %d", current+1, len(handlers))
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandler(t *testing.T) {
|
||||
tempDir, err := ioutil.TempDir("", "test_handler")
|
||||
if err != nil {
|
||||
log.Fatalf("can't create temp dir. %q", err)
|
||||
}
|
||||
defer os.RemoveAll(tempDir)
|
||||
|
||||
gofile := filepath.Join(tempDir, "gofile.go")
|
||||
if err := ioutil.WriteFile(gofile, testprog, 0666); err != nil {
|
||||
t.Fatalf("can't create go file. %q", err)
|
||||
}
|
||||
|
||||
outfile := filepath.Join(tempDir, "outfile.out")
|
||||
arg := time.Now().UTC().String()
|
||||
err = exec.Command("go", "run", gofile, outfile, arg).Run()
|
||||
if err == nil {
|
||||
t.Fatalf("completed normally, should have failed")
|
||||
}
|
||||
|
||||
data, err := ioutil.ReadFile(outfile)
|
||||
if err != nil {
|
||||
t.Fatalf("can't read output file %s. %q", outfile, err)
|
||||
}
|
||||
|
||||
if string(data) != arg {
|
||||
t.Fatalf("bad data. Expected %q, got %q", data, arg)
|
||||
}
|
||||
}
|
||||
|
||||
var testprog = []byte(`
|
||||
// Test program for atexit, gets output file and data as arguments and writes
|
||||
// data to output file in atexit handler.
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/sirupsen/logrus"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
var outfile = ""
|
||||
var data = ""
|
||||
|
||||
func handler() {
|
||||
ioutil.WriteFile(outfile, []byte(data), 0666)
|
||||
}
|
||||
|
||||
func badHandler() {
|
||||
n := 0
|
||||
fmt.Println(1/n)
|
||||
}
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
outfile = flag.Arg(0)
|
||||
data = flag.Arg(1)
|
||||
|
||||
logrus.RegisterExitHandler(handler)
|
||||
logrus.RegisterExitHandler(badHandler)
|
||||
logrus.Fatal("Bye bye")
|
||||
}
|
||||
`)
|
|
@ -0,0 +1,14 @@
|
|||
version: "{build}"
|
||||
platform: x64
|
||||
clone_folder: c:\gopath\src\github.com\sirupsen\logrus
|
||||
environment:
|
||||
GOPATH: c:\gopath
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
install:
|
||||
- set PATH=%GOPATH%\bin;c:\go\bin;%PATH%
|
||||
- go version
|
||||
build_script:
|
||||
- go get -t
|
||||
- go test
|
|
@ -0,0 +1,26 @@
|
|||
/*
|
||||
Package logrus is a structured logger for Go, completely API compatible with the standard library logger.
|
||||
|
||||
|
||||
The simplest way to use Logrus is simply the package-level exported logger:
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log.WithFields(log.Fields{
|
||||
"animal": "walrus",
|
||||
"number": 1,
|
||||
"size": 10,
|
||||
}).Info("A walrus appears")
|
||||
}
|
||||
|
||||
Output:
|
||||
time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10
|
||||
|
||||
For a full guide visit https://github.com/sirupsen/logrus
|
||||
*/
|
||||
package logrus
|
|
@ -0,0 +1,276 @@
|
|||
package logrus
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var bufferPool *sync.Pool
|
||||
|
||||
func init() {
|
||||
bufferPool = &sync.Pool{
|
||||
New: func() interface{} {
|
||||
return new(bytes.Buffer)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Defines the key when adding errors using WithError.
|
||||
var ErrorKey = "error"
|
||||
|
||||
// An entry is the final or intermediate Logrus logging entry. It contains all
|
||||
// the fields passed with WithField{,s}. It's finally logged when Debug, Info,
|
||||
// Warn, Error, Fatal or Panic is called on it. These objects can be reused and
|
||||
// passed around as much as you wish to avoid field duplication.
|
||||
type Entry struct {
|
||||
Logger *Logger
|
||||
|
||||
// Contains all the fields set by the user.
|
||||
Data Fields
|
||||
|
||||
// Time at which the log entry was created
|
||||
Time time.Time
|
||||
|
||||
// Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic
|
||||
// This field will be set on entry firing and the value will be equal to the one in Logger struct field.
|
||||
Level Level
|
||||
|
||||
// Message passed to Debug, Info, Warn, Error, Fatal or Panic
|
||||
Message string
|
||||
|
||||
// When formatter is called in entry.log(), an Buffer may be set to entry
|
||||
Buffer *bytes.Buffer
|
||||
}
|
||||
|
||||
func NewEntry(logger *Logger) *Entry {
|
||||
return &Entry{
|
||||
Logger: logger,
|
||||
// Default is three fields, give a little extra room
|
||||
Data: make(Fields, 5),
|
||||
}
|
||||
}
|
||||
|
||||
// Returns the string representation from the reader and ultimately the
|
||||
// formatter.
|
||||
func (entry *Entry) String() (string, error) {
|
||||
serialized, err := entry.Logger.Formatter.Format(entry)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
str := string(serialized)
|
||||
return str, nil
|
||||
}
|
||||
|
||||
// Add an error as single field (using the key defined in ErrorKey) to the Entry.
|
||||
func (entry *Entry) WithError(err error) *Entry {
|
||||
return entry.WithField(ErrorKey, err)
|
||||
}
|
||||
|
||||
// Add a single field to the Entry.
|
||||
func (entry *Entry) WithField(key string, value interface{}) *Entry {
|
||||
return entry.WithFields(Fields{key: value})
|
||||
}
|
||||
|
||||
// Add a map of fields to the Entry.
|
||||
func (entry *Entry) WithFields(fields Fields) *Entry {
|
||||
data := make(Fields, len(entry.Data)+len(fields))
|
||||
for k, v := range entry.Data {
|
||||
data[k] = v
|
||||
}
|
||||
for k, v := range fields {
|
||||
data[k] = v
|
||||
}
|
||||
return &Entry{Logger: entry.Logger, Data: data}
|
||||
}
|
||||
|
||||
// This function is not declared with a pointer value because otherwise
|
||||
// race conditions will occur when using multiple goroutines
|
||||
func (entry Entry) log(level Level, msg string) {
|
||||
var buffer *bytes.Buffer
|
||||
entry.Time = time.Now()
|
||||
entry.Level = level
|
||||
entry.Message = msg
|
||||
|
||||
if err := entry.Logger.Hooks.Fire(level, &entry); err != nil {
|
||||
entry.Logger.mu.Lock()
|
||||
fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
|
||||
entry.Logger.mu.Unlock()
|
||||
}
|
||||
buffer = bufferPool.Get().(*bytes.Buffer)
|
||||
buffer.Reset()
|
||||
defer bufferPool.Put(buffer)
|
||||
entry.Buffer = buffer
|
||||
serialized, err := entry.Logger.Formatter.Format(&entry)
|
||||
entry.Buffer = nil
|
||||
if err != nil {
|
||||
entry.Logger.mu.Lock()
|
||||
fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
|
||||
entry.Logger.mu.Unlock()
|
||||
} else {
|
||||
entry.Logger.mu.Lock()
|
||||
_, err = entry.Logger.Out.Write(serialized)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
|
||||
}
|
||||
entry.Logger.mu.Unlock()
|
||||
}
|
||||
|
||||
// To avoid Entry#log() returning a value that only would make sense for
|
||||
// panic() to use in Entry#Panic(), we avoid the allocation by checking
|
||||
// directly here.
|
||||
if level <= PanicLevel {
|
||||
panic(&entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (entry *Entry) Debug(args ...interface{}) {
|
||||
if entry.Logger.level() >= DebugLevel {
|
||||
entry.log(DebugLevel, fmt.Sprint(args...))
|
||||
}
|
||||
}
|
||||
|
||||
func (entry *Entry) Print(args ...interface{}) {
|
||||
entry.Info(args...)
|
||||
}
|
||||
|
||||
func (entry *Entry) Info(args ...interface{}) {
|
||||
if entry.Logger.level() >= InfoLevel {
|
||||
entry.log(InfoLevel, fmt.Sprint(args...))
|
||||
}
|
||||
}
|
||||
|
||||
func (entry *Entry) Warn(args ...interface{}) {
|
||||
if entry.Logger.level() >= WarnLevel {
|
||||
entry.log(WarnLevel, fmt.Sprint(args...))
|
||||
}
|
||||
}
|
||||
|
||||
func (entry *Entry) Warning(args ...interface{}) {
|
||||
entry.Warn(args...)
|
||||
}
|
||||
|
||||
func (entry *Entry) Error(args ...interface{}) {
|
||||
if entry.Logger.level() >= ErrorLevel {
|
||||
entry.log(ErrorLevel, fmt.Sprint(args...))
|
||||
}
|
||||
}
|
||||
|
||||
func (entry *Entry) Fatal(args ...interface{}) {
|
||||
if entry.Logger.level() >= FatalLevel {
|
||||
entry.log(FatalLevel, fmt.Sprint(args...))
|
||||
}
|
||||
Exit(1)
|
||||
}
|
||||
|
||||
func (entry *Entry) Panic(args ...interface{}) {
|
||||
if entry.Logger.level() >= PanicLevel {
|
||||
entry.log(PanicLevel, fmt.Sprint(args...))
|
||||
}
|
||||
panic(fmt.Sprint(args...))
|
||||
}
|
||||
|
||||
// Entry Printf family functions
|
||||
|
||||
func (entry *Entry) Debugf(format string, args ...interface{}) {
|
||||
if entry.Logger.level() >= DebugLevel {
|
||||
entry.Debug(fmt.Sprintf(format, args...))
|
||||
}
|
||||
}
|
||||
|
||||
func (entry *Entry) Infof(format string, args ...interface{}) {
|
||||
if entry.Logger.level() >= InfoLevel {
|
||||
entry.Info(fmt.Sprintf(format, args...))
|
||||
}
|
||||
}
|
||||
|
||||
func (entry *Entry) Printf(format string, args ...interface{}) {
|
||||
entry.Infof(format, args...)
|
||||
}
|
||||
|
||||
func (entry *Entry) Warnf(format string, args ...interface{}) {
|
||||
if entry.Logger.level() >= WarnLevel {
|
||||
entry.Warn(fmt.Sprintf(format, args...))
|
||||
}
|
||||
}
|
||||
|
||||
func (entry *Entry) Warningf(format string, args ...interface{}) {
|
||||
entry.Warnf(format, args...)
|
||||
}
|
||||
|
||||
func (entry *Entry) Errorf(format string, args ...interface{}) {
|
||||
if entry.Logger.level() >= ErrorLevel {
|
||||
entry.Error(fmt.Sprintf(format, args...))
|
||||
}
|
||||
}
|
||||
|
||||
func (entry *Entry) Fatalf(format string, args ...interface{}) {
|
||||
if entry.Logger.level() >= FatalLevel {
|
||||
entry.Fatal(fmt.Sprintf(format, args...))
|
||||
}
|
||||
Exit(1)
|
||||
}
|
||||
|
||||
func (entry *Entry) Panicf(format string, args ...interface{}) {
|
||||
if entry.Logger.level() >= PanicLevel {
|
||||
entry.Panic(fmt.Sprintf(format, args...))
|
||||
}
|
||||
}
|
||||
|
||||
// Entry Println family functions
|
||||
|
||||
func (entry *Entry) Debugln(args ...interface{}) {
|
||||
if entry.Logger.level() >= DebugLevel {
|
||||
entry.Debug(entry.sprintlnn(args...))
|
||||
}
|
||||
}
|
||||
|
||||
func (entry *Entry) Infoln(args ...interface{}) {
|
||||
if entry.Logger.level() >= InfoLevel {
|
||||
entry.Info(entry.sprintlnn(args...))
|
||||
}
|
||||
}
|
||||
|
||||
func (entry *Entry) Println(args ...interface{}) {
|
||||
entry.Infoln(args...)
|
||||
}
|
||||
|
||||
func (entry *Entry) Warnln(args ...interface{}) {
|
||||
if entry.Logger.level() >= WarnLevel {
|
||||
entry.Warn(entry.sprintlnn(args...))
|
||||
}
|
||||
}
|
||||
|
||||
func (entry *Entry) Warningln(args ...interface{}) {
|
||||
entry.Warnln(args...)
|
||||
}
|
||||
|
||||
func (entry *Entry) Errorln(args ...interface{}) {
|
||||
if entry.Logger.level() >= ErrorLevel {
|
||||
entry.Error(entry.sprintlnn(args...))
|
||||
}
|
||||
}
|
||||
|
||||
func (entry *Entry) Fatalln(args ...interface{}) {
|
||||
if entry.Logger.level() >= FatalLevel {
|
||||
entry.Fatal(entry.sprintlnn(args...))
|
||||
}
|
||||
Exit(1)
|
||||
}
|
||||
|
||||
func (entry *Entry) Panicln(args ...interface{}) {
|
||||
if entry.Logger.level() >= PanicLevel {
|
||||
entry.Panic(entry.sprintlnn(args...))
|
||||
}
|
||||
}
|
||||
|
||||
// Sprintlnn => Sprint no newline. This is to get the behavior of how
|
||||
// fmt.Sprintln where spaces are always added between operands, regardless of
|
||||
// their type. Instead of vendoring the Sprintln implementation to spare a
|
||||
// string allocation, we do the simplest thing.
|
||||
func (entry *Entry) sprintlnn(args ...interface{}) string {
|
||||
msg := fmt.Sprintln(args...)
|
||||
return msg[:len(msg)-1]
|
||||
}
|
|
@ -0,0 +1,77 @@
|
|||
package logrus
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestEntryWithError(t *testing.T) {
|
||||
|
||||
assert := assert.New(t)
|
||||
|
||||
defer func() {
|
||||
ErrorKey = "error"
|
||||
}()
|
||||
|
||||
err := fmt.Errorf("kaboom at layer %d", 4711)
|
||||
|
||||
assert.Equal(err, WithError(err).Data["error"])
|
||||
|
||||
logger := New()
|
||||
logger.Out = &bytes.Buffer{}
|
||||
entry := NewEntry(logger)
|
||||
|
||||
assert.Equal(err, entry.WithError(err).Data["error"])
|
||||
|
||||
ErrorKey = "err"
|
||||
|
||||
assert.Equal(err, entry.WithError(err).Data["err"])
|
||||
|
||||
}
|
||||
|
||||
func TestEntryPanicln(t *testing.T) {
|
||||
errBoom := fmt.Errorf("boom time")
|
||||
|
||||
defer func() {
|
||||
p := recover()
|
||||
assert.NotNil(t, p)
|
||||
|
||||
switch pVal := p.(type) {
|
||||
case *Entry:
|
||||
assert.Equal(t, "kaboom", pVal.Message)
|
||||
assert.Equal(t, errBoom, pVal.Data["err"])
|
||||
default:
|
||||
t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal)
|
||||
}
|
||||
}()
|
||||
|
||||
logger := New()
|
||||
logger.Out = &bytes.Buffer{}
|
||||
entry := NewEntry(logger)
|
||||
entry.WithField("err", errBoom).Panicln("kaboom")
|
||||
}
|
||||
|
||||
func TestEntryPanicf(t *testing.T) {
|
||||
errBoom := fmt.Errorf("boom again")
|
||||
|
||||
defer func() {
|
||||
p := recover()
|
||||
assert.NotNil(t, p)
|
||||
|
||||
switch pVal := p.(type) {
|
||||
case *Entry:
|
||||
assert.Equal(t, "kaboom true", pVal.Message)
|
||||
assert.Equal(t, errBoom, pVal.Data["err"])
|
||||
default:
|
||||
t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal)
|
||||
}
|
||||
}()
|
||||
|
||||
logger := New()
|
||||
logger.Out = &bytes.Buffer{}
|
||||
entry := NewEntry(logger)
|
||||
entry.WithField("err", errBoom).Panicf("kaboom %v", true)
|
||||
}
|
|
@ -0,0 +1,69 @@
|
|||
package logrus_test
|
||||
|
||||
import (
|
||||
"github.com/sirupsen/logrus"
|
||||
"os"
|
||||
)
|
||||
|
||||
func Example_basic() {
|
||||
var log = logrus.New()
|
||||
log.Formatter = new(logrus.JSONFormatter)
|
||||
log.Formatter = new(logrus.TextFormatter) //default
|
||||
log.Formatter.(*logrus.TextFormatter).DisableTimestamp = true // remove timestamp from test output
|
||||
log.Level = logrus.DebugLevel
|
||||
log.Out = os.Stdout
|
||||
|
||||
// file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666)
|
||||
// if err == nil {
|
||||
// log.Out = file
|
||||
// } else {
|
||||
// log.Info("Failed to log to file, using default stderr")
|
||||
// }
|
||||
|
||||
defer func() {
|
||||
err := recover()
|
||||
if err != nil {
|
||||
entry := err.(*logrus.Entry)
|
||||
log.WithFields(logrus.Fields{
|
||||
"omg": true,
|
||||
"err_animal": entry.Data["animal"],
|
||||
"err_size": entry.Data["size"],
|
||||
"err_level": entry.Level,
|
||||
"err_message": entry.Message,
|
||||
"number": 100,
|
||||
}).Error("The ice breaks!") // or use Fatal() to force the process to exit with a nonzero code
|
||||
}
|
||||
}()
|
||||
|
||||
log.WithFields(logrus.Fields{
|
||||
"animal": "walrus",
|
||||
"number": 8,
|
||||
}).Debug("Started observing beach")
|
||||
|
||||
log.WithFields(logrus.Fields{
|
||||
"animal": "walrus",
|
||||
"size": 10,
|
||||
}).Info("A group of walrus emerges from the ocean")
|
||||
|
||||
log.WithFields(logrus.Fields{
|
||||
"omg": true,
|
||||
"number": 122,
|
||||
}).Warn("The group's number increased tremendously!")
|
||||
|
||||
log.WithFields(logrus.Fields{
|
||||
"temperature": -4,
|
||||
}).Debug("Temperature changes")
|
||||
|
||||
log.WithFields(logrus.Fields{
|
||||
"animal": "orca",
|
||||
"size": 9009,
|
||||
}).Panic("It's over 9000!")
|
||||
|
||||
// Output:
|
||||
// level=debug msg="Started observing beach" animal=walrus number=8
|
||||
// level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
|
||||
// level=warning msg="The group's number increased tremendously!" number=122 omg=true
|
||||
// level=debug msg="Temperature changes" temperature=-4
|
||||
// level=panic msg="It's over 9000!" animal=orca size=9009
|
||||
// level=error msg="The ice breaks!" err_animal=orca err_level=panic err_message="It's over 9000!" err_size=9009 number=100 omg=true
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package logrus_test
|
||||
|
||||
import (
|
||||
"github.com/sirupsen/logrus"
|
||||
"gopkg.in/gemnasium/logrus-airbrake-hook.v2"
|
||||
"os"
|
||||
)
|
||||
|
||||
func Example_hook() {
|
||||
var log = logrus.New()
|
||||
log.Formatter = new(logrus.TextFormatter) // default
|
||||
log.Formatter.(*logrus.TextFormatter).DisableTimestamp = true // remove timestamp from test output
|
||||
log.Hooks.Add(airbrake.NewHook(123, "xyz", "development"))
|
||||
log.Out = os.Stdout
|
||||
|
||||
log.WithFields(logrus.Fields{
|
||||
"animal": "walrus",
|
||||
"size": 10,
|
||||
}).Info("A group of walrus emerges from the ocean")
|
||||
|
||||
log.WithFields(logrus.Fields{
|
||||
"omg": true,
|
||||
"number": 122,
|
||||
}).Warn("The group's number increased tremendously!")
|
||||
|
||||
log.WithFields(logrus.Fields{
|
||||
"omg": true,
|
||||
"number": 100,
|
||||
}).Error("The ice breaks!")
|
||||
|
||||
// Output:
|
||||
// level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
|
||||
// level=warning msg="The group's number increased tremendously!" number=122 omg=true
|
||||
// level=error msg="The ice breaks!" number=100 omg=true
|
||||
}
|
|
@ -0,0 +1,193 @@
|
|||
package logrus
|
||||
|
||||
import (
|
||||
"io"
|
||||
)
|
||||
|
||||
var (
|
||||
// std is the name of the standard logger in stdlib `log`
|
||||
std = New()
|
||||
)
|
||||
|
||||
func StandardLogger() *Logger {
|
||||
return std
|
||||
}
|
||||
|
||||
// SetOutput sets the standard logger output.
|
||||
func SetOutput(out io.Writer) {
|
||||
std.mu.Lock()
|
||||
defer std.mu.Unlock()
|
||||
std.Out = out
|
||||
}
|
||||
|
||||
// SetFormatter sets the standard logger formatter.
|
||||
func SetFormatter(formatter Formatter) {
|
||||
std.mu.Lock()
|
||||
defer std.mu.Unlock()
|
||||
std.Formatter = formatter
|
||||
}
|
||||
|
||||
// SetLevel sets the standard logger level.
|
||||
func SetLevel(level Level) {
|
||||
std.mu.Lock()
|
||||
defer std.mu.Unlock()
|
||||
std.SetLevel(level)
|
||||
}
|
||||
|
||||
// GetLevel returns the standard logger level.
|
||||
func GetLevel() Level {
|
||||
std.mu.Lock()
|
||||
defer std.mu.Unlock()
|
||||
return std.level()
|
||||
}
|
||||
|
||||
// AddHook adds a hook to the standard logger hooks.
|
||||
func AddHook(hook Hook) {
|
||||
std.mu.Lock()
|
||||
defer std.mu.Unlock()
|
||||
std.Hooks.Add(hook)
|
||||
}
|
||||
|
||||
// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key.
|
||||
func WithError(err error) *Entry {
|
||||
return std.WithField(ErrorKey, err)
|
||||
}
|
||||
|
||||
// WithField creates an entry from the standard logger and adds a field to
|
||||
// it. If you want multiple fields, use `WithFields`.
|
||||
//
|
||||
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
|
||||
// or Panic on the Entry it returns.
|
||||
func WithField(key string, value interface{}) *Entry {
|
||||
return std.WithField(key, value)
|
||||
}
|
||||
|
||||
// WithFields creates an entry from the standard logger and adds multiple
|
||||
// fields to it. This is simply a helper for `WithField`, invoking it
|
||||
// once for each field.
|
||||
//
|
||||
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
|
||||
// or Panic on the Entry it returns.
|
||||
func WithFields(fields Fields) *Entry {
|
||||
return std.WithFields(fields)
|
||||
}
|
||||
|
||||
// Debug logs a message at level Debug on the standard logger.
|
||||
func Debug(args ...interface{}) {
|
||||
std.Debug(args...)
|
||||
}
|
||||
|
||||
// Print logs a message at level Info on the standard logger.
|
||||
func Print(args ...interface{}) {
|
||||
std.Print(args...)
|
||||
}
|
||||
|
||||
// Info logs a message at level Info on the standard logger.
|
||||
func Info(args ...interface{}) {
|
||||
std.Info(args...)
|
||||
}
|
||||
|
||||
// Warn logs a message at level Warn on the standard logger.
|
||||
func Warn(args ...interface{}) {
|
||||
std.Warn(args...)
|
||||
}
|
||||
|
||||
// Warning logs a message at level Warn on the standard logger.
|
||||
func Warning(args ...interface{}) {
|
||||
std.Warning(args...)
|
||||
}
|
||||
|
||||
// Error logs a message at level Error on the standard logger.
|
||||
func Error(args ...interface{}) {
|
||||
std.Error(args...)
|
||||
}
|
||||
|
||||
// Panic logs a message at level Panic on the standard logger.
|
||||
func Panic(args ...interface{}) {
|
||||
std.Panic(args...)
|
||||
}
|
||||
|
||||
// Fatal logs a message at level Fatal on the standard logger.
|
||||
func Fatal(args ...interface{}) {
|
||||
std.Fatal(args...)
|
||||
}
|
||||
|
||||
// Debugf logs a message at level Debug on the standard logger.
|
||||
func Debugf(format string, args ...interface{}) {
|
||||
std.Debugf(format, args...)
|
||||
}
|
||||
|
||||
// Printf logs a message at level Info on the standard logger.
|
||||
func Printf(format string, args ...interface{}) {
|
||||
std.Printf(format, args...)
|
||||
}
|
||||
|
||||
// Infof logs a message at level Info on the standard logger.
|
||||
func Infof(format string, args ...interface{}) {
|
||||
std.Infof(format, args...)
|
||||
}
|
||||
|
||||
// Warnf logs a message at level Warn on the standard logger.
|
||||
func Warnf(format string, args ...interface{}) {
|
||||
std.Warnf(format, args...)
|
||||
}
|
||||
|
||||
// Warningf logs a message at level Warn on the standard logger.
|
||||
func Warningf(format string, args ...interface{}) {
|
||||
std.Warningf(format, args...)
|
||||
}
|
||||
|
||||
// Errorf logs a message at level Error on the standard logger.
|
||||
func Errorf(format string, args ...interface{}) {
|
||||
std.Errorf(format, args...)
|
||||
}
|
||||
|
||||
// Panicf logs a message at level Panic on the standard logger.
|
||||
func Panicf(format string, args ...interface{}) {
|
||||
std.Panicf(format, args...)
|
||||
}
|
||||
|
||||
// Fatalf logs a message at level Fatal on the standard logger.
|
||||
func Fatalf(format string, args ...interface{}) {
|
||||
std.Fatalf(format, args...)
|
||||
}
|
||||
|
||||
// Debugln logs a message at level Debug on the standard logger.
|
||||
func Debugln(args ...interface{}) {
|
||||
std.Debugln(args...)
|
||||
}
|
||||
|
||||
// Println logs a message at level Info on the standard logger.
|
||||
func Println(args ...interface{}) {
|
||||
std.Println(args...)
|
||||
}
|
||||
|
||||
// Infoln logs a message at level Info on the standard logger.
|
||||
func Infoln(args ...interface{}) {
|
||||
std.Infoln(args...)
|
||||
}
|
||||
|
||||
// Warnln logs a message at level Warn on the standard logger.
|
||||
func Warnln(args ...interface{}) {
|
||||
std.Warnln(args...)
|
||||
}
|
||||
|
||||
// Warningln logs a message at level Warn on the standard logger.
|
||||
func Warningln(args ...interface{}) {
|
||||
std.Warningln(args...)
|
||||
}
|
||||
|
||||
// Errorln logs a message at level Error on the standard logger.
|
||||
func Errorln(args ...interface{}) {
|
||||
std.Errorln(args...)
|
||||
}
|
||||
|
||||
// Panicln logs a message at level Panic on the standard logger.
|
||||
func Panicln(args ...interface{}) {
|
||||
std.Panicln(args...)
|
||||
}
|
||||
|
||||
// Fatalln logs a message at level Fatal on the standard logger.
|
||||
func Fatalln(args ...interface{}) {
|
||||
std.Fatalln(args...)
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package logrus
|
||||
|
||||
import "time"
|
||||
|
||||
const defaultTimestampFormat = time.RFC3339
|
||||
|
||||
// The Formatter interface is used to implement a custom Formatter. It takes an
|
||||
// `Entry`. It exposes all the fields, including the default ones:
|
||||
//
|
||||
// * `entry.Data["msg"]`. The message passed from Info, Warn, Error ..
|
||||
// * `entry.Data["time"]`. The timestamp.
|
||||
// * `entry.Data["level"]. The level the entry was logged at.
|
||||
//
|
||||
// Any additional fields added with `WithField` or `WithFields` are also in
|
||||
// `entry.Data`. Format is expected to return an array of bytes which are then
|
||||
// logged to `logger.Out`.
|
||||
type Formatter interface {
|
||||
Format(*Entry) ([]byte, error)
|
||||
}
|
||||
|
||||
// This is to not silently overwrite `time`, `msg` and `level` fields when
|
||||
// dumping it. If this code wasn't there doing:
|
||||
//
|
||||
// logrus.WithField("level", 1).Info("hello")
|
||||
//
|
||||
// Would just silently drop the user provided level. Instead with this code
|
||||
// it'll logged as:
|
||||
//
|
||||
// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."}
|
||||
//
|
||||
// It's not exported because it's still using Data in an opinionated way. It's to
|
||||
// avoid code duplication between the two default formatters.
|
||||
func prefixFieldClashes(data Fields) {
|
||||
if t, ok := data["time"]; ok {
|
||||
data["fields.time"] = t
|
||||
}
|
||||
|
||||
if m, ok := data["msg"]; ok {
|
||||
data["fields.msg"] = m
|
||||
}
|
||||
|
||||
if l, ok := data["level"]; ok {
|
||||
data["fields.level"] = l
|
||||
}
|
||||
}
|
|
@ -0,0 +1,101 @@
|
|||
package logrus
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// smallFields is a small size data set for benchmarking
|
||||
var smallFields = Fields{
|
||||
"foo": "bar",
|
||||
"baz": "qux",
|
||||
"one": "two",
|
||||
"three": "four",
|
||||
}
|
||||
|
||||
// largeFields is a large size data set for benchmarking
|
||||
var largeFields = Fields{
|
||||
"foo": "bar",
|
||||
"baz": "qux",
|
||||
"one": "two",
|
||||
"three": "four",
|
||||
"five": "six",
|
||||
"seven": "eight",
|
||||
"nine": "ten",
|
||||
"eleven": "twelve",
|
||||
"thirteen": "fourteen",
|
||||
"fifteen": "sixteen",
|
||||
"seventeen": "eighteen",
|
||||
"nineteen": "twenty",
|
||||
"a": "b",
|
||||
"c": "d",
|
||||
"e": "f",
|
||||
"g": "h",
|
||||
"i": "j",
|
||||
"k": "l",
|
||||
"m": "n",
|
||||
"o": "p",
|
||||
"q": "r",
|
||||
"s": "t",
|
||||
"u": "v",
|
||||
"w": "x",
|
||||
"y": "z",
|
||||
"this": "will",
|
||||
"make": "thirty",
|
||||
"entries": "yeah",
|
||||
}
|
||||
|
||||
var errorFields = Fields{
|
||||
"foo": fmt.Errorf("bar"),
|
||||
"baz": fmt.Errorf("qux"),
|
||||
}
|
||||
|
||||
func BenchmarkErrorTextFormatter(b *testing.B) {
|
||||
doBenchmark(b, &TextFormatter{DisableColors: true}, errorFields)
|
||||
}
|
||||
|
||||
func BenchmarkSmallTextFormatter(b *testing.B) {
|
||||
doBenchmark(b, &TextFormatter{DisableColors: true}, smallFields)
|
||||
}
|
||||
|
||||
func BenchmarkLargeTextFormatter(b *testing.B) {
|
||||
doBenchmark(b, &TextFormatter{DisableColors: true}, largeFields)
|
||||
}
|
||||
|
||||
func BenchmarkSmallColoredTextFormatter(b *testing.B) {
|
||||
doBenchmark(b, &TextFormatter{ForceColors: true}, smallFields)
|
||||
}
|
||||
|
||||
func BenchmarkLargeColoredTextFormatter(b *testing.B) {
|
||||
doBenchmark(b, &TextFormatter{ForceColors: true}, largeFields)
|
||||
}
|
||||
|
||||
func BenchmarkSmallJSONFormatter(b *testing.B) {
|
||||
doBenchmark(b, &JSONFormatter{}, smallFields)
|
||||
}
|
||||
|
||||
func BenchmarkLargeJSONFormatter(b *testing.B) {
|
||||
doBenchmark(b, &JSONFormatter{}, largeFields)
|
||||
}
|
||||
|
||||
func doBenchmark(b *testing.B, formatter Formatter, fields Fields) {
|
||||
logger := New()
|
||||
|
||||
entry := &Entry{
|
||||
Time: time.Time{},
|
||||
Level: InfoLevel,
|
||||
Message: "message",
|
||||
Data: fields,
|
||||
Logger: logger,
|
||||
}
|
||||
var d []byte
|
||||
var err error
|
||||
for i := 0; i < b.N; i++ {
|
||||
d, err = formatter.Format(entry)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
b.SetBytes(int64(len(d)))
|
||||
}
|
||||
}
|
|
@ -0,0 +1,122 @@
|
|||
package logrus
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
type TestHook struct {
|
||||
Fired bool
|
||||
}
|
||||
|
||||
func (hook *TestHook) Fire(entry *Entry) error {
|
||||
hook.Fired = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hook *TestHook) Levels() []Level {
|
||||
return []Level{
|
||||
DebugLevel,
|
||||
InfoLevel,
|
||||
WarnLevel,
|
||||
ErrorLevel,
|
||||
FatalLevel,
|
||||
PanicLevel,
|
||||
}
|
||||
}
|
||||
|
||||
func TestHookFires(t *testing.T) {
|
||||
hook := new(TestHook)
|
||||
|
||||
LogAndAssertJSON(t, func(log *Logger) {
|
||||
log.Hooks.Add(hook)
|
||||
assert.Equal(t, hook.Fired, false)
|
||||
|
||||
log.Print("test")
|
||||
}, func(fields Fields) {
|
||||
assert.Equal(t, hook.Fired, true)
|
||||
})
|
||||
}
|
||||
|
||||
type ModifyHook struct {
|
||||
}
|
||||
|
||||
func (hook *ModifyHook) Fire(entry *Entry) error {
|
||||
entry.Data["wow"] = "whale"
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hook *ModifyHook) Levels() []Level {
|
||||
return []Level{
|
||||
DebugLevel,
|
||||
InfoLevel,
|
||||
WarnLevel,
|
||||
ErrorLevel,
|
||||
FatalLevel,
|
||||
PanicLevel,
|
||||
}
|
||||
}
|
||||
|
||||
func TestHookCanModifyEntry(t *testing.T) {
|
||||
hook := new(ModifyHook)
|
||||
|
||||
LogAndAssertJSON(t, func(log *Logger) {
|
||||
log.Hooks.Add(hook)
|
||||
log.WithField("wow", "elephant").Print("test")
|
||||
}, func(fields Fields) {
|
||||
assert.Equal(t, fields["wow"], "whale")
|
||||
})
|
||||
}
|
||||
|
||||
func TestCanFireMultipleHooks(t *testing.T) {
|
||||
hook1 := new(ModifyHook)
|
||||
hook2 := new(TestHook)
|
||||
|
||||
LogAndAssertJSON(t, func(log *Logger) {
|
||||
log.Hooks.Add(hook1)
|
||||
log.Hooks.Add(hook2)
|
||||
|
||||
log.WithField("wow", "elephant").Print("test")
|
||||
}, func(fields Fields) {
|
||||
assert.Equal(t, fields["wow"], "whale")
|
||||
assert.Equal(t, hook2.Fired, true)
|
||||
})
|
||||
}
|
||||
|
||||
type ErrorHook struct {
|
||||
Fired bool
|
||||
}
|
||||
|
||||
func (hook *ErrorHook) Fire(entry *Entry) error {
|
||||
hook.Fired = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hook *ErrorHook) Levels() []Level {
|
||||
return []Level{
|
||||
ErrorLevel,
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorHookShouldntFireOnInfo(t *testing.T) {
|
||||
hook := new(ErrorHook)
|
||||
|
||||
LogAndAssertJSON(t, func(log *Logger) {
|
||||
log.Hooks.Add(hook)
|
||||
log.Info("test")
|
||||
}, func(fields Fields) {
|
||||
assert.Equal(t, hook.Fired, false)
|
||||
})
|
||||
}
|
||||
|
||||
func TestErrorHookShouldFireOnError(t *testing.T) {
|
||||
hook := new(ErrorHook)
|
||||
|
||||
LogAndAssertJSON(t, func(log *Logger) {
|
||||
log.Hooks.Add(hook)
|
||||
log.Error("test")
|
||||
}, func(fields Fields) {
|
||||
assert.Equal(t, hook.Fired, true)
|
||||
})
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package logrus
|
||||
|
||||
// A hook to be fired when logging on the logging levels returned from
|
||||
// `Levels()` on your implementation of the interface. Note that this is not
|
||||
// fired in a goroutine or a channel with workers, you should handle such
|
||||
// functionality yourself if your call is non-blocking and you don't wish for
|
||||
// the logging calls for levels returned from `Levels()` to block.
|
||||
type Hook interface {
|
||||
Levels() []Level
|
||||
Fire(*Entry) error
|
||||
}
|
||||
|
||||
// Internal type for storing the hooks on a logger instance.
|
||||
type LevelHooks map[Level][]Hook
|
||||
|
||||
// Add a hook to an instance of logger. This is called with
|
||||
// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface.
|
||||
func (hooks LevelHooks) Add(hook Hook) {
|
||||
for _, level := range hook.Levels() {
|
||||
hooks[level] = append(hooks[level], hook)
|
||||
}
|
||||
}
|
||||
|
||||
// Fire all the hooks for the passed level. Used by `entry.log` to fire
|
||||
// appropriate hooks for a log entry.
|
||||
func (hooks LevelHooks) Fire(level Level, entry *Entry) error {
|
||||
for _, hook := range hooks[level] {
|
||||
if err := hook.Fire(entry); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
# Syslog Hooks for Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/>
|
||||
|
||||
## Usage
|
||||
|
||||
```go
|
||||
import (
|
||||
"log/syslog"
|
||||
"github.com/sirupsen/logrus"
|
||||
lSyslog "github.com/sirupsen/logrus/hooks/syslog"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log := logrus.New()
|
||||
hook, err := lSyslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
|
||||
|
||||
if err == nil {
|
||||
log.Hooks.Add(hook)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If you want to connect to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). Just assign empty string to the first two parameters of `NewSyslogHook`. It should look like the following.
|
||||
|
||||
```go
|
||||
import (
|
||||
"log/syslog"
|
||||
"github.com/sirupsen/logrus"
|
||||
lSyslog "github.com/sirupsen/logrus/hooks/syslog"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log := logrus.New()
|
||||
hook, err := lSyslog.NewSyslogHook("", "", syslog.LOG_INFO, "")
|
||||
|
||||
if err == nil {
|
||||
log.Hooks.Add(hook)
|
||||
}
|
||||
}
|
||||
```
|
|
@ -0,0 +1,55 @@
|
|||
// +build !windows,!nacl,!plan9
|
||||
|
||||
package syslog
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/syslog"
|
||||
"os"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// SyslogHook to send logs via syslog.
|
||||
type SyslogHook struct {
|
||||
Writer *syslog.Writer
|
||||
SyslogNetwork string
|
||||
SyslogRaddr string
|
||||
}
|
||||
|
||||
// Creates a hook to be added to an instance of logger. This is called with
|
||||
// `hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_DEBUG, "")`
|
||||
// `if err == nil { log.Hooks.Add(hook) }`
|
||||
func NewSyslogHook(network, raddr string, priority syslog.Priority, tag string) (*SyslogHook, error) {
|
||||
w, err := syslog.Dial(network, raddr, priority, tag)
|
||||
return &SyslogHook{w, network, raddr}, err
|
||||
}
|
||||
|
||||
func (hook *SyslogHook) Fire(entry *logrus.Entry) error {
|
||||
line, err := entry.String()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Unable to read entry, %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
switch entry.Level {
|
||||
case logrus.PanicLevel:
|
||||
return hook.Writer.Crit(line)
|
||||
case logrus.FatalLevel:
|
||||
return hook.Writer.Crit(line)
|
||||
case logrus.ErrorLevel:
|
||||
return hook.Writer.Err(line)
|
||||
case logrus.WarnLevel:
|
||||
return hook.Writer.Warning(line)
|
||||
case logrus.InfoLevel:
|
||||
return hook.Writer.Info(line)
|
||||
case logrus.DebugLevel:
|
||||
return hook.Writer.Debug(line)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (hook *SyslogHook) Levels() []logrus.Level {
|
||||
return logrus.AllLevels
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package syslog
|
||||
|
||||
import (
|
||||
"log/syslog"
|
||||
"testing"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func TestLocalhostAddAndPrint(t *testing.T) {
|
||||
log := logrus.New()
|
||||
hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Unable to connect to local syslog.")
|
||||
}
|
||||
|
||||
log.Hooks.Add(hook)
|
||||
|
||||
for _, level := range hook.Levels() {
|
||||
if len(log.Hooks[level]) != 1 {
|
||||
t.Errorf("SyslogHook was not added. The length of log.Hooks[%v]: %v", level, len(log.Hooks[level]))
|
||||
}
|
||||
}
|
||||
|
||||
log.Info("Congratulations!")
|
||||
}
|
|
@ -0,0 +1,95 @@
|
|||
// The Test package is used for testing logrus. It is here for backwards
|
||||
// compatibility from when logrus' organization was upper-case. Please use
|
||||
// lower-case logrus and the `null` package instead of this one.
|
||||
package test
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"sync"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Hook is a hook designed for dealing with logs in test scenarios.
|
||||
type Hook struct {
|
||||
// Entries is an array of all entries that have been received by this hook.
|
||||
// For safe access, use the AllEntries() method, rather than reading this
|
||||
// value directly.
|
||||
Entries []*logrus.Entry
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewGlobal installs a test hook for the global logger.
|
||||
func NewGlobal() *Hook {
|
||||
|
||||
hook := new(Hook)
|
||||
logrus.AddHook(hook)
|
||||
|
||||
return hook
|
||||
|
||||
}
|
||||
|
||||
// NewLocal installs a test hook for a given local logger.
|
||||
func NewLocal(logger *logrus.Logger) *Hook {
|
||||
|
||||
hook := new(Hook)
|
||||
logger.Hooks.Add(hook)
|
||||
|
||||
return hook
|
||||
|
||||
}
|
||||
|
||||
// NewNullLogger creates a discarding logger and installs the test hook.
|
||||
func NewNullLogger() (*logrus.Logger, *Hook) {
|
||||
|
||||
logger := logrus.New()
|
||||
logger.Out = ioutil.Discard
|
||||
|
||||
return logger, NewLocal(logger)
|
||||
|
||||
}
|
||||
|
||||
func (t *Hook) Fire(e *logrus.Entry) error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.Entries = append(t.Entries, e)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Hook) Levels() []logrus.Level {
|
||||
return logrus.AllLevels
|
||||
}
|
||||
|
||||
// LastEntry returns the last entry that was logged or nil.
|
||||
func (t *Hook) LastEntry() *logrus.Entry {
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
i := len(t.Entries) - 1
|
||||
if i < 0 {
|
||||
return nil
|
||||
}
|
||||
// Make a copy, for safety
|
||||
e := *t.Entries[i]
|
||||
return &e
|
||||
}
|
||||
|
||||
// AllEntries returns all entries that were logged.
|
||||
func (t *Hook) AllEntries() []*logrus.Entry {
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
// Make a copy so the returned value won't race with future log requests
|
||||
entries := make([]*logrus.Entry, len(t.Entries))
|
||||
for i, entry := range t.Entries {
|
||||
// Make a copy, for safety
|
||||
e := *entry
|
||||
entries[i] = &e
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
// Reset removes all Entries from this test hook.
|
||||
func (t *Hook) Reset() {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.Entries = make([]*logrus.Entry, 0)
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestAllHooks(t *testing.T) {
|
||||
|
||||
assert := assert.New(t)
|
||||
|
||||
logger, hook := NewNullLogger()
|
||||
assert.Nil(hook.LastEntry())
|
||||
assert.Equal(0, len(hook.Entries))
|
||||
|
||||
logger.Error("Hello error")
|
||||
assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
|
||||
assert.Equal("Hello error", hook.LastEntry().Message)
|
||||
assert.Equal(1, len(hook.Entries))
|
||||
|
||||
logger.Warn("Hello warning")
|
||||
assert.Equal(logrus.WarnLevel, hook.LastEntry().Level)
|
||||
assert.Equal("Hello warning", hook.LastEntry().Message)
|
||||
assert.Equal(2, len(hook.Entries))
|
||||
|
||||
hook.Reset()
|
||||
assert.Nil(hook.LastEntry())
|
||||
assert.Equal(0, len(hook.Entries))
|
||||
|
||||
hook = NewGlobal()
|
||||
|
||||
logrus.Error("Hello error")
|
||||
assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
|
||||
assert.Equal("Hello error", hook.LastEntry().Message)
|
||||
assert.Equal(1, len(hook.Entries))
|
||||
|
||||
}
|
|
@ -0,0 +1,79 @@
|
|||
package logrus
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type fieldKey string
|
||||
|
||||
// FieldMap allows customization of the key names for default fields.
|
||||
type FieldMap map[fieldKey]string
|
||||
|
||||
// Default key names for the default fields
|
||||
const (
|
||||
FieldKeyMsg = "msg"
|
||||
FieldKeyLevel = "level"
|
||||
FieldKeyTime = "time"
|
||||
)
|
||||
|
||||
func (f FieldMap) resolve(key fieldKey) string {
|
||||
if k, ok := f[key]; ok {
|
||||
return k
|
||||
}
|
||||
|
||||
return string(key)
|
||||
}
|
||||
|
||||
// JSONFormatter formats logs into parsable json
|
||||
type JSONFormatter struct {
|
||||
// TimestampFormat sets the format used for marshaling timestamps.
|
||||
TimestampFormat string
|
||||
|
||||
// DisableTimestamp allows disabling automatic timestamps in output
|
||||
DisableTimestamp bool
|
||||
|
||||
// FieldMap allows users to customize the names of keys for default fields.
|
||||
// As an example:
|
||||
// formatter := &JSONFormatter{
|
||||
// FieldMap: FieldMap{
|
||||
// FieldKeyTime: "@timestamp",
|
||||
// FieldKeyLevel: "@level",
|
||||
// FieldKeyMsg: "@message",
|
||||
// },
|
||||
// }
|
||||
FieldMap FieldMap
|
||||
}
|
||||
|
||||
// Format renders a single log entry
|
||||
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
|
||||
data := make(Fields, len(entry.Data)+3)
|
||||
for k, v := range entry.Data {
|
||||
switch v := v.(type) {
|
||||
case error:
|
||||
// Otherwise errors are ignored by `encoding/json`
|
||||
// https://github.com/sirupsen/logrus/issues/137
|
||||
data[k] = v.Error()
|
||||
default:
|
||||
data[k] = v
|
||||
}
|
||||
}
|
||||
prefixFieldClashes(data)
|
||||
|
||||
timestampFormat := f.TimestampFormat
|
||||
if timestampFormat == "" {
|
||||
timestampFormat = defaultTimestampFormat
|
||||
}
|
||||
|
||||
if !f.DisableTimestamp {
|
||||
data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
|
||||
}
|
||||
data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
|
||||
data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
|
||||
|
||||
serialized, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
|
||||
}
|
||||
return append(serialized, '\n'), nil
|
||||
}
|
|
@ -0,0 +1,199 @@
|
|||
package logrus
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestErrorNotLost(t *testing.T) {
|
||||
formatter := &JSONFormatter{}
|
||||
|
||||
b, err := formatter.Format(WithField("error", errors.New("wild walrus")))
|
||||
if err != nil {
|
||||
t.Fatal("Unable to format entry: ", err)
|
||||
}
|
||||
|
||||
entry := make(map[string]interface{})
|
||||
err = json.Unmarshal(b, &entry)
|
||||
if err != nil {
|
||||
t.Fatal("Unable to unmarshal formatted entry: ", err)
|
||||
}
|
||||
|
||||
if entry["error"] != "wild walrus" {
|
||||
t.Fatal("Error field not set")
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorNotLostOnFieldNotNamedError(t *testing.T) {
|
||||
formatter := &JSONFormatter{}
|
||||
|
||||
b, err := formatter.Format(WithField("omg", errors.New("wild walrus")))
|
||||
if err != nil {
|
||||
t.Fatal("Unable to format entry: ", err)
|
||||
}
|
||||
|
||||
entry := make(map[string]interface{})
|
||||
err = json.Unmarshal(b, &entry)
|
||||
if err != nil {
|
||||
t.Fatal("Unable to unmarshal formatted entry: ", err)
|
||||
}
|
||||
|
||||
if entry["omg"] != "wild walrus" {
|
||||
t.Fatal("Error field not set")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFieldClashWithTime(t *testing.T) {
|
||||
formatter := &JSONFormatter{}
|
||||
|
||||
b, err := formatter.Format(WithField("time", "right now!"))
|
||||
if err != nil {
|
||||
t.Fatal("Unable to format entry: ", err)
|
||||
}
|
||||
|
||||
entry := make(map[string]interface{})
|
||||
err = json.Unmarshal(b, &entry)
|
||||
if err != nil {
|
||||
t.Fatal("Unable to unmarshal formatted entry: ", err)
|
||||
}
|
||||
|
||||
if entry["fields.time"] != "right now!" {
|
||||
t.Fatal("fields.time not set to original time field")
|
||||
}
|
||||
|
||||
if entry["time"] != "0001-01-01T00:00:00Z" {
|
||||
t.Fatal("time field not set to current time, was: ", entry["time"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestFieldClashWithMsg(t *testing.T) {
|
||||
formatter := &JSONFormatter{}
|
||||
|
||||
b, err := formatter.Format(WithField("msg", "something"))
|
||||
if err != nil {
|
||||
t.Fatal("Unable to format entry: ", err)
|
||||
}
|
||||
|
||||
entry := make(map[string]interface{})
|
||||
err = json.Unmarshal(b, &entry)
|
||||
if err != nil {
|
||||
t.Fatal("Unable to unmarshal formatted entry: ", err)
|
||||
}
|
||||
|
||||
if entry["fields.msg"] != "something" {
|
||||
t.Fatal("fields.msg not set to original msg field")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFieldClashWithLevel(t *testing.T) {
|
||||
formatter := &JSONFormatter{}
|
||||
|
||||
b, err := formatter.Format(WithField("level", "something"))
|
||||
if err != nil {
|
||||
t.Fatal("Unable to format entry: ", err)
|
||||
}
|
||||
|
||||
entry := make(map[string]interface{})
|
||||
err = json.Unmarshal(b, &entry)
|
||||
if err != nil {
|
||||
t.Fatal("Unable to unmarshal formatted entry: ", err)
|
||||
}
|
||||
|
||||
if entry["fields.level"] != "something" {
|
||||
t.Fatal("fields.level not set to original level field")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJSONEntryEndsWithNewline(t *testing.T) {
|
||||
formatter := &JSONFormatter{}
|
||||
|
||||
b, err := formatter.Format(WithField("level", "something"))
|
||||
if err != nil {
|
||||
t.Fatal("Unable to format entry: ", err)
|
||||
}
|
||||
|
||||
if b[len(b)-1] != '\n' {
|
||||
t.Fatal("Expected JSON log entry to end with a newline")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJSONMessageKey(t *testing.T) {
|
||||
formatter := &JSONFormatter{
|
||||
FieldMap: FieldMap{
|
||||
FieldKeyMsg: "message",
|
||||
},
|
||||
}
|
||||
|
||||
b, err := formatter.Format(&Entry{Message: "oh hai"})
|
||||
if err != nil {
|
||||
t.Fatal("Unable to format entry: ", err)
|
||||
}
|
||||
s := string(b)
|
||||
if !(strings.Contains(s, "message") && strings.Contains(s, "oh hai")) {
|
||||
t.Fatal("Expected JSON to format message key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJSONLevelKey(t *testing.T) {
|
||||
formatter := &JSONFormatter{
|
||||
FieldMap: FieldMap{
|
||||
FieldKeyLevel: "somelevel",
|
||||
},
|
||||
}
|
||||
|
||||
b, err := formatter.Format(WithField("level", "something"))
|
||||
if err != nil {
|
||||
t.Fatal("Unable to format entry: ", err)
|
||||
}
|
||||
s := string(b)
|
||||
if !strings.Contains(s, "somelevel") {
|
||||
t.Fatal("Expected JSON to format level key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJSONTimeKey(t *testing.T) {
|
||||
formatter := &JSONFormatter{
|
||||
FieldMap: FieldMap{
|
||||
FieldKeyTime: "timeywimey",
|
||||
},
|
||||
}
|
||||
|
||||
b, err := formatter.Format(WithField("level", "something"))
|
||||
if err != nil {
|
||||
t.Fatal("Unable to format entry: ", err)
|
||||
}
|
||||
s := string(b)
|
||||
if !strings.Contains(s, "timeywimey") {
|
||||
t.Fatal("Expected JSON to format time key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJSONDisableTimestamp(t *testing.T) {
|
||||
formatter := &JSONFormatter{
|
||||
DisableTimestamp: true,
|
||||
}
|
||||
|
||||
b, err := formatter.Format(WithField("level", "something"))
|
||||
if err != nil {
|
||||
t.Fatal("Unable to format entry: ", err)
|
||||
}
|
||||
s := string(b)
|
||||
if strings.Contains(s, FieldKeyTime) {
|
||||
t.Error("Did not prevent timestamp", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJSONEnableTimestamp(t *testing.T) {
|
||||
formatter := &JSONFormatter{}
|
||||
|
||||
b, err := formatter.Format(WithField("level", "something"))
|
||||
if err != nil {
|
||||
t.Fatal("Unable to format entry: ", err)
|
||||
}
|
||||
s := string(b)
|
||||
if !strings.Contains(s, FieldKeyTime) {
|
||||
t.Error("Timestamp not present", s)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,317 @@
|
|||
package logrus
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
type Logger struct {
|
||||
// The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
|
||||
// file, or leave it default which is `os.Stderr`. You can also set this to
|
||||
// something more adventorous, such as logging to Kafka.
|
||||
Out io.Writer
|
||||
// Hooks for the logger instance. These allow firing events based on logging
|
||||
// levels and log entries. For example, to send errors to an error tracking
|
||||
// service, log to StatsD or dump the core on fatal errors.
|
||||
Hooks LevelHooks
|
||||
// All log entries pass through the formatter before logged to Out. The
|
||||
// included formatters are `TextFormatter` and `JSONFormatter` for which
|
||||
// TextFormatter is the default. In development (when a TTY is attached) it
|
||||
// logs with colors, but to a file it wouldn't. You can easily implement your
|
||||
// own that implements the `Formatter` interface, see the `README` or included
|
||||
// formatters for examples.
|
||||
Formatter Formatter
|
||||
// The logging level the logger should log at. This is typically (and defaults
|
||||
// to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be
|
||||
// logged.
|
||||
Level Level
|
||||
// Used to sync writing to the log. Locking is enabled by Default
|
||||
mu MutexWrap
|
||||
// Reusable empty entry
|
||||
entryPool sync.Pool
|
||||
}
|
||||
|
||||
type MutexWrap struct {
|
||||
lock sync.Mutex
|
||||
disabled bool
|
||||
}
|
||||
|
||||
func (mw *MutexWrap) Lock() {
|
||||
if !mw.disabled {
|
||||
mw.lock.Lock()
|
||||
}
|
||||
}
|
||||
|
||||
func (mw *MutexWrap) Unlock() {
|
||||
if !mw.disabled {
|
||||
mw.lock.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (mw *MutexWrap) Disable() {
|
||||
mw.disabled = true
|
||||
}
|
||||
|
||||
// Creates a new logger. Configuration should be set by changing `Formatter`,
|
||||
// `Out` and `Hooks` directly on the default logger instance. You can also just
|
||||
// instantiate your own:
|
||||
//
|
||||
// var log = &Logger{
|
||||
// Out: os.Stderr,
|
||||
// Formatter: new(JSONFormatter),
|
||||
// Hooks: make(LevelHooks),
|
||||
// Level: logrus.DebugLevel,
|
||||
// }
|
||||
//
|
||||
// It's recommended to make this a global instance called `log`.
|
||||
func New() *Logger {
|
||||
return &Logger{
|
||||
Out: os.Stderr,
|
||||
Formatter: new(TextFormatter),
|
||||
Hooks: make(LevelHooks),
|
||||
Level: InfoLevel,
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) newEntry() *Entry {
|
||||
entry, ok := logger.entryPool.Get().(*Entry)
|
||||
if ok {
|
||||
return entry
|
||||
}
|
||||
return NewEntry(logger)
|
||||
}
|
||||
|
||||
func (logger *Logger) releaseEntry(entry *Entry) {
|
||||
logger.entryPool.Put(entry)
|
||||
}
|
||||
|
||||
// Adds a field to the log entry, note that it doesn't log until you call
|
||||
// Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry.
|
||||
// If you want multiple fields, use `WithFields`.
|
||||
func (logger *Logger) WithField(key string, value interface{}) *Entry {
|
||||
entry := logger.newEntry()
|
||||
defer logger.releaseEntry(entry)
|
||||
return entry.WithField(key, value)
|
||||
}
|
||||
|
||||
// Adds a struct of fields to the log entry. All it does is call `WithField` for
|
||||
// each `Field`.
|
||||
func (logger *Logger) WithFields(fields Fields) *Entry {
|
||||
entry := logger.newEntry()
|
||||
defer logger.releaseEntry(entry)
|
||||
return entry.WithFields(fields)
|
||||
}
|
||||
|
||||
// Add an error as single field to the log entry. All it does is call
|
||||
// `WithError` for the given `error`.
|
||||
func (logger *Logger) WithError(err error) *Entry {
|
||||
entry := logger.newEntry()
|
||||
defer logger.releaseEntry(entry)
|
||||
return entry.WithError(err)
|
||||
}
|
||||
|
||||
func (logger *Logger) Debugf(format string, args ...interface{}) {
|
||||
if logger.level() >= DebugLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Debugf(format, args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Infof(format string, args ...interface{}) {
|
||||
if logger.level() >= InfoLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Infof(format, args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Printf(format string, args ...interface{}) {
|
||||
entry := logger.newEntry()
|
||||
entry.Printf(format, args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
|
||||
func (logger *Logger) Warnf(format string, args ...interface{}) {
|
||||
if logger.level() >= WarnLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Warnf(format, args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Warningf(format string, args ...interface{}) {
|
||||
if logger.level() >= WarnLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Warnf(format, args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Errorf(format string, args ...interface{}) {
|
||||
if logger.level() >= ErrorLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Errorf(format, args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Fatalf(format string, args ...interface{}) {
|
||||
if logger.level() >= FatalLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Fatalf(format, args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
Exit(1)
|
||||
}
|
||||
|
||||
func (logger *Logger) Panicf(format string, args ...interface{}) {
|
||||
if logger.level() >= PanicLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Panicf(format, args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Debug(args ...interface{}) {
|
||||
if logger.level() >= DebugLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Debug(args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Info(args ...interface{}) {
|
||||
if logger.level() >= InfoLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Info(args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Print(args ...interface{}) {
|
||||
entry := logger.newEntry()
|
||||
entry.Info(args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
|
||||
func (logger *Logger) Warn(args ...interface{}) {
|
||||
if logger.level() >= WarnLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Warn(args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Warning(args ...interface{}) {
|
||||
if logger.level() >= WarnLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Warn(args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Error(args ...interface{}) {
|
||||
if logger.level() >= ErrorLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Error(args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Fatal(args ...interface{}) {
|
||||
if logger.level() >= FatalLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Fatal(args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
Exit(1)
|
||||
}
|
||||
|
||||
func (logger *Logger) Panic(args ...interface{}) {
|
||||
if logger.level() >= PanicLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Panic(args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Debugln(args ...interface{}) {
|
||||
if logger.level() >= DebugLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Debugln(args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Infoln(args ...interface{}) {
|
||||
if logger.level() >= InfoLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Infoln(args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Println(args ...interface{}) {
|
||||
entry := logger.newEntry()
|
||||
entry.Println(args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
|
||||
func (logger *Logger) Warnln(args ...interface{}) {
|
||||
if logger.level() >= WarnLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Warnln(args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Warningln(args ...interface{}) {
|
||||
if logger.level() >= WarnLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Warnln(args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Errorln(args ...interface{}) {
|
||||
if logger.level() >= ErrorLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Errorln(args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (logger *Logger) Fatalln(args ...interface{}) {
|
||||
if logger.level() >= FatalLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Fatalln(args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
Exit(1)
|
||||
}
|
||||
|
||||
func (logger *Logger) Panicln(args ...interface{}) {
|
||||
if logger.level() >= PanicLevel {
|
||||
entry := logger.newEntry()
|
||||
entry.Panicln(args...)
|
||||
logger.releaseEntry(entry)
|
||||
}
|
||||
}
|
||||
|
||||
//When file is opened with appending mode, it's safe to
|
||||
//write concurrently to a file (within 4k message on Linux).
|
||||
//In these cases user can choose to disable the lock.
|
||||
func (logger *Logger) SetNoLock() {
|
||||
logger.mu.Disable()
|
||||
}
|
||||
|
||||
func (logger *Logger) level() Level {
|
||||
return Level(atomic.LoadUint32((*uint32)(&logger.Level)))
|
||||
}
|
||||
|
||||
func (logger *Logger) SetLevel(level Level) {
|
||||
atomic.StoreUint32((*uint32)(&logger.Level), uint32(level))
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
package logrus
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// smallFields is a small size data set for benchmarking
|
||||
var loggerFields = Fields{
|
||||
"foo": "bar",
|
||||
"baz": "qux",
|
||||
"one": "two",
|
||||
"three": "four",
|
||||
}
|
||||
|
||||
func BenchmarkDummyLogger(b *testing.B) {
|
||||
nullf, err := os.OpenFile("/dev/null", os.O_WRONLY, 0666)
|
||||
if err != nil {
|
||||
b.Fatalf("%v", err)
|
||||
}
|
||||
defer nullf.Close()
|
||||
doLoggerBenchmark(b, nullf, &TextFormatter{DisableColors: true}, smallFields)
|
||||
}
|
||||
|
||||
func BenchmarkDummyLoggerNoLock(b *testing.B) {
|
||||
nullf, err := os.OpenFile("/dev/null", os.O_WRONLY|os.O_APPEND, 0666)
|
||||
if err != nil {
|
||||
b.Fatalf("%v", err)
|
||||
}
|
||||
defer nullf.Close()
|
||||
doLoggerBenchmarkNoLock(b, nullf, &TextFormatter{DisableColors: true}, smallFields)
|
||||
}
|
||||
|
||||
func doLoggerBenchmark(b *testing.B, out *os.File, formatter Formatter, fields Fields) {
|
||||
logger := Logger{
|
||||
Out: out,
|
||||
Level: InfoLevel,
|
||||
Formatter: formatter,
|
||||
}
|
||||
entry := logger.WithFields(fields)
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
entry.Info("aaa")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func doLoggerBenchmarkNoLock(b *testing.B, out *os.File, formatter Formatter, fields Fields) {
|
||||
logger := Logger{
|
||||
Out: out,
|
||||
Level: InfoLevel,
|
||||
Formatter: formatter,
|
||||
}
|
||||
logger.SetNoLock()
|
||||
entry := logger.WithFields(fields)
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
entry.Info("aaa")
|
||||
}
|
||||
})
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue