You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by ro...@apache.org on 2018/04/13 22:06:53 UTC
[cloudstack-cloudmonkey] branch master updated (fa6d97b -> 88fcf8f)
This is an automated email from the ASF dual-hosted git repository.
rohit pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/cloudstack-cloudmonkey.git.
from fa6d97b docs: display better formatted help with 80char width
new 351fb28 vendor: merge readline forks, add go-ini for config management
new ed77ec0 config: implement ini based config same as legacy cloudmonkey
new 86b9e4a about: add separate go file for cli name, version
new 88fcf8f prompt: emoji-roulette on new shell
The 4 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
cli/completer.go | 4 +-
cli/exec.go | 2 +-
cli/selector.go | 2 +-
cli/shell.go | 6 +-
cmd/network.go | 6 +-
cmd/request.go | 2 +-
cmd/version.go | 2 +-
cmd/version.go => config/about.go | 23 +-
config/config.go | 211 +++---
cmd/set.go => config/prompt.go | 41 +-
vendor/github.com/chzyer/readline/runes.go | 1 +
vendor/github.com/rhtyd/readline/ansi_windows.go | 249 -------
vendor/github.com/rhtyd/readline/complete.go | 285 --------
.../github.com/rhtyd/readline/complete_helper.go | 165 -----
.../github.com/rhtyd/readline/complete_segment.go | 82 ---
vendor/github.com/rhtyd/readline/history.go | 330 ---------
vendor/github.com/rhtyd/readline/operation.go | 531 ---------------
vendor/github.com/rhtyd/readline/password.go | 33 -
.../github.com/rhtyd/readline/rawreader_windows.go | 125 ----
vendor/github.com/rhtyd/readline/readline.go | 326 ---------
vendor/github.com/rhtyd/readline/remote.go | 475 -------------
vendor/github.com/rhtyd/readline/runebuf.go | 629 -----------------
vendor/github.com/rhtyd/readline/runes.go | 224 ------
vendor/github.com/rhtyd/readline/runes/runes.go | 155 -----
vendor/github.com/rhtyd/readline/search.go | 164 -----
vendor/github.com/rhtyd/readline/std.go | 197 ------
vendor/github.com/rhtyd/readline/std_windows.go | 9 -
vendor/github.com/rhtyd/readline/term.go | 123 ----
vendor/github.com/rhtyd/readline/term_bsd.go | 29 -
vendor/github.com/rhtyd/readline/term_linux.go | 33 -
vendor/github.com/rhtyd/readline/term_solaris.go | 32 -
vendor/github.com/rhtyd/readline/term_unix.go | 24 -
vendor/github.com/rhtyd/readline/term_windows.go | 171 -----
vendor/github.com/rhtyd/readline/terminal.go | 238 -------
vendor/github.com/rhtyd/readline/utils.go | 277 --------
vendor/github.com/rhtyd/readline/utils_unix.go | 83 ---
vendor/github.com/rhtyd/readline/utils_windows.go | 41 --
vendor/github.com/rhtyd/readline/vim.go | 176 -----
vendor/github.com/rhtyd/readline/windows_api.go | 152 -----
vendor/gopkg.in/ini.v1/error.go | 32 +
vendor/gopkg.in/ini.v1/file.go | 407 +++++++++++
vendor/gopkg.in/ini.v1/ini.go | 197 ++++++
vendor/gopkg.in/ini.v1/key.go | 751 +++++++++++++++++++++
vendor/gopkg.in/ini.v1/parser.go | 401 +++++++++++
vendor/gopkg.in/ini.v1/section.go | 257 +++++++
vendor/gopkg.in/ini.v1/struct.go | 512 ++++++++++++++
46 files changed, 2741 insertions(+), 5474 deletions(-)
copy cmd/version.go => config/about.go (70%)
copy cmd/set.go => config/prompt.go (51%)
delete mode 100644 vendor/github.com/rhtyd/readline/ansi_windows.go
delete mode 100644 vendor/github.com/rhtyd/readline/complete.go
delete mode 100644 vendor/github.com/rhtyd/readline/complete_helper.go
delete mode 100644 vendor/github.com/rhtyd/readline/complete_segment.go
delete mode 100644 vendor/github.com/rhtyd/readline/history.go
delete mode 100644 vendor/github.com/rhtyd/readline/operation.go
delete mode 100644 vendor/github.com/rhtyd/readline/password.go
delete mode 100644 vendor/github.com/rhtyd/readline/rawreader_windows.go
delete mode 100644 vendor/github.com/rhtyd/readline/readline.go
delete mode 100644 vendor/github.com/rhtyd/readline/remote.go
delete mode 100644 vendor/github.com/rhtyd/readline/runebuf.go
delete mode 100644 vendor/github.com/rhtyd/readline/runes.go
delete mode 100644 vendor/github.com/rhtyd/readline/runes/runes.go
delete mode 100644 vendor/github.com/rhtyd/readline/search.go
delete mode 100644 vendor/github.com/rhtyd/readline/std.go
delete mode 100644 vendor/github.com/rhtyd/readline/std_windows.go
delete mode 100644 vendor/github.com/rhtyd/readline/term.go
delete mode 100644 vendor/github.com/rhtyd/readline/term_bsd.go
delete mode 100644 vendor/github.com/rhtyd/readline/term_linux.go
delete mode 100644 vendor/github.com/rhtyd/readline/term_solaris.go
delete mode 100644 vendor/github.com/rhtyd/readline/term_unix.go
delete mode 100644 vendor/github.com/rhtyd/readline/term_windows.go
delete mode 100644 vendor/github.com/rhtyd/readline/terminal.go
delete mode 100644 vendor/github.com/rhtyd/readline/utils.go
delete mode 100644 vendor/github.com/rhtyd/readline/utils_unix.go
delete mode 100644 vendor/github.com/rhtyd/readline/utils_windows.go
delete mode 100644 vendor/github.com/rhtyd/readline/vim.go
delete mode 100644 vendor/github.com/rhtyd/readline/windows_api.go
create mode 100644 vendor/gopkg.in/ini.v1/error.go
create mode 100644 vendor/gopkg.in/ini.v1/file.go
create mode 100644 vendor/gopkg.in/ini.v1/ini.go
create mode 100644 vendor/gopkg.in/ini.v1/key.go
create mode 100644 vendor/gopkg.in/ini.v1/parser.go
create mode 100644 vendor/gopkg.in/ini.v1/section.go
create mode 100644 vendor/gopkg.in/ini.v1/struct.go
--
To stop receiving notification emails like this one, please contact
rohit@apache.org.
[cloudstack-cloudmonkey] 01/04: vendor: merge readline forks,
add go-ini for config management
Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rohit pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/cloudstack-cloudmonkey.git
commit 351fb286cb4f3e17c949593b6270cbc91441df3f
Author: Rohit Yadav <ro...@apache.org>
AuthorDate: Sat Apr 14 00:20:39 2018 +0530
vendor: merge readline forks, add go-ini for config management
Signed-off-by: Rohit Yadav <ro...@apache.org>
---
cli/completer.go | 2 +-
cli/exec.go | 2 +-
cli/selector.go | 2 +-
cli/shell.go | 2 +-
cmd/request.go | 2 +-
vendor/github.com/chzyer/readline/runes.go | 1 +
vendor/github.com/rhtyd/readline/ansi_windows.go | 249 -------
vendor/github.com/rhtyd/readline/complete.go | 285 --------
.../github.com/rhtyd/readline/complete_helper.go | 165 -----
.../github.com/rhtyd/readline/complete_segment.go | 82 ---
vendor/github.com/rhtyd/readline/history.go | 330 ---------
vendor/github.com/rhtyd/readline/operation.go | 531 ---------------
vendor/github.com/rhtyd/readline/password.go | 33 -
.../github.com/rhtyd/readline/rawreader_windows.go | 125 ----
vendor/github.com/rhtyd/readline/readline.go | 326 ---------
vendor/github.com/rhtyd/readline/remote.go | 475 -------------
vendor/github.com/rhtyd/readline/runebuf.go | 629 -----------------
vendor/github.com/rhtyd/readline/runes.go | 224 ------
vendor/github.com/rhtyd/readline/runes/runes.go | 155 -----
vendor/github.com/rhtyd/readline/search.go | 164 -----
vendor/github.com/rhtyd/readline/std.go | 197 ------
vendor/github.com/rhtyd/readline/std_windows.go | 9 -
vendor/github.com/rhtyd/readline/term.go | 123 ----
vendor/github.com/rhtyd/readline/term_bsd.go | 29 -
vendor/github.com/rhtyd/readline/term_linux.go | 33 -
vendor/github.com/rhtyd/readline/term_solaris.go | 32 -
vendor/github.com/rhtyd/readline/term_unix.go | 24 -
vendor/github.com/rhtyd/readline/term_windows.go | 171 -----
vendor/github.com/rhtyd/readline/terminal.go | 238 -------
vendor/github.com/rhtyd/readline/utils.go | 277 --------
vendor/github.com/rhtyd/readline/utils_unix.go | 83 ---
vendor/github.com/rhtyd/readline/utils_windows.go | 41 --
vendor/github.com/rhtyd/readline/vim.go | 176 -----
vendor/github.com/rhtyd/readline/windows_api.go | 152 -----
vendor/gopkg.in/ini.v1/error.go | 32 +
vendor/gopkg.in/ini.v1/file.go | 407 +++++++++++
vendor/gopkg.in/ini.v1/ini.go | 197 ++++++
vendor/gopkg.in/ini.v1/key.go | 751 +++++++++++++++++++++
vendor/gopkg.in/ini.v1/parser.go | 401 +++++++++++
vendor/gopkg.in/ini.v1/section.go | 257 +++++++
vendor/gopkg.in/ini.v1/struct.go | 512 ++++++++++++++
41 files changed, 2563 insertions(+), 5363 deletions(-)
diff --git a/cli/completer.go b/cli/completer.go
index 58dadcc..9cd9a04 100644
--- a/cli/completer.go
+++ b/cli/completer.go
@@ -26,7 +26,7 @@ import (
"cloudmonkey/cmd"
"cloudmonkey/config"
- "github.com/rhtyd/readline/runes"
+ "github.com/chzyer/readline/runes"
)
type CliCompleter struct {
diff --git a/cli/exec.go b/cli/exec.go
index ab06f0d..f118768 100644
--- a/cli/exec.go
+++ b/cli/exec.go
@@ -20,7 +20,7 @@ package cli
import (
"cloudmonkey/cmd"
"cloudmonkey/config"
- "github.com/rhtyd/readline"
+ "github.com/chzyer/readline"
)
func ExecCmd(cfg *config.Config, args []string, shell *readline.Instance) error {
diff --git a/cli/selector.go b/cli/selector.go
index cfb8629..0f0b998 100644
--- a/cli/selector.go
+++ b/cli/selector.go
@@ -22,7 +22,7 @@ import (
"strings"
"github.com/manifoldco/promptui"
- "github.com/rhtyd/readline"
+ "github.com/chzyer/readline"
)
type SelectOption struct {
diff --git a/cli/shell.go b/cli/shell.go
index bf9f93e..f8fc031 100644
--- a/cli/shell.go
+++ b/cli/shell.go
@@ -25,7 +25,7 @@ import (
"cloudmonkey/config"
"github.com/mattn/go-shellwords"
- "github.com/rhtyd/readline"
+ "github.com/chzyer/readline"
)
func ExecShell(cfg *config.Config) {
diff --git a/cmd/request.go b/cmd/request.go
index 70b7023..66d7a48 100644
--- a/cmd/request.go
+++ b/cmd/request.go
@@ -19,7 +19,7 @@ package cmd
import (
"cloudmonkey/config"
- "github.com/rhtyd/readline"
+ "github.com/chzyer/readline"
)
type Request struct {
diff --git a/vendor/github.com/chzyer/readline/runes.go b/vendor/github.com/chzyer/readline/runes.go
index a669bc4..bcf483e 100644
--- a/vendor/github.com/chzyer/readline/runes.go
+++ b/vendor/github.com/chzyer/readline/runes.go
@@ -141,6 +141,7 @@ var doubleWidth = []*unicode.RangeTable{
unicode.Hangul,
unicode.Hiragana,
unicode.Katakana,
+ unicode.So,
}
func (Runes) Width(r rune) int {
diff --git a/vendor/github.com/rhtyd/readline/ansi_windows.go b/vendor/github.com/rhtyd/readline/ansi_windows.go
deleted file mode 100644
index 63b908c..0000000
--- a/vendor/github.com/rhtyd/readline/ansi_windows.go
+++ /dev/null
@@ -1,249 +0,0 @@
-// +build windows
-
-package readline
-
-import (
- "bufio"
- "io"
- "strconv"
- "strings"
- "sync"
- "unicode/utf8"
- "unsafe"
-)
-
-const (
- _ = uint16(0)
- COLOR_FBLUE = 0x0001
- COLOR_FGREEN = 0x0002
- COLOR_FRED = 0x0004
- COLOR_FINTENSITY = 0x0008
-
- COLOR_BBLUE = 0x0010
- COLOR_BGREEN = 0x0020
- COLOR_BRED = 0x0040
- COLOR_BINTENSITY = 0x0080
-
- COMMON_LVB_UNDERSCORE = 0x8000
- COMMON_LVB_BOLD = 0x0007
-)
-
-var ColorTableFg = []word{
- 0, // 30: Black
- COLOR_FRED, // 31: Red
- COLOR_FGREEN, // 32: Green
- COLOR_FRED | COLOR_FGREEN, // 33: Yellow
- COLOR_FBLUE, // 34: Blue
- COLOR_FRED | COLOR_FBLUE, // 35: Magenta
- COLOR_FGREEN | COLOR_FBLUE, // 36: Cyan
- COLOR_FRED | COLOR_FBLUE | COLOR_FGREEN, // 37: White
-}
-
-var ColorTableBg = []word{
- 0, // 40: Black
- COLOR_BRED, // 41: Red
- COLOR_BGREEN, // 42: Green
- COLOR_BRED | COLOR_BGREEN, // 43: Yellow
- COLOR_BBLUE, // 44: Blue
- COLOR_BRED | COLOR_BBLUE, // 45: Magenta
- COLOR_BGREEN | COLOR_BBLUE, // 46: Cyan
- COLOR_BRED | COLOR_BBLUE | COLOR_BGREEN, // 47: White
-}
-
-type ANSIWriter struct {
- target io.Writer
- wg sync.WaitGroup
- ctx *ANSIWriterCtx
- sync.Mutex
-}
-
-func NewANSIWriter(w io.Writer) *ANSIWriter {
- a := &ANSIWriter{
- target: w,
- ctx: NewANSIWriterCtx(w),
- }
- return a
-}
-
-func (a *ANSIWriter) Close() error {
- a.wg.Wait()
- return nil
-}
-
-type ANSIWriterCtx struct {
- isEsc bool
- isEscSeq bool
- arg []string
- target *bufio.Writer
- wantFlush bool
-}
-
-func NewANSIWriterCtx(target io.Writer) *ANSIWriterCtx {
- return &ANSIWriterCtx{
- target: bufio.NewWriter(target),
- }
-}
-
-func (a *ANSIWriterCtx) Flush() {
- a.target.Flush()
-}
-
-func (a *ANSIWriterCtx) process(r rune) bool {
- if a.wantFlush {
- if r == 0 || r == CharEsc {
- a.wantFlush = false
- a.target.Flush()
- }
- }
- if a.isEscSeq {
- a.isEscSeq = a.ioloopEscSeq(a.target, r, &a.arg)
- return true
- }
-
- switch r {
- case CharEsc:
- a.isEsc = true
- case '[':
- if a.isEsc {
- a.arg = nil
- a.isEscSeq = true
- a.isEsc = false
- break
- }
- fallthrough
- default:
- a.target.WriteRune(r)
- a.wantFlush = true
- }
- return true
-}
-
-func (a *ANSIWriterCtx) ioloopEscSeq(w *bufio.Writer, r rune, argptr *[]string) bool {
- arg := *argptr
- var err error
-
- if r >= 'A' && r <= 'D' {
- count := short(GetInt(arg, 1))
- info, err := GetConsoleScreenBufferInfo()
- if err != nil {
- return false
- }
- switch r {
- case 'A': // up
- info.dwCursorPosition.y -= count
- case 'B': // down
- info.dwCursorPosition.y += count
- case 'C': // right
- info.dwCursorPosition.x += count
- case 'D': // left
- info.dwCursorPosition.x -= count
- }
- SetConsoleCursorPosition(&info.dwCursorPosition)
- return false
- }
-
- switch r {
- case 'J':
- killLines()
- case 'K':
- eraseLine()
- case 'm':
- color := word(0)
- for _, item := range arg {
- var c int
- c, err = strconv.Atoi(item)
- if err != nil {
- w.WriteString("[" + strings.Join(arg, ";") + "m")
- break
- }
- if c >= 30 && c < 40 {
- color ^= COLOR_FINTENSITY
- color |= ColorTableFg[c-30]
- } else if c >= 40 && c < 50 {
- color ^= COLOR_BINTENSITY
- color |= ColorTableBg[c-40]
- } else if c == 4 {
- color |= COMMON_LVB_UNDERSCORE | ColorTableFg[7]
- } else if c == 1 {
- color |= COMMON_LVB_BOLD | COLOR_FINTENSITY
- } else { // unknown code treat as reset
- color = ColorTableFg[7]
- }
- }
- if err != nil {
- break
- }
- kernel.SetConsoleTextAttribute(stdout, uintptr(color))
- case '\007': // set title
- case ';':
- if len(arg) == 0 || arg[len(arg)-1] != "" {
- arg = append(arg, "")
- *argptr = arg
- }
- return true
- default:
- if len(arg) == 0 {
- arg = append(arg, "")
- }
- arg[len(arg)-1] += string(r)
- *argptr = arg
- return true
- }
- *argptr = nil
- return false
-}
-
-func (a *ANSIWriter) Write(b []byte) (int, error) {
- a.Lock()
- defer a.Unlock()
-
- off := 0
- for len(b) > off {
- r, size := utf8.DecodeRune(b[off:])
- if size == 0 {
- return off, io.ErrShortWrite
- }
- off += size
- a.ctx.process(r)
- }
- a.ctx.Flush()
- return off, nil
-}
-
-func killLines() error {
- sbi, err := GetConsoleScreenBufferInfo()
- if err != nil {
- return err
- }
-
- size := (sbi.dwCursorPosition.y - sbi.dwSize.y) * sbi.dwSize.x
- size += sbi.dwCursorPosition.x
-
- var written int
- kernel.FillConsoleOutputAttribute(stdout, uintptr(ColorTableFg[7]),
- uintptr(size),
- sbi.dwCursorPosition.ptr(),
- uintptr(unsafe.Pointer(&written)),
- )
- return kernel.FillConsoleOutputCharacterW(stdout, uintptr(' '),
- uintptr(size),
- sbi.dwCursorPosition.ptr(),
- uintptr(unsafe.Pointer(&written)),
- )
-}
-
-func eraseLine() error {
- sbi, err := GetConsoleScreenBufferInfo()
- if err != nil {
- return err
- }
-
- size := sbi.dwSize.x
- sbi.dwCursorPosition.x = 0
- var written int
- return kernel.FillConsoleOutputCharacterW(stdout, uintptr(' '),
- uintptr(size),
- sbi.dwCursorPosition.ptr(),
- uintptr(unsafe.Pointer(&written)),
- )
-}
diff --git a/vendor/github.com/rhtyd/readline/complete.go b/vendor/github.com/rhtyd/readline/complete.go
deleted file mode 100644
index d1351f7..0000000
--- a/vendor/github.com/rhtyd/readline/complete.go
+++ /dev/null
@@ -1,285 +0,0 @@
-package readline
-
-import (
- "bufio"
- "bytes"
- "fmt"
- "io"
-)
-
-type AutoCompleter interface {
- // Readline will pass the whole line and current offset to it
- // Completer need to pass all the candidates, and how long they shared the same characters in line
- // Example:
- // [go, git, git-shell, grep]
- // Do("g", 1) => ["o", "it", "it-shell", "rep"], 1
- // Do("gi", 2) => ["t", "t-shell"], 2
- // Do("git", 3) => ["", "-shell"], 3
- Do(line []rune, pos int) (newLine [][]rune, length int)
-}
-
-type TabCompleter struct{}
-
-func (t *TabCompleter) Do([]rune, int) ([][]rune, int) {
- return [][]rune{[]rune("\t")}, 0
-}
-
-type opCompleter struct {
- w io.Writer
- op *Operation
- width int
-
- inCompleteMode bool
- inSelectMode bool
- candidate [][]rune
- candidateSource []rune
- candidateOff int
- candidateChoise int
- candidateColNum int
-}
-
-func newOpCompleter(w io.Writer, op *Operation, width int) *opCompleter {
- return &opCompleter{
- w: w,
- op: op,
- width: width,
- }
-}
-
-func (o *opCompleter) doSelect() {
- if len(o.candidate) == 1 {
- o.op.buf.WriteRunes(o.candidate[0])
- o.ExitCompleteMode(false)
- return
- }
- o.nextCandidate(1)
- o.CompleteRefresh()
-}
-
-func (o *opCompleter) nextCandidate(i int) {
- o.candidateChoise += i
- o.candidateChoise = o.candidateChoise % len(o.candidate)
- if o.candidateChoise < 0 {
- o.candidateChoise = len(o.candidate) + o.candidateChoise
- }
-}
-
-func (o *opCompleter) OnComplete() bool {
- if o.width == 0 {
- return false
- }
- if o.IsInCompleteSelectMode() {
- o.doSelect()
- return true
- }
-
- buf := o.op.buf
- rs := buf.Runes()
-
- if o.IsInCompleteMode() && o.candidateSource != nil && runes.Equal(rs, o.candidateSource) {
- o.EnterCompleteSelectMode()
- o.doSelect()
- return true
- }
-
- o.ExitCompleteSelectMode()
- o.candidateSource = rs
- newLines, offset := o.op.cfg.AutoComplete.Do(rs, buf.idx)
- if len(newLines) == 0 {
- o.ExitCompleteMode(false)
- return true
- }
-
- // only Aggregate candidates in non-complete mode
- if !o.IsInCompleteMode() {
- if len(newLines) == 1 {
- buf.WriteRunes(newLines[0])
- o.ExitCompleteMode(false)
- return true
- }
-
- same, size := runes.Aggregate(newLines)
- if size > 0 {
- buf.WriteRunes(same)
- o.ExitCompleteMode(false)
- return true
- }
- }
-
- o.EnterCompleteMode(offset, newLines)
- return true
-}
-
-func (o *opCompleter) IsInCompleteSelectMode() bool {
- return o.inSelectMode
-}
-
-func (o *opCompleter) IsInCompleteMode() bool {
- return o.inCompleteMode
-}
-
-func (o *opCompleter) HandleCompleteSelect(r rune) bool {
- next := true
- switch r {
- case CharEnter, CharCtrlJ:
- next = false
- o.op.buf.WriteRunes(o.op.candidate[o.op.candidateChoise])
- o.ExitCompleteMode(false)
- case CharLineStart:
- num := o.candidateChoise % o.candidateColNum
- o.nextCandidate(-num)
- case CharLineEnd:
- num := o.candidateColNum - o.candidateChoise%o.candidateColNum - 1
- o.candidateChoise += num
- if o.candidateChoise >= len(o.candidate) {
- o.candidateChoise = len(o.candidate) - 1
- }
- case CharBackspace:
- o.ExitCompleteSelectMode()
- next = false
- case CharTab, CharForward:
- o.doSelect()
- case CharBell, CharInterrupt:
- o.ExitCompleteMode(true)
- next = false
- case CharNext:
- tmpChoise := o.candidateChoise + o.candidateColNum
- if tmpChoise >= o.getMatrixSize() {
- tmpChoise -= o.getMatrixSize()
- } else if tmpChoise >= len(o.candidate) {
- tmpChoise += o.candidateColNum
- tmpChoise -= o.getMatrixSize()
- }
- o.candidateChoise = tmpChoise
- case CharBackward:
- o.nextCandidate(-1)
- case CharPrev:
- tmpChoise := o.candidateChoise - o.candidateColNum
- if tmpChoise < 0 {
- tmpChoise += o.getMatrixSize()
- if tmpChoise >= len(o.candidate) {
- tmpChoise -= o.candidateColNum
- }
- }
- o.candidateChoise = tmpChoise
- default:
- next = false
- o.ExitCompleteSelectMode()
- }
- if next {
- o.CompleteRefresh()
- return true
- }
- return false
-}
-
-func (o *opCompleter) getMatrixSize() int {
- line := len(o.candidate) / o.candidateColNum
- if len(o.candidate)%o.candidateColNum != 0 {
- line++
- }
- return line * o.candidateColNum
-}
-
-func (o *opCompleter) OnWidthChange(newWidth int) {
- o.width = newWidth
-}
-
-func (o *opCompleter) CompleteRefresh() {
- if !o.inCompleteMode {
- return
- }
- lineCnt := o.op.buf.CursorLineCount()
- colWidth := 0
- for _, c := range o.candidate {
- w := runes.WidthAll(c)
- if w > colWidth {
- colWidth = w
- }
- }
- colWidth += o.candidateOff + 1
- same := o.op.buf.RuneSlice(-o.candidateOff)
-
- // -1 to avoid reach the end of line
- width := o.width - 1
- colNum := width / colWidth
- if colNum != 0 {
- colWidth += (width - (colWidth * colNum)) / colNum
- }
-
- o.candidateColNum = colNum
- buf := bufio.NewWriter(o.w)
- buf.Write(bytes.Repeat([]byte("\n"), lineCnt))
-
- colIdx := 0
- lines := 1
- buf.WriteString("\033[J")
- for idx, c := range o.candidate {
- inSelect := idx == o.candidateChoise && o.IsInCompleteSelectMode()
- if inSelect {
- buf.WriteString("\033[30;47m")
- }
- buf.WriteString(string(same))
- buf.WriteString(string(c))
- buf.Write(bytes.Repeat([]byte(" "), colWidth-len(c)-len(same)))
-
- if inSelect {
- buf.WriteString("\033[0m")
- }
-
- colIdx++
- if colIdx == colNum {
- buf.WriteString("\n")
- lines++
- colIdx = 0
- }
- }
-
- // move back
- fmt.Fprintf(buf, "\033[%dA\r", lineCnt-1+lines)
- fmt.Fprintf(buf, "\033[%dC", o.op.buf.idx+o.op.buf.PromptLen())
- buf.Flush()
-}
-
-func (o *opCompleter) aggCandidate(candidate [][]rune) int {
- offset := 0
- for i := 0; i < len(candidate[0]); i++ {
- for j := 0; j < len(candidate)-1; j++ {
- if i > len(candidate[j]) {
- goto aggregate
- }
- if candidate[j][i] != candidate[j+1][i] {
- goto aggregate
- }
- }
- offset = i
- }
-aggregate:
- return offset
-}
-
-func (o *opCompleter) EnterCompleteSelectMode() {
- o.inSelectMode = true
- o.candidateChoise = -1
- o.CompleteRefresh()
-}
-
-func (o *opCompleter) EnterCompleteMode(offset int, candidate [][]rune) {
- o.inCompleteMode = true
- o.candidate = candidate
- o.candidateOff = offset
- o.CompleteRefresh()
-}
-
-func (o *opCompleter) ExitCompleteSelectMode() {
- o.inSelectMode = false
- o.candidate = nil
- o.candidateChoise = -1
- o.candidateOff = -1
- o.candidateSource = nil
-}
-
-func (o *opCompleter) ExitCompleteMode(revent bool) {
- o.inCompleteMode = false
- o.ExitCompleteSelectMode()
-}
diff --git a/vendor/github.com/rhtyd/readline/complete_helper.go b/vendor/github.com/rhtyd/readline/complete_helper.go
deleted file mode 100644
index 58d7248..0000000
--- a/vendor/github.com/rhtyd/readline/complete_helper.go
+++ /dev/null
@@ -1,165 +0,0 @@
-package readline
-
-import (
- "bytes"
- "strings"
-)
-
-// Caller type for dynamic completion
-type DynamicCompleteFunc func(string) []string
-
-type PrefixCompleterInterface interface {
- Print(prefix string, level int, buf *bytes.Buffer)
- Do(line []rune, pos int) (newLine [][]rune, length int)
- GetName() []rune
- GetChildren() []PrefixCompleterInterface
- SetChildren(children []PrefixCompleterInterface)
-}
-
-type DynamicPrefixCompleterInterface interface {
- PrefixCompleterInterface
- IsDynamic() bool
- GetDynamicNames(line []rune) [][]rune
-}
-
-type PrefixCompleter struct {
- Name []rune
- Dynamic bool
- Callback DynamicCompleteFunc
- Children []PrefixCompleterInterface
-}
-
-func (p *PrefixCompleter) Tree(prefix string) string {
- buf := bytes.NewBuffer(nil)
- p.Print(prefix, 0, buf)
- return buf.String()
-}
-
-func Print(p PrefixCompleterInterface, prefix string, level int, buf *bytes.Buffer) {
- if strings.TrimSpace(string(p.GetName())) != "" {
- buf.WriteString(prefix)
- if level > 0 {
- buf.WriteString("├")
- buf.WriteString(strings.Repeat("─", (level*4)-2))
- buf.WriteString(" ")
- }
- buf.WriteString(string(p.GetName()) + "\n")
- level++
- }
- for _, ch := range p.GetChildren() {
- ch.Print(prefix, level, buf)
- }
-}
-
-func (p *PrefixCompleter) Print(prefix string, level int, buf *bytes.Buffer) {
- Print(p, prefix, level, buf)
-}
-
-func (p *PrefixCompleter) IsDynamic() bool {
- return p.Dynamic
-}
-
-func (p *PrefixCompleter) GetName() []rune {
- return p.Name
-}
-
-func (p *PrefixCompleter) GetDynamicNames(line []rune) [][]rune {
- var names = [][]rune{}
- for _, name := range p.Callback(string(line)) {
- names = append(names, []rune(name+" "))
- }
- return names
-}
-
-func (p *PrefixCompleter) GetChildren() []PrefixCompleterInterface {
- return p.Children
-}
-
-func (p *PrefixCompleter) SetChildren(children []PrefixCompleterInterface) {
- p.Children = children
-}
-
-func NewPrefixCompleter(pc ...PrefixCompleterInterface) *PrefixCompleter {
- return PcItem("", pc...)
-}
-
-func PcItem(name string, pc ...PrefixCompleterInterface) *PrefixCompleter {
- name += " "
- return &PrefixCompleter{
- Name: []rune(name),
- Dynamic: false,
- Children: pc,
- }
-}
-
-func PcItemDynamic(callback DynamicCompleteFunc, pc ...PrefixCompleterInterface) *PrefixCompleter {
- return &PrefixCompleter{
- Callback: callback,
- Dynamic: true,
- Children: pc,
- }
-}
-
-func (p *PrefixCompleter) Do(line []rune, pos int) (newLine [][]rune, offset int) {
- return doInternal(p, line, pos, line)
-}
-
-func Do(p PrefixCompleterInterface, line []rune, pos int) (newLine [][]rune, offset int) {
- return doInternal(p, line, pos, line)
-}
-
-func doInternal(p PrefixCompleterInterface, line []rune, pos int, origLine []rune) (newLine [][]rune, offset int) {
- line = runes.TrimSpaceLeft(line[:pos])
- goNext := false
- var lineCompleter PrefixCompleterInterface
- for _, child := range p.GetChildren() {
- childNames := make([][]rune, 1)
-
- childDynamic, ok := child.(DynamicPrefixCompleterInterface)
- if ok && childDynamic.IsDynamic() {
- childNames = childDynamic.GetDynamicNames(origLine)
- } else {
- childNames[0] = child.GetName()
- }
-
- for _, childName := range childNames {
- if len(line) >= len(childName) {
- if runes.HasPrefix(line, childName) {
- if len(line) == len(childName) {
- newLine = append(newLine, []rune{' '})
- } else {
- newLine = append(newLine, childName)
- }
- offset = len(childName)
- lineCompleter = child
- goNext = true
- }
- } else {
- if runes.HasPrefix(childName, line) {
- newLine = append(newLine, childName[len(line):])
- offset = len(line)
- lineCompleter = child
- }
- }
- }
- }
-
- if len(newLine) != 1 {
- return
- }
-
- tmpLine := make([]rune, 0, len(line))
- for i := offset; i < len(line); i++ {
- if line[i] == ' ' {
- continue
- }
-
- tmpLine = append(tmpLine, line[i:]...)
- return doInternal(lineCompleter, tmpLine, len(tmpLine), origLine)
- }
-
- if goNext {
- return doInternal(lineCompleter, nil, 0, origLine)
- }
- return
-}
diff --git a/vendor/github.com/rhtyd/readline/complete_segment.go b/vendor/github.com/rhtyd/readline/complete_segment.go
deleted file mode 100644
index 5ceadd8..0000000
--- a/vendor/github.com/rhtyd/readline/complete_segment.go
+++ /dev/null
@@ -1,82 +0,0 @@
-package readline
-
-type SegmentCompleter interface {
- // a
- // |- a1
- // |--- a11
- // |- a2
- // b
- // input:
- // DoTree([], 0) [a, b]
- // DoTree([a], 1) [a]
- // DoTree([a, ], 0) [a1, a2]
- // DoTree([a, a], 1) [a1, a2]
- // DoTree([a, a1], 2) [a1]
- // DoTree([a, a1, ], 0) [a11]
- // DoTree([a, a1, a], 1) [a11]
- DoSegment([][]rune, int) [][]rune
-}
-
-type dumpSegmentCompleter struct {
- f func([][]rune, int) [][]rune
-}
-
-func (d *dumpSegmentCompleter) DoSegment(segment [][]rune, n int) [][]rune {
- return d.f(segment, n)
-}
-
-func SegmentFunc(f func([][]rune, int) [][]rune) AutoCompleter {
- return &SegmentComplete{&dumpSegmentCompleter{f}}
-}
-
-func SegmentAutoComplete(completer SegmentCompleter) *SegmentComplete {
- return &SegmentComplete{
- SegmentCompleter: completer,
- }
-}
-
-type SegmentComplete struct {
- SegmentCompleter
-}
-
-func RetSegment(segments [][]rune, cands [][]rune, idx int) ([][]rune, int) {
- ret := make([][]rune, 0, len(cands))
- lastSegment := segments[len(segments)-1]
- for _, cand := range cands {
- if !runes.HasPrefix(cand, lastSegment) {
- continue
- }
- ret = append(ret, cand[len(lastSegment):])
- }
- return ret, idx
-}
-
-func SplitSegment(line []rune, pos int) ([][]rune, int) {
- segs := [][]rune{}
- lastIdx := -1
- line = line[:pos]
- pos = 0
- for idx, l := range line {
- if l == ' ' {
- pos = 0
- segs = append(segs, line[lastIdx+1:idx])
- lastIdx = idx
- } else {
- pos++
- }
- }
- segs = append(segs, line[lastIdx+1:])
- return segs, pos
-}
-
-func (c *SegmentComplete) Do(line []rune, pos int) (newLine [][]rune, offset int) {
-
- segment, idx := SplitSegment(line, pos)
-
- cands := c.DoSegment(segment, idx)
- newLine, offset = RetSegment(segment, cands, idx)
- for idx := range newLine {
- newLine[idx] = append(newLine[idx], ' ')
- }
- return newLine, offset
-}
diff --git a/vendor/github.com/rhtyd/readline/history.go b/vendor/github.com/rhtyd/readline/history.go
deleted file mode 100644
index 6b17c46..0000000
--- a/vendor/github.com/rhtyd/readline/history.go
+++ /dev/null
@@ -1,330 +0,0 @@
-package readline
-
-import (
- "bufio"
- "container/list"
- "fmt"
- "os"
- "strings"
- "sync"
-)
-
-type hisItem struct {
- Source []rune
- Version int64
- Tmp []rune
-}
-
-func (h *hisItem) Clean() {
- h.Source = nil
- h.Tmp = nil
-}
-
-type opHistory struct {
- cfg *Config
- history *list.List
- historyVer int64
- current *list.Element
- fd *os.File
- fdLock sync.Mutex
- enable bool
-}
-
-func newOpHistory(cfg *Config) (o *opHistory) {
- o = &opHistory{
- cfg: cfg,
- history: list.New(),
- enable: true,
- }
- return o
-}
-
-func (o *opHistory) Reset() {
- o.history = list.New()
- o.current = nil
-}
-
-func (o *opHistory) IsHistoryClosed() bool {
- o.fdLock.Lock()
- defer o.fdLock.Unlock()
- return o.fd.Fd() == ^(uintptr(0))
-}
-
-func (o *opHistory) Init() {
- if o.IsHistoryClosed() {
- o.initHistory()
- }
-}
-
-func (o *opHistory) initHistory() {
- if o.cfg.HistoryFile != "" {
- o.historyUpdatePath(o.cfg.HistoryFile)
- }
-}
-
-// only called by newOpHistory
-func (o *opHistory) historyUpdatePath(path string) {
- o.fdLock.Lock()
- defer o.fdLock.Unlock()
- f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
- if err != nil {
- return
- }
- o.fd = f
- r := bufio.NewReader(o.fd)
- total := 0
- for ; ; total++ {
- line, err := r.ReadString('\n')
- if err != nil {
- break
- }
- // ignore the empty line
- line = strings.TrimSpace(line)
- if len(line) == 0 {
- continue
- }
- o.Push([]rune(line))
- o.Compact()
- }
- if total > o.cfg.HistoryLimit {
- o.rewriteLocked()
- }
- o.historyVer++
- o.Push(nil)
- return
-}
-
-func (o *opHistory) Compact() {
- for o.history.Len() > o.cfg.HistoryLimit && o.history.Len() > 0 {
- o.history.Remove(o.history.Front())
- }
-}
-
-func (o *opHistory) Rewrite() {
- o.fdLock.Lock()
- defer o.fdLock.Unlock()
- o.rewriteLocked()
-}
-
-func (o *opHistory) rewriteLocked() {
- if o.cfg.HistoryFile == "" {
- return
- }
-
- tmpFile := o.cfg.HistoryFile + ".tmp"
- fd, err := os.OpenFile(tmpFile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC|os.O_APPEND, 0666)
- if err != nil {
- return
- }
-
- buf := bufio.NewWriter(fd)
- for elem := o.history.Front(); elem != nil; elem = elem.Next() {
- buf.WriteString(string(elem.Value.(*hisItem).Source) + "\n")
- }
- buf.Flush()
-
- // replace history file
- if err = os.Rename(tmpFile, o.cfg.HistoryFile); err != nil {
- fd.Close()
- return
- }
-
- if o.fd != nil {
- o.fd.Close()
- }
- // fd is write only, just satisfy what we need.
- o.fd = fd
-}
-
-func (o *opHistory) Close() {
- o.fdLock.Lock()
- defer o.fdLock.Unlock()
- if o.fd != nil {
- o.fd.Close()
- }
-}
-
-func (o *opHistory) FindBck(isNewSearch bool, rs []rune, start int) (int, *list.Element) {
- for elem := o.current; elem != nil; elem = elem.Prev() {
- item := o.showItem(elem.Value)
- if isNewSearch {
- start += len(rs)
- }
- if elem == o.current {
- if len(item) >= start {
- item = item[:start]
- }
- }
- idx := runes.IndexAllBckEx(item, rs, o.cfg.HistorySearchFold)
- if idx < 0 {
- continue
- }
- return idx, elem
- }
- return -1, nil
-}
-
-func (o *opHistory) FindFwd(isNewSearch bool, rs []rune, start int) (int, *list.Element) {
- for elem := o.current; elem != nil; elem = elem.Next() {
- item := o.showItem(elem.Value)
- if isNewSearch {
- start -= len(rs)
- if start < 0 {
- start = 0
- }
- }
- if elem == o.current {
- if len(item)-1 >= start {
- item = item[start:]
- } else {
- continue
- }
- }
- idx := runes.IndexAllEx(item, rs, o.cfg.HistorySearchFold)
- if idx < 0 {
- continue
- }
- if elem == o.current {
- idx += start
- }
- return idx, elem
- }
- return -1, nil
-}
-
-func (o *opHistory) showItem(obj interface{}) []rune {
- item := obj.(*hisItem)
- if item.Version == o.historyVer {
- return item.Tmp
- }
- return item.Source
-}
-
-func (o *opHistory) Prev() []rune {
- if o.current == nil {
- return nil
- }
- current := o.current.Prev()
- if current == nil {
- return nil
- }
- o.current = current
- return runes.Copy(o.showItem(current.Value))
-}
-
-func (o *opHistory) Next() ([]rune, bool) {
- if o.current == nil {
- return nil, false
- }
- current := o.current.Next()
- if current == nil {
- return nil, false
- }
-
- o.current = current
- return runes.Copy(o.showItem(current.Value)), true
-}
-
-// Disable the current history
-func (o *opHistory) Disable() {
- o.enable = false
-}
-
-// Enable the current history
-func (o *opHistory) Enable() {
- o.enable = true
-}
-
-func (o *opHistory) debug() {
- Debug("-------")
- for item := o.history.Front(); item != nil; item = item.Next() {
- Debug(fmt.Sprintf("%+v", item.Value))
- }
-}
-
-// save history
-func (o *opHistory) New(current []rune) (err error) {
-
- // history deactivated
- if !o.enable {
- return nil
- }
-
- current = runes.Copy(current)
-
- // if just use last command without modify
- // just clean lastest history
- if back := o.history.Back(); back != nil {
- prev := back.Prev()
- if prev != nil {
- if runes.Equal(current, prev.Value.(*hisItem).Source) {
- o.current = o.history.Back()
- o.current.Value.(*hisItem).Clean()
- o.historyVer++
- return nil
- }
- }
- }
-
- if len(current) == 0 {
- o.current = o.history.Back()
- if o.current != nil {
- o.current.Value.(*hisItem).Clean()
- o.historyVer++
- return nil
- }
- }
-
- if o.current != o.history.Back() {
- // move history item to current command
- currentItem := o.current.Value.(*hisItem)
- // set current to last item
- o.current = o.history.Back()
-
- current = runes.Copy(currentItem.Tmp)
- }
-
- // err only can be a IO error, just report
- err = o.Update(current, true)
-
- // push a new one to commit current command
- o.historyVer++
- o.Push(nil)
- return
-}
-
-func (o *opHistory) Revert() {
- o.historyVer++
- o.current = o.history.Back()
-}
-
-func (o *opHistory) Update(s []rune, commit bool) (err error) {
- o.fdLock.Lock()
- defer o.fdLock.Unlock()
- s = runes.Copy(s)
- if o.current == nil {
- o.Push(s)
- o.Compact()
- return
- }
- r := o.current.Value.(*hisItem)
- r.Version = o.historyVer
- if commit {
- r.Source = s
- if o.fd != nil {
- // just report the error
- _, err = o.fd.Write([]byte(string(r.Source) + "\n"))
- }
- } else {
- r.Tmp = append(r.Tmp[:0], s...)
- }
- o.current.Value = r
- o.Compact()
- return
-}
-
-func (o *opHistory) Push(s []rune) {
- s = runes.Copy(s)
- elem := o.history.PushBack(&hisItem{Source: s})
- o.current = elem
-}
diff --git a/vendor/github.com/rhtyd/readline/operation.go b/vendor/github.com/rhtyd/readline/operation.go
deleted file mode 100644
index 4c31624..0000000
--- a/vendor/github.com/rhtyd/readline/operation.go
+++ /dev/null
@@ -1,531 +0,0 @@
-package readline
-
-import (
- "errors"
- "io"
- "sync"
-)
-
-var (
- ErrInterrupt = errors.New("Interrupt")
-)
-
-type InterruptError struct {
- Line []rune
-}
-
-func (*InterruptError) Error() string {
- return "Interrupted"
-}
-
-type Operation struct {
- m sync.Mutex
- cfg *Config
- t *Terminal
- buf *RuneBuffer
- outchan chan []rune
- errchan chan error
- w io.Writer
-
- history *opHistory
- *opSearch
- *opCompleter
- *opPassword
- *opVim
-}
-
-func (o *Operation) SetBuffer(what string) {
- o.buf.Set([]rune(what))
-}
-
-type wrapWriter struct {
- r *Operation
- t *Terminal
- target io.Writer
-}
-
-func (w *wrapWriter) Write(b []byte) (int, error) {
- if !w.t.IsReading() {
- return w.target.Write(b)
- }
-
- var (
- n int
- err error
- )
- w.r.buf.Refresh(func() {
- n, err = w.target.Write(b)
- })
-
- if w.r.IsSearchMode() {
- w.r.SearchRefresh(-1)
- }
- if w.r.IsInCompleteMode() {
- w.r.CompleteRefresh()
- }
- return n, err
-}
-
-func NewOperation(t *Terminal, cfg *Config) *Operation {
- width := cfg.FuncGetWidth()
- op := &Operation{
- t: t,
- buf: NewRuneBuffer(t, cfg.Prompt, cfg, width),
- outchan: make(chan []rune),
- errchan: make(chan error, 1),
- }
- op.w = op.buf.w
- op.SetConfig(cfg)
- op.opVim = newVimMode(op)
- op.opCompleter = newOpCompleter(op.buf.w, op, width)
- op.opPassword = newOpPassword(op)
- op.cfg.FuncOnWidthChanged(func() {
- newWidth := cfg.FuncGetWidth()
- op.opCompleter.OnWidthChange(newWidth)
- op.opSearch.OnWidthChange(newWidth)
- op.buf.OnWidthChange(newWidth)
- })
- go op.ioloop()
- return op
-}
-
-func (o *Operation) SetPrompt(s string) {
- o.buf.SetPrompt(s)
-}
-
-func (o *Operation) SetMaskRune(r rune) {
- o.buf.SetMask(r)
-}
-
-func (o *Operation) GetConfig() *Config {
- o.m.Lock()
- cfg := *o.cfg
- o.m.Unlock()
- return &cfg
-}
-
-func (o *Operation) ioloop() {
- for {
- keepInSearchMode := false
- keepInCompleteMode := false
- r := o.t.ReadRune()
- if o.GetConfig().FuncFilterInputRune != nil {
- var process bool
- r, process = o.GetConfig().FuncFilterInputRune(r)
- if !process {
- o.buf.Refresh(nil) // to refresh the line
- continue // ignore this rune
- }
- }
-
- if r == 0 { // io.EOF
- if o.buf.Len() == 0 {
- o.buf.Clean()
- select {
- case o.errchan <- io.EOF:
- }
- break
- } else {
- // if stdin got io.EOF and there is something left in buffer,
- // let's flush them by sending CharEnter.
- // And we will got io.EOF int next loop.
- r = CharEnter
- }
- }
- isUpdateHistory := true
-
- if o.IsInCompleteSelectMode() {
- keepInCompleteMode = o.HandleCompleteSelect(r)
- if keepInCompleteMode {
- continue
- }
-
- o.buf.Refresh(nil)
- switch r {
- case CharEnter, CharCtrlJ:
- o.history.Update(o.buf.Runes(), false)
- fallthrough
- case CharInterrupt:
- o.t.KickRead()
- fallthrough
- case CharBell:
- continue
- }
- }
-
- if o.IsEnableVimMode() {
- r = o.HandleVim(r, o.t.ReadRune)
- if r == 0 {
- continue
- }
- }
-
- switch r {
- case CharBell:
- if o.IsSearchMode() {
- o.ExitSearchMode(true)
- o.buf.Refresh(nil)
- }
- if o.IsInCompleteMode() {
- o.ExitCompleteMode(true)
- o.buf.Refresh(nil)
- }
- case CharTab:
- if o.GetConfig().AutoComplete == nil {
- o.t.Bell()
- break
- }
- if o.OnComplete() {
- keepInCompleteMode = true
- } else {
- o.t.Bell()
- break
- }
-
- case CharBckSearch:
- if !o.SearchMode(S_DIR_BCK) {
- o.t.Bell()
- break
- }
- keepInSearchMode = true
- case CharCtrlU:
- o.buf.KillFront()
- case CharFwdSearch:
- if !o.SearchMode(S_DIR_FWD) {
- o.t.Bell()
- break
- }
- keepInSearchMode = true
- case CharKill:
- o.buf.Kill()
- keepInCompleteMode = true
- case MetaForward:
- o.buf.MoveToNextWord()
- case CharTranspose:
- o.buf.Transpose()
- case MetaBackward:
- o.buf.MoveToPrevWord()
- case MetaDelete:
- o.buf.DeleteWord()
- case CharLineStart:
- o.buf.MoveToLineStart()
- case CharLineEnd:
- o.buf.MoveToLineEnd()
- case CharBackspace, CharCtrlH:
- if o.IsSearchMode() {
- o.SearchBackspace()
- keepInSearchMode = true
- break
- }
-
- if o.buf.Len() == 0 {
- o.t.Bell()
- break
- }
- o.buf.Backspace()
- if o.IsInCompleteMode() {
- o.OnComplete()
- }
- case CharCtrlZ:
- o.buf.Clean()
- o.t.SleepToResume()
- o.Refresh()
- case CharCtrlL:
- ClearScreen(o.w)
- o.Refresh()
- case MetaBackspace, CharCtrlW:
- o.buf.BackEscapeWord()
- case CharCtrlY:
- o.buf.Yank()
- case CharEnter, CharCtrlJ:
- if o.IsSearchMode() {
- o.ExitSearchMode(false)
- }
- o.buf.MoveToLineEnd()
- var data []rune
- if !o.GetConfig().UniqueEditLine {
- o.buf.WriteRune('\n')
- data = o.buf.Reset()
- data = data[:len(data)-1] // trim \n
- } else {
- o.buf.Clean()
- data = o.buf.Reset()
- }
- o.outchan <- data
- if !o.GetConfig().DisableAutoSaveHistory {
- // ignore IO error
- _ = o.history.New(data)
- } else {
- isUpdateHistory = false
- }
- case CharBackward:
- o.buf.MoveBackward()
- case CharForward:
- o.buf.MoveForward()
- case CharPrev:
- buf := o.history.Prev()
- if buf != nil {
- o.buf.Set(buf)
- } else {
- o.t.Bell()
- }
- case CharNext:
- buf, ok := o.history.Next()
- if ok {
- o.buf.Set(buf)
- } else {
- o.t.Bell()
- }
- case CharDelete:
- if o.buf.Len() > 0 || !o.IsNormalMode() {
- o.t.KickRead()
- if !o.buf.Delete() {
- o.t.Bell()
- }
- break
- }
-
- // treat as EOF
- if !o.GetConfig().UniqueEditLine {
- o.buf.WriteString(o.GetConfig().EOFPrompt + "\n")
- }
- o.buf.Reset()
- isUpdateHistory = false
- o.history.Revert()
- o.errchan <- io.EOF
- if o.GetConfig().UniqueEditLine {
- o.buf.Clean()
- }
- case CharInterrupt:
- if o.IsSearchMode() {
- o.t.KickRead()
- o.ExitSearchMode(true)
- break
- }
- if o.IsInCompleteMode() {
- o.t.KickRead()
- o.ExitCompleteMode(true)
- o.buf.Refresh(nil)
- break
- }
- o.buf.MoveToLineEnd()
- o.buf.Refresh(nil)
- hint := o.GetConfig().InterruptPrompt + "\n"
- if !o.GetConfig().UniqueEditLine {
- o.buf.WriteString(hint)
- }
- remain := o.buf.Reset()
- if !o.GetConfig().UniqueEditLine {
- remain = remain[:len(remain)-len([]rune(hint))]
- }
- isUpdateHistory = false
- o.history.Revert()
- o.errchan <- &InterruptError{remain}
- default:
- if o.IsSearchMode() {
- o.SearchChar(r)
- keepInSearchMode = true
- break
- }
- o.buf.WriteRune(r)
- if o.IsInCompleteMode() {
- o.OnComplete()
- keepInCompleteMode = true
- }
- }
-
- listener := o.GetConfig().Listener
- if listener != nil {
- newLine, newPos, ok := listener.OnChange(o.buf.Runes(), o.buf.Pos(), r)
- if ok {
- o.buf.SetWithIdx(newPos, newLine)
- }
- }
-
- o.m.Lock()
- if !keepInSearchMode && o.IsSearchMode() {
- o.ExitSearchMode(false)
- o.buf.Refresh(nil)
- } else if o.IsInCompleteMode() {
- if !keepInCompleteMode {
- o.ExitCompleteMode(false)
- o.Refresh()
- } else {
- o.buf.Refresh(nil)
- o.CompleteRefresh()
- }
- }
- if isUpdateHistory && !o.IsSearchMode() {
- // it will cause null history
- o.history.Update(o.buf.Runes(), false)
- }
- o.m.Unlock()
- }
-}
-
-func (o *Operation) Stderr() io.Writer {
- return &wrapWriter{target: o.GetConfig().Stderr, r: o, t: o.t}
-}
-
-func (o *Operation) Stdout() io.Writer {
- return &wrapWriter{target: o.GetConfig().Stdout, r: o, t: o.t}
-}
-
-func (o *Operation) String() (string, error) {
- r, err := o.Runes()
- return string(r), err
-}
-
-func (o *Operation) Runes() ([]rune, error) {
- o.t.EnterRawMode()
- defer o.t.ExitRawMode()
-
- listener := o.GetConfig().Listener
- if listener != nil {
- listener.OnChange(nil, 0, 0)
- }
-
- o.buf.Refresh(nil) // print prompt
- o.t.KickRead()
- select {
- case r := <-o.outchan:
- return r, nil
- case err := <-o.errchan:
- if e, ok := err.(*InterruptError); ok {
- return e.Line, ErrInterrupt
- }
- return nil, err
- }
-}
-
-func (o *Operation) PasswordEx(prompt string, l Listener) ([]byte, error) {
- cfg := o.GenPasswordConfig()
- cfg.Prompt = prompt
- cfg.Listener = l
- return o.PasswordWithConfig(cfg)
-}
-
-func (o *Operation) GenPasswordConfig() *Config {
- return o.opPassword.PasswordConfig()
-}
-
-func (o *Operation) PasswordWithConfig(cfg *Config) ([]byte, error) {
- if err := o.opPassword.EnterPasswordMode(cfg); err != nil {
- return nil, err
- }
- defer o.opPassword.ExitPasswordMode()
- return o.Slice()
-}
-
-func (o *Operation) Password(prompt string) ([]byte, error) {
- return o.PasswordEx(prompt, nil)
-}
-
-func (o *Operation) SetTitle(t string) {
- o.w.Write([]byte("\033[2;" + t + "\007"))
-}
-
-func (o *Operation) Slice() ([]byte, error) {
- r, err := o.Runes()
- if err != nil {
- return nil, err
- }
- return []byte(string(r)), nil
-}
-
-func (o *Operation) Close() {
- o.history.Close()
-}
-
-func (o *Operation) SetHistoryPath(path string) {
- if o.history != nil {
- o.history.Close()
- }
- o.cfg.HistoryFile = path
- o.history = newOpHistory(o.cfg)
-}
-
-func (o *Operation) IsNormalMode() bool {
- return !o.IsInCompleteMode() && !o.IsSearchMode()
-}
-
-func (op *Operation) SetConfig(cfg *Config) (*Config, error) {
- op.m.Lock()
- defer op.m.Unlock()
- if op.cfg == cfg {
- return op.cfg, nil
- }
- if err := cfg.Init(); err != nil {
- return op.cfg, err
- }
- old := op.cfg
- op.cfg = cfg
- op.SetPrompt(cfg.Prompt)
- op.SetMaskRune(cfg.MaskRune)
- op.buf.SetConfig(cfg)
- width := op.cfg.FuncGetWidth()
-
- if cfg.opHistory == nil {
- op.SetHistoryPath(cfg.HistoryFile)
- cfg.opHistory = op.history
- cfg.opSearch = newOpSearch(op.buf.w, op.buf, op.history, cfg, width)
- }
- op.history = cfg.opHistory
-
- // SetHistoryPath will close opHistory which already exists
- // so if we use it next time, we need to reopen it by `InitHistory()`
- op.history.Init()
-
- if op.cfg.AutoComplete != nil {
- op.opCompleter = newOpCompleter(op.buf.w, op, width)
- }
-
- op.opSearch = cfg.opSearch
- return old, nil
-}
-
-func (o *Operation) ResetHistory() {
- o.history.Reset()
-}
-
-// if err is not nil, it just mean it fail to write to file
-// other things goes fine.
-func (o *Operation) SaveHistory(content string) error {
- return o.history.New([]rune(content))
-}
-
-func (o *Operation) Refresh() {
- if o.t.IsReading() {
- o.buf.Refresh(nil)
- }
-}
-
-func (o *Operation) Clean() {
- o.buf.Clean()
-}
-
-func FuncListener(f func(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool)) Listener {
- return &DumpListener{f: f}
-}
-
-type DumpListener struct {
- f func(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool)
-}
-
-func (d *DumpListener) OnChange(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool) {
- return d.f(line, pos, key)
-}
-
-type Listener interface {
- OnChange(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool)
-}
-
-type Painter interface {
- Paint(line []rune, pos int) []rune
-}
-
-type defaultPainter struct{}
-
-func (p *defaultPainter) Paint(line []rune, _ int) []rune {
- return line
-}
diff --git a/vendor/github.com/rhtyd/readline/password.go b/vendor/github.com/rhtyd/readline/password.go
deleted file mode 100644
index 414288c..0000000
--- a/vendor/github.com/rhtyd/readline/password.go
+++ /dev/null
@@ -1,33 +0,0 @@
-package readline
-
-type opPassword struct {
- o *Operation
- backupCfg *Config
-}
-
-func newOpPassword(o *Operation) *opPassword {
- return &opPassword{o: o}
-}
-
-func (o *opPassword) ExitPasswordMode() {
- o.o.SetConfig(o.backupCfg)
- o.backupCfg = nil
-}
-
-func (o *opPassword) EnterPasswordMode(cfg *Config) (err error) {
- o.backupCfg, err = o.o.SetConfig(cfg)
- return
-}
-
-func (o *opPassword) PasswordConfig() *Config {
- return &Config{
- EnableMask: true,
- InterruptPrompt: "\n",
- EOFPrompt: "\n",
- HistoryLimit: -1,
- Painter: &defaultPainter{},
-
- Stdout: o.o.cfg.Stdout,
- Stderr: o.o.cfg.Stderr,
- }
-}
diff --git a/vendor/github.com/rhtyd/readline/rawreader_windows.go b/vendor/github.com/rhtyd/readline/rawreader_windows.go
deleted file mode 100644
index 073ef15..0000000
--- a/vendor/github.com/rhtyd/readline/rawreader_windows.go
+++ /dev/null
@@ -1,125 +0,0 @@
-// +build windows
-
-package readline
-
-import "unsafe"
-
-const (
- VK_CANCEL = 0x03
- VK_BACK = 0x08
- VK_TAB = 0x09
- VK_RETURN = 0x0D
- VK_SHIFT = 0x10
- VK_CONTROL = 0x11
- VK_MENU = 0x12
- VK_ESCAPE = 0x1B
- VK_LEFT = 0x25
- VK_UP = 0x26
- VK_RIGHT = 0x27
- VK_DOWN = 0x28
- VK_DELETE = 0x2E
- VK_LSHIFT = 0xA0
- VK_RSHIFT = 0xA1
- VK_LCONTROL = 0xA2
- VK_RCONTROL = 0xA3
-)
-
-// RawReader translate input record to ANSI escape sequence.
-// To provides same behavior as unix terminal.
-type RawReader struct {
- ctrlKey bool
- altKey bool
-}
-
-func NewRawReader() *RawReader {
- r := new(RawReader)
- return r
-}
-
-// only process one action in one read
-func (r *RawReader) Read(buf []byte) (int, error) {
- ir := new(_INPUT_RECORD)
- var read int
- var err error
-next:
- err = kernel.ReadConsoleInputW(stdin,
- uintptr(unsafe.Pointer(ir)),
- 1,
- uintptr(unsafe.Pointer(&read)),
- )
- if err != nil {
- return 0, err
- }
- if ir.EventType != EVENT_KEY {
- goto next
- }
- ker := (*_KEY_EVENT_RECORD)(unsafe.Pointer(&ir.Event[0]))
- if ker.bKeyDown == 0 { // keyup
- if r.ctrlKey || r.altKey {
- switch ker.wVirtualKeyCode {
- case VK_RCONTROL, VK_LCONTROL:
- r.ctrlKey = false
- case VK_MENU: //alt
- r.altKey = false
- }
- }
- goto next
- }
-
- if ker.unicodeChar == 0 {
- var target rune
- switch ker.wVirtualKeyCode {
- case VK_RCONTROL, VK_LCONTROL:
- r.ctrlKey = true
- case VK_MENU: //alt
- r.altKey = true
- case VK_LEFT:
- target = CharBackward
- case VK_RIGHT:
- target = CharForward
- case VK_UP:
- target = CharPrev
- case VK_DOWN:
- target = CharNext
- }
- if target != 0 {
- return r.write(buf, target)
- }
- goto next
- }
- char := rune(ker.unicodeChar)
- if r.ctrlKey {
- switch char {
- case 'A':
- char = CharLineStart
- case 'E':
- char = CharLineEnd
- case 'R':
- char = CharBckSearch
- case 'S':
- char = CharFwdSearch
- }
- } else if r.altKey {
- switch char {
- case VK_BACK:
- char = CharBackspace
- }
- return r.writeEsc(buf, char)
- }
- return r.write(buf, char)
-}
-
-func (r *RawReader) writeEsc(b []byte, char rune) (int, error) {
- b[0] = '\033'
- n := copy(b[1:], []byte(string(char)))
- return n + 1, nil
-}
-
-func (r *RawReader) write(b []byte, char rune) (int, error) {
- n := copy(b, []byte(string(char)))
- return n, nil
-}
-
-func (r *RawReader) Close() error {
- return nil
-}
diff --git a/vendor/github.com/rhtyd/readline/readline.go b/vendor/github.com/rhtyd/readline/readline.go
deleted file mode 100644
index 0e7aca0..0000000
--- a/vendor/github.com/rhtyd/readline/readline.go
+++ /dev/null
@@ -1,326 +0,0 @@
-// Readline is a pure go implementation for GNU-Readline kind library.
-//
-// example:
-// rl, err := readline.New("> ")
-// if err != nil {
-// panic(err)
-// }
-// defer rl.Close()
-//
-// for {
-// line, err := rl.Readline()
-// if err != nil { // io.EOF
-// break
-// }
-// println(line)
-// }
-//
-package readline
-
-import "io"
-
-type Instance struct {
- Config *Config
- Terminal *Terminal
- Operation *Operation
-}
-
-type Config struct {
- // prompt supports ANSI escape sequence, so we can color some characters even in windows
- Prompt string
-
- // readline will persist historys to file where HistoryFile specified
- HistoryFile string
- // specify the max length of historys, it's 500 by default, set it to -1 to disable history
- HistoryLimit int
- DisableAutoSaveHistory bool
- // enable case-insensitive history searching
- HistorySearchFold bool
-
- // AutoCompleter will called once user press TAB
- AutoComplete AutoCompleter
-
- // Any key press will pass to Listener
- // NOTE: Listener will be triggered by (nil, 0, 0) immediately
- Listener Listener
-
- Painter Painter
-
- // If VimMode is true, readline will in vim.insert mode by default
- VimMode bool
-
- InterruptPrompt string
- EOFPrompt string
-
- FuncGetWidth func() int
-
- Stdin io.ReadCloser
- StdinWriter io.Writer
- Stdout io.Writer
- Stderr io.Writer
-
- EnableMask bool
- MaskRune rune
-
- // erase the editing line after user submited it
- // it use in IM usually.
- UniqueEditLine bool
-
- // filter input runes (may be used to disable CtrlZ or for translating some keys to different actions)
- // -> output = new (translated) rune and true/false if continue with processing this one
- FuncFilterInputRune func(rune) (rune, bool)
-
- // force use interactive even stdout is not a tty
- FuncIsTerminal func() bool
- FuncMakeRaw func() error
- FuncExitRaw func() error
- FuncOnWidthChanged func(func())
- ForceUseInteractive bool
-
- // private fields
- inited bool
- opHistory *opHistory
- opSearch *opSearch
-}
-
-func (c *Config) useInteractive() bool {
- if c.ForceUseInteractive {
- return true
- }
- return c.FuncIsTerminal()
-}
-
-func (c *Config) Init() error {
- if c.inited {
- return nil
- }
- c.inited = true
- if c.Stdin == nil {
- c.Stdin = NewCancelableStdin(Stdin)
- }
-
- c.Stdin, c.StdinWriter = NewFillableStdin(c.Stdin)
-
- if c.Stdout == nil {
- c.Stdout = Stdout
- }
- if c.Stderr == nil {
- c.Stderr = Stderr
- }
- if c.HistoryLimit == 0 {
- c.HistoryLimit = 500
- }
-
- if c.InterruptPrompt == "" {
- c.InterruptPrompt = "^C"
- } else if c.InterruptPrompt == "\n" {
- c.InterruptPrompt = ""
- }
- if c.EOFPrompt == "" {
- c.EOFPrompt = "^D"
- } else if c.EOFPrompt == "\n" {
- c.EOFPrompt = ""
- }
-
- if c.AutoComplete == nil {
- c.AutoComplete = &TabCompleter{}
- }
- if c.FuncGetWidth == nil {
- c.FuncGetWidth = GetScreenWidth
- }
- if c.FuncIsTerminal == nil {
- c.FuncIsTerminal = DefaultIsTerminal
- }
- rm := new(RawMode)
- if c.FuncMakeRaw == nil {
- c.FuncMakeRaw = rm.Enter
- }
- if c.FuncExitRaw == nil {
- c.FuncExitRaw = rm.Exit
- }
- if c.FuncOnWidthChanged == nil {
- c.FuncOnWidthChanged = DefaultOnWidthChanged
- }
-
- return nil
-}
-
-func (c Config) Clone() *Config {
- c.opHistory = nil
- c.opSearch = nil
- return &c
-}
-
-func (c *Config) SetListener(f func(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool)) {
- c.Listener = FuncListener(f)
-}
-
-func (c *Config) SetPainter(p Painter) {
- c.Painter = p
-}
-
-func NewEx(cfg *Config) (*Instance, error) {
- t, err := NewTerminal(cfg)
- if err != nil {
- return nil, err
- }
- rl := t.Readline()
- if cfg.Painter == nil {
- cfg.Painter = &defaultPainter{}
- }
- return &Instance{
- Config: cfg,
- Terminal: t,
- Operation: rl,
- }, nil
-}
-
-func New(prompt string) (*Instance, error) {
- return NewEx(&Config{Prompt: prompt})
-}
-
-func (i *Instance) ResetHistory() {
- i.Operation.ResetHistory()
-}
-
-func (i *Instance) SetPrompt(s string) {
- i.Operation.SetPrompt(s)
-}
-
-func (i *Instance) SetMaskRune(r rune) {
- i.Operation.SetMaskRune(r)
-}
-
-// change history persistence in runtime
-func (i *Instance) SetHistoryPath(p string) {
- i.Operation.SetHistoryPath(p)
-}
-
-// readline will refresh automatic when write through Stdout()
-func (i *Instance) Stdout() io.Writer {
- return i.Operation.Stdout()
-}
-
-// readline will refresh automatic when write through Stdout()
-func (i *Instance) Stderr() io.Writer {
- return i.Operation.Stderr()
-}
-
-// switch VimMode in runtime
-func (i *Instance) SetVimMode(on bool) {
- i.Operation.SetVimMode(on)
-}
-
-func (i *Instance) IsVimMode() bool {
- return i.Operation.IsEnableVimMode()
-}
-
-func (i *Instance) GenPasswordConfig() *Config {
- return i.Operation.GenPasswordConfig()
-}
-
-// we can generate a config by `i.GenPasswordConfig()`
-func (i *Instance) ReadPasswordWithConfig(cfg *Config) ([]byte, error) {
- return i.Operation.PasswordWithConfig(cfg)
-}
-
-func (i *Instance) ReadPasswordEx(prompt string, l Listener) ([]byte, error) {
- return i.Operation.PasswordEx(prompt, l)
-}
-
-func (i *Instance) ReadPassword(prompt string) ([]byte, error) {
- return i.Operation.Password(prompt)
-}
-
-type Result struct {
- Line string
- Error error
-}
-
-func (l *Result) CanContinue() bool {
- return len(l.Line) != 0 && l.Error == ErrInterrupt
-}
-
-func (l *Result) CanBreak() bool {
- return !l.CanContinue() && l.Error != nil
-}
-
-func (i *Instance) Line() *Result {
- ret, err := i.Readline()
- return &Result{ret, err}
-}
-
-// err is one of (nil, io.EOF, readline.ErrInterrupt)
-func (i *Instance) Readline() (string, error) {
- return i.Operation.String()
-}
-
-func (i *Instance) ReadlineWithDefault(what string) (string, error) {
- i.Operation.SetBuffer(what)
- return i.Operation.String()
-}
-
-func (i *Instance) SaveHistory(content string) error {
- return i.Operation.SaveHistory(content)
-}
-
-// same as readline
-func (i *Instance) ReadSlice() ([]byte, error) {
- return i.Operation.Slice()
-}
-
-// we must make sure that call Close() before process exit.
-func (i *Instance) Close() error {
- if err := i.Terminal.Close(); err != nil {
- return err
- }
- i.Config.Stdin.Close()
- i.Operation.Close()
- return nil
-}
-func (i *Instance) Clean() {
- i.Operation.Clean()
-}
-
-func (i *Instance) Write(b []byte) (int, error) {
- return i.Stdout().Write(b)
-}
-
-// WriteStdin prefill the next Stdin fetch
-// Next time you call ReadLine() this value will be writen before the user input
-// ie :
-// i := readline.New()
-// i.WriteStdin([]byte("test"))
-// _, _= i.Readline()
-//
-// gives
-//
-// > test[cursor]
-func (i *Instance) WriteStdin(val []byte) (int, error) {
- return i.Terminal.WriteStdin(val)
-}
-
-func (i *Instance) SetConfig(cfg *Config) *Config {
- if i.Config == cfg {
- return cfg
- }
- old := i.Config
- i.Config = cfg
- i.Operation.SetConfig(cfg)
- i.Terminal.SetConfig(cfg)
- return old
-}
-
-func (i *Instance) Refresh() {
- i.Operation.Refresh()
-}
-
-// HistoryDisable the save of the commands into the history
-func (i *Instance) HistoryDisable() {
- i.Operation.history.Disable()
-}
-
-// HistoryEnable the save of the commands into the history (default on)
-func (i *Instance) HistoryEnable() {
- i.Operation.history.Enable()
-}
diff --git a/vendor/github.com/rhtyd/readline/remote.go b/vendor/github.com/rhtyd/readline/remote.go
deleted file mode 100644
index 74dbf56..0000000
--- a/vendor/github.com/rhtyd/readline/remote.go
+++ /dev/null
@@ -1,475 +0,0 @@
-package readline
-
-import (
- "bufio"
- "bytes"
- "encoding/binary"
- "fmt"
- "io"
- "net"
- "os"
- "sync"
- "sync/atomic"
-)
-
-type MsgType int16
-
-const (
- T_DATA = MsgType(iota)
- T_WIDTH
- T_WIDTH_REPORT
- T_ISTTY_REPORT
- T_RAW
- T_ERAW // exit raw
- T_EOF
-)
-
-type RemoteSvr struct {
- eof int32
- closed int32
- width int32
- reciveChan chan struct{}
- writeChan chan *writeCtx
- conn net.Conn
- isTerminal bool
- funcWidthChan func()
- stopChan chan struct{}
-
- dataBufM sync.Mutex
- dataBuf bytes.Buffer
-}
-
-type writeReply struct {
- n int
- err error
-}
-
-type writeCtx struct {
- msg *Message
- reply chan *writeReply
-}
-
-func newWriteCtx(msg *Message) *writeCtx {
- return &writeCtx{
- msg: msg,
- reply: make(chan *writeReply),
- }
-}
-
-func NewRemoteSvr(conn net.Conn) (*RemoteSvr, error) {
- rs := &RemoteSvr{
- width: -1,
- conn: conn,
- writeChan: make(chan *writeCtx),
- reciveChan: make(chan struct{}),
- stopChan: make(chan struct{}),
- }
- buf := bufio.NewReader(rs.conn)
-
- if err := rs.init(buf); err != nil {
- return nil, err
- }
-
- go rs.readLoop(buf)
- go rs.writeLoop()
- return rs, nil
-}
-
-func (r *RemoteSvr) init(buf *bufio.Reader) error {
- m, err := ReadMessage(buf)
- if err != nil {
- return err
- }
- // receive isTerminal
- if m.Type != T_ISTTY_REPORT {
- return fmt.Errorf("unexpected init message")
- }
- r.GotIsTerminal(m.Data)
-
- // receive width
- m, err = ReadMessage(buf)
- if err != nil {
- return err
- }
- if m.Type != T_WIDTH_REPORT {
- return fmt.Errorf("unexpected init message")
- }
- r.GotReportWidth(m.Data)
-
- return nil
-}
-
-func (r *RemoteSvr) HandleConfig(cfg *Config) {
- cfg.Stderr = r
- cfg.Stdout = r
- cfg.Stdin = r
- cfg.FuncExitRaw = r.ExitRawMode
- cfg.FuncIsTerminal = r.IsTerminal
- cfg.FuncMakeRaw = r.EnterRawMode
- cfg.FuncExitRaw = r.ExitRawMode
- cfg.FuncGetWidth = r.GetWidth
- cfg.FuncOnWidthChanged = func(f func()) {
- r.funcWidthChan = f
- }
-}
-
-func (r *RemoteSvr) IsTerminal() bool {
- return r.isTerminal
-}
-
-func (r *RemoteSvr) checkEOF() error {
- if atomic.LoadInt32(&r.eof) == 1 {
- return io.EOF
- }
- return nil
-}
-
-func (r *RemoteSvr) Read(b []byte) (int, error) {
- r.dataBufM.Lock()
- n, err := r.dataBuf.Read(b)
- r.dataBufM.Unlock()
- if n == 0 {
- if err := r.checkEOF(); err != nil {
- return 0, err
- }
- }
-
- if n == 0 && err == io.EOF {
- <-r.reciveChan
- r.dataBufM.Lock()
- n, err = r.dataBuf.Read(b)
- r.dataBufM.Unlock()
- }
- if n == 0 {
- if err := r.checkEOF(); err != nil {
- return 0, err
- }
- }
-
- return n, err
-}
-
-func (r *RemoteSvr) writeMsg(m *Message) error {
- ctx := newWriteCtx(m)
- r.writeChan <- ctx
- reply := <-ctx.reply
- return reply.err
-}
-
-func (r *RemoteSvr) Write(b []byte) (int, error) {
- ctx := newWriteCtx(NewMessage(T_DATA, b))
- r.writeChan <- ctx
- reply := <-ctx.reply
- return reply.n, reply.err
-}
-
-func (r *RemoteSvr) EnterRawMode() error {
- return r.writeMsg(NewMessage(T_RAW, nil))
-}
-
-func (r *RemoteSvr) ExitRawMode() error {
- return r.writeMsg(NewMessage(T_ERAW, nil))
-}
-
-func (r *RemoteSvr) writeLoop() {
- defer r.Close()
-
-loop:
- for {
- select {
- case ctx, ok := <-r.writeChan:
- if !ok {
- break
- }
- n, err := ctx.msg.WriteTo(r.conn)
- ctx.reply <- &writeReply{n, err}
- case <-r.stopChan:
- break loop
- }
- }
-}
-
-func (r *RemoteSvr) Close() error {
- if atomic.CompareAndSwapInt32(&r.closed, 0, 1) {
- close(r.stopChan)
- r.conn.Close()
- }
- return nil
-}
-
-func (r *RemoteSvr) readLoop(buf *bufio.Reader) {
- defer r.Close()
- for {
- m, err := ReadMessage(buf)
- if err != nil {
- break
- }
- switch m.Type {
- case T_EOF:
- atomic.StoreInt32(&r.eof, 1)
- select {
- case r.reciveChan <- struct{}{}:
- default:
- }
- case T_DATA:
- r.dataBufM.Lock()
- r.dataBuf.Write(m.Data)
- r.dataBufM.Unlock()
- select {
- case r.reciveChan <- struct{}{}:
- default:
- }
- case T_WIDTH_REPORT:
- r.GotReportWidth(m.Data)
- case T_ISTTY_REPORT:
- r.GotIsTerminal(m.Data)
- }
- }
-}
-
-func (r *RemoteSvr) GotIsTerminal(data []byte) {
- if binary.BigEndian.Uint16(data) == 0 {
- r.isTerminal = false
- } else {
- r.isTerminal = true
- }
-}
-
-func (r *RemoteSvr) GotReportWidth(data []byte) {
- atomic.StoreInt32(&r.width, int32(binary.BigEndian.Uint16(data)))
- if r.funcWidthChan != nil {
- r.funcWidthChan()
- }
-}
-
-func (r *RemoteSvr) GetWidth() int {
- return int(atomic.LoadInt32(&r.width))
-}
-
-// -----------------------------------------------------------------------------
-
-type Message struct {
- Type MsgType
- Data []byte
-}
-
-func ReadMessage(r io.Reader) (*Message, error) {
- m := new(Message)
- var length int32
- if err := binary.Read(r, binary.BigEndian, &length); err != nil {
- return nil, err
- }
- if err := binary.Read(r, binary.BigEndian, &m.Type); err != nil {
- return nil, err
- }
- m.Data = make([]byte, int(length)-2)
- if _, err := io.ReadFull(r, m.Data); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func NewMessage(t MsgType, data []byte) *Message {
- return &Message{t, data}
-}
-
-func (m *Message) WriteTo(w io.Writer) (int, error) {
- buf := bytes.NewBuffer(make([]byte, 0, len(m.Data)+2+4))
- binary.Write(buf, binary.BigEndian, int32(len(m.Data)+2))
- binary.Write(buf, binary.BigEndian, m.Type)
- buf.Write(m.Data)
- n, err := buf.WriteTo(w)
- return int(n), err
-}
-
-// -----------------------------------------------------------------------------
-
-type RemoteCli struct {
- conn net.Conn
- raw RawMode
- receiveChan chan struct{}
- inited int32
- isTerminal *bool
-
- data bytes.Buffer
- dataM sync.Mutex
-}
-
-func NewRemoteCli(conn net.Conn) (*RemoteCli, error) {
- r := &RemoteCli{
- conn: conn,
- receiveChan: make(chan struct{}),
- }
- return r, nil
-}
-
-func (r *RemoteCli) MarkIsTerminal(is bool) {
- r.isTerminal = &is
-}
-
-func (r *RemoteCli) init() error {
- if !atomic.CompareAndSwapInt32(&r.inited, 0, 1) {
- return nil
- }
-
- if err := r.reportIsTerminal(); err != nil {
- return err
- }
-
- if err := r.reportWidth(); err != nil {
- return err
- }
-
- // register sig for width changed
- DefaultOnWidthChanged(func() {
- r.reportWidth()
- })
- return nil
-}
-
-func (r *RemoteCli) writeMsg(m *Message) error {
- r.dataM.Lock()
- _, err := m.WriteTo(r.conn)
- r.dataM.Unlock()
- return err
-}
-
-func (r *RemoteCli) Write(b []byte) (int, error) {
- m := NewMessage(T_DATA, b)
- r.dataM.Lock()
- _, err := m.WriteTo(r.conn)
- r.dataM.Unlock()
- return len(b), err
-}
-
-func (r *RemoteCli) reportWidth() error {
- screenWidth := GetScreenWidth()
- data := make([]byte, 2)
- binary.BigEndian.PutUint16(data, uint16(screenWidth))
- msg := NewMessage(T_WIDTH_REPORT, data)
-
- if err := r.writeMsg(msg); err != nil {
- return err
- }
- return nil
-}
-
-func (r *RemoteCli) reportIsTerminal() error {
- var isTerminal bool
- if r.isTerminal != nil {
- isTerminal = *r.isTerminal
- } else {
- isTerminal = DefaultIsTerminal()
- }
- data := make([]byte, 2)
- if isTerminal {
- binary.BigEndian.PutUint16(data, 1)
- } else {
- binary.BigEndian.PutUint16(data, 0)
- }
- msg := NewMessage(T_ISTTY_REPORT, data)
- if err := r.writeMsg(msg); err != nil {
- return err
- }
- return nil
-}
-
-func (r *RemoteCli) readLoop() {
- buf := bufio.NewReader(r.conn)
- for {
- msg, err := ReadMessage(buf)
- if err != nil {
- break
- }
- switch msg.Type {
- case T_ERAW:
- r.raw.Exit()
- case T_RAW:
- r.raw.Enter()
- case T_DATA:
- os.Stdout.Write(msg.Data)
- }
- }
-}
-
-func (r *RemoteCli) ServeBy(source io.Reader) error {
- if err := r.init(); err != nil {
- return err
- }
-
- go func() {
- defer r.Close()
- for {
- n, _ := io.Copy(r, source)
- if n == 0 {
- break
- }
- }
- }()
- defer r.raw.Exit()
- r.readLoop()
- return nil
-}
-
-func (r *RemoteCli) Close() {
- r.writeMsg(NewMessage(T_EOF, nil))
-}
-
-func (r *RemoteCli) Serve() error {
- return r.ServeBy(os.Stdin)
-}
-
-func ListenRemote(n, addr string, cfg *Config, h func(*Instance), onListen ...func(net.Listener) error) error {
- ln, err := net.Listen(n, addr)
- if err != nil {
- return err
- }
- if len(onListen) > 0 {
- if err := onListen[0](ln); err != nil {
- return err
- }
- }
- for {
- conn, err := ln.Accept()
- if err != nil {
- break
- }
- go func() {
- defer conn.Close()
- rl, err := HandleConn(*cfg, conn)
- if err != nil {
- return
- }
- h(rl)
- }()
- }
- return nil
-}
-
-func HandleConn(cfg Config, conn net.Conn) (*Instance, error) {
- r, err := NewRemoteSvr(conn)
- if err != nil {
- return nil, err
- }
- r.HandleConfig(&cfg)
-
- rl, err := NewEx(&cfg)
- if err != nil {
- return nil, err
- }
- return rl, nil
-}
-
-func DialRemote(n, addr string) error {
- conn, err := net.Dial(n, addr)
- if err != nil {
- return err
- }
- defer conn.Close()
-
- cli, err := NewRemoteCli(conn)
- if err != nil {
- return err
- }
- return cli.Serve()
-}
diff --git a/vendor/github.com/rhtyd/readline/runebuf.go b/vendor/github.com/rhtyd/readline/runebuf.go
deleted file mode 100644
index 81d2da5..0000000
--- a/vendor/github.com/rhtyd/readline/runebuf.go
+++ /dev/null
@@ -1,629 +0,0 @@
-package readline
-
-import (
- "bufio"
- "bytes"
- "io"
- "strconv"
- "strings"
- "sync"
-)
-
-type runeBufferBck struct {
- buf []rune
- idx int
-}
-
-type RuneBuffer struct {
- buf []rune
- idx int
- prompt []rune
- w io.Writer
-
- hadClean bool
- interactive bool
- cfg *Config
-
- width int
-
- bck *runeBufferBck
-
- offset string
-
- lastKill []rune
-
- sync.Mutex
-}
-
-func (r* RuneBuffer) pushKill(text []rune) {
- r.lastKill = append([]rune{}, text...)
-}
-
-func (r *RuneBuffer) OnWidthChange(newWidth int) {
- r.Lock()
- r.width = newWidth
- r.Unlock()
-}
-
-func (r *RuneBuffer) Backup() {
- r.Lock()
- r.bck = &runeBufferBck{r.buf, r.idx}
- r.Unlock()
-}
-
-func (r *RuneBuffer) Restore() {
- r.Refresh(func() {
- if r.bck == nil {
- return
- }
- r.buf = r.bck.buf
- r.idx = r.bck.idx
- })
-}
-
-func NewRuneBuffer(w io.Writer, prompt string, cfg *Config, width int) *RuneBuffer {
- rb := &RuneBuffer{
- w: w,
- interactive: cfg.useInteractive(),
- cfg: cfg,
- width: width,
- }
- rb.SetPrompt(prompt)
- return rb
-}
-
-func (r *RuneBuffer) SetConfig(cfg *Config) {
- r.Lock()
- r.cfg = cfg
- r.interactive = cfg.useInteractive()
- r.Unlock()
-}
-
-func (r *RuneBuffer) SetMask(m rune) {
- r.Lock()
- r.cfg.MaskRune = m
- r.Unlock()
-}
-
-func (r *RuneBuffer) CurrentWidth(x int) int {
- r.Lock()
- defer r.Unlock()
- return runes.WidthAll(r.buf[:x])
-}
-
-func (r *RuneBuffer) PromptLen() int {
- r.Lock()
- width := r.promptLen()
- r.Unlock()
- return width
-}
-
-func (r *RuneBuffer) promptLen() int {
- return runes.WidthAll(runes.ColorFilter(r.prompt))
-}
-
-func (r *RuneBuffer) RuneSlice(i int) []rune {
- r.Lock()
- defer r.Unlock()
-
- if i > 0 {
- rs := make([]rune, i)
- copy(rs, r.buf[r.idx:r.idx+i])
- return rs
- }
- rs := make([]rune, -i)
- copy(rs, r.buf[r.idx+i:r.idx])
- return rs
-}
-
-func (r *RuneBuffer) Runes() []rune {
- r.Lock()
- newr := make([]rune, len(r.buf))
- copy(newr, r.buf)
- r.Unlock()
- return newr
-}
-
-func (r *RuneBuffer) Pos() int {
- r.Lock()
- defer r.Unlock()
- return r.idx
-}
-
-func (r *RuneBuffer) Len() int {
- r.Lock()
- defer r.Unlock()
- return len(r.buf)
-}
-
-func (r *RuneBuffer) MoveToLineStart() {
- r.Refresh(func() {
- if r.idx == 0 {
- return
- }
- r.idx = 0
- })
-}
-
-func (r *RuneBuffer) MoveBackward() {
- r.Refresh(func() {
- if r.idx == 0 {
- return
- }
- r.idx--
- })
-}
-
-func (r *RuneBuffer) WriteString(s string) {
- r.WriteRunes([]rune(s))
-}
-
-func (r *RuneBuffer) WriteRune(s rune) {
- r.WriteRunes([]rune{s})
-}
-
-func (r *RuneBuffer) WriteRunes(s []rune) {
- r.Refresh(func() {
- tail := append(s, r.buf[r.idx:]...)
- r.buf = append(r.buf[:r.idx], tail...)
- r.idx += len(s)
- })
-}
-
-func (r *RuneBuffer) MoveForward() {
- r.Refresh(func() {
- if r.idx == len(r.buf) {
- return
- }
- r.idx++
- })
-}
-
-func (r *RuneBuffer) IsCursorInEnd() bool {
- r.Lock()
- defer r.Unlock()
- return r.idx == len(r.buf)
-}
-
-func (r *RuneBuffer) Replace(ch rune) {
- r.Refresh(func() {
- r.buf[r.idx] = ch
- })
-}
-
-func (r *RuneBuffer) Erase() {
- r.Refresh(func() {
- r.idx = 0
- r.pushKill(r.buf[:])
- r.buf = r.buf[:0]
- })
-}
-
-func (r *RuneBuffer) Delete() (success bool) {
- r.Refresh(func() {
- if r.idx == len(r.buf) {
- return
- }
- r.pushKill(r.buf[r.idx : r.idx+1])
- r.buf = append(r.buf[:r.idx], r.buf[r.idx+1:]...)
- success = true
- })
- return
-}
-
-func (r *RuneBuffer) DeleteWord() {
- if r.idx == len(r.buf) {
- return
- }
- init := r.idx
- for init < len(r.buf) && IsWordBreak(r.buf[init]) {
- init++
- }
- for i := init + 1; i < len(r.buf); i++ {
- if !IsWordBreak(r.buf[i]) && IsWordBreak(r.buf[i-1]) {
- r.pushKill(r.buf[r.idx:i-1])
- r.Refresh(func() {
- r.buf = append(r.buf[:r.idx], r.buf[i-1:]...)
- })
- return
- }
- }
- r.Kill()
-}
-
-func (r *RuneBuffer) MoveToPrevWord() (success bool) {
- r.Refresh(func() {
- if r.idx == 0 {
- return
- }
-
- for i := r.idx - 1; i > 0; i-- {
- if !IsWordBreak(r.buf[i]) && IsWordBreak(r.buf[i-1]) {
- r.idx = i
- success = true
- return
- }
- }
- r.idx = 0
- success = true
- })
- return
-}
-
-func (r *RuneBuffer) KillFront() {
- r.Refresh(func() {
- if r.idx == 0 {
- return
- }
-
- length := len(r.buf) - r.idx
- r.pushKill(r.buf[:r.idx])
- copy(r.buf[:length], r.buf[r.idx:])
- r.idx = 0
- r.buf = r.buf[:length]
- })
-}
-
-func (r *RuneBuffer) Kill() {
- r.Refresh(func() {
- r.pushKill(r.buf[r.idx:])
- r.buf = r.buf[:r.idx]
- })
-}
-
-func (r *RuneBuffer) Transpose() {
- r.Refresh(func() {
- if len(r.buf) == 1 {
- r.idx++
- }
-
- if len(r.buf) < 2 {
- return
- }
-
- if r.idx == 0 {
- r.idx = 1
- } else if r.idx >= len(r.buf) {
- r.idx = len(r.buf) - 1
- }
- r.buf[r.idx], r.buf[r.idx-1] = r.buf[r.idx-1], r.buf[r.idx]
- r.idx++
- })
-}
-
-func (r *RuneBuffer) MoveToNextWord() {
- r.Refresh(func() {
- for i := r.idx + 1; i < len(r.buf); i++ {
- if !IsWordBreak(r.buf[i]) && IsWordBreak(r.buf[i-1]) {
- r.idx = i
- return
- }
- }
-
- r.idx = len(r.buf)
- })
-}
-
-func (r *RuneBuffer) MoveToEndWord() {
- r.Refresh(func() {
- // already at the end, so do nothing
- if r.idx == len(r.buf) {
- return
- }
- // if we are at the end of a word already, go to next
- if !IsWordBreak(r.buf[r.idx]) && IsWordBreak(r.buf[r.idx+1]) {
- r.idx++
- }
-
- // keep going until at the end of a word
- for i := r.idx + 1; i < len(r.buf); i++ {
- if IsWordBreak(r.buf[i]) && !IsWordBreak(r.buf[i-1]) {
- r.idx = i - 1
- return
- }
- }
- r.idx = len(r.buf)
- })
-}
-
-func (r *RuneBuffer) BackEscapeWord() {
- r.Refresh(func() {
- if r.idx == 0 {
- return
- }
- for i := r.idx - 1; i > 0; i-- {
- if !IsWordBreak(r.buf[i]) && IsWordBreak(r.buf[i-1]) {
- r.pushKill(r.buf[i:r.idx])
- r.buf = append(r.buf[:i], r.buf[r.idx:]...)
- r.idx = i
- return
- }
- }
-
- r.buf = r.buf[:0]
- r.idx = 0
- })
-}
-
-func (r *RuneBuffer) Yank() {
- if len(r.lastKill) == 0 {
- return
- }
- r.Refresh(func() {
- buf := make([]rune, 0, len(r.buf) + len(r.lastKill))
- buf = append(buf, r.buf[:r.idx]...)
- buf = append(buf, r.lastKill...)
- buf = append(buf, r.buf[r.idx:]...)
- r.buf = buf
- r.idx += len(r.lastKill)
- })
-}
-
-func (r *RuneBuffer) Backspace() {
- r.Refresh(func() {
- if r.idx == 0 {
- return
- }
-
- r.idx--
- r.buf = append(r.buf[:r.idx], r.buf[r.idx+1:]...)
- })
-}
-
-func (r *RuneBuffer) MoveToLineEnd() {
- r.Refresh(func() {
- if r.idx == len(r.buf) {
- return
- }
-
- r.idx = len(r.buf)
- })
-}
-
-func (r *RuneBuffer) LineCount(width int) int {
- if width == -1 {
- width = r.width
- }
- return LineCount(width,
- runes.WidthAll(r.buf)+r.PromptLen())
-}
-
-func (r *RuneBuffer) MoveTo(ch rune, prevChar, reverse bool) (success bool) {
- r.Refresh(func() {
- if reverse {
- for i := r.idx - 1; i >= 0; i-- {
- if r.buf[i] == ch {
- r.idx = i
- if prevChar {
- r.idx++
- }
- success = true
- return
- }
- }
- return
- }
- for i := r.idx + 1; i < len(r.buf); i++ {
- if r.buf[i] == ch {
- r.idx = i
- if prevChar {
- r.idx--
- }
- success = true
- return
- }
- }
- })
- return
-}
-
-func (r *RuneBuffer) isInLineEdge() bool {
- if isWindows {
- return false
- }
- sp := r.getSplitByLine(r.buf)
- return len(sp[len(sp)-1]) == 0
-}
-
-func (r *RuneBuffer) getSplitByLine(rs []rune) []string {
- return SplitByLine(r.promptLen(), r.width, rs)
-}
-
-func (r *RuneBuffer) IdxLine(width int) int {
- r.Lock()
- defer r.Unlock()
- return r.idxLine(width)
-}
-
-func (r *RuneBuffer) idxLine(width int) int {
- if width == 0 {
- return 0
- }
- sp := r.getSplitByLine(r.buf[:r.idx])
- return len(sp) - 1
-}
-
-func (r *RuneBuffer) CursorLineCount() int {
- return r.LineCount(r.width) - r.IdxLine(r.width)
-}
-
-func (r *RuneBuffer) Refresh(f func()) {
- r.Lock()
- defer r.Unlock()
-
- if !r.interactive {
- if f != nil {
- f()
- }
- return
- }
-
- r.clean()
- if f != nil {
- f()
- }
- r.print()
-}
-
-func (r *RuneBuffer) SetOffset(offset string) {
- r.Lock()
- r.offset = offset
- r.Unlock()
-}
-
-func (r *RuneBuffer) print() {
- r.w.Write(r.output())
- r.hadClean = false
-}
-
-func (r *RuneBuffer) output() []byte {
- buf := bytes.NewBuffer(nil)
- buf.WriteString(string(r.prompt))
- if r.cfg.EnableMask && len(r.buf) > 0 {
- buf.Write([]byte(strings.Repeat(string(r.cfg.MaskRune), len(r.buf)-1)))
- if r.buf[len(r.buf)-1] == '\n' {
- buf.Write([]byte{'\n'})
- } else {
- buf.Write([]byte(string(r.cfg.MaskRune)))
- }
- if len(r.buf) > r.idx {
- buf.Write(r.getBackspaceSequence())
- }
-
- } else {
- for _, e := range r.cfg.Painter.Paint(r.buf, r.idx) {
- if e == '\t' {
- buf.WriteString(strings.Repeat(" ", TabWidth))
- } else {
- buf.WriteRune(e)
- }
- }
- if r.isInLineEdge() {
- buf.Write([]byte(" \b"))
- }
- }
- // cursor position
- if len(r.buf) > r.idx {
- buf.Write(r.getBackspaceSequence())
- }
- return buf.Bytes()
-}
-
-func (r *RuneBuffer) getBackspaceSequence() []byte {
- var sep = map[int]bool{}
-
- var i int
- for {
- if i >= runes.WidthAll(r.buf) {
- break
- }
-
- if i == 0 {
- i -= r.promptLen()
- }
- i += r.width
-
- sep[i] = true
- }
- var buf []byte
- for i := len(r.buf); i > r.idx; i-- {
- // move input to the left of one
- buf = append(buf, '\b')
- if sep[i] {
- // up one line, go to the start of the line and move cursor right to the end (r.width)
- buf = append(buf, "\033[A\r"+"\033["+strconv.Itoa(r.width)+"C"...)
- }
- }
-
- return buf
-
-}
-
-func (r *RuneBuffer) Reset() []rune {
- ret := runes.Copy(r.buf)
- r.buf = r.buf[:0]
- r.idx = 0
- return ret
-}
-
-func (r *RuneBuffer) calWidth(m int) int {
- if m > 0 {
- return runes.WidthAll(r.buf[r.idx : r.idx+m])
- }
- return runes.WidthAll(r.buf[r.idx+m : r.idx])
-}
-
-func (r *RuneBuffer) SetStyle(start, end int, style string) {
- if end < start {
- panic("end < start")
- }
-
- // goto start
- move := start - r.idx
- if move > 0 {
- r.w.Write([]byte(string(r.buf[r.idx : r.idx+move])))
- } else {
- r.w.Write(bytes.Repeat([]byte("\b"), r.calWidth(move)))
- }
- r.w.Write([]byte("\033[" + style + "m"))
- r.w.Write([]byte(string(r.buf[start:end])))
- r.w.Write([]byte("\033[0m"))
- // TODO: move back
-}
-
-func (r *RuneBuffer) SetWithIdx(idx int, buf []rune) {
- r.Refresh(func() {
- r.buf = buf
- r.idx = idx
- })
-}
-
-func (r *RuneBuffer) Set(buf []rune) {
- r.SetWithIdx(len(buf), buf)
-}
-
-func (r *RuneBuffer) SetPrompt(prompt string) {
- r.Lock()
- r.prompt = []rune(prompt)
- r.Unlock()
-}
-
-func (r *RuneBuffer) cleanOutput(w io.Writer, idxLine int) {
- buf := bufio.NewWriter(w)
-
- if r.width == 0 {
- buf.WriteString(strings.Repeat("\r\b", len(r.buf)+r.promptLen()))
- buf.Write([]byte("\033[J"))
- } else {
- buf.Write([]byte("\033[J")) // just like ^k :)
- if idxLine == 0 {
- buf.WriteString("\033[2K")
- buf.WriteString("\r")
- } else {
- for i := 0; i < idxLine; i++ {
- io.WriteString(buf, "\033[2K\r\033[A")
- }
- io.WriteString(buf, "\033[2K\r")
- }
- }
- buf.Flush()
- return
-}
-
-func (r *RuneBuffer) Clean() {
- r.Lock()
- r.clean()
- r.Unlock()
-}
-
-func (r *RuneBuffer) clean() {
- r.cleanWithIdxLine(r.idxLine(r.width))
-}
-
-func (r *RuneBuffer) cleanWithIdxLine(idxLine int) {
- if r.hadClean || !r.interactive {
- return
- }
- r.hadClean = true
- r.cleanOutput(r.w, idxLine)
-}
diff --git a/vendor/github.com/rhtyd/readline/runes.go b/vendor/github.com/rhtyd/readline/runes.go
deleted file mode 100644
index bcf483e..0000000
--- a/vendor/github.com/rhtyd/readline/runes.go
+++ /dev/null
@@ -1,224 +0,0 @@
-package readline
-
-import (
- "bytes"
- "unicode"
- "unicode/utf8"
-)
-
-var runes = Runes{}
-var TabWidth = 4
-
-type Runes struct{}
-
-func (Runes) EqualRune(a, b rune, fold bool) bool {
- if a == b {
- return true
- }
- if !fold {
- return false
- }
- if a > b {
- a, b = b, a
- }
- if b < utf8.RuneSelf && 'A' <= a && a <= 'Z' {
- if b == a+'a'-'A' {
- return true
- }
- }
- return false
-}
-
-func (r Runes) EqualRuneFold(a, b rune) bool {
- return r.EqualRune(a, b, true)
-}
-
-func (r Runes) EqualFold(a, b []rune) bool {
- if len(a) != len(b) {
- return false
- }
- for i := 0; i < len(a); i++ {
- if r.EqualRuneFold(a[i], b[i]) {
- continue
- }
- return false
- }
-
- return true
-}
-
-func (Runes) Equal(a, b []rune) bool {
- if len(a) != len(b) {
- return false
- }
- for i := 0; i < len(a); i++ {
- if a[i] != b[i] {
- return false
- }
- }
- return true
-}
-
-func (rs Runes) IndexAllBckEx(r, sub []rune, fold bool) int {
- for i := len(r) - len(sub); i >= 0; i-- {
- found := true
- for j := 0; j < len(sub); j++ {
- if !rs.EqualRune(r[i+j], sub[j], fold) {
- found = false
- break
- }
- }
- if found {
- return i
- }
- }
- return -1
-}
-
-// Search in runes from end to front
-func (rs Runes) IndexAllBck(r, sub []rune) int {
- return rs.IndexAllBckEx(r, sub, false)
-}
-
-// Search in runes from front to end
-func (rs Runes) IndexAll(r, sub []rune) int {
- return rs.IndexAllEx(r, sub, false)
-}
-
-func (rs Runes) IndexAllEx(r, sub []rune, fold bool) int {
- for i := 0; i < len(r); i++ {
- found := true
- if len(r[i:]) < len(sub) {
- return -1
- }
- for j := 0; j < len(sub); j++ {
- if !rs.EqualRune(r[i+j], sub[j], fold) {
- found = false
- break
- }
- }
- if found {
- return i
- }
- }
- return -1
-}
-
-func (Runes) Index(r rune, rs []rune) int {
- for i := 0; i < len(rs); i++ {
- if rs[i] == r {
- return i
- }
- }
- return -1
-}
-
-func (Runes) ColorFilter(r []rune) []rune {
- newr := make([]rune, 0, len(r))
- for pos := 0; pos < len(r); pos++ {
- if r[pos] == '\033' && r[pos+1] == '[' {
- idx := runes.Index('m', r[pos+2:])
- if idx == -1 {
- continue
- }
- pos += idx + 2
- continue
- }
- newr = append(newr, r[pos])
- }
- return newr
-}
-
-var zeroWidth = []*unicode.RangeTable{
- unicode.Mn,
- unicode.Me,
- unicode.Cc,
- unicode.Cf,
-}
-
-var doubleWidth = []*unicode.RangeTable{
- unicode.Han,
- unicode.Hangul,
- unicode.Hiragana,
- unicode.Katakana,
- unicode.So,
-}
-
-func (Runes) Width(r rune) int {
- if r == '\t' {
- return TabWidth
- }
- if unicode.IsOneOf(zeroWidth, r) {
- return 0
- }
- if unicode.IsOneOf(doubleWidth, r) {
- return 2
- }
- return 1
-}
-
-func (Runes) WidthAll(r []rune) (length int) {
- for i := 0; i < len(r); i++ {
- length += runes.Width(r[i])
- }
- return
-}
-
-func (Runes) Backspace(r []rune) []byte {
- return bytes.Repeat([]byte{'\b'}, runes.WidthAll(r))
-}
-
-func (Runes) Copy(r []rune) []rune {
- n := make([]rune, len(r))
- copy(n, r)
- return n
-}
-
-func (Runes) HasPrefixFold(r, prefix []rune) bool {
- if len(r) < len(prefix) {
- return false
- }
- return runes.EqualFold(r[:len(prefix)], prefix)
-}
-
-func (Runes) HasPrefix(r, prefix []rune) bool {
- if len(r) < len(prefix) {
- return false
- }
- return runes.Equal(r[:len(prefix)], prefix)
-}
-
-func (Runes) Aggregate(candicate [][]rune) (same []rune, size int) {
- for i := 0; i < len(candicate[0]); i++ {
- for j := 0; j < len(candicate)-1; j++ {
- if i >= len(candicate[j]) || i >= len(candicate[j+1]) {
- goto aggregate
- }
- if candicate[j][i] != candicate[j+1][i] {
- goto aggregate
- }
- }
- size = i + 1
- }
-aggregate:
- if size > 0 {
- same = runes.Copy(candicate[0][:size])
- for i := 0; i < len(candicate); i++ {
- n := runes.Copy(candicate[i])
- copy(n, n[size:])
- candicate[i] = n[:len(n)-size]
- }
- }
- return
-}
-
-func (Runes) TrimSpaceLeft(in []rune) []rune {
- firstIndex := len(in)
- for i, r := range in {
- if unicode.IsSpace(r) == false {
- firstIndex = i
- break
- }
- }
- return in[firstIndex:]
-}
diff --git a/vendor/github.com/rhtyd/readline/runes/runes.go b/vendor/github.com/rhtyd/readline/runes/runes.go
deleted file mode 100644
index b069440..0000000
--- a/vendor/github.com/rhtyd/readline/runes/runes.go
+++ /dev/null
@@ -1,155 +0,0 @@
-// deprecated.
-// see https://github.com/chzyer/readline/issues/43
-// use github.com/chzyer/readline/runes.go
-package runes
-
-import (
- "bytes"
- "unicode"
-)
-
-func Equal(a, b []rune) bool {
- if len(a) != len(b) {
- return false
- }
- for i := 0; i < len(a); i++ {
- if a[i] != b[i] {
- return false
- }
- }
- return true
-}
-
-// Search in runes from end to front
-func IndexAllBck(r, sub []rune) int {
- for i := len(r) - len(sub); i >= 0; i-- {
- found := true
- for j := 0; j < len(sub); j++ {
- if r[i+j] != sub[j] {
- found = false
- break
- }
- }
- if found {
- return i
- }
- }
- return -1
-}
-
-// Search in runes from front to end
-func IndexAll(r, sub []rune) int {
- for i := 0; i < len(r); i++ {
- found := true
- if len(r[i:]) < len(sub) {
- return -1
- }
- for j := 0; j < len(sub); j++ {
- if r[i+j] != sub[j] {
- found = false
- break
- }
- }
- if found {
- return i
- }
- }
- return -1
-}
-
-func Index(r rune, rs []rune) int {
- for i := 0; i < len(rs); i++ {
- if rs[i] == r {
- return i
- }
- }
- return -1
-}
-
-func ColorFilter(r []rune) []rune {
- newr := make([]rune, 0, len(r))
- for pos := 0; pos < len(r); pos++ {
- if r[pos] == '\033' && r[pos+1] == '[' {
- idx := Index('m', r[pos+2:])
- if idx == -1 {
- continue
- }
- pos += idx + 2
- continue
- }
- newr = append(newr, r[pos])
- }
- return newr
-}
-
-var zeroWidth = []*unicode.RangeTable{
- unicode.Mn,
- unicode.Me,
- unicode.Cc,
- unicode.Cf,
-}
-
-var doubleWidth = []*unicode.RangeTable{
- unicode.Han,
- unicode.Hangul,
- unicode.Hiragana,
- unicode.Katakana,
-}
-
-func Width(r rune) int {
- if unicode.IsOneOf(zeroWidth, r) {
- return 0
- }
- if unicode.IsOneOf(doubleWidth, r) {
- return 2
- }
- return 1
-}
-
-func WidthAll(r []rune) (length int) {
- for i := 0; i < len(r); i++ {
- length += Width(r[i])
- }
- return
-}
-
-func Backspace(r []rune) []byte {
- return bytes.Repeat([]byte{'\b'}, WidthAll(r))
-}
-
-func Copy(r []rune) []rune {
- n := make([]rune, len(r))
- copy(n, r)
- return n
-}
-
-func HasPrefix(r, prefix []rune) bool {
- if len(r) < len(prefix) {
- return false
- }
- return Equal(r[:len(prefix)], prefix)
-}
-
-func Aggregate(candicate [][]rune) (same []rune, size int) {
- for i := 0; i < len(candicate[0]); i++ {
- for j := 0; j < len(candicate)-1; j++ {
- if i >= len(candicate[j]) || i >= len(candicate[j+1]) {
- goto aggregate
- }
- if candicate[j][i] != candicate[j+1][i] {
- goto aggregate
- }
- }
- size = i + 1
- }
-aggregate:
- if size > 0 {
- same = Copy(candicate[0][:size])
- for i := 0; i < len(candicate); i++ {
- n := Copy(candicate[i])
- copy(n, n[size:])
- candicate[i] = n[:len(n)-size]
- }
- }
- return
-}
diff --git a/vendor/github.com/rhtyd/readline/search.go b/vendor/github.com/rhtyd/readline/search.go
deleted file mode 100644
index 52e8ff0..0000000
--- a/vendor/github.com/rhtyd/readline/search.go
+++ /dev/null
@@ -1,164 +0,0 @@
-package readline
-
-import (
- "bytes"
- "container/list"
- "fmt"
- "io"
-)
-
-const (
- S_STATE_FOUND = iota
- S_STATE_FAILING
-)
-
-const (
- S_DIR_BCK = iota
- S_DIR_FWD
-)
-
-type opSearch struct {
- inMode bool
- state int
- dir int
- source *list.Element
- w io.Writer
- buf *RuneBuffer
- data []rune
- history *opHistory
- cfg *Config
- markStart int
- markEnd int
- width int
-}
-
-func newOpSearch(w io.Writer, buf *RuneBuffer, history *opHistory, cfg *Config, width int) *opSearch {
- return &opSearch{
- w: w,
- buf: buf,
- cfg: cfg,
- history: history,
- width: width,
- }
-}
-
-func (o *opSearch) OnWidthChange(newWidth int) {
- o.width = newWidth
-}
-
-func (o *opSearch) IsSearchMode() bool {
- return o.inMode
-}
-
-func (o *opSearch) SearchBackspace() {
- if len(o.data) > 0 {
- o.data = o.data[:len(o.data)-1]
- o.search(true)
- }
-}
-
-func (o *opSearch) findHistoryBy(isNewSearch bool) (int, *list.Element) {
- if o.dir == S_DIR_BCK {
- return o.history.FindBck(isNewSearch, o.data, o.buf.idx)
- }
- return o.history.FindFwd(isNewSearch, o.data, o.buf.idx)
-}
-
-func (o *opSearch) search(isChange bool) bool {
- if len(o.data) == 0 {
- o.state = S_STATE_FOUND
- o.SearchRefresh(-1)
- return true
- }
- idx, elem := o.findHistoryBy(isChange)
- if elem == nil {
- o.SearchRefresh(-2)
- return false
- }
- o.history.current = elem
-
- item := o.history.showItem(o.history.current.Value)
- start, end := 0, 0
- if o.dir == S_DIR_BCK {
- start, end = idx, idx+len(o.data)
- } else {
- start, end = idx, idx+len(o.data)
- idx += len(o.data)
- }
- o.buf.SetWithIdx(idx, item)
- o.markStart, o.markEnd = start, end
- o.SearchRefresh(idx)
- return true
-}
-
-func (o *opSearch) SearchChar(r rune) {
- o.data = append(o.data, r)
- o.search(true)
-}
-
-func (o *opSearch) SearchMode(dir int) bool {
- if o.width == 0 {
- return false
- }
- alreadyInMode := o.inMode
- o.inMode = true
- o.dir = dir
- o.source = o.history.current
- if alreadyInMode {
- o.search(false)
- } else {
- o.SearchRefresh(-1)
- }
- return true
-}
-
-func (o *opSearch) ExitSearchMode(revert bool) {
- if revert {
- o.history.current = o.source
- o.buf.Set(o.history.showItem(o.history.current.Value))
- }
- o.markStart, o.markEnd = 0, 0
- o.state = S_STATE_FOUND
- o.inMode = false
- o.source = nil
- o.data = nil
-}
-
-func (o *opSearch) SearchRefresh(x int) {
- if x == -2 {
- o.state = S_STATE_FAILING
- } else if x >= 0 {
- o.state = S_STATE_FOUND
- }
- if x < 0 {
- x = o.buf.idx
- }
- x = o.buf.CurrentWidth(x)
- x += o.buf.PromptLen()
- x = x % o.width
-
- if o.markStart > 0 {
- o.buf.SetStyle(o.markStart, o.markEnd, "4")
- }
-
- lineCnt := o.buf.CursorLineCount()
- buf := bytes.NewBuffer(nil)
- buf.Write(bytes.Repeat([]byte("\n"), lineCnt))
- buf.WriteString("\033[J")
- if o.state == S_STATE_FAILING {
- buf.WriteString("failing ")
- }
- if o.dir == S_DIR_BCK {
- buf.WriteString("bck")
- } else if o.dir == S_DIR_FWD {
- buf.WriteString("fwd")
- }
- buf.WriteString("-i-search: ")
- buf.WriteString(string(o.data)) // keyword
- buf.WriteString("\033[4m \033[0m") // _
- fmt.Fprintf(buf, "\r\033[%dA", lineCnt) // move prev
- if x > 0 {
- fmt.Fprintf(buf, "\033[%dC", x) // move forward
- }
- o.w.Write(buf.Bytes())
-}
diff --git a/vendor/github.com/rhtyd/readline/std.go b/vendor/github.com/rhtyd/readline/std.go
deleted file mode 100644
index 61d44b7..0000000
--- a/vendor/github.com/rhtyd/readline/std.go
+++ /dev/null
@@ -1,197 +0,0 @@
-package readline
-
-import (
- "io"
- "os"
- "sync"
- "sync/atomic"
-)
-
-var (
- Stdin io.ReadCloser = os.Stdin
- Stdout io.WriteCloser = os.Stdout
- Stderr io.WriteCloser = os.Stderr
-)
-
-var (
- std *Instance
- stdOnce sync.Once
-)
-
-// global instance will not submit history automatic
-func getInstance() *Instance {
- stdOnce.Do(func() {
- std, _ = NewEx(&Config{
- DisableAutoSaveHistory: true,
- })
- })
- return std
-}
-
-// let readline load history from filepath
-// and try to persist history into disk
-// set fp to "" to prevent readline persisting history to disk
-// so the `AddHistory` will return nil error forever.
-func SetHistoryPath(fp string) {
- ins := getInstance()
- cfg := ins.Config.Clone()
- cfg.HistoryFile = fp
- ins.SetConfig(cfg)
-}
-
-// set auto completer to global instance
-func SetAutoComplete(completer AutoCompleter) {
- ins := getInstance()
- cfg := ins.Config.Clone()
- cfg.AutoComplete = completer
- ins.SetConfig(cfg)
-}
-
-// add history to global instance manually
-// raise error only if `SetHistoryPath` is set with a non-empty path
-func AddHistory(content string) error {
- ins := getInstance()
- return ins.SaveHistory(content)
-}
-
-func Password(prompt string) ([]byte, error) {
- ins := getInstance()
- return ins.ReadPassword(prompt)
-}
-
-// readline with global configs
-func Line(prompt string) (string, error) {
- ins := getInstance()
- ins.SetPrompt(prompt)
- return ins.Readline()
-}
-
-type CancelableStdin struct {
- r io.Reader
- mutex sync.Mutex
- stop chan struct{}
- closed int32
- notify chan struct{}
- data []byte
- read int
- err error
-}
-
-func NewCancelableStdin(r io.Reader) *CancelableStdin {
- c := &CancelableStdin{
- r: r,
- notify: make(chan struct{}),
- stop: make(chan struct{}),
- }
- go c.ioloop()
- return c
-}
-
-func (c *CancelableStdin) ioloop() {
-loop:
- for {
- select {
- case <-c.notify:
- c.read, c.err = c.r.Read(c.data)
- select {
- case c.notify <- struct{}{}:
- case <-c.stop:
- break loop
- }
- case <-c.stop:
- break loop
- }
- }
-}
-
-func (c *CancelableStdin) Read(b []byte) (n int, err error) {
- c.mutex.Lock()
- defer c.mutex.Unlock()
- if atomic.LoadInt32(&c.closed) == 1 {
- return 0, io.EOF
- }
-
- c.data = b
- select {
- case c.notify <- struct{}{}:
- case <-c.stop:
- return 0, io.EOF
- }
- select {
- case <-c.notify:
- return c.read, c.err
- case <-c.stop:
- return 0, io.EOF
- }
-}
-
-func (c *CancelableStdin) Close() error {
- if atomic.CompareAndSwapInt32(&c.closed, 0, 1) {
- close(c.stop)
- }
- return nil
-}
-
-// FillableStdin is a stdin reader which can prepend some data before
-// reading into the real stdin
-type FillableStdin struct {
- sync.Mutex
- stdin io.Reader
- stdinBuffer io.ReadCloser
- buf []byte
- bufErr error
-}
-
-// NewFillableStdin gives you FillableStdin
-func NewFillableStdin(stdin io.Reader) (io.ReadCloser, io.Writer) {
- r, w := io.Pipe()
- s := &FillableStdin{
- stdinBuffer: r,
- stdin: stdin,
- }
- s.ioloop()
- return s, w
-}
-
-func (s *FillableStdin) ioloop() {
- go func() {
- for {
- bufR := make([]byte, 100)
- var n int
- n, s.bufErr = s.stdinBuffer.Read(bufR)
- if s.bufErr != nil {
- if s.bufErr == io.ErrClosedPipe {
- break
- }
- }
- s.Lock()
- s.buf = append(s.buf, bufR[:n]...)
- s.Unlock()
- }
- }()
-}
-
-// Read will read from the local buffer and if no data, read from stdin
-func (s *FillableStdin) Read(p []byte) (n int, err error) {
- s.Lock()
- i := len(s.buf)
- if len(p) < i {
- i = len(p)
- }
- if i > 0 {
- n := copy(p, s.buf)
- s.buf = s.buf[:0]
- cerr := s.bufErr
- s.bufErr = nil
- s.Unlock()
- return n, cerr
- }
- s.Unlock()
- n, err = s.stdin.Read(p)
- return n, err
-}
-
-func (s *FillableStdin) Close() error {
- s.stdinBuffer.Close()
- return nil
-}
diff --git a/vendor/github.com/rhtyd/readline/std_windows.go b/vendor/github.com/rhtyd/readline/std_windows.go
deleted file mode 100644
index b10f91b..0000000
--- a/vendor/github.com/rhtyd/readline/std_windows.go
+++ /dev/null
@@ -1,9 +0,0 @@
-// +build windows
-
-package readline
-
-func init() {
- Stdin = NewRawReader()
- Stdout = NewANSIWriter(Stdout)
- Stderr = NewANSIWriter(Stderr)
-}
diff --git a/vendor/github.com/rhtyd/readline/term.go b/vendor/github.com/rhtyd/readline/term.go
deleted file mode 100644
index 133993c..0000000
--- a/vendor/github.com/rhtyd/readline/term.go
+++ /dev/null
@@ -1,123 +0,0 @@
-// Copyright 2011 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build darwin dragonfly freebsd linux,!appengine netbsd openbsd solaris
-
-// Package terminal provides support functions for dealing with terminals, as
-// commonly found on UNIX systems.
-//
-// Putting a terminal into raw mode is the most common requirement:
-//
-// oldState, err := terminal.MakeRaw(0)
-// if err != nil {
-// panic(err)
-// }
-// defer terminal.Restore(0, oldState)
-package readline
-
-import (
- "io"
- "syscall"
-)
-
-// State contains the state of a terminal.
-type State struct {
- termios Termios
-}
-
-// IsTerminal returns true if the given file descriptor is a terminal.
-func IsTerminal(fd int) bool {
- _, err := getTermios(fd)
- return err == nil
-}
-
-// MakeRaw put the terminal connected to the given file descriptor into raw
-// mode and returns the previous state of the terminal so that it can be
-// restored.
-func MakeRaw(fd int) (*State, error) {
- var oldState State
-
- if termios, err := getTermios(fd); err != nil {
- return nil, err
- } else {
- oldState.termios = *termios
- }
-
- newState := oldState.termios
- // This attempts to replicate the behaviour documented for cfmakeraw in
- // the termios(3) manpage.
- newState.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK | syscall.ISTRIP | syscall.INLCR | syscall.IGNCR | syscall.ICRNL | syscall.IXON
- // newState.Oflag &^= syscall.OPOST
- newState.Lflag &^= syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG | syscall.IEXTEN
- newState.Cflag &^= syscall.CSIZE | syscall.PARENB
- newState.Cflag |= syscall.CS8
-
- newState.Cc[syscall.VMIN] = 1
- newState.Cc[syscall.VTIME] = 0
-
- return &oldState, setTermios(fd, &newState)
-}
-
-// GetState returns the current state of a terminal which may be useful to
-// restore the terminal after a signal.
-func GetState(fd int) (*State, error) {
- termios, err := getTermios(fd)
- if err != nil {
- return nil, err
- }
-
- return &State{termios: *termios}, nil
-}
-
-// Restore restores the terminal connected to the given file descriptor to a
-// previous state.
-func restoreTerm(fd int, state *State) error {
- return setTermios(fd, &state.termios)
-}
-
-// ReadPassword reads a line of input from a terminal without local echo. This
-// is commonly used for inputting passwords and other sensitive data. The slice
-// returned does not include the \n.
-func ReadPassword(fd int) ([]byte, error) {
- oldState, err := getTermios(fd)
- if err != nil {
- return nil, err
- }
-
- newState := oldState
- newState.Lflag &^= syscall.ECHO
- newState.Lflag |= syscall.ICANON | syscall.ISIG
- newState.Iflag |= syscall.ICRNL
- if err := setTermios(fd, newState); err != nil {
- return nil, err
- }
-
- defer func() {
- setTermios(fd, oldState)
- }()
-
- var buf [16]byte
- var ret []byte
- for {
- n, err := syscall.Read(fd, buf[:])
- if err != nil {
- return nil, err
- }
- if n == 0 {
- if len(ret) == 0 {
- return nil, io.EOF
- }
- break
- }
- if buf[n-1] == '\n' {
- n--
- }
- ret = append(ret, buf[:n]...)
- if n < len(buf) {
- break
- }
- }
-
- return ret, nil
-}
diff --git a/vendor/github.com/rhtyd/readline/term_bsd.go b/vendor/github.com/rhtyd/readline/term_bsd.go
deleted file mode 100644
index 68b56ea..0000000
--- a/vendor/github.com/rhtyd/readline/term_bsd.go
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2013 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build darwin dragonfly freebsd netbsd openbsd
-
-package readline
-
-import (
- "syscall"
- "unsafe"
-)
-
-func getTermios(fd int) (*Termios, error) {
- termios := new(Termios)
- _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), syscall.TIOCGETA, uintptr(unsafe.Pointer(termios)), 0, 0, 0)
- if err != 0 {
- return nil, err
- }
- return termios, nil
-}
-
-func setTermios(fd int, termios *Termios) error {
- _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), syscall.TIOCSETA, uintptr(unsafe.Pointer(termios)), 0, 0, 0)
- if err != 0 {
- return err
- }
- return nil
-}
diff --git a/vendor/github.com/rhtyd/readline/term_linux.go b/vendor/github.com/rhtyd/readline/term_linux.go
deleted file mode 100644
index e3392b4..0000000
--- a/vendor/github.com/rhtyd/readline/term_linux.go
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2013 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package readline
-
-import (
- "syscall"
- "unsafe"
-)
-
-// These constants are declared here, rather than importing
-// them from the syscall package as some syscall packages, even
-// on linux, for example gccgo, do not declare them.
-const ioctlReadTermios = 0x5401 // syscall.TCGETS
-const ioctlWriteTermios = 0x5402 // syscall.TCSETS
-
-func getTermios(fd int) (*Termios, error) {
- termios := new(Termios)
- _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(termios)), 0, 0, 0)
- if err != 0 {
- return nil, err
- }
- return termios, nil
-}
-
-func setTermios(fd int, termios *Termios) error {
- _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlWriteTermios, uintptr(unsafe.Pointer(termios)), 0, 0, 0)
- if err != 0 {
- return err
- }
- return nil
-}
diff --git a/vendor/github.com/rhtyd/readline/term_solaris.go b/vendor/github.com/rhtyd/readline/term_solaris.go
deleted file mode 100644
index 4c27273..0000000
--- a/vendor/github.com/rhtyd/readline/term_solaris.go
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright 2013 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build solaris
-
-package readline
-
-import "golang.org/x/sys/unix"
-
-// GetSize returns the dimensions of the given terminal.
-func GetSize(fd int) (int, int, error) {
- ws, err := unix.IoctlGetWinsize(fd, unix.TIOCGWINSZ)
- if err != nil {
- return 0, 0, err
- }
- return int(ws.Col), int(ws.Row), nil
-}
-
-type Termios unix.Termios
-
-func getTermios(fd int) (*Termios, error) {
- termios, err := unix.IoctlGetTermios(fd, unix.TCGETS)
- if err != nil {
- return nil, err
- }
- return (*Termios)(termios), nil
-}
-
-func setTermios(fd int, termios *Termios) error {
- return unix.IoctlSetTermios(fd, unix.TCSETSF, (*unix.Termios)(termios))
-}
diff --git a/vendor/github.com/rhtyd/readline/term_unix.go b/vendor/github.com/rhtyd/readline/term_unix.go
deleted file mode 100644
index d3ea242..0000000
--- a/vendor/github.com/rhtyd/readline/term_unix.go
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright 2011 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build darwin dragonfly freebsd linux,!appengine netbsd openbsd
-
-package readline
-
-import (
- "syscall"
- "unsafe"
-)
-
-type Termios syscall.Termios
-
-// GetSize returns the dimensions of the given terminal.
-func GetSize(fd int) (int, int, error) {
- var dimensions [4]uint16
- _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&dimensions)), 0, 0, 0)
- if err != 0 {
- return 0, 0, err
- }
- return int(dimensions[1]), int(dimensions[0]), nil
-}
diff --git a/vendor/github.com/rhtyd/readline/term_windows.go b/vendor/github.com/rhtyd/readline/term_windows.go
deleted file mode 100644
index 1290e00..0000000
--- a/vendor/github.com/rhtyd/readline/term_windows.go
+++ /dev/null
@@ -1,171 +0,0 @@
-// Copyright 2011 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build windows
-
-// Package terminal provides support functions for dealing with terminals, as
-// commonly found on UNIX systems.
-//
-// Putting a terminal into raw mode is the most common requirement:
-//
-// oldState, err := terminal.MakeRaw(0)
-// if err != nil {
-// panic(err)
-// }
-// defer terminal.Restore(0, oldState)
-package readline
-
-import (
- "io"
- "syscall"
- "unsafe"
-)
-
-const (
- enableLineInput = 2
- enableEchoInput = 4
- enableProcessedInput = 1
- enableWindowInput = 8
- enableMouseInput = 16
- enableInsertMode = 32
- enableQuickEditMode = 64
- enableExtendedFlags = 128
- enableAutoPosition = 256
- enableProcessedOutput = 1
- enableWrapAtEolOutput = 2
-)
-
-var kernel32 = syscall.NewLazyDLL("kernel32.dll")
-
-var (
- procGetConsoleMode = kernel32.NewProc("GetConsoleMode")
- procSetConsoleMode = kernel32.NewProc("SetConsoleMode")
- procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo")
-)
-
-type (
- coord struct {
- x short
- y short
- }
- smallRect struct {
- left short
- top short
- right short
- bottom short
- }
- consoleScreenBufferInfo struct {
- size coord
- cursorPosition coord
- attributes word
- window smallRect
- maximumWindowSize coord
- }
-)
-
-type State struct {
- mode uint32
-}
-
-// IsTerminal returns true if the given file descriptor is a terminal.
-func IsTerminal(fd int) bool {
- var st uint32
- r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0)
- return r != 0 && e == 0
-}
-
-// MakeRaw put the terminal connected to the given file descriptor into raw
-// mode and returns the previous state of the terminal so that it can be
-// restored.
-func MakeRaw(fd int) (*State, error) {
- var st uint32
- _, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0)
- if e != 0 {
- return nil, error(e)
- }
- raw := st &^ (enableEchoInput | enableProcessedInput | enableLineInput | enableProcessedOutput)
- _, _, e = syscall.Syscall(procSetConsoleMode.Addr(), 2, uintptr(fd), uintptr(raw), 0)
- if e != 0 {
- return nil, error(e)
- }
- return &State{st}, nil
-}
-
-// GetState returns the current state of a terminal which may be useful to
-// restore the terminal after a signal.
-func GetState(fd int) (*State, error) {
- var st uint32
- _, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0)
- if e != 0 {
- return nil, error(e)
- }
- return &State{st}, nil
-}
-
-// Restore restores the terminal connected to the given file descriptor to a
-// previous state.
-func restoreTerm(fd int, state *State) error {
- _, _, err := syscall.Syscall(procSetConsoleMode.Addr(), 2, uintptr(fd), uintptr(state.mode), 0)
- return err
-}
-
-// GetSize returns the dimensions of the given terminal.
-func GetSize(fd int) (width, height int, err error) {
- var info consoleScreenBufferInfo
- _, _, e := syscall.Syscall(procGetConsoleScreenBufferInfo.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&info)), 0)
- if e != 0 {
- return 0, 0, error(e)
- }
- return int(info.size.x), int(info.size.y), nil
-}
-
-// ReadPassword reads a line of input from a terminal without local echo. This
-// is commonly used for inputting passwords and other sensitive data. The slice
-// returned does not include the \n.
-func ReadPassword(fd int) ([]byte, error) {
- var st uint32
- _, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0)
- if e != 0 {
- return nil, error(e)
- }
- old := st
-
- st &^= (enableEchoInput)
- st |= (enableProcessedInput | enableLineInput | enableProcessedOutput)
- _, _, e = syscall.Syscall(procSetConsoleMode.Addr(), 2, uintptr(fd), uintptr(st), 0)
- if e != 0 {
- return nil, error(e)
- }
-
- defer func() {
- syscall.Syscall(procSetConsoleMode.Addr(), 2, uintptr(fd), uintptr(old), 0)
- }()
-
- var buf [16]byte
- var ret []byte
- for {
- n, err := syscall.Read(syscall.Handle(fd), buf[:])
- if err != nil {
- return nil, err
- }
- if n == 0 {
- if len(ret) == 0 {
- return nil, io.EOF
- }
- break
- }
- if buf[n-1] == '\n' {
- n--
- }
- if n > 0 && buf[n-1] == '\r' {
- n--
- }
- ret = append(ret, buf[:n]...)
- if n < len(buf) {
- break
- }
- }
-
- return ret, nil
-}
diff --git a/vendor/github.com/rhtyd/readline/terminal.go b/vendor/github.com/rhtyd/readline/terminal.go
deleted file mode 100644
index 1078631..0000000
--- a/vendor/github.com/rhtyd/readline/terminal.go
+++ /dev/null
@@ -1,238 +0,0 @@
-package readline
-
-import (
- "bufio"
- "fmt"
- "io"
- "strings"
- "sync"
- "sync/atomic"
-)
-
-type Terminal struct {
- m sync.Mutex
- cfg *Config
- outchan chan rune
- closed int32
- stopChan chan struct{}
- kickChan chan struct{}
- wg sync.WaitGroup
- isReading int32
- sleeping int32
-
- sizeChan chan string
-}
-
-func NewTerminal(cfg *Config) (*Terminal, error) {
- if err := cfg.Init(); err != nil {
- return nil, err
- }
- t := &Terminal{
- cfg: cfg,
- kickChan: make(chan struct{}, 1),
- outchan: make(chan rune),
- stopChan: make(chan struct{}, 1),
- sizeChan: make(chan string, 1),
- }
-
- go t.ioloop()
- return t, nil
-}
-
-// SleepToResume will sleep myself, and return only if I'm resumed.
-func (t *Terminal) SleepToResume() {
- if !atomic.CompareAndSwapInt32(&t.sleeping, 0, 1) {
- return
- }
- defer atomic.StoreInt32(&t.sleeping, 0)
-
- t.ExitRawMode()
- ch := WaitForResume()
- SuspendMe()
- <-ch
- t.EnterRawMode()
-}
-
-func (t *Terminal) EnterRawMode() (err error) {
- return t.cfg.FuncMakeRaw()
-}
-
-func (t *Terminal) ExitRawMode() (err error) {
- return t.cfg.FuncExitRaw()
-}
-
-func (t *Terminal) Write(b []byte) (int, error) {
- return t.cfg.Stdout.Write(b)
-}
-
-// WriteStdin prefill the next Stdin fetch
-// Next time you call ReadLine() this value will be writen before the user input
-func (t *Terminal) WriteStdin(b []byte) (int, error) {
- return t.cfg.StdinWriter.Write(b)
-}
-
-type termSize struct {
- left int
- top int
-}
-
-func (t *Terminal) GetOffset(f func(offset string)) {
- go func() {
- f(<-t.sizeChan)
- }()
- t.Write([]byte("\033[6n"))
-}
-
-func (t *Terminal) Print(s string) {
- fmt.Fprintf(t.cfg.Stdout, "%s", s)
-}
-
-func (t *Terminal) PrintRune(r rune) {
- fmt.Fprintf(t.cfg.Stdout, "%c", r)
-}
-
-func (t *Terminal) Readline() *Operation {
- return NewOperation(t, t.cfg)
-}
-
-// return rune(0) if meet EOF
-func (t *Terminal) ReadRune() rune {
- ch, ok := <-t.outchan
- if !ok {
- return rune(0)
- }
- return ch
-}
-
-func (t *Terminal) IsReading() bool {
- return atomic.LoadInt32(&t.isReading) == 1
-}
-
-func (t *Terminal) KickRead() {
- select {
- case t.kickChan <- struct{}{}:
- default:
- }
-}
-
-func (t *Terminal) ioloop() {
- t.wg.Add(1)
- defer func() {
- t.wg.Done()
- close(t.outchan)
- }()
-
- var (
- isEscape bool
- isEscapeEx bool
- expectNextChar bool
- )
-
- buf := bufio.NewReader(t.getStdin())
- for {
- if !expectNextChar {
- atomic.StoreInt32(&t.isReading, 0)
- select {
- case <-t.kickChan:
- atomic.StoreInt32(&t.isReading, 1)
- case <-t.stopChan:
- return
- }
- }
- expectNextChar = false
- r, _, err := buf.ReadRune()
- if err != nil {
- if strings.Contains(err.Error(), "interrupted system call") {
- expectNextChar = true
- continue
- }
- break
- }
-
- if isEscape {
- isEscape = false
- if r == CharEscapeEx {
- expectNextChar = true
- isEscapeEx = true
- continue
- }
- r = escapeKey(r, buf)
- } else if isEscapeEx {
- isEscapeEx = false
- if key := readEscKey(r, buf); key != nil {
- r = escapeExKey(key)
- // offset
- if key.typ == 'R' {
- if _, _, ok := key.Get2(); ok {
- select {
- case t.sizeChan <- key.attr:
- default:
- }
- }
- expectNextChar = true
- continue
- }
- }
- if r == 0 {
- expectNextChar = true
- continue
- }
- }
-
- expectNextChar = true
- switch r {
- case CharEsc:
- if t.cfg.VimMode {
- t.outchan <- r
- break
- }
- isEscape = true
- case CharInterrupt, CharEnter, CharCtrlJ, CharDelete:
- expectNextChar = false
- fallthrough
- default:
- t.outchan <- r
- }
- }
-
-}
-
-func (t *Terminal) Bell() {
- fmt.Fprintf(t, "%c", CharBell)
-}
-
-func (t *Terminal) Close() error {
- if atomic.SwapInt32(&t.closed, 1) != 0 {
- return nil
- }
- if closer, ok := t.cfg.Stdin.(io.Closer); ok {
- closer.Close()
- }
- close(t.stopChan)
- t.wg.Wait()
- return t.ExitRawMode()
-}
-
-func (t *Terminal) GetConfig() *Config {
- t.m.Lock()
- cfg := *t.cfg
- t.m.Unlock()
- return &cfg
-}
-
-func (t *Terminal) getStdin() io.Reader {
- t.m.Lock()
- r := t.cfg.Stdin
- t.m.Unlock()
- return r
-}
-
-func (t *Terminal) SetConfig(c *Config) error {
- if err := c.Init(); err != nil {
- return err
- }
- t.m.Lock()
- t.cfg = c
- t.m.Unlock()
- return nil
-}
diff --git a/vendor/github.com/rhtyd/readline/utils.go b/vendor/github.com/rhtyd/readline/utils.go
deleted file mode 100644
index af4e005..0000000
--- a/vendor/github.com/rhtyd/readline/utils.go
+++ /dev/null
@@ -1,277 +0,0 @@
-package readline
-
-import (
- "bufio"
- "bytes"
- "container/list"
- "fmt"
- "os"
- "strconv"
- "strings"
- "sync"
- "time"
- "unicode"
-)
-
-var (
- isWindows = false
-)
-
-const (
- CharLineStart = 1
- CharBackward = 2
- CharInterrupt = 3
- CharDelete = 4
- CharLineEnd = 5
- CharForward = 6
- CharBell = 7
- CharCtrlH = 8
- CharTab = 9
- CharCtrlJ = 10
- CharKill = 11
- CharCtrlL = 12
- CharEnter = 13
- CharNext = 14
- CharPrev = 16
- CharBckSearch = 18
- CharFwdSearch = 19
- CharTranspose = 20
- CharCtrlU = 21
- CharCtrlW = 23
- CharCtrlY = 25
- CharCtrlZ = 26
- CharEsc = 27
- CharEscapeEx = 91
- CharBackspace = 127
-)
-
-const (
- MetaBackward rune = -iota - 1
- MetaForward
- MetaDelete
- MetaBackspace
- MetaTranspose
-)
-
-// WaitForResume need to call before current process got suspend.
-// It will run a ticker until a long duration is occurs,
-// which means this process is resumed.
-func WaitForResume() chan struct{} {
- ch := make(chan struct{})
- var wg sync.WaitGroup
- wg.Add(1)
- go func() {
- ticker := time.NewTicker(10 * time.Millisecond)
- t := time.Now()
- wg.Done()
- for {
- now := <-ticker.C
- if now.Sub(t) > 100*time.Millisecond {
- break
- }
- t = now
- }
- ticker.Stop()
- ch <- struct{}{}
- }()
- wg.Wait()
- return ch
-}
-
-func Restore(fd int, state *State) error {
- err := restoreTerm(fd, state)
- if err != nil {
- // errno 0 means everything is ok :)
- if err.Error() == "errno 0" {
- return nil
- } else {
- return err
- }
- }
- return nil
-}
-
-func IsPrintable(key rune) bool {
- isInSurrogateArea := key >= 0xd800 && key <= 0xdbff
- return key >= 32 && !isInSurrogateArea
-}
-
-// translate Esc[X
-func escapeExKey(key *escapeKeyPair) rune {
- var r rune
- switch key.typ {
- case 'D':
- r = CharBackward
- case 'C':
- r = CharForward
- case 'A':
- r = CharPrev
- case 'B':
- r = CharNext
- case 'H':
- r = CharLineStart
- case 'F':
- r = CharLineEnd
- case '~':
- if key.attr == "3" {
- r = CharDelete
- }
- default:
- }
- return r
-}
-
-type escapeKeyPair struct {
- attr string
- typ rune
-}
-
-func (e *escapeKeyPair) Get2() (int, int, bool) {
- sp := strings.Split(e.attr, ";")
- if len(sp) < 2 {
- return -1, -1, false
- }
- s1, err := strconv.Atoi(sp[0])
- if err != nil {
- return -1, -1, false
- }
- s2, err := strconv.Atoi(sp[1])
- if err != nil {
- return -1, -1, false
- }
- return s1, s2, true
-}
-
-func readEscKey(r rune, reader *bufio.Reader) *escapeKeyPair {
- p := escapeKeyPair{}
- buf := bytes.NewBuffer(nil)
- for {
- if r == ';' {
- } else if unicode.IsNumber(r) {
- } else {
- p.typ = r
- break
- }
- buf.WriteRune(r)
- r, _, _ = reader.ReadRune()
- }
- p.attr = buf.String()
- return &p
-}
-
-// translate EscX to Meta+X
-func escapeKey(r rune, reader *bufio.Reader) rune {
- switch r {
- case 'b':
- r = MetaBackward
- case 'f':
- r = MetaForward
- case 'd':
- r = MetaDelete
- case CharTranspose:
- r = MetaTranspose
- case CharBackspace:
- r = MetaBackspace
- case 'O':
- d, _, _ := reader.ReadRune()
- switch d {
- case 'H':
- r = CharLineStart
- case 'F':
- r = CharLineEnd
- default:
- reader.UnreadRune()
- }
- case CharEsc:
-
- }
- return r
-}
-
-func SplitByLine(start, screenWidth int, rs []rune) []string {
- var ret []string
- buf := bytes.NewBuffer(nil)
- currentWidth := start
- for _, r := range rs {
- w := runes.Width(r)
- currentWidth += w
- buf.WriteRune(r)
- if currentWidth >= screenWidth {
- ret = append(ret, buf.String())
- buf.Reset()
- currentWidth = 0
- }
- }
- ret = append(ret, buf.String())
- return ret
-}
-
-// calculate how many lines for N character
-func LineCount(screenWidth, w int) int {
- r := w / screenWidth
- if w%screenWidth != 0 {
- r++
- }
- return r
-}
-
-func IsWordBreak(i rune) bool {
- switch {
- case i >= 'a' && i <= 'z':
- case i >= 'A' && i <= 'Z':
- case i >= '0' && i <= '9':
- default:
- return true
- }
- return false
-}
-
-func GetInt(s []string, def int) int {
- if len(s) == 0 {
- return def
- }
- c, err := strconv.Atoi(s[0])
- if err != nil {
- return def
- }
- return c
-}
-
-type RawMode struct {
- state *State
-}
-
-func (r *RawMode) Enter() (err error) {
- r.state, err = MakeRaw(GetStdin())
- return err
-}
-
-func (r *RawMode) Exit() error {
- if r.state == nil {
- return nil
- }
- return Restore(GetStdin(), r.state)
-}
-
-// -----------------------------------------------------------------------------
-
-func sleep(n int) {
- Debug(n)
- time.Sleep(2000 * time.Millisecond)
-}
-
-// print a linked list to Debug()
-func debugList(l *list.List) {
- idx := 0
- for e := l.Front(); e != nil; e = e.Next() {
- Debug(idx, fmt.Sprintf("%+v", e.Value))
- idx++
- }
-}
-
-// append log info to another file
-func Debug(o ...interface{}) {
- f, _ := os.OpenFile("debug.tmp", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
- fmt.Fprintln(f, o...)
- f.Close()
-}
diff --git a/vendor/github.com/rhtyd/readline/utils_unix.go b/vendor/github.com/rhtyd/readline/utils_unix.go
deleted file mode 100644
index f88dac9..0000000
--- a/vendor/github.com/rhtyd/readline/utils_unix.go
+++ /dev/null
@@ -1,83 +0,0 @@
-// +build darwin dragonfly freebsd linux,!appengine netbsd openbsd solaris
-
-package readline
-
-import (
- "io"
- "os"
- "os/signal"
- "sync"
- "syscall"
-)
-
-type winsize struct {
- Row uint16
- Col uint16
- Xpixel uint16
- Ypixel uint16
-}
-
-// SuspendMe use to send suspend signal to myself, when we in the raw mode.
-// For OSX it need to send to parent's pid
-// For Linux it need to send to myself
-func SuspendMe() {
- p, _ := os.FindProcess(os.Getppid())
- p.Signal(syscall.SIGTSTP)
- p, _ = os.FindProcess(os.Getpid())
- p.Signal(syscall.SIGTSTP)
-}
-
-// get width of the terminal
-func getWidth(stdoutFd int) int {
- cols, _, err := GetSize(stdoutFd)
- if err != nil {
- return -1
- }
- return cols
-}
-
-func GetScreenWidth() int {
- w := getWidth(syscall.Stdout)
- if w < 0 {
- w = getWidth(syscall.Stderr)
- }
- return w
-}
-
-// ClearScreen clears the console screen
-func ClearScreen(w io.Writer) (int, error) {
- return w.Write([]byte("\033[H"))
-}
-
-func DefaultIsTerminal() bool {
- return IsTerminal(syscall.Stdin) && (IsTerminal(syscall.Stdout) || IsTerminal(syscall.Stderr))
-}
-
-func GetStdin() int {
- return syscall.Stdin
-}
-
-// -----------------------------------------------------------------------------
-
-var (
- widthChange sync.Once
- widthChangeCallback func()
-)
-
-func DefaultOnWidthChanged(f func()) {
- widthChangeCallback = f
- widthChange.Do(func() {
- ch := make(chan os.Signal, 1)
- signal.Notify(ch, syscall.SIGWINCH)
-
- go func() {
- for {
- _, ok := <-ch
- if !ok {
- break
- }
- widthChangeCallback()
- }
- }()
- })
-}
diff --git a/vendor/github.com/rhtyd/readline/utils_windows.go b/vendor/github.com/rhtyd/readline/utils_windows.go
deleted file mode 100644
index 5bfa55d..0000000
--- a/vendor/github.com/rhtyd/readline/utils_windows.go
+++ /dev/null
@@ -1,41 +0,0 @@
-// +build windows
-
-package readline
-
-import (
- "io"
- "syscall"
-)
-
-func SuspendMe() {
-}
-
-func GetStdin() int {
- return int(syscall.Stdin)
-}
-
-func init() {
- isWindows = true
-}
-
-// get width of the terminal
-func GetScreenWidth() int {
- info, _ := GetConsoleScreenBufferInfo()
- if info == nil {
- return -1
- }
- return int(info.dwSize.x)
-}
-
-// ClearScreen clears the console screen
-func ClearScreen(_ io.Writer) error {
- return SetConsoleCursorPosition(&_COORD{0, 0})
-}
-
-func DefaultIsTerminal() bool {
- return true
-}
-
-func DefaultOnWidthChanged(func()) {
-
-}
diff --git a/vendor/github.com/rhtyd/readline/vim.go b/vendor/github.com/rhtyd/readline/vim.go
deleted file mode 100644
index bedf2c1..0000000
--- a/vendor/github.com/rhtyd/readline/vim.go
+++ /dev/null
@@ -1,176 +0,0 @@
-package readline
-
-const (
- VIM_NORMAL = iota
- VIM_INSERT
- VIM_VISUAL
-)
-
-type opVim struct {
- cfg *Config
- op *Operation
- vimMode int
-}
-
-func newVimMode(op *Operation) *opVim {
- ov := &opVim{
- cfg: op.cfg,
- op: op,
- }
- ov.SetVimMode(ov.cfg.VimMode)
- return ov
-}
-
-func (o *opVim) SetVimMode(on bool) {
- if o.cfg.VimMode && !on { // turn off
- o.ExitVimMode()
- }
- o.cfg.VimMode = on
- o.vimMode = VIM_INSERT
-}
-
-func (o *opVim) ExitVimMode() {
- o.vimMode = VIM_INSERT
-}
-
-func (o *opVim) IsEnableVimMode() bool {
- return o.cfg.VimMode
-}
-
-func (o *opVim) handleVimNormalMovement(r rune, readNext func() rune) (t rune, handled bool) {
- rb := o.op.buf
- handled = true
- switch r {
- case 'h':
- t = CharBackward
- case 'j':
- t = CharNext
- case 'k':
- t = CharPrev
- case 'l':
- t = CharForward
- case '0', '^':
- rb.MoveToLineStart()
- case '$':
- rb.MoveToLineEnd()
- case 'x':
- rb.Delete()
- if rb.IsCursorInEnd() {
- rb.MoveBackward()
- }
- case 'r':
- rb.Replace(readNext())
- case 'd':
- next := readNext()
- switch next {
- case 'd':
- rb.Erase()
- case 'w':
- rb.DeleteWord()
- case 'h':
- rb.Backspace()
- case 'l':
- rb.Delete()
- }
- case 'p':
- rb.Yank()
- case 'b', 'B':
- rb.MoveToPrevWord()
- case 'w', 'W':
- rb.MoveToNextWord()
- case 'e', 'E':
- rb.MoveToEndWord()
- case 'f', 'F', 't', 'T':
- next := readNext()
- prevChar := r == 't' || r == 'T'
- reverse := r == 'F' || r == 'T'
- switch next {
- case CharEsc:
- default:
- rb.MoveTo(next, prevChar, reverse)
- }
- default:
- return r, false
- }
- return t, true
-}
-
-func (o *opVim) handleVimNormalEnterInsert(r rune, readNext func() rune) (t rune, handled bool) {
- rb := o.op.buf
- handled = true
- switch r {
- case 'i':
- case 'I':
- rb.MoveToLineStart()
- case 'a':
- rb.MoveForward()
- case 'A':
- rb.MoveToLineEnd()
- case 's':
- rb.Delete()
- case 'S':
- rb.Erase()
- case 'c':
- next := readNext()
- switch next {
- case 'c':
- rb.Erase()
- case 'w':
- rb.DeleteWord()
- case 'h':
- rb.Backspace()
- case 'l':
- rb.Delete()
- }
- default:
- return r, false
- }
-
- o.EnterVimInsertMode()
- return
-}
-
-func (o *opVim) HandleVimNormal(r rune, readNext func() rune) (t rune) {
- switch r {
- case CharEnter, CharInterrupt:
- o.ExitVimMode()
- return r
- }
-
- if r, handled := o.handleVimNormalMovement(r, readNext); handled {
- return r
- }
-
- if r, handled := o.handleVimNormalEnterInsert(r, readNext); handled {
- return r
- }
-
- // invalid operation
- o.op.t.Bell()
- return 0
-}
-
-func (o *opVim) EnterVimInsertMode() {
- o.vimMode = VIM_INSERT
-}
-
-func (o *opVim) ExitVimInsertMode() {
- o.vimMode = VIM_NORMAL
-}
-
-func (o *opVim) HandleVim(r rune, readNext func() rune) rune {
- if o.vimMode == VIM_NORMAL {
- return o.HandleVimNormal(r, readNext)
- }
- if r == CharEsc {
- o.ExitVimInsertMode()
- return 0
- }
-
- switch o.vimMode {
- case VIM_INSERT:
- return r
- case VIM_VISUAL:
- }
- return r
-}
diff --git a/vendor/github.com/rhtyd/readline/windows_api.go b/vendor/github.com/rhtyd/readline/windows_api.go
deleted file mode 100644
index 63f4f7b..0000000
--- a/vendor/github.com/rhtyd/readline/windows_api.go
+++ /dev/null
@@ -1,152 +0,0 @@
-// +build windows
-
-package readline
-
-import (
- "reflect"
- "syscall"
- "unsafe"
-)
-
-var (
- kernel = NewKernel()
- stdout = uintptr(syscall.Stdout)
- stdin = uintptr(syscall.Stdin)
-)
-
-type Kernel struct {
- SetConsoleCursorPosition,
- SetConsoleTextAttribute,
- FillConsoleOutputCharacterW,
- FillConsoleOutputAttribute,
- ReadConsoleInputW,
- GetConsoleScreenBufferInfo,
- GetConsoleCursorInfo,
- GetStdHandle CallFunc
-}
-
-type short int16
-type word uint16
-type dword uint32
-type wchar uint16
-
-type _COORD struct {
- x short
- y short
-}
-
-func (c *_COORD) ptr() uintptr {
- return uintptr(*(*int32)(unsafe.Pointer(c)))
-}
-
-const (
- EVENT_KEY = 0x0001
- EVENT_MOUSE = 0x0002
- EVENT_WINDOW_BUFFER_SIZE = 0x0004
- EVENT_MENU = 0x0008
- EVENT_FOCUS = 0x0010
-)
-
-type _KEY_EVENT_RECORD struct {
- bKeyDown int32
- wRepeatCount word
- wVirtualKeyCode word
- wVirtualScanCode word
- unicodeChar wchar
- dwControlKeyState dword
-}
-
-// KEY_EVENT_RECORD KeyEvent;
-// MOUSE_EVENT_RECORD MouseEvent;
-// WINDOW_BUFFER_SIZE_RECORD WindowBufferSizeEvent;
-// MENU_EVENT_RECORD MenuEvent;
-// FOCUS_EVENT_RECORD FocusEvent;
-type _INPUT_RECORD struct {
- EventType word
- Padding uint16
- Event [16]byte
-}
-
-type _CONSOLE_SCREEN_BUFFER_INFO struct {
- dwSize _COORD
- dwCursorPosition _COORD
- wAttributes word
- srWindow _SMALL_RECT
- dwMaximumWindowSize _COORD
-}
-
-type _SMALL_RECT struct {
- left short
- top short
- right short
- bottom short
-}
-
-type _CONSOLE_CURSOR_INFO struct {
- dwSize dword
- bVisible bool
-}
-
-type CallFunc func(u ...uintptr) error
-
-func NewKernel() *Kernel {
- k := &Kernel{}
- kernel32 := syscall.NewLazyDLL("kernel32.dll")
- v := reflect.ValueOf(k).Elem()
- t := v.Type()
- for i := 0; i < t.NumField(); i++ {
- name := t.Field(i).Name
- f := kernel32.NewProc(name)
- v.Field(i).Set(reflect.ValueOf(k.Wrap(f)))
- }
- return k
-}
-
-func (k *Kernel) Wrap(p *syscall.LazyProc) CallFunc {
- return func(args ...uintptr) error {
- var r0 uintptr
- var e1 syscall.Errno
- size := uintptr(len(args))
- if len(args) <= 3 {
- buf := make([]uintptr, 3)
- copy(buf, args)
- r0, _, e1 = syscall.Syscall(p.Addr(), size,
- buf[0], buf[1], buf[2])
- } else {
- buf := make([]uintptr, 6)
- copy(buf, args)
- r0, _, e1 = syscall.Syscall6(p.Addr(), size,
- buf[0], buf[1], buf[2], buf[3], buf[4], buf[5],
- )
- }
-
- if int(r0) == 0 {
- if e1 != 0 {
- return error(e1)
- } else {
- return syscall.EINVAL
- }
- }
- return nil
- }
-
-}
-
-func GetConsoleScreenBufferInfo() (*_CONSOLE_SCREEN_BUFFER_INFO, error) {
- t := new(_CONSOLE_SCREEN_BUFFER_INFO)
- err := kernel.GetConsoleScreenBufferInfo(
- stdout,
- uintptr(unsafe.Pointer(t)),
- )
- return t, err
-}
-
-func GetConsoleCursorInfo() (*_CONSOLE_CURSOR_INFO, error) {
- t := new(_CONSOLE_CURSOR_INFO)
- err := kernel.GetConsoleCursorInfo(stdout, uintptr(unsafe.Pointer(t)))
- return t, err
-}
-
-func SetConsoleCursorPosition(c *_COORD) error {
- return kernel.SetConsoleCursorPosition(stdout, c.ptr())
-}
diff --git a/vendor/gopkg.in/ini.v1/error.go b/vendor/gopkg.in/ini.v1/error.go
new file mode 100644
index 0000000..80afe74
--- /dev/null
+++ b/vendor/gopkg.in/ini.v1/error.go
@@ -0,0 +1,32 @@
+// Copyright 2016 Unknwon
+//
+// Licensed under the Apache License, Version 2.0 (the "License"): you may
+// not use this file except in compliance with the License. You may obtain
+// a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+
+package ini
+
+import (
+ "fmt"
+)
+
+type ErrDelimiterNotFound struct {
+ Line string
+}
+
+func IsErrDelimiterNotFound(err error) bool {
+ _, ok := err.(ErrDelimiterNotFound)
+ return ok
+}
+
+func (err ErrDelimiterNotFound) Error() string {
+ return fmt.Sprintf("key-value delimiter not found: %s", err.Line)
+}
diff --git a/vendor/gopkg.in/ini.v1/file.go b/vendor/gopkg.in/ini.v1/file.go
new file mode 100644
index 0000000..d7982c3
--- /dev/null
+++ b/vendor/gopkg.in/ini.v1/file.go
@@ -0,0 +1,407 @@
+// Copyright 2017 Unknwon
+//
+// Licensed under the Apache License, Version 2.0 (the "License"): you may
+// not use this file except in compliance with the License. You may obtain
+// a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+
+package ini
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "strings"
+ "sync"
+)
+
+// File represents a combination of a or more INI file(s) in memory.
+type File struct {
+ options LoadOptions
+ dataSources []dataSource
+
+ // Should make things safe, but sometimes doesn't matter.
+ BlockMode bool
+ lock sync.RWMutex
+
+ // To keep data in order.
+ sectionList []string
+ // Actual data is stored here.
+ sections map[string]*Section
+
+ NameMapper
+ ValueMapper
+}
+
+// newFile initializes File object with given data sources.
+func newFile(dataSources []dataSource, opts LoadOptions) *File {
+ return &File{
+ BlockMode: true,
+ dataSources: dataSources,
+ sections: make(map[string]*Section),
+ sectionList: make([]string, 0, 10),
+ options: opts,
+ }
+}
+
+// Empty returns an empty file object.
+func Empty() *File {
+ // Ignore error here, we sure our data is good.
+ f, _ := Load([]byte(""))
+ return f
+}
+
+// NewSection creates a new section.
+func (f *File) NewSection(name string) (*Section, error) {
+ if len(name) == 0 {
+ return nil, errors.New("error creating new section: empty section name")
+ } else if f.options.Insensitive && name != DEFAULT_SECTION {
+ name = strings.ToLower(name)
+ }
+
+ if f.BlockMode {
+ f.lock.Lock()
+ defer f.lock.Unlock()
+ }
+
+ if inSlice(name, f.sectionList) {
+ return f.sections[name], nil
+ }
+
+ f.sectionList = append(f.sectionList, name)
+ f.sections[name] = newSection(f, name)
+ return f.sections[name], nil
+}
+
+// NewRawSection creates a new section with an unparseable body.
+func (f *File) NewRawSection(name, body string) (*Section, error) {
+ section, err := f.NewSection(name)
+ if err != nil {
+ return nil, err
+ }
+
+ section.isRawSection = true
+ section.rawBody = body
+ return section, nil
+}
+
+// NewSections creates a list of sections.
+func (f *File) NewSections(names ...string) (err error) {
+ for _, name := range names {
+ if _, err = f.NewSection(name); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// GetSection returns section by given name.
+func (f *File) GetSection(name string) (*Section, error) {
+ if len(name) == 0 {
+ name = DEFAULT_SECTION
+ }
+ if f.options.Insensitive {
+ name = strings.ToLower(name)
+ }
+
+ if f.BlockMode {
+ f.lock.RLock()
+ defer f.lock.RUnlock()
+ }
+
+ sec := f.sections[name]
+ if sec == nil {
+ return nil, fmt.Errorf("section '%s' does not exist", name)
+ }
+ return sec, nil
+}
+
+// Section assumes named section exists and returns a zero-value when not.
+func (f *File) Section(name string) *Section {
+ sec, err := f.GetSection(name)
+ if err != nil {
+ // Note: It's OK here because the only possible error is empty section name,
+ // but if it's empty, this piece of code won't be executed.
+ sec, _ = f.NewSection(name)
+ return sec
+ }
+ return sec
+}
+
+// Section returns list of Section.
+func (f *File) Sections() []*Section {
+ if f.BlockMode {
+ f.lock.RLock()
+ defer f.lock.RUnlock()
+ }
+
+ sections := make([]*Section, len(f.sectionList))
+ for i, name := range f.sectionList {
+ sections[i] = f.sections[name]
+ }
+ return sections
+}
+
+// ChildSections returns a list of child sections of given section name.
+func (f *File) ChildSections(name string) []*Section {
+ return f.Section(name).ChildSections()
+}
+
+// SectionStrings returns list of section names.
+func (f *File) SectionStrings() []string {
+ list := make([]string, len(f.sectionList))
+ copy(list, f.sectionList)
+ return list
+}
+
+// DeleteSection deletes a section.
+func (f *File) DeleteSection(name string) {
+ if f.BlockMode {
+ f.lock.Lock()
+ defer f.lock.Unlock()
+ }
+
+ if len(name) == 0 {
+ name = DEFAULT_SECTION
+ }
+
+ for i, s := range f.sectionList {
+ if s == name {
+ f.sectionList = append(f.sectionList[:i], f.sectionList[i+1:]...)
+ delete(f.sections, name)
+ return
+ }
+ }
+}
+
+func (f *File) reload(s dataSource) error {
+ r, err := s.ReadCloser()
+ if err != nil {
+ return err
+ }
+ defer r.Close()
+
+ return f.parse(r)
+}
+
+// Reload reloads and parses all data sources.
+func (f *File) Reload() (err error) {
+ for _, s := range f.dataSources {
+ if err = f.reload(s); err != nil {
+ // In loose mode, we create an empty default section for nonexistent files.
+ if os.IsNotExist(err) && f.options.Loose {
+ f.parse(bytes.NewBuffer(nil))
+ continue
+ }
+ return err
+ }
+ }
+ return nil
+}
+
+// Append appends one or more data sources and reloads automatically.
+func (f *File) Append(source interface{}, others ...interface{}) error {
+ ds, err := parseDataSource(source)
+ if err != nil {
+ return err
+ }
+ f.dataSources = append(f.dataSources, ds)
+ for _, s := range others {
+ ds, err = parseDataSource(s)
+ if err != nil {
+ return err
+ }
+ f.dataSources = append(f.dataSources, ds)
+ }
+ return f.Reload()
+}
+
+func (f *File) writeToBuffer(indent string) (*bytes.Buffer, error) {
+ equalSign := "="
+ if PrettyFormat || PrettyEqual {
+ equalSign = " = "
+ }
+
+ // Use buffer to make sure target is safe until finish encoding.
+ buf := bytes.NewBuffer(nil)
+ for i, sname := range f.sectionList {
+ sec := f.Section(sname)
+ if len(sec.Comment) > 0 {
+ if sec.Comment[0] != '#' && sec.Comment[0] != ';' {
+ sec.Comment = "; " + sec.Comment
+ } else {
+ sec.Comment = sec.Comment[:1] + " " + strings.TrimSpace(sec.Comment[1:])
+ }
+ if _, err := buf.WriteString(sec.Comment + LineBreak); err != nil {
+ return nil, err
+ }
+ }
+
+ if i > 0 || DefaultHeader {
+ if _, err := buf.WriteString("[" + sname + "]" + LineBreak); err != nil {
+ return nil, err
+ }
+ } else {
+ // Write nothing if default section is empty
+ if len(sec.keyList) == 0 {
+ continue
+ }
+ }
+
+ if sec.isRawSection {
+ if _, err := buf.WriteString(sec.rawBody); err != nil {
+ return nil, err
+ }
+
+ if PrettySection {
+ // Put a line between sections
+ if _, err := buf.WriteString(LineBreak); err != nil {
+ return nil, err
+ }
+ }
+ continue
+ }
+
+ // Count and generate alignment length and buffer spaces using the
+ // longest key. Keys may be modifed if they contain certain characters so
+ // we need to take that into account in our calculation.
+ alignLength := 0
+ if PrettyFormat {
+ for _, kname := range sec.keyList {
+ keyLength := len(kname)
+ // First case will surround key by ` and second by """
+ if strings.ContainsAny(kname, "\"=:") {
+ keyLength += 2
+ } else if strings.Contains(kname, "`") {
+ keyLength += 6
+ }
+
+ if keyLength > alignLength {
+ alignLength = keyLength
+ }
+ }
+ }
+ alignSpaces := bytes.Repeat([]byte(" "), alignLength)
+
+ KEY_LIST:
+ for _, kname := range sec.keyList {
+ key := sec.Key(kname)
+ if len(key.Comment) > 0 {
+ if len(indent) > 0 && sname != DEFAULT_SECTION {
+ buf.WriteString(indent)
+ }
+ if key.Comment[0] != '#' && key.Comment[0] != ';' {
+ key.Comment = "; " + key.Comment
+ } else {
+ key.Comment = key.Comment[:1] + " " + strings.TrimSpace(key.Comment[1:])
+ }
+
+ // Support multiline comments
+ key.Comment = strings.Replace(key.Comment, "\n", "\n; ", -1)
+
+ if _, err := buf.WriteString(key.Comment + LineBreak); err != nil {
+ return nil, err
+ }
+ }
+
+ if len(indent) > 0 && sname != DEFAULT_SECTION {
+ buf.WriteString(indent)
+ }
+
+ switch {
+ case key.isAutoIncrement:
+ kname = "-"
+ case strings.ContainsAny(kname, "\"=:"):
+ kname = "`" + kname + "`"
+ case strings.Contains(kname, "`"):
+ kname = `"""` + kname + `"""`
+ }
+
+ for _, val := range key.ValueWithShadows() {
+ if _, err := buf.WriteString(kname); err != nil {
+ return nil, err
+ }
+
+ if key.isBooleanType {
+ if kname != sec.keyList[len(sec.keyList)-1] {
+ buf.WriteString(LineBreak)
+ }
+ continue KEY_LIST
+ }
+
+ // Write out alignment spaces before "=" sign
+ if PrettyFormat {
+ buf.Write(alignSpaces[:alignLength-len(kname)])
+ }
+
+ // In case key value contains "\n", "`", "\"", "#" or ";"
+ if strings.ContainsAny(val, "\n`") {
+ val = `"""` + val + `"""`
+ } else if !f.options.IgnoreInlineComment && strings.ContainsAny(val, "#;") {
+ val = "`" + val + "`"
+ }
+ if _, err := buf.WriteString(equalSign + val + LineBreak); err != nil {
+ return nil, err
+ }
+ }
+
+ for _, val := range key.nestedValues {
+ if _, err := buf.WriteString(indent + " " + val + LineBreak); err != nil {
+ return nil, err
+ }
+ }
+ }
+
+ if PrettySection {
+ // Put a line between sections
+ if _, err := buf.WriteString(LineBreak); err != nil {
+ return nil, err
+ }
+ }
+ }
+
+ return buf, nil
+}
+
+// WriteToIndent writes content into io.Writer with given indention.
+// If PrettyFormat has been set to be true,
+// it will align "=" sign with spaces under each section.
+func (f *File) WriteToIndent(w io.Writer, indent string) (int64, error) {
+ buf, err := f.writeToBuffer(indent)
+ if err != nil {
+ return 0, err
+ }
+ return buf.WriteTo(w)
+}
+
+// WriteTo writes file content into io.Writer.
+func (f *File) WriteTo(w io.Writer) (int64, error) {
+ return f.WriteToIndent(w, "")
+}
+
+// SaveToIndent writes content to file system with given value indention.
+func (f *File) SaveToIndent(filename, indent string) error {
+ // Note: Because we are truncating with os.Create,
+ // so it's safer to save to a temporary file location and rename afte done.
+ buf, err := f.writeToBuffer(indent)
+ if err != nil {
+ return err
+ }
+
+ return ioutil.WriteFile(filename, buf.Bytes(), 0666)
+}
+
+// SaveTo writes content to file system.
+func (f *File) SaveTo(filename string) error {
+ return f.SaveToIndent(filename, "")
+}
diff --git a/vendor/gopkg.in/ini.v1/ini.go b/vendor/gopkg.in/ini.v1/ini.go
new file mode 100644
index 0000000..ccba1ee
--- /dev/null
+++ b/vendor/gopkg.in/ini.v1/ini.go
@@ -0,0 +1,197 @@
+// Copyright 2014 Unknwon
+//
+// Licensed under the Apache License, Version 2.0 (the "License"): you may
+// not use this file except in compliance with the License. You may obtain
+// a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+
+// Package ini provides INI file read and write functionality in Go.
+package ini
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "regexp"
+ "runtime"
+)
+
+const (
+ // Name for default section. You can use this constant or the string literal.
+ // In most of cases, an empty string is all you need to access the section.
+ DEFAULT_SECTION = "DEFAULT"
+
+ // Maximum allowed depth when recursively substituing variable names.
+ _DEPTH_VALUES = 99
+ _VERSION = "1.35.0"
+)
+
+// Version returns current package version literal.
+func Version() string {
+ return _VERSION
+}
+
+var (
+ // Delimiter to determine or compose a new line.
+ // This variable will be changed to "\r\n" automatically on Windows
+ // at package init time.
+ LineBreak = "\n"
+
+ // Variable regexp pattern: %(variable)s
+ varPattern = regexp.MustCompile(`%\(([^\)]+)\)s`)
+
+ // Indicate whether to align "=" sign with spaces to produce pretty output
+ // or reduce all possible spaces for compact format.
+ PrettyFormat = true
+
+ // Place spaces around "=" sign even when PrettyFormat is false
+ PrettyEqual = false
+
+ // Explicitly write DEFAULT section header
+ DefaultHeader = false
+
+ // Indicate whether to put a line between sections
+ PrettySection = true
+)
+
+func init() {
+ if runtime.GOOS == "windows" {
+ LineBreak = "\r\n"
+ }
+}
+
+func inSlice(str string, s []string) bool {
+ for _, v := range s {
+ if str == v {
+ return true
+ }
+ }
+ return false
+}
+
+// dataSource is an interface that returns object which can be read and closed.
+type dataSource interface {
+ ReadCloser() (io.ReadCloser, error)
+}
+
+// sourceFile represents an object that contains content on the local file system.
+type sourceFile struct {
+ name string
+}
+
+func (s sourceFile) ReadCloser() (_ io.ReadCloser, err error) {
+ return os.Open(s.name)
+}
+
+// sourceData represents an object that contains content in memory.
+type sourceData struct {
+ data []byte
+}
+
+func (s *sourceData) ReadCloser() (io.ReadCloser, error) {
+ return ioutil.NopCloser(bytes.NewReader(s.data)), nil
+}
+
+// sourceReadCloser represents an input stream with Close method.
+type sourceReadCloser struct {
+ reader io.ReadCloser
+}
+
+func (s *sourceReadCloser) ReadCloser() (io.ReadCloser, error) {
+ return s.reader, nil
+}
+
+func parseDataSource(source interface{}) (dataSource, error) {
+ switch s := source.(type) {
+ case string:
+ return sourceFile{s}, nil
+ case []byte:
+ return &sourceData{s}, nil
+ case io.ReadCloser:
+ return &sourceReadCloser{s}, nil
+ default:
+ return nil, fmt.Errorf("error parsing data source: unknown type '%s'", s)
+ }
+}
+
+type LoadOptions struct {
+ // Loose indicates whether the parser should ignore nonexistent files or return error.
+ Loose bool
+ // Insensitive indicates whether the parser forces all section and key names to lowercase.
+ Insensitive bool
+ // IgnoreContinuation indicates whether to ignore continuation lines while parsing.
+ IgnoreContinuation bool
+ // IgnoreInlineComment indicates whether to ignore comments at the end of value and treat it as part of value.
+ IgnoreInlineComment bool
+ // AllowBooleanKeys indicates whether to allow boolean type keys or treat as value is missing.
+ // This type of keys are mostly used in my.cnf.
+ AllowBooleanKeys bool
+ // AllowShadows indicates whether to keep track of keys with same name under same section.
+ AllowShadows bool
+ // AllowNestedValues indicates whether to allow AWS-like nested values.
+ // Docs: http://docs.aws.amazon.com/cli/latest/topic/config-vars.html#nested-values
+ AllowNestedValues bool
+ // UnescapeValueDoubleQuotes indicates whether to unescape double quotes inside value to regular format
+ // when value is surrounded by double quotes, e.g. key="a \"value\"" => key=a "value"
+ UnescapeValueDoubleQuotes bool
+ // UnescapeValueCommentSymbols indicates to unescape comment symbols (\# and \;) inside value to regular format
+ // when value is NOT surrounded by any quotes.
+ // Note: UNSTABLE, behavior might change to only unescape inside double quotes but may noy necessary at all.
+ UnescapeValueCommentSymbols bool
+ // Some INI formats allow group blocks that store a block of raw content that doesn't otherwise
+ // conform to key/value pairs. Specify the names of those blocks here.
+ UnparseableSections []string
+}
+
+func LoadSources(opts LoadOptions, source interface{}, others ...interface{}) (_ *File, err error) {
+ sources := make([]dataSource, len(others)+1)
+ sources[0], err = parseDataSource(source)
+ if err != nil {
+ return nil, err
+ }
+ for i := range others {
+ sources[i+1], err = parseDataSource(others[i])
+ if err != nil {
+ return nil, err
+ }
+ }
+ f := newFile(sources, opts)
+ if err = f.Reload(); err != nil {
+ return nil, err
+ }
+ return f, nil
+}
+
+// Load loads and parses from INI data sources.
+// Arguments can be mixed of file name with string type, or raw data in []byte.
+// It will return error if list contains nonexistent files.
+func Load(source interface{}, others ...interface{}) (*File, error) {
+ return LoadSources(LoadOptions{}, source, others...)
+}
+
+// LooseLoad has exactly same functionality as Load function
+// except it ignores nonexistent files instead of returning error.
+func LooseLoad(source interface{}, others ...interface{}) (*File, error) {
+ return LoadSources(LoadOptions{Loose: true}, source, others...)
+}
+
+// InsensitiveLoad has exactly same functionality as Load function
+// except it forces all section and key names to be lowercased.
+func InsensitiveLoad(source interface{}, others ...interface{}) (*File, error) {
+ return LoadSources(LoadOptions{Insensitive: true}, source, others...)
+}
+
+// InsensitiveLoad has exactly same functionality as Load function
+// except it allows have shadow keys.
+func ShadowLoad(source interface{}, others ...interface{}) (*File, error) {
+ return LoadSources(LoadOptions{AllowShadows: true}, source, others...)
+}
diff --git a/vendor/gopkg.in/ini.v1/key.go b/vendor/gopkg.in/ini.v1/key.go
new file mode 100644
index 0000000..7c8566a
--- /dev/null
+++ b/vendor/gopkg.in/ini.v1/key.go
@@ -0,0 +1,751 @@
+// Copyright 2014 Unknwon
+//
+// Licensed under the Apache License, Version 2.0 (the "License"): you may
+// not use this file except in compliance with the License. You may obtain
+// a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+
+package ini
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// Key represents a key under a section.
+type Key struct {
+ s *Section
+ Comment string
+ name string
+ value string
+ isAutoIncrement bool
+ isBooleanType bool
+
+ isShadow bool
+ shadows []*Key
+
+ nestedValues []string
+}
+
+// newKey simply return a key object with given values.
+func newKey(s *Section, name, val string) *Key {
+ return &Key{
+ s: s,
+ name: name,
+ value: val,
+ }
+}
+
+func (k *Key) addShadow(val string) error {
+ if k.isShadow {
+ return errors.New("cannot add shadow to another shadow key")
+ } else if k.isAutoIncrement || k.isBooleanType {
+ return errors.New("cannot add shadow to auto-increment or boolean key")
+ }
+
+ shadow := newKey(k.s, k.name, val)
+ shadow.isShadow = true
+ k.shadows = append(k.shadows, shadow)
+ return nil
+}
+
+// AddShadow adds a new shadow key to itself.
+func (k *Key) AddShadow(val string) error {
+ if !k.s.f.options.AllowShadows {
+ return errors.New("shadow key is not allowed")
+ }
+ return k.addShadow(val)
+}
+
+func (k *Key) addNestedValue(val string) error {
+ if k.isAutoIncrement || k.isBooleanType {
+ return errors.New("cannot add nested value to auto-increment or boolean key")
+ }
+
+ k.nestedValues = append(k.nestedValues, val)
+ return nil
+}
+
+func (k *Key) AddNestedValue(val string) error {
+ if !k.s.f.options.AllowNestedValues {
+ return errors.New("nested value is not allowed")
+ }
+ return k.addNestedValue(val)
+}
+
+// ValueMapper represents a mapping function for values, e.g. os.ExpandEnv
+type ValueMapper func(string) string
+
+// Name returns name of key.
+func (k *Key) Name() string {
+ return k.name
+}
+
+// Value returns raw value of key for performance purpose.
+func (k *Key) Value() string {
+ return k.value
+}
+
+// ValueWithShadows returns raw values of key and its shadows if any.
+func (k *Key) ValueWithShadows() []string {
+ if len(k.shadows) == 0 {
+ return []string{k.value}
+ }
+ vals := make([]string, len(k.shadows)+1)
+ vals[0] = k.value
+ for i := range k.shadows {
+ vals[i+1] = k.shadows[i].value
+ }
+ return vals
+}
+
+// NestedValues returns nested values stored in the key.
+// It is possible returned value is nil if no nested values stored in the key.
+func (k *Key) NestedValues() []string {
+ return k.nestedValues
+}
+
+// transformValue takes a raw value and transforms to its final string.
+func (k *Key) transformValue(val string) string {
+ if k.s.f.ValueMapper != nil {
+ val = k.s.f.ValueMapper(val)
+ }
+
+ // Fail-fast if no indicate char found for recursive value
+ if !strings.Contains(val, "%") {
+ return val
+ }
+ for i := 0; i < _DEPTH_VALUES; i++ {
+ vr := varPattern.FindString(val)
+ if len(vr) == 0 {
+ break
+ }
+
+ // Take off leading '%(' and trailing ')s'.
+ noption := strings.TrimLeft(vr, "%(")
+ noption = strings.TrimRight(noption, ")s")
+
+ // Search in the same section.
+ nk, err := k.s.GetKey(noption)
+ if err != nil || k == nk {
+ // Search again in default section.
+ nk, _ = k.s.f.Section("").GetKey(noption)
+ }
+
+ // Substitute by new value and take off leading '%(' and trailing ')s'.
+ val = strings.Replace(val, vr, nk.value, -1)
+ }
+ return val
+}
+
+// String returns string representation of value.
+func (k *Key) String() string {
+ return k.transformValue(k.value)
+}
+
+// Validate accepts a validate function which can
+// return modifed result as key value.
+func (k *Key) Validate(fn func(string) string) string {
+ return fn(k.String())
+}
+
+// parseBool returns the boolean value represented by the string.
+//
+// It accepts 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On,
+// 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off.
+// Any other value returns an error.
+func parseBool(str string) (value bool, err error) {
+ switch str {
+ case "1", "t", "T", "true", "TRUE", "True", "YES", "yes", "Yes", "y", "ON", "on", "On":
+ return true, nil
+ case "0", "f", "F", "false", "FALSE", "False", "NO", "no", "No", "n", "OFF", "off", "Off":
+ return false, nil
+ }
+ return false, fmt.Errorf("parsing \"%s\": invalid syntax", str)
+}
+
+// Bool returns bool type value.
+func (k *Key) Bool() (bool, error) {
+ return parseBool(k.String())
+}
+
+// Float64 returns float64 type value.
+func (k *Key) Float64() (float64, error) {
+ return strconv.ParseFloat(k.String(), 64)
+}
+
+// Int returns int type value.
+func (k *Key) Int() (int, error) {
+ return strconv.Atoi(k.String())
+}
+
+// Int64 returns int64 type value.
+func (k *Key) Int64() (int64, error) {
+ return strconv.ParseInt(k.String(), 10, 64)
+}
+
+// Uint returns uint type valued.
+func (k *Key) Uint() (uint, error) {
+ u, e := strconv.ParseUint(k.String(), 10, 64)
+ return uint(u), e
+}
+
+// Uint64 returns uint64 type value.
+func (k *Key) Uint64() (uint64, error) {
+ return strconv.ParseUint(k.String(), 10, 64)
+}
+
+// Duration returns time.Duration type value.
+func (k *Key) Duration() (time.Duration, error) {
+ return time.ParseDuration(k.String())
+}
+
+// TimeFormat parses with given format and returns time.Time type value.
+func (k *Key) TimeFormat(format string) (time.Time, error) {
+ return time.Parse(format, k.String())
+}
+
+// Time parses with RFC3339 format and returns time.Time type value.
+func (k *Key) Time() (time.Time, error) {
+ return k.TimeFormat(time.RFC3339)
+}
+
+// MustString returns default value if key value is empty.
+func (k *Key) MustString(defaultVal string) string {
+ val := k.String()
+ if len(val) == 0 {
+ k.value = defaultVal
+ return defaultVal
+ }
+ return val
+}
+
+// MustBool always returns value without error,
+// it returns false if error occurs.
+func (k *Key) MustBool(defaultVal ...bool) bool {
+ val, err := k.Bool()
+ if len(defaultVal) > 0 && err != nil {
+ k.value = strconv.FormatBool(defaultVal[0])
+ return defaultVal[0]
+ }
+ return val
+}
+
+// MustFloat64 always returns value without error,
+// it returns 0.0 if error occurs.
+func (k *Key) MustFloat64(defaultVal ...float64) float64 {
+ val, err := k.Float64()
+ if len(defaultVal) > 0 && err != nil {
+ k.value = strconv.FormatFloat(defaultVal[0], 'f', -1, 64)
+ return defaultVal[0]
+ }
+ return val
+}
+
+// MustInt always returns value without error,
+// it returns 0 if error occurs.
+func (k *Key) MustInt(defaultVal ...int) int {
+ val, err := k.Int()
+ if len(defaultVal) > 0 && err != nil {
+ k.value = strconv.FormatInt(int64(defaultVal[0]), 10)
+ return defaultVal[0]
+ }
+ return val
+}
+
+// MustInt64 always returns value without error,
+// it returns 0 if error occurs.
+func (k *Key) MustInt64(defaultVal ...int64) int64 {
+ val, err := k.Int64()
+ if len(defaultVal) > 0 && err != nil {
+ k.value = strconv.FormatInt(defaultVal[0], 10)
+ return defaultVal[0]
+ }
+ return val
+}
+
+// MustUint always returns value without error,
+// it returns 0 if error occurs.
+func (k *Key) MustUint(defaultVal ...uint) uint {
+ val, err := k.Uint()
+ if len(defaultVal) > 0 && err != nil {
+ k.value = strconv.FormatUint(uint64(defaultVal[0]), 10)
+ return defaultVal[0]
+ }
+ return val
+}
+
+// MustUint64 always returns value without error,
+// it returns 0 if error occurs.
+func (k *Key) MustUint64(defaultVal ...uint64) uint64 {
+ val, err := k.Uint64()
+ if len(defaultVal) > 0 && err != nil {
+ k.value = strconv.FormatUint(defaultVal[0], 10)
+ return defaultVal[0]
+ }
+ return val
+}
+
+// MustDuration always returns value without error,
+// it returns zero value if error occurs.
+func (k *Key) MustDuration(defaultVal ...time.Duration) time.Duration {
+ val, err := k.Duration()
+ if len(defaultVal) > 0 && err != nil {
+ k.value = defaultVal[0].String()
+ return defaultVal[0]
+ }
+ return val
+}
+
+// MustTimeFormat always parses with given format and returns value without error,
+// it returns zero value if error occurs.
+func (k *Key) MustTimeFormat(format string, defaultVal ...time.Time) time.Time {
+ val, err := k.TimeFormat(format)
+ if len(defaultVal) > 0 && err != nil {
+ k.value = defaultVal[0].Format(format)
+ return defaultVal[0]
+ }
+ return val
+}
+
+// MustTime always parses with RFC3339 format and returns value without error,
+// it returns zero value if error occurs.
+func (k *Key) MustTime(defaultVal ...time.Time) time.Time {
+ return k.MustTimeFormat(time.RFC3339, defaultVal...)
+}
+
+// In always returns value without error,
+// it returns default value if error occurs or doesn't fit into candidates.
+func (k *Key) In(defaultVal string, candidates []string) string {
+ val := k.String()
+ for _, cand := range candidates {
+ if val == cand {
+ return val
+ }
+ }
+ return defaultVal
+}
+
+// InFloat64 always returns value without error,
+// it returns default value if error occurs or doesn't fit into candidates.
+func (k *Key) InFloat64(defaultVal float64, candidates []float64) float64 {
+ val := k.MustFloat64()
+ for _, cand := range candidates {
+ if val == cand {
+ return val
+ }
+ }
+ return defaultVal
+}
+
+// InInt always returns value without error,
+// it returns default value if error occurs or doesn't fit into candidates.
+func (k *Key) InInt(defaultVal int, candidates []int) int {
+ val := k.MustInt()
+ for _, cand := range candidates {
+ if val == cand {
+ return val
+ }
+ }
+ return defaultVal
+}
+
+// InInt64 always returns value without error,
+// it returns default value if error occurs or doesn't fit into candidates.
+func (k *Key) InInt64(defaultVal int64, candidates []int64) int64 {
+ val := k.MustInt64()
+ for _, cand := range candidates {
+ if val == cand {
+ return val
+ }
+ }
+ return defaultVal
+}
+
+// InUint always returns value without error,
+// it returns default value if error occurs or doesn't fit into candidates.
+func (k *Key) InUint(defaultVal uint, candidates []uint) uint {
+ val := k.MustUint()
+ for _, cand := range candidates {
+ if val == cand {
+ return val
+ }
+ }
+ return defaultVal
+}
+
+// InUint64 always returns value without error,
+// it returns default value if error occurs or doesn't fit into candidates.
+func (k *Key) InUint64(defaultVal uint64, candidates []uint64) uint64 {
+ val := k.MustUint64()
+ for _, cand := range candidates {
+ if val == cand {
+ return val
+ }
+ }
+ return defaultVal
+}
+
+// InTimeFormat always parses with given format and returns value without error,
+// it returns default value if error occurs or doesn't fit into candidates.
+func (k *Key) InTimeFormat(format string, defaultVal time.Time, candidates []time.Time) time.Time {
+ val := k.MustTimeFormat(format)
+ for _, cand := range candidates {
+ if val == cand {
+ return val
+ }
+ }
+ return defaultVal
+}
+
+// InTime always parses with RFC3339 format and returns value without error,
+// it returns default value if error occurs or doesn't fit into candidates.
+func (k *Key) InTime(defaultVal time.Time, candidates []time.Time) time.Time {
+ return k.InTimeFormat(time.RFC3339, defaultVal, candidates)
+}
+
+// RangeFloat64 checks if value is in given range inclusively,
+// and returns default value if it's not.
+func (k *Key) RangeFloat64(defaultVal, min, max float64) float64 {
+ val := k.MustFloat64()
+ if val < min || val > max {
+ return defaultVal
+ }
+ return val
+}
+
+// RangeInt checks if value is in given range inclusively,
+// and returns default value if it's not.
+func (k *Key) RangeInt(defaultVal, min, max int) int {
+ val := k.MustInt()
+ if val < min || val > max {
+ return defaultVal
+ }
+ return val
+}
+
+// RangeInt64 checks if value is in given range inclusively,
+// and returns default value if it's not.
+func (k *Key) RangeInt64(defaultVal, min, max int64) int64 {
+ val := k.MustInt64()
+ if val < min || val > max {
+ return defaultVal
+ }
+ return val
+}
+
+// RangeTimeFormat checks if value with given format is in given range inclusively,
+// and returns default value if it's not.
+func (k *Key) RangeTimeFormat(format string, defaultVal, min, max time.Time) time.Time {
+ val := k.MustTimeFormat(format)
+ if val.Unix() < min.Unix() || val.Unix() > max.Unix() {
+ return defaultVal
+ }
+ return val
+}
+
+// RangeTime checks if value with RFC3339 format is in given range inclusively,
+// and returns default value if it's not.
+func (k *Key) RangeTime(defaultVal, min, max time.Time) time.Time {
+ return k.RangeTimeFormat(time.RFC3339, defaultVal, min, max)
+}
+
+// Strings returns list of string divided by given delimiter.
+func (k *Key) Strings(delim string) []string {
+ str := k.String()
+ if len(str) == 0 {
+ return []string{}
+ }
+
+ runes := []rune(str)
+ vals := make([]string, 0, 2)
+ var buf bytes.Buffer
+ escape := false
+ idx := 0
+ for {
+ if escape {
+ escape = false
+ if runes[idx] != '\\' && !strings.HasPrefix(string(runes[idx:]), delim) {
+ buf.WriteRune('\\')
+ }
+ buf.WriteRune(runes[idx])
+ } else {
+ if runes[idx] == '\\' {
+ escape = true
+ } else if strings.HasPrefix(string(runes[idx:]), delim) {
+ idx += len(delim) - 1
+ vals = append(vals, strings.TrimSpace(buf.String()))
+ buf.Reset()
+ } else {
+ buf.WriteRune(runes[idx])
+ }
+ }
+ idx += 1
+ if idx == len(runes) {
+ break
+ }
+ }
+
+ if buf.Len() > 0 {
+ vals = append(vals, strings.TrimSpace(buf.String()))
+ }
+
+ return vals
+}
+
+// StringsWithShadows returns list of string divided by given delimiter.
+// Shadows will also be appended if any.
+func (k *Key) StringsWithShadows(delim string) []string {
+ vals := k.ValueWithShadows()
+ results := make([]string, 0, len(vals)*2)
+ for i := range vals {
+ if len(vals) == 0 {
+ continue
+ }
+
+ results = append(results, strings.Split(vals[i], delim)...)
+ }
+
+ for i := range results {
+ results[i] = k.transformValue(strings.TrimSpace(results[i]))
+ }
+ return results
+}
+
+// Float64s returns list of float64 divided by given delimiter. Any invalid input will be treated as zero value.
+func (k *Key) Float64s(delim string) []float64 {
+ vals, _ := k.parseFloat64s(k.Strings(delim), true, false)
+ return vals
+}
+
+// Ints returns list of int divided by given delimiter. Any invalid input will be treated as zero value.
+func (k *Key) Ints(delim string) []int {
+ vals, _ := k.parseInts(k.Strings(delim), true, false)
+ return vals
+}
+
+// Int64s returns list of int64 divided by given delimiter. Any invalid input will be treated as zero value.
+func (k *Key) Int64s(delim string) []int64 {
+ vals, _ := k.parseInt64s(k.Strings(delim), true, false)
+ return vals
+}
+
+// Uints returns list of uint divided by given delimiter. Any invalid input will be treated as zero value.
+func (k *Key) Uints(delim string) []uint {
+ vals, _ := k.parseUints(k.Strings(delim), true, false)
+ return vals
+}
+
+// Uint64s returns list of uint64 divided by given delimiter. Any invalid input will be treated as zero value.
+func (k *Key) Uint64s(delim string) []uint64 {
+ vals, _ := k.parseUint64s(k.Strings(delim), true, false)
+ return vals
+}
+
+// TimesFormat parses with given format and returns list of time.Time divided by given delimiter.
+// Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC).
+func (k *Key) TimesFormat(format, delim string) []time.Time {
+ vals, _ := k.parseTimesFormat(format, k.Strings(delim), true, false)
+ return vals
+}
+
+// Times parses with RFC3339 format and returns list of time.Time divided by given delimiter.
+// Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC).
+func (k *Key) Times(delim string) []time.Time {
+ return k.TimesFormat(time.RFC3339, delim)
+}
+
+// ValidFloat64s returns list of float64 divided by given delimiter. If some value is not float, then
+// it will not be included to result list.
+func (k *Key) ValidFloat64s(delim string) []float64 {
+ vals, _ := k.parseFloat64s(k.Strings(delim), false, false)
+ return vals
+}
+
+// ValidInts returns list of int divided by given delimiter. If some value is not integer, then it will
+// not be included to result list.
+func (k *Key) ValidInts(delim string) []int {
+ vals, _ := k.parseInts(k.Strings(delim), false, false)
+ return vals
+}
+
+// ValidInt64s returns list of int64 divided by given delimiter. If some value is not 64-bit integer,
+// then it will not be included to result list.
+func (k *Key) ValidInt64s(delim string) []int64 {
+ vals, _ := k.parseInt64s(k.Strings(delim), false, false)
+ return vals
+}
+
+// ValidUints returns list of uint divided by given delimiter. If some value is not unsigned integer,
+// then it will not be included to result list.
+func (k *Key) ValidUints(delim string) []uint {
+ vals, _ := k.parseUints(k.Strings(delim), false, false)
+ return vals
+}
+
+// ValidUint64s returns list of uint64 divided by given delimiter. If some value is not 64-bit unsigned
+// integer, then it will not be included to result list.
+func (k *Key) ValidUint64s(delim string) []uint64 {
+ vals, _ := k.parseUint64s(k.Strings(delim), false, false)
+ return vals
+}
+
+// ValidTimesFormat parses with given format and returns list of time.Time divided by given delimiter.
+func (k *Key) ValidTimesFormat(format, delim string) []time.Time {
+ vals, _ := k.parseTimesFormat(format, k.Strings(delim), false, false)
+ return vals
+}
+
+// ValidTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter.
+func (k *Key) ValidTimes(delim string) []time.Time {
+ return k.ValidTimesFormat(time.RFC3339, delim)
+}
+
+// StrictFloat64s returns list of float64 divided by given delimiter or error on first invalid input.
+func (k *Key) StrictFloat64s(delim string) ([]float64, error) {
+ return k.parseFloat64s(k.Strings(delim), false, true)
+}
+
+// StrictInts returns list of int divided by given delimiter or error on first invalid input.
+func (k *Key) StrictInts(delim string) ([]int, error) {
+ return k.parseInts(k.Strings(delim), false, true)
+}
+
+// StrictInt64s returns list of int64 divided by given delimiter or error on first invalid input.
+func (k *Key) StrictInt64s(delim string) ([]int64, error) {
+ return k.parseInt64s(k.Strings(delim), false, true)
+}
+
+// StrictUints returns list of uint divided by given delimiter or error on first invalid input.
+func (k *Key) StrictUints(delim string) ([]uint, error) {
+ return k.parseUints(k.Strings(delim), false, true)
+}
+
+// StrictUint64s returns list of uint64 divided by given delimiter or error on first invalid input.
+func (k *Key) StrictUint64s(delim string) ([]uint64, error) {
+ return k.parseUint64s(k.Strings(delim), false, true)
+}
+
+// StrictTimesFormat parses with given format and returns list of time.Time divided by given delimiter
+// or error on first invalid input.
+func (k *Key) StrictTimesFormat(format, delim string) ([]time.Time, error) {
+ return k.parseTimesFormat(format, k.Strings(delim), false, true)
+}
+
+// StrictTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter
+// or error on first invalid input.
+func (k *Key) StrictTimes(delim string) ([]time.Time, error) {
+ return k.StrictTimesFormat(time.RFC3339, delim)
+}
+
+// parseFloat64s transforms strings to float64s.
+func (k *Key) parseFloat64s(strs []string, addInvalid, returnOnInvalid bool) ([]float64, error) {
+ vals := make([]float64, 0, len(strs))
+ for _, str := range strs {
+ val, err := strconv.ParseFloat(str, 64)
+ if err != nil && returnOnInvalid {
+ return nil, err
+ }
+ if err == nil || addInvalid {
+ vals = append(vals, val)
+ }
+ }
+ return vals, nil
+}
+
+// parseInts transforms strings to ints.
+func (k *Key) parseInts(strs []string, addInvalid, returnOnInvalid bool) ([]int, error) {
+ vals := make([]int, 0, len(strs))
+ for _, str := range strs {
+ val, err := strconv.Atoi(str)
+ if err != nil && returnOnInvalid {
+ return nil, err
+ }
+ if err == nil || addInvalid {
+ vals = append(vals, val)
+ }
+ }
+ return vals, nil
+}
+
+// parseInt64s transforms strings to int64s.
+func (k *Key) parseInt64s(strs []string, addInvalid, returnOnInvalid bool) ([]int64, error) {
+ vals := make([]int64, 0, len(strs))
+ for _, str := range strs {
+ val, err := strconv.ParseInt(str, 10, 64)
+ if err != nil && returnOnInvalid {
+ return nil, err
+ }
+ if err == nil || addInvalid {
+ vals = append(vals, val)
+ }
+ }
+ return vals, nil
+}
+
+// parseUints transforms strings to uints.
+func (k *Key) parseUints(strs []string, addInvalid, returnOnInvalid bool) ([]uint, error) {
+ vals := make([]uint, 0, len(strs))
+ for _, str := range strs {
+ val, err := strconv.ParseUint(str, 10, 0)
+ if err != nil && returnOnInvalid {
+ return nil, err
+ }
+ if err == nil || addInvalid {
+ vals = append(vals, uint(val))
+ }
+ }
+ return vals, nil
+}
+
+// parseUint64s transforms strings to uint64s.
+func (k *Key) parseUint64s(strs []string, addInvalid, returnOnInvalid bool) ([]uint64, error) {
+ vals := make([]uint64, 0, len(strs))
+ for _, str := range strs {
+ val, err := strconv.ParseUint(str, 10, 64)
+ if err != nil && returnOnInvalid {
+ return nil, err
+ }
+ if err == nil || addInvalid {
+ vals = append(vals, val)
+ }
+ }
+ return vals, nil
+}
+
+// parseTimesFormat transforms strings to times in given format.
+func (k *Key) parseTimesFormat(format string, strs []string, addInvalid, returnOnInvalid bool) ([]time.Time, error) {
+ vals := make([]time.Time, 0, len(strs))
+ for _, str := range strs {
+ val, err := time.Parse(format, str)
+ if err != nil && returnOnInvalid {
+ return nil, err
+ }
+ if err == nil || addInvalid {
+ vals = append(vals, val)
+ }
+ }
+ return vals, nil
+}
+
+// SetValue changes key value.
+func (k *Key) SetValue(v string) {
+ if k.s.f.BlockMode {
+ k.s.f.lock.Lock()
+ defer k.s.f.lock.Unlock()
+ }
+
+ k.value = v
+ k.s.keysHash[k.name] = v
+}
diff --git a/vendor/gopkg.in/ini.v1/parser.go b/vendor/gopkg.in/ini.v1/parser.go
new file mode 100644
index 0000000..db3af8f
--- /dev/null
+++ b/vendor/gopkg.in/ini.v1/parser.go
@@ -0,0 +1,401 @@
+// Copyright 2015 Unknwon
+//
+// Licensed under the Apache License, Version 2.0 (the "License"): you may
+// not use this file except in compliance with the License. You may obtain
+// a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+
+package ini
+
+import (
+ "bufio"
+ "bytes"
+ "fmt"
+ "io"
+ "strconv"
+ "strings"
+ "unicode"
+)
+
+type tokenType int
+
+const (
+ _TOKEN_INVALID tokenType = iota
+ _TOKEN_COMMENT
+ _TOKEN_SECTION
+ _TOKEN_KEY
+)
+
+type parser struct {
+ buf *bufio.Reader
+ isEOF bool
+ count int
+ comment *bytes.Buffer
+}
+
+func newParser(r io.Reader) *parser {
+ return &parser{
+ buf: bufio.NewReader(r),
+ count: 1,
+ comment: &bytes.Buffer{},
+ }
+}
+
+// BOM handles header of UTF-8, UTF-16 LE and UTF-16 BE's BOM format.
+// http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding
+func (p *parser) BOM() error {
+ mask, err := p.buf.Peek(2)
+ if err != nil && err != io.EOF {
+ return err
+ } else if len(mask) < 2 {
+ return nil
+ }
+
+ switch {
+ case mask[0] == 254 && mask[1] == 255:
+ fallthrough
+ case mask[0] == 255 && mask[1] == 254:
+ p.buf.Read(mask)
+ case mask[0] == 239 && mask[1] == 187:
+ mask, err := p.buf.Peek(3)
+ if err != nil && err != io.EOF {
+ return err
+ } else if len(mask) < 3 {
+ return nil
+ }
+ if mask[2] == 191 {
+ p.buf.Read(mask)
+ }
+ }
+ return nil
+}
+
+func (p *parser) readUntil(delim byte) ([]byte, error) {
+ data, err := p.buf.ReadBytes(delim)
+ if err != nil {
+ if err == io.EOF {
+ p.isEOF = true
+ } else {
+ return nil, err
+ }
+ }
+ return data, nil
+}
+
+func cleanComment(in []byte) ([]byte, bool) {
+ i := bytes.IndexAny(in, "#;")
+ if i == -1 {
+ return nil, false
+ }
+ return in[i:], true
+}
+
+func readKeyName(in []byte) (string, int, error) {
+ line := string(in)
+
+ // Check if key name surrounded by quotes.
+ var keyQuote string
+ if line[0] == '"' {
+ if len(line) > 6 && string(line[0:3]) == `"""` {
+ keyQuote = `"""`
+ } else {
+ keyQuote = `"`
+ }
+ } else if line[0] == '`' {
+ keyQuote = "`"
+ }
+
+ // Get out key name
+ endIdx := -1
+ if len(keyQuote) > 0 {
+ startIdx := len(keyQuote)
+ // FIXME: fail case -> """"""name"""=value
+ pos := strings.Index(line[startIdx:], keyQuote)
+ if pos == -1 {
+ return "", -1, fmt.Errorf("missing closing key quote: %s", line)
+ }
+ pos += startIdx
+
+ // Find key-value delimiter
+ i := strings.IndexAny(line[pos+startIdx:], "=:")
+ if i < 0 {
+ return "", -1, ErrDelimiterNotFound{line}
+ }
+ endIdx = pos + i
+ return strings.TrimSpace(line[startIdx:pos]), endIdx + startIdx + 1, nil
+ }
+
+ endIdx = strings.IndexAny(line, "=:")
+ if endIdx < 0 {
+ return "", -1, ErrDelimiterNotFound{line}
+ }
+ return strings.TrimSpace(line[0:endIdx]), endIdx + 1, nil
+}
+
+func (p *parser) readMultilines(line, val, valQuote string) (string, error) {
+ for {
+ data, err := p.readUntil('\n')
+ if err != nil {
+ return "", err
+ }
+ next := string(data)
+
+ pos := strings.LastIndex(next, valQuote)
+ if pos > -1 {
+ val += next[:pos]
+
+ comment, has := cleanComment([]byte(next[pos:]))
+ if has {
+ p.comment.Write(bytes.TrimSpace(comment))
+ }
+ break
+ }
+ val += next
+ if p.isEOF {
+ return "", fmt.Errorf("missing closing key quote from '%s' to '%s'", line, next)
+ }
+ }
+ return val, nil
+}
+
+func (p *parser) readContinuationLines(val string) (string, error) {
+ for {
+ data, err := p.readUntil('\n')
+ if err != nil {
+ return "", err
+ }
+ next := strings.TrimSpace(string(data))
+
+ if len(next) == 0 {
+ break
+ }
+ val += next
+ if val[len(val)-1] != '\\' {
+ break
+ }
+ val = val[:len(val)-1]
+ }
+ return val, nil
+}
+
+// hasSurroundedQuote check if and only if the first and last characters
+// are quotes \" or \'.
+// It returns false if any other parts also contain same kind of quotes.
+func hasSurroundedQuote(in string, quote byte) bool {
+ return len(in) >= 2 && in[0] == quote && in[len(in)-1] == quote &&
+ strings.IndexByte(in[1:], quote) == len(in)-2
+}
+
+func (p *parser) readValue(in []byte,
+ ignoreContinuation, ignoreInlineComment, unescapeValueDoubleQuotes, unescapeValueCommentSymbols bool) (string, error) {
+
+ line := strings.TrimLeftFunc(string(in), unicode.IsSpace)
+ if len(line) == 0 {
+ return "", nil
+ }
+
+ var valQuote string
+ if len(line) > 3 && string(line[0:3]) == `"""` {
+ valQuote = `"""`
+ } else if line[0] == '`' {
+ valQuote = "`"
+ } else if unescapeValueDoubleQuotes && line[0] == '"' {
+ valQuote = `"`
+ }
+
+ if len(valQuote) > 0 {
+ startIdx := len(valQuote)
+ pos := strings.LastIndex(line[startIdx:], valQuote)
+ // Check for multi-line value
+ if pos == -1 {
+ return p.readMultilines(line, line[startIdx:], valQuote)
+ }
+
+ if unescapeValueDoubleQuotes && valQuote == `"` {
+ return strings.Replace(line[startIdx:pos+startIdx], `\"`, `"`, -1), nil
+ }
+ return line[startIdx : pos+startIdx], nil
+ }
+
+ // Won't be able to reach here if value only contains whitespace
+ line = strings.TrimSpace(line)
+
+ // Check continuation lines when desired
+ if !ignoreContinuation && line[len(line)-1] == '\\' {
+ return p.readContinuationLines(line[:len(line)-1])
+ }
+
+ // Check if ignore inline comment
+ if !ignoreInlineComment {
+ i := strings.IndexAny(line, "#;")
+ if i > -1 {
+ p.comment.WriteString(line[i:])
+ line = strings.TrimSpace(line[:i])
+ }
+ }
+
+ // Trim single and double quotes
+ if hasSurroundedQuote(line, '\'') ||
+ hasSurroundedQuote(line, '"') {
+ line = line[1 : len(line)-1]
+ } else if len(valQuote) == 0 && unescapeValueCommentSymbols {
+ if strings.Contains(line, `\;`) {
+ line = strings.Replace(line, `\;`, ";", -1)
+ }
+ if strings.Contains(line, `\#`) {
+ line = strings.Replace(line, `\#`, "#", -1)
+ }
+ }
+ return line, nil
+}
+
+// parse parses data through an io.Reader.
+func (f *File) parse(reader io.Reader) (err error) {
+ p := newParser(reader)
+ if err = p.BOM(); err != nil {
+ return fmt.Errorf("BOM: %v", err)
+ }
+
+ // Ignore error because default section name is never empty string.
+ name := DEFAULT_SECTION
+ if f.options.Insensitive {
+ name = strings.ToLower(DEFAULT_SECTION)
+ }
+ section, _ := f.NewSection(name)
+
+ // This "last" is not strictly equivalent to "previous one" if current key is not the first nested key
+ var isLastValueEmpty bool
+ var lastRegularKey *Key
+
+ var line []byte
+ var inUnparseableSection bool
+ for !p.isEOF {
+ line, err = p.readUntil('\n')
+ if err != nil {
+ return err
+ }
+
+ if f.options.AllowNestedValues &&
+ isLastValueEmpty && len(line) > 0 {
+ if line[0] == ' ' || line[0] == '\t' {
+ lastRegularKey.addNestedValue(string(bytes.TrimSpace(line)))
+ continue
+ }
+ }
+
+ line = bytes.TrimLeftFunc(line, unicode.IsSpace)
+ if len(line) == 0 {
+ continue
+ }
+
+ // Comments
+ if line[0] == '#' || line[0] == ';' {
+ // Note: we do not care ending line break,
+ // it is needed for adding second line,
+ // so just clean it once at the end when set to value.
+ p.comment.Write(line)
+ continue
+ }
+
+ // Section
+ if line[0] == '[' {
+ // Read to the next ']' (TODO: support quoted strings)
+ // TODO(unknwon): use LastIndexByte when stop supporting Go1.4
+ closeIdx := bytes.LastIndex(line, []byte("]"))
+ if closeIdx == -1 {
+ return fmt.Errorf("unclosed section: %s", line)
+ }
+
+ name := string(line[1:closeIdx])
+ section, err = f.NewSection(name)
+ if err != nil {
+ return err
+ }
+
+ comment, has := cleanComment(line[closeIdx+1:])
+ if has {
+ p.comment.Write(comment)
+ }
+
+ section.Comment = strings.TrimSpace(p.comment.String())
+
+ // Reset aotu-counter and comments
+ p.comment.Reset()
+ p.count = 1
+
+ inUnparseableSection = false
+ for i := range f.options.UnparseableSections {
+ if f.options.UnparseableSections[i] == name ||
+ (f.options.Insensitive && strings.ToLower(f.options.UnparseableSections[i]) == strings.ToLower(name)) {
+ inUnparseableSection = true
+ continue
+ }
+ }
+ continue
+ }
+
+ if inUnparseableSection {
+ section.isRawSection = true
+ section.rawBody += string(line)
+ continue
+ }
+
+ kname, offset, err := readKeyName(line)
+ if err != nil {
+ // Treat as boolean key when desired, and whole line is key name.
+ if IsErrDelimiterNotFound(err) && f.options.AllowBooleanKeys {
+ kname, err := p.readValue(line,
+ f.options.IgnoreContinuation,
+ f.options.IgnoreInlineComment,
+ f.options.UnescapeValueDoubleQuotes,
+ f.options.UnescapeValueCommentSymbols)
+ if err != nil {
+ return err
+ }
+ key, err := section.NewBooleanKey(kname)
+ if err != nil {
+ return err
+ }
+ key.Comment = strings.TrimSpace(p.comment.String())
+ p.comment.Reset()
+ continue
+ }
+ return err
+ }
+
+ // Auto increment.
+ isAutoIncr := false
+ if kname == "-" {
+ isAutoIncr = true
+ kname = "#" + strconv.Itoa(p.count)
+ p.count++
+ }
+
+ value, err := p.readValue(line[offset:],
+ f.options.IgnoreContinuation,
+ f.options.IgnoreInlineComment,
+ f.options.UnescapeValueDoubleQuotes,
+ f.options.UnescapeValueCommentSymbols)
+ if err != nil {
+ return err
+ }
+ isLastValueEmpty = len(value) == 0
+
+ key, err := section.NewKey(kname, value)
+ if err != nil {
+ return err
+ }
+ key.isAutoIncrement = isAutoIncr
+ key.Comment = strings.TrimSpace(p.comment.String())
+ p.comment.Reset()
+ lastRegularKey = key
+ }
+ return nil
+}
diff --git a/vendor/gopkg.in/ini.v1/section.go b/vendor/gopkg.in/ini.v1/section.go
new file mode 100644
index 0000000..d8a4026
--- /dev/null
+++ b/vendor/gopkg.in/ini.v1/section.go
@@ -0,0 +1,257 @@
+// Copyright 2014 Unknwon
+//
+// Licensed under the Apache License, Version 2.0 (the "License"): you may
+// not use this file except in compliance with the License. You may obtain
+// a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+
+package ini
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+)
+
+// Section represents a config section.
+type Section struct {
+ f *File
+ Comment string
+ name string
+ keys map[string]*Key
+ keyList []string
+ keysHash map[string]string
+
+ isRawSection bool
+ rawBody string
+}
+
+func newSection(f *File, name string) *Section {
+ return &Section{
+ f: f,
+ name: name,
+ keys: make(map[string]*Key),
+ keyList: make([]string, 0, 10),
+ keysHash: make(map[string]string),
+ }
+}
+
+// Name returns name of Section.
+func (s *Section) Name() string {
+ return s.name
+}
+
+// Body returns rawBody of Section if the section was marked as unparseable.
+// It still follows the other rules of the INI format surrounding leading/trailing whitespace.
+func (s *Section) Body() string {
+ return strings.TrimSpace(s.rawBody)
+}
+
+// SetBody updates body content only if section is raw.
+func (s *Section) SetBody(body string) {
+ if !s.isRawSection {
+ return
+ }
+ s.rawBody = body
+}
+
+// NewKey creates a new key to given section.
+func (s *Section) NewKey(name, val string) (*Key, error) {
+ if len(name) == 0 {
+ return nil, errors.New("error creating new key: empty key name")
+ } else if s.f.options.Insensitive {
+ name = strings.ToLower(name)
+ }
+
+ if s.f.BlockMode {
+ s.f.lock.Lock()
+ defer s.f.lock.Unlock()
+ }
+
+ if inSlice(name, s.keyList) {
+ if s.f.options.AllowShadows {
+ if err := s.keys[name].addShadow(val); err != nil {
+ return nil, err
+ }
+ } else {
+ s.keys[name].value = val
+ }
+ return s.keys[name], nil
+ }
+
+ s.keyList = append(s.keyList, name)
+ s.keys[name] = newKey(s, name, val)
+ s.keysHash[name] = val
+ return s.keys[name], nil
+}
+
+// NewBooleanKey creates a new boolean type key to given section.
+func (s *Section) NewBooleanKey(name string) (*Key, error) {
+ key, err := s.NewKey(name, "true")
+ if err != nil {
+ return nil, err
+ }
+
+ key.isBooleanType = true
+ return key, nil
+}
+
+// GetKey returns key in section by given name.
+func (s *Section) GetKey(name string) (*Key, error) {
+ // FIXME: change to section level lock?
+ if s.f.BlockMode {
+ s.f.lock.RLock()
+ }
+ if s.f.options.Insensitive {
+ name = strings.ToLower(name)
+ }
+ key := s.keys[name]
+ if s.f.BlockMode {
+ s.f.lock.RUnlock()
+ }
+
+ if key == nil {
+ // Check if it is a child-section.
+ sname := s.name
+ for {
+ if i := strings.LastIndex(sname, "."); i > -1 {
+ sname = sname[:i]
+ sec, err := s.f.GetSection(sname)
+ if err != nil {
+ continue
+ }
+ return sec.GetKey(name)
+ } else {
+ break
+ }
+ }
+ return nil, fmt.Errorf("error when getting key of section '%s': key '%s' not exists", s.name, name)
+ }
+ return key, nil
+}
+
+// HasKey returns true if section contains a key with given name.
+func (s *Section) HasKey(name string) bool {
+ key, _ := s.GetKey(name)
+ return key != nil
+}
+
+// Haskey is a backwards-compatible name for HasKey.
+// TODO: delete me in v2
+func (s *Section) Haskey(name string) bool {
+ return s.HasKey(name)
+}
+
+// HasValue returns true if section contains given raw value.
+func (s *Section) HasValue(value string) bool {
+ if s.f.BlockMode {
+ s.f.lock.RLock()
+ defer s.f.lock.RUnlock()
+ }
+
+ for _, k := range s.keys {
+ if value == k.value {
+ return true
+ }
+ }
+ return false
+}
+
+// Key assumes named Key exists in section and returns a zero-value when not.
+func (s *Section) Key(name string) *Key {
+ key, err := s.GetKey(name)
+ if err != nil {
+ // It's OK here because the only possible error is empty key name,
+ // but if it's empty, this piece of code won't be executed.
+ key, _ = s.NewKey(name, "")
+ return key
+ }
+ return key
+}
+
+// Keys returns list of keys of section.
+func (s *Section) Keys() []*Key {
+ keys := make([]*Key, len(s.keyList))
+ for i := range s.keyList {
+ keys[i] = s.Key(s.keyList[i])
+ }
+ return keys
+}
+
+// ParentKeys returns list of keys of parent section.
+func (s *Section) ParentKeys() []*Key {
+ var parentKeys []*Key
+ sname := s.name
+ for {
+ if i := strings.LastIndex(sname, "."); i > -1 {
+ sname = sname[:i]
+ sec, err := s.f.GetSection(sname)
+ if err != nil {
+ continue
+ }
+ parentKeys = append(parentKeys, sec.Keys()...)
+ } else {
+ break
+ }
+
+ }
+ return parentKeys
+}
+
+// KeyStrings returns list of key names of section.
+func (s *Section) KeyStrings() []string {
+ list := make([]string, len(s.keyList))
+ copy(list, s.keyList)
+ return list
+}
+
+// KeysHash returns keys hash consisting of names and values.
+func (s *Section) KeysHash() map[string]string {
+ if s.f.BlockMode {
+ s.f.lock.RLock()
+ defer s.f.lock.RUnlock()
+ }
+
+ hash := map[string]string{}
+ for key, value := range s.keysHash {
+ hash[key] = value
+ }
+ return hash
+}
+
+// DeleteKey deletes a key from section.
+func (s *Section) DeleteKey(name string) {
+ if s.f.BlockMode {
+ s.f.lock.Lock()
+ defer s.f.lock.Unlock()
+ }
+
+ for i, k := range s.keyList {
+ if k == name {
+ s.keyList = append(s.keyList[:i], s.keyList[i+1:]...)
+ delete(s.keys, name)
+ return
+ }
+ }
+}
+
+// ChildSections returns a list of child sections of current section.
+// For example, "[parent.child1]" and "[parent.child12]" are child sections
+// of section "[parent]".
+func (s *Section) ChildSections() []*Section {
+ prefix := s.name + "."
+ children := make([]*Section, 0, 3)
+ for _, name := range s.f.sectionList {
+ if strings.HasPrefix(name, prefix) {
+ children = append(children, s.f.sections[name])
+ }
+ }
+ return children
+}
diff --git a/vendor/gopkg.in/ini.v1/struct.go b/vendor/gopkg.in/ini.v1/struct.go
new file mode 100644
index 0000000..9719dc6
--- /dev/null
+++ b/vendor/gopkg.in/ini.v1/struct.go
@@ -0,0 +1,512 @@
+// Copyright 2014 Unknwon
+//
+// Licensed under the Apache License, Version 2.0 (the "License"): you may
+// not use this file except in compliance with the License. You may obtain
+// a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+
+package ini
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "reflect"
+ "strings"
+ "time"
+ "unicode"
+)
+
+// NameMapper represents a ini tag name mapper.
+type NameMapper func(string) string
+
+// Built-in name getters.
+var (
+ // AllCapsUnderscore converts to format ALL_CAPS_UNDERSCORE.
+ AllCapsUnderscore NameMapper = func(raw string) string {
+ newstr := make([]rune, 0, len(raw))
+ for i, chr := range raw {
+ if isUpper := 'A' <= chr && chr <= 'Z'; isUpper {
+ if i > 0 {
+ newstr = append(newstr, '_')
+ }
+ }
+ newstr = append(newstr, unicode.ToUpper(chr))
+ }
+ return string(newstr)
+ }
+ // TitleUnderscore converts to format title_underscore.
+ TitleUnderscore NameMapper = func(raw string) string {
+ newstr := make([]rune, 0, len(raw))
+ for i, chr := range raw {
+ if isUpper := 'A' <= chr && chr <= 'Z'; isUpper {
+ if i > 0 {
+ newstr = append(newstr, '_')
+ }
+ chr -= ('A' - 'a')
+ }
+ newstr = append(newstr, chr)
+ }
+ return string(newstr)
+ }
+)
+
+func (s *Section) parseFieldName(raw, actual string) string {
+ if len(actual) > 0 {
+ return actual
+ }
+ if s.f.NameMapper != nil {
+ return s.f.NameMapper(raw)
+ }
+ return raw
+}
+
+func parseDelim(actual string) string {
+ if len(actual) > 0 {
+ return actual
+ }
+ return ","
+}
+
+var reflectTime = reflect.TypeOf(time.Now()).Kind()
+
+// setSliceWithProperType sets proper values to slice based on its type.
+func setSliceWithProperType(key *Key, field reflect.Value, delim string, allowShadow, isStrict bool) error {
+ var strs []string
+ if allowShadow {
+ strs = key.StringsWithShadows(delim)
+ } else {
+ strs = key.Strings(delim)
+ }
+
+ numVals := len(strs)
+ if numVals == 0 {
+ return nil
+ }
+
+ var vals interface{}
+ var err error
+
+ sliceOf := field.Type().Elem().Kind()
+ switch sliceOf {
+ case reflect.String:
+ vals = strs
+ case reflect.Int:
+ vals, err = key.parseInts(strs, true, false)
+ case reflect.Int64:
+ vals, err = key.parseInt64s(strs, true, false)
+ case reflect.Uint:
+ vals, err = key.parseUints(strs, true, false)
+ case reflect.Uint64:
+ vals, err = key.parseUint64s(strs, true, false)
+ case reflect.Float64:
+ vals, err = key.parseFloat64s(strs, true, false)
+ case reflectTime:
+ vals, err = key.parseTimesFormat(time.RFC3339, strs, true, false)
+ default:
+ return fmt.Errorf("unsupported type '[]%s'", sliceOf)
+ }
+ if err != nil && isStrict {
+ return err
+ }
+
+ slice := reflect.MakeSlice(field.Type(), numVals, numVals)
+ for i := 0; i < numVals; i++ {
+ switch sliceOf {
+ case reflect.String:
+ slice.Index(i).Set(reflect.ValueOf(vals.([]string)[i]))
+ case reflect.Int:
+ slice.Index(i).Set(reflect.ValueOf(vals.([]int)[i]))
+ case reflect.Int64:
+ slice.Index(i).Set(reflect.ValueOf(vals.([]int64)[i]))
+ case reflect.Uint:
+ slice.Index(i).Set(reflect.ValueOf(vals.([]uint)[i]))
+ case reflect.Uint64:
+ slice.Index(i).Set(reflect.ValueOf(vals.([]uint64)[i]))
+ case reflect.Float64:
+ slice.Index(i).Set(reflect.ValueOf(vals.([]float64)[i]))
+ case reflectTime:
+ slice.Index(i).Set(reflect.ValueOf(vals.([]time.Time)[i]))
+ }
+ }
+ field.Set(slice)
+ return nil
+}
+
+func wrapStrictError(err error, isStrict bool) error {
+ if isStrict {
+ return err
+ }
+ return nil
+}
+
+// setWithProperType sets proper value to field based on its type,
+// but it does not return error for failing parsing,
+// because we want to use default value that is already assigned to strcut.
+func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string, allowShadow, isStrict bool) error {
+ switch t.Kind() {
+ case reflect.String:
+ if len(key.String()) == 0 {
+ return nil
+ }
+ field.SetString(key.String())
+ case reflect.Bool:
+ boolVal, err := key.Bool()
+ if err != nil {
+ return wrapStrictError(err, isStrict)
+ }
+ field.SetBool(boolVal)
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ durationVal, err := key.Duration()
+ // Skip zero value
+ if err == nil && int64(durationVal) > 0 {
+ field.Set(reflect.ValueOf(durationVal))
+ return nil
+ }
+
+ intVal, err := key.Int64()
+ if err != nil {
+ return wrapStrictError(err, isStrict)
+ }
+ field.SetInt(intVal)
+ // byte is an alias for uint8, so supporting uint8 breaks support for byte
+ case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
+ durationVal, err := key.Duration()
+ // Skip zero value
+ if err == nil && int(durationVal) > 0 {
+ field.Set(reflect.ValueOf(durationVal))
+ return nil
+ }
+
+ uintVal, err := key.Uint64()
+ if err != nil {
+ return wrapStrictError(err, isStrict)
+ }
+ field.SetUint(uintVal)
+
+ case reflect.Float32, reflect.Float64:
+ floatVal, err := key.Float64()
+ if err != nil {
+ return wrapStrictError(err, isStrict)
+ }
+ field.SetFloat(floatVal)
+ case reflectTime:
+ timeVal, err := key.Time()
+ if err != nil {
+ return wrapStrictError(err, isStrict)
+ }
+ field.Set(reflect.ValueOf(timeVal))
+ case reflect.Slice:
+ return setSliceWithProperType(key, field, delim, allowShadow, isStrict)
+ default:
+ return fmt.Errorf("unsupported type '%s'", t)
+ }
+ return nil
+}
+
+func parseTagOptions(tag string) (rawName string, omitEmpty bool, allowShadow bool) {
+ opts := strings.SplitN(tag, ",", 3)
+ rawName = opts[0]
+ if len(opts) > 1 {
+ omitEmpty = opts[1] == "omitempty"
+ }
+ if len(opts) > 2 {
+ allowShadow = opts[2] == "allowshadow"
+ }
+ return rawName, omitEmpty, allowShadow
+}
+
+func (s *Section) mapTo(val reflect.Value, isStrict bool) error {
+ if val.Kind() == reflect.Ptr {
+ val = val.Elem()
+ }
+ typ := val.Type()
+
+ for i := 0; i < typ.NumField(); i++ {
+ field := val.Field(i)
+ tpField := typ.Field(i)
+
+ tag := tpField.Tag.Get("ini")
+ if tag == "-" {
+ continue
+ }
+
+ rawName, _, allowShadow := parseTagOptions(tag)
+ fieldName := s.parseFieldName(tpField.Name, rawName)
+ if len(fieldName) == 0 || !field.CanSet() {
+ continue
+ }
+
+ isAnonymous := tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous
+ isStruct := tpField.Type.Kind() == reflect.Struct
+ if isAnonymous {
+ field.Set(reflect.New(tpField.Type.Elem()))
+ }
+
+ if isAnonymous || isStruct {
+ if sec, err := s.f.GetSection(fieldName); err == nil {
+ if err = sec.mapTo(field, isStrict); err != nil {
+ return fmt.Errorf("error mapping field(%s): %v", fieldName, err)
+ }
+ continue
+ }
+ }
+
+ if key, err := s.GetKey(fieldName); err == nil {
+ delim := parseDelim(tpField.Tag.Get("delim"))
+ if err = setWithProperType(tpField.Type, key, field, delim, allowShadow, isStrict); err != nil {
+ return fmt.Errorf("error mapping field(%s): %v", fieldName, err)
+ }
+ }
+ }
+ return nil
+}
+
+// MapTo maps section to given struct.
+func (s *Section) MapTo(v interface{}) error {
+ typ := reflect.TypeOf(v)
+ val := reflect.ValueOf(v)
+ if typ.Kind() == reflect.Ptr {
+ typ = typ.Elem()
+ val = val.Elem()
+ } else {
+ return errors.New("cannot map to non-pointer struct")
+ }
+
+ return s.mapTo(val, false)
+}
+
+// MapTo maps section to given struct in strict mode,
+// which returns all possible error including value parsing error.
+func (s *Section) StrictMapTo(v interface{}) error {
+ typ := reflect.TypeOf(v)
+ val := reflect.ValueOf(v)
+ if typ.Kind() == reflect.Ptr {
+ typ = typ.Elem()
+ val = val.Elem()
+ } else {
+ return errors.New("cannot map to non-pointer struct")
+ }
+
+ return s.mapTo(val, true)
+}
+
+// MapTo maps file to given struct.
+func (f *File) MapTo(v interface{}) error {
+ return f.Section("").MapTo(v)
+}
+
+// MapTo maps file to given struct in strict mode,
+// which returns all possible error including value parsing error.
+func (f *File) StrictMapTo(v interface{}) error {
+ return f.Section("").StrictMapTo(v)
+}
+
+// MapTo maps data sources to given struct with name mapper.
+func MapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error {
+ cfg, err := Load(source, others...)
+ if err != nil {
+ return err
+ }
+ cfg.NameMapper = mapper
+ return cfg.MapTo(v)
+}
+
+// StrictMapToWithMapper maps data sources to given struct with name mapper in strict mode,
+// which returns all possible error including value parsing error.
+func StrictMapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error {
+ cfg, err := Load(source, others...)
+ if err != nil {
+ return err
+ }
+ cfg.NameMapper = mapper
+ return cfg.StrictMapTo(v)
+}
+
+// MapTo maps data sources to given struct.
+func MapTo(v, source interface{}, others ...interface{}) error {
+ return MapToWithMapper(v, nil, source, others...)
+}
+
+// StrictMapTo maps data sources to given struct in strict mode,
+// which returns all possible error including value parsing error.
+func StrictMapTo(v, source interface{}, others ...interface{}) error {
+ return StrictMapToWithMapper(v, nil, source, others...)
+}
+
+// reflectSliceWithProperType does the opposite thing as setSliceWithProperType.
+func reflectSliceWithProperType(key *Key, field reflect.Value, delim string) error {
+ slice := field.Slice(0, field.Len())
+ if field.Len() == 0 {
+ return nil
+ }
+
+ var buf bytes.Buffer
+ sliceOf := field.Type().Elem().Kind()
+ for i := 0; i < field.Len(); i++ {
+ switch sliceOf {
+ case reflect.String:
+ buf.WriteString(slice.Index(i).String())
+ case reflect.Int, reflect.Int64:
+ buf.WriteString(fmt.Sprint(slice.Index(i).Int()))
+ case reflect.Uint, reflect.Uint64:
+ buf.WriteString(fmt.Sprint(slice.Index(i).Uint()))
+ case reflect.Float64:
+ buf.WriteString(fmt.Sprint(slice.Index(i).Float()))
+ case reflectTime:
+ buf.WriteString(slice.Index(i).Interface().(time.Time).Format(time.RFC3339))
+ default:
+ return fmt.Errorf("unsupported type '[]%s'", sliceOf)
+ }
+ buf.WriteString(delim)
+ }
+ key.SetValue(buf.String()[:buf.Len()-1])
+ return nil
+}
+
+// reflectWithProperType does the opposite thing as setWithProperType.
+func reflectWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string) error {
+ switch t.Kind() {
+ case reflect.String:
+ key.SetValue(field.String())
+ case reflect.Bool:
+ key.SetValue(fmt.Sprint(field.Bool()))
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ key.SetValue(fmt.Sprint(field.Int()))
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
+ key.SetValue(fmt.Sprint(field.Uint()))
+ case reflect.Float32, reflect.Float64:
+ key.SetValue(fmt.Sprint(field.Float()))
+ case reflectTime:
+ key.SetValue(fmt.Sprint(field.Interface().(time.Time).Format(time.RFC3339)))
+ case reflect.Slice:
+ return reflectSliceWithProperType(key, field, delim)
+ default:
+ return fmt.Errorf("unsupported type '%s'", t)
+ }
+ return nil
+}
+
+// CR: copied from encoding/json/encode.go with modifications of time.Time support.
+// TODO: add more test coverage.
+func isEmptyValue(v reflect.Value) bool {
+ switch v.Kind() {
+ case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
+ return v.Len() == 0
+ case reflect.Bool:
+ return !v.Bool()
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ return v.Int() == 0
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
+ return v.Uint() == 0
+ case reflect.Float32, reflect.Float64:
+ return v.Float() == 0
+ case reflect.Interface, reflect.Ptr:
+ return v.IsNil()
+ case reflectTime:
+ t, ok := v.Interface().(time.Time)
+ return ok && t.IsZero()
+ }
+ return false
+}
+
+func (s *Section) reflectFrom(val reflect.Value) error {
+ if val.Kind() == reflect.Ptr {
+ val = val.Elem()
+ }
+ typ := val.Type()
+
+ for i := 0; i < typ.NumField(); i++ {
+ field := val.Field(i)
+ tpField := typ.Field(i)
+
+ tag := tpField.Tag.Get("ini")
+ if tag == "-" {
+ continue
+ }
+
+ opts := strings.SplitN(tag, ",", 2)
+ if len(opts) == 2 && opts[1] == "omitempty" && isEmptyValue(field) {
+ continue
+ }
+
+ fieldName := s.parseFieldName(tpField.Name, opts[0])
+ if len(fieldName) == 0 || !field.CanSet() {
+ continue
+ }
+
+ if (tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous) ||
+ (tpField.Type.Kind() == reflect.Struct && tpField.Type.Name() != "Time") {
+ // Note: The only error here is section doesn't exist.
+ sec, err := s.f.GetSection(fieldName)
+ if err != nil {
+ // Note: fieldName can never be empty here, ignore error.
+ sec, _ = s.f.NewSection(fieldName)
+ }
+
+ // Add comment from comment tag
+ if len(sec.Comment) == 0 {
+ sec.Comment = tpField.Tag.Get("comment")
+ }
+
+ if err = sec.reflectFrom(field); err != nil {
+ return fmt.Errorf("error reflecting field (%s): %v", fieldName, err)
+ }
+ continue
+ }
+
+ // Note: Same reason as secion.
+ key, err := s.GetKey(fieldName)
+ if err != nil {
+ key, _ = s.NewKey(fieldName, "")
+ }
+
+ // Add comment from comment tag
+ if len(key.Comment) == 0 {
+ key.Comment = tpField.Tag.Get("comment")
+ }
+
+ if err = reflectWithProperType(tpField.Type, key, field, parseDelim(tpField.Tag.Get("delim"))); err != nil {
+ return fmt.Errorf("error reflecting field (%s): %v", fieldName, err)
+ }
+
+ }
+ return nil
+}
+
+// ReflectFrom reflects secion from given struct.
+func (s *Section) ReflectFrom(v interface{}) error {
+ typ := reflect.TypeOf(v)
+ val := reflect.ValueOf(v)
+ if typ.Kind() == reflect.Ptr {
+ typ = typ.Elem()
+ val = val.Elem()
+ } else {
+ return errors.New("cannot reflect from non-pointer struct")
+ }
+
+ return s.reflectFrom(val)
+}
+
+// ReflectFrom reflects file from given struct.
+func (f *File) ReflectFrom(v interface{}) error {
+ return f.Section("").ReflectFrom(v)
+}
+
+// ReflectFrom reflects data sources from given struct with name mapper.
+func ReflectFromWithMapper(cfg *File, v interface{}, mapper NameMapper) error {
+ cfg.NameMapper = mapper
+ return cfg.ReflectFrom(v)
+}
+
+// ReflectFrom reflects data sources from given struct.
+func ReflectFrom(cfg *File, v interface{}) error {
+ return ReflectFromWithMapper(cfg, v, nil)
+}
--
To stop receiving notification emails like this one, please contact
rohit@apache.org.
[cloudstack-cloudmonkey] 03/04: about: add separate go file for cli
name, version
Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rohit pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/cloudstack-cloudmonkey.git
commit 86b9e4a347a6f56c62af6ec98765a0c900884f47
Author: Rohit Yadav <ro...@apache.org>
AuthorDate: Sat Apr 14 03:25:06 2018 +0530
about: add separate go file for cli name, version
Signed-off-by: Rohit Yadav <ro...@apache.org>
---
cmd/version.go | 2 +-
config/about.go | 33 +++++++++++++++++++++++++++++++++
2 files changed, 34 insertions(+), 1 deletion(-)
diff --git a/cmd/version.go b/cmd/version.go
index 72fde90..c07c1d7 100644
--- a/cmd/version.go
+++ b/cmd/version.go
@@ -24,7 +24,7 @@ func init() {
Name: "version",
Help: "Version info",
Handle: func(r *Request) error {
- fmt.Println("Apache CloudStack 🐵 cloudmonkey", r.Config.Version())
+ fmt.Println(r.Config.Name(), r.Config.Version())
return nil
},
})
diff --git a/config/about.go b/config/about.go
index d912156..0d59518 100644
--- a/config/about.go
+++ b/config/about.go
@@ -1 +1,34 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
package config
+
+import "fmt"
+
+func (c *Config) Name() string {
+ return "Apache CloudStack 🐵 cloudmonkey"
+}
+
+func (c *Config) Version() string {
+ return "6.0.0-alpha1"
+}
+
+func (c *Config) PrintHeader() {
+ fmt.Println(c.Name(), c.Version())
+ fmt.Println("Type \"help\" for details, \"sync\" to update API cache or press tab to list commands")
+ fmt.Println()
+}
--
To stop receiving notification emails like this one, please contact
rohit@apache.org.
[cloudstack-cloudmonkey] 02/04: config: implement ini based config
same as legacy cloudmonkey
Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rohit pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/cloudstack-cloudmonkey.git
commit ed77ec07d952c49d987a26a3c3d355bcaf00233b
Author: Rohit Yadav <ro...@apache.org>
AuthorDate: Sat Apr 14 03:24:27 2018 +0530
config: implement ini based config same as legacy cloudmonkey
Signed-off-by: Rohit Yadav <ro...@apache.org>
---
cli/completer.go | 2 +-
cli/selector.go | 2 +-
cli/shell.go | 3 +
cmd/network.go | 6 +-
config/about.go | 1 +
config/config.go | 211 +++++++++++++++++++++++++++++++++++--------------------
6 files changed, 144 insertions(+), 81 deletions(-)
diff --git a/cli/completer.go b/cli/completer.go
index 9cd9a04..58ff60b 100644
--- a/cli/completer.go
+++ b/cli/completer.go
@@ -188,7 +188,7 @@ func (t *CliCompleter) Do(line []rune, pos int) (options [][]rune, offset int) {
return nil, 0
}
- r := cmd.NewRequest(nil, config.NewConfig(), nil, nil)
+ r := cmd.NewRequest(nil, shellConfig, nil, nil)
autocompleteApiArgs := []string{"listall=true"}
if autocompleteApi.Noun == "templates" {
autocompleteApiArgs = append(autocompleteApiArgs, "templatefilter=all")
diff --git a/cli/selector.go b/cli/selector.go
index 0f0b998..27e03b2 100644
--- a/cli/selector.go
+++ b/cli/selector.go
@@ -21,8 +21,8 @@ import (
"fmt"
"strings"
- "github.com/manifoldco/promptui"
"github.com/chzyer/readline"
+ "github.com/manifoldco/promptui"
)
type SelectOption struct {
diff --git a/cli/shell.go b/cli/shell.go
index f8fc031..1dfc075 100644
--- a/cli/shell.go
+++ b/cli/shell.go
@@ -28,7 +28,10 @@ import (
"github.com/chzyer/readline"
)
+var shellConfig *config.Config
+
func ExecShell(cfg *config.Config) {
+ shellConfig = cfg
shell, err := readline.NewEx(&readline.Config{
Prompt: cfg.GetPrompt(),
HistoryFile: cfg.HistoryFile,
diff --git a/cmd/network.go b/cmd/network.go
index 6ff7d7c..94f67ad 100644
--- a/cmd/network.go
+++ b/cmd/network.go
@@ -66,8 +66,8 @@ func NewAPIRequest(r *Request, api string, args []string) (map[string]interface{
}
}
- apiKey := r.Config.ActiveProfile.ApiKey
- secretKey := r.Config.ActiveProfile.SecretKey
+ apiKey := r.Config.Core.ActiveProfile.ApiKey
+ secretKey := r.Config.Core.ActiveProfile.SecretKey
if len(apiKey) > 0 {
params.Add("apiKey", apiKey)
@@ -81,7 +81,7 @@ func NewAPIRequest(r *Request, api string, args []string) (map[string]interface{
signature := base64.StdEncoding.EncodeToString(mac.Sum(nil))
encodedParams = encodedParams + fmt.Sprintf("&signature=%s", url.QueryEscape(signature))
- apiUrl := fmt.Sprintf("%s?%s", r.Config.ActiveProfile.Url, encodedParams)
+ apiUrl := fmt.Sprintf("%s?%s", r.Config.Core.ActiveProfile.Url, encodedParams)
//fmt.Println("[debug] Requesting: ", apiUrl)
response, err := http.Get(apiUrl)
diff --git a/config/about.go b/config/about.go
new file mode 100644
index 0000000..d912156
--- /dev/null
+++ b/config/about.go
@@ -0,0 +1 @@
+package config
diff --git a/config/config.go b/config/config.go
index 9122ec8..b89cc54 100644
--- a/config/config.go
+++ b/config/config.go
@@ -19,56 +19,54 @@ package config
import (
"fmt"
- homedir "github.com/mitchellh/go-homedir"
+ "github.com/mitchellh/go-homedir"
+ "gopkg.in/ini.v1"
"os"
"path"
+ "strconv"
)
-var name = "cloudmonkey"
-var version = "6.0.0-alpha1"
-
-func getDefaultConfigDir() string {
- home, err := homedir.Dir()
- if err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
- return path.Join(home, ".cmk")
-}
-
-type OutputFormat string
-
const (
- Json OutputFormat = "json"
- Xml OutputFormat = "xml"
- Table OutputFormat = "table"
- Text OutputFormat = "text"
+ Json = "json"
+ Xml = "xml"
+ Table = "table"
+ Text = "text"
)
-type Profile struct {
- Name string
- Url string
- VerifyCert bool
- Username string
- Password string
- Domain string
- ApiKey string
- SecretKey string
+type ServerProfile struct {
+ Url string `ini:"url"`
+ Username string `ini:"username"`
+ Password string `ini:"password"`
+ Domain string `ini:"domain"`
+ ApiKey string `ini:"apikey"`
+ SecretKey string `ini:"secretkey"`
+ VerifyCert bool `ini:"verifycert"`
+}
+
+type Core struct {
+ AsyncBlock bool `ini:"asyncblock"`
+ Timeout int `ini:"timeout"`
+ Output string `ini:"output"`
+ ProfileName string `ini:"profile"`
+ ActiveProfile *ServerProfile `ini:"-"`
}
type Config struct {
- Dir string
- ConfigFile string
- HistoryFile string
- CacheFile string
- LogFile string
- Output OutputFormat
- AsyncBlock bool
- ActiveProfile Profile
+ Dir string
+ ConfigFile string
+ HistoryFile string
+ CacheFile string
+ LogFile string
+ Core *Core
}
-func NewConfig() *Config {
- return loadConfig()
+func getDefaultConfigDir() string {
+ home, err := homedir.Dir()
+ if err != nil {
+ fmt.Println(err)
+ os.Exit(1)
+ }
+ return path.Join(home, ".cmk")
}
func defaultConfig() *Config {
@@ -76,58 +74,86 @@ func defaultConfig() *Config {
return &Config{
Dir: configDir,
ConfigFile: path.Join(configDir, "config"),
- HistoryFile: path.Join(configDir, "history"),
CacheFile: path.Join(configDir, "cache"),
+ HistoryFile: path.Join(configDir, "history"),
LogFile: path.Join(configDir, "log"),
- Output: Json,
- AsyncBlock: true,
- ActiveProfile: Profile{
- Name: "local",
- Url: "http://192.168.1.10:8080/client/api",
- VerifyCert: false,
- Username: "admin",
- Password: "password",
- Domain: "/",
- // TODO: remove test data
- ApiKey: "IgrUOA_46IVoBNzAR_Th2JbdbgIs2lMW1kGe9A80F9X0uOnfGO0Su23IqOSqbdzZW3To95PNrcdWsk60ieXYBQ",
- SecretKey: "E7NRSv5d_1VhqXUHJEqvAsm7htR_V_vtPJZsCPkgPKSgkiS3sh4SOrIqMm_eWhSFoL6RHRIlxtA_viQAt7EDVA",
+ Core: &Core{
+ AsyncBlock: false,
+ Timeout: 1800,
+ Output: Json,
+ ProfileName: "local",
+ ActiveProfile: &ServerProfile{
+ Url: "http://localhost:8080/client/api",
+ Username: "admin",
+ Password: "password",
+ Domain: "/",
+ ApiKey: "",
+ SecretKey: "",
+ VerifyCert: false,
+ },
},
}
}
-func loadConfig() *Config {
- cfg := defaultConfig()
+func reloadConfig(cfg *Config) *Config {
if _, err := os.Stat(cfg.Dir); err != nil {
os.Mkdir(cfg.Dir, 0700)
}
+ // Save on missing config
if _, err := os.Stat(cfg.ConfigFile); err != nil {
- // FIXME: write default cfg
- } else {
- //load config?
+ defaultConf := defaultConfig()
+ conf := ini.Empty()
+ conf.Section(ini.DEFAULT_SECTION).ReflectFrom(defaultConf.Core)
+ conf.Section(cfg.Core.ProfileName).ReflectFrom(defaultConf.Core.ActiveProfile)
+ conf.SaveTo(cfg.ConfigFile)
}
- LoadCache(cfg)
-
- return cfg
-}
+ // Read config
+ conf, err := ini.LoadSources(ini.LoadOptions{
+ IgnoreInlineComment: true,
+ }, cfg.ConfigFile)
-func (c *Config) Name() string {
- return name
-}
+ if err != nil {
+ fmt.Printf("Fail to read config file: %v", err)
+ os.Exit(1)
+ }
-func (c *Config) Version() string {
- return version
-}
+ core, err := conf.GetSection(ini.DEFAULT_SECTION)
+ if core == nil {
+ section, _ := conf.NewSection(ini.DEFAULT_SECTION)
+ section.ReflectFrom(&defaultConfig().Core)
+ } else {
+ // Write
+ if cfg.Core != nil {
+ conf.Section(ini.DEFAULT_SECTION).ReflectFrom(&cfg.Core)
+ }
+ // Update
+ core := new(Core)
+ conf.Section(ini.DEFAULT_SECTION).MapTo(core)
+ cfg.Core = core
+ }
-func (c *Config) PrintHeader() {
- fmt.Printf("Apache CloudStack 🐵 cloudmonkey %s.\n", version)
- fmt.Printf("Type \"help\" for details, \"sync\" to update API cache or press tab to list commands.\n\n")
-}
+ profile, err := conf.GetSection(cfg.Core.ProfileName)
+ if profile == nil {
+ section, _ := conf.NewSection(cfg.Core.ProfileName)
+ section.ReflectFrom(&defaultConfig().Core.ActiveProfile)
+ } else {
+ // Write
+ if cfg.Core.ActiveProfile != nil {
+ conf.Section(cfg.Core.ProfileName).ReflectFrom(&cfg.Core.ActiveProfile)
+ }
+ // Update
+ profile := new(ServerProfile)
+ conf.Section(cfg.Core.ProfileName).MapTo(profile)
+ cfg.Core.ActiveProfile = profile
+ }
+ // Save
+ conf.SaveTo(cfg.ConfigFile)
-func (c *Config) GetPrompt() string {
- return fmt.Sprintf("(%s) 🐒 > ", c.ActiveProfile.Name)
+ fmt.Println("Updating config to:", cfg.Core, cfg.Core.ActiveProfile)
+ return cfg
}
func (c *Config) UpdateGlobalConfig(key string, value string) {
@@ -135,9 +161,42 @@ func (c *Config) UpdateGlobalConfig(key string, value string) {
}
func (c *Config) UpdateConfig(namespace string, key string, value string) {
- fmt.Println("👌 Updating for key", key, ", value=", value, ", in ns=", namespace)
- if key == "profile" {
- //FIXME
- c.ActiveProfile.Name = value
+ switch key {
+ case "asyncblock":
+ c.Core.AsyncBlock = value == "true"
+ case "output":
+ c.Core.Output = value
+ case "timeout":
+ intValue, _ := strconv.Atoi(value)
+ c.Core.Timeout = intValue
+ case "profile":
+ c.Core.ProfileName = value
+ c.Core.ActiveProfile = nil
+ case "url":
+ c.Core.ActiveProfile.Url = value
+ case "username":
+ c.Core.ActiveProfile.Username = value
+ case "password":
+ c.Core.ActiveProfile.Password = value
+ case "domain":
+ c.Core.ActiveProfile.Domain = value
+ case "apikey":
+ c.Core.ActiveProfile.ApiKey = value
+ case "secretkey":
+ c.Core.ActiveProfile.SecretKey = value
+ case "verifycert":
+ c.Core.ActiveProfile.VerifyCert = value == "true"
+ default:
+ return
}
+
+ reloadConfig(c)
+}
+
+func NewConfig() *Config {
+ defaultConf := defaultConfig()
+ defaultConf.Core = nil
+ cfg := reloadConfig(defaultConf)
+ LoadCache(cfg)
+ return cfg
}
--
To stop receiving notification emails like this one, please contact
rohit@apache.org.
[cloudstack-cloudmonkey] 04/04: prompt: emoji-roulette on new shell
Posted by ro...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
rohit pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/cloudstack-cloudmonkey.git
commit 88fcf8fe17735eb8a29613f228960815c189550b
Author: Rohit Yadav <ro...@apache.org>
AuthorDate: Sat Apr 14 03:35:58 2018 +0530
prompt: emoji-roulette on new shell
Signed-off-by: Rohit Yadav <ro...@apache.org>
---
cli/shell.go | 1 +
config/config.go | 2 --
config/prompt.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 49 insertions(+), 2 deletions(-)
diff --git a/cli/shell.go b/cli/shell.go
index 1dfc075..903a607 100644
--- a/cli/shell.go
+++ b/cli/shell.go
@@ -57,6 +57,7 @@ func ExecShell(cfg *config.Config) {
cfg.PrintHeader()
for {
+ shell.SetPrompt(cfg.GetPrompt())
line, err := shell.Readline()
if err == readline.ErrInterrupt {
continue
diff --git a/config/config.go b/config/config.go
index b89cc54..e5336e5 100644
--- a/config/config.go
+++ b/config/config.go
@@ -151,8 +151,6 @@ func reloadConfig(cfg *Config) *Config {
}
// Save
conf.SaveTo(cfg.ConfigFile)
-
- fmt.Println("Updating config to:", cfg.Core, cfg.Core.ActiveProfile)
return cfg
}
diff --git a/config/prompt.go b/config/prompt.go
new file mode 100644
index 0000000..ea8dd82
--- /dev/null
+++ b/config/prompt.go
@@ -0,0 +1,48 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package config
+
+import (
+ "fmt"
+ "math/rand"
+ "runtime"
+ "strings"
+ "time"
+)
+
+var emojis []string
+
+func init() {
+ rand.Seed(time.Now().Unix())
+ emojis = strings.Split("🐶 🐹 🐰 🐻 🐼 🐨 🐯 🦁 🐷 🐙 🙈 🙉 🙊 🐒 🐔 🐧 🐦 🐤 🐣 🐥 🐺 🐗 🐴 🦄 🐝 🐛 🐌 🐞 🐜 🕷 🦂 🦀 🐍 🐢 🐠 🐟 🐡 🐬 🐳 🐋 🐅 🐃 🐂 🐄 🐘 🐐 🐑 🐎 🐖 🐀 🐓 🦃 🕊 🐕 🐩 🐈 🐇 🐿 🐲 🌵 🦍 🦊 🦌 🦏 🦇 🦅 🦆 🦉 🦈 🦐 🦑 🦋 🌴 🍀 🍂 🍁 🍄 🌍 ⛅️", " ")
+}
+
+func emoji() string {
+ return emojis[rand.Intn(len(emojis)-1)]
+}
+
+func promptMoji() string {
+ if runtime.GOOS == "windows" {
+ return "cmk"
+ }
+ return emoji() // 🐒
+}
+
+func (c *Config) GetPrompt() string {
+ return fmt.Sprintf("(%s) %s > ", c.Core.ProfileName, promptMoji())
+}
--
To stop receiving notification emails like this one, please contact
rohit@apache.org.