diff --git a/CMDREF.md b/CMDREF.md index 508f2dea..17c4d460 100644 --- a/CMDREF.md +++ b/CMDREF.md @@ -33,6 +33,9 @@ Command This is shortcut of: volt profile rm -current {repository} [{repository2} ...] + edit [-e|--editor {editor}] {repository} [{repository2} ...] + Open the plugconf file(s) of one or more {repository} for editing. + profile set {name} Set profile name @@ -112,6 +115,23 @@ Description volt profile rm {current profile} {repository} [{repository2} ...] ``` +# volt edit + +``` +Usage + volt edit [-help] [-e|--editor {editor}] {repository} [{repository2} ...] + +Quick example + $ volt edit tyru/caw.vim # will open the plugconf file for tyru/caw.vim for editing + +Description + Open the plugconf file(s) of one or more {repository} for editing. + + If the -e option was given, use the given editor for editing those files (unless it cannot be found) + + It also calls "volt build" afterwards if modifications were made to the plugconf file(s). +``` + # volt enable ``` diff --git a/Gopkg.lock b/Gopkg.lock index 9a060c1b..ca87bfdb 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -78,6 +78,14 @@ pruneopts = "" revision = "b8bc1bf767474819792c23f32d8286a45736f1c6" +[[projects]] + digest = "1:7365acd48986e205ccb8652cc746f09c8b7876030d53710ea6ef7d0bd0dcd7ca" + name = "github.com/pkg/errors" + packages = ["."] + pruneopts = "" + revision = "645ef00459ed84a119197bfb8d8205042c6df63d" + version = "v0.8.0" + [[projects]] branch = "master" digest = "1:3962f553b77bf6c03fc07cd687a22dd3b00fe11aa14d31194f5505f5bb65cdc8" @@ -235,6 +243,7 @@ "github.com/haya14busa/go-vimlparser/ast", "github.com/haya14busa/go-vimlparser/token", "github.com/mattn/go-colorable", + "github.com/pkg/errors", "gopkg.in/src-d/go-git.v4", "gopkg.in/src-d/go-git.v4/plumbing", "gopkg.in/src-d/go-git.v4/plumbing/object", diff --git a/Makefile b/Makefile index 5335e30a..58889afe 100644 --- a/Makefile +++ b/Makefile @@ -18,12 +18,6 @@ precompile: go build -a -i -o $(BIN_DIR)/$(NAME) rm $(BIN_DIR)/$(NAME) -install-dep: - [ -x bin/dep ] || go build -o bin/dep github.com/golang/dep/cmd/dep - -dep-ensure: install-dep - bin/dep ensure -v - test: make go test -v -race -parallel 3 ./... @@ -38,11 +32,11 @@ release: $(BIN_DIR)/$(NAME) exe=$$exe.exe; \ fi; \ echo "Creating $$exe ... (os=$$os, arch=$$arch)"; \ - GOOS=$$os GOARCH=$$arch GO111MODULE=off go build -tags netgo -installsuffix netgo -ldflags "$(RELEASE_LDFLAGS)" -o $$exe; \ + GOOS=$$os GOARCH=$$arch go build -tags netgo -installsuffix netgo -ldflags "$(RELEASE_LDFLAGS)" -o $$exe; \ done; \ done update-doc: all go run _scripts/update-cmdref.go >CMDREF.md -.PHONY: all precompile install-dep dep-ensure test release update-doc +.PHONY: all precompile test release update-doc diff --git a/README.md b/README.md index e43552c3..74df4501 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,13 @@ create_skeleton_plugconf = true # installed, it tries to execute "git clone" or "git pull" as a fallback # * false: "volt get" or "volt get -u" won't try to execute fallback commands fallback_git_cmd = true + +[edit] +# If you ever wanted to use emacs to edit your vim plugin config, you can +# do so with the following. If not specified, volt will try to use +# vim/nvim, $VISUAL, sensible-editor, or $EDITOR in this order until a usable +# one is found. +editor = "emacs" ``` ## Features @@ -228,8 +235,10 @@ For example, [tyru/open-browser-github.vim](https://github.com/tyru/open-browser Some special functions can be defined in plugconf file: -* `s:config()` - * Plugin configuration +* `s:on_load_pre()` + * Plugin configuration to be executed before a plugin is loaded +* `s:on_load_post()` + * Plugin configuration to be executed after a plugin is loaded * `s:loaded_on()` (optional) * Return value: String (when to load a plugin by `:packadd`) * This function specifies when to load a plugin by `:packadd` @@ -247,7 +256,8 @@ An example config of [tyru/open-browser-github.vim](https://github.com/tyru/open ```vim " Plugin configuration like the code written in vimrc. -function! s:config() +" This configuration is executed *before* a plugin is loaded. +function! s:on_load_pre() let g:openbrowser_github_always_use_commit_hash = 1 endfunction @@ -361,12 +371,7 @@ NOTE: If the path(s) exists, `$MYVIMRC` and `$MYGVIMRC` are set. So `:edit $MYVI This file is copied to `~/.vim/vimrc` and `~/.vim/gvimrc` with magic comment (shows error if existing vimrc/gvimrc files exist with no magic comment). -And you can enable/disable vimrc by `volt profile use` (or you can simply remove `$VOLTPATH/rc//vimrc.vim` file if you don't want vimrc for the profile). - -``` -$ volt profile use -current vimrc false # Disable installing vimrc on current profile -$ volt profile use default gvimrc true # Enable installing gvimrc on profile default -``` +And you can enable/disable vimrc by removing (or renaming) `$VOLTPATH/rc//vimrc.vim` file if you don't want vimrc for the profile. See `volt help profile` for more detailed information. diff --git a/_contrib/completion/bash b/_contrib/completion/bash index e8d60763..156beccd 100644 --- a/_contrib/completion/bash +++ b/_contrib/completion/bash @@ -26,7 +26,7 @@ this_plug() { volt list -f "{{ range .Profiles }}{{ if eq \"$1\" .Name }}{{ range .ReposPath }}{{ println . }}{{ end }}{{ end }}{{ end }}" | sed -E 's@^(www\.)?github\.com/@@' | sort -u } -CMDS="get rm list enable disable profile build migrate self-upgrade version" +CMDS="get rm list enable disable edit profile build migrate self-upgrade version" PROFILE_CMDS="set show list new destroy rename add rm" MIGRATE_CMDS="lockjson plugconf/config-func" @@ -53,7 +53,7 @@ _volt() { elif [[ "${first}" == "profile" && "${last}" == "profile" ]] ; then COMPREPLY=( $(compgen -W "${PROFILE_CMDS}" -- ${cur}) ) - elif [[ "${first}" =~ ^(rm|disable)$ ]] ; then + elif [[ "${first}" =~ ^(rm|disable|edit)$ ]] ; then local profile=$(get_profile) plugs=$(get_plugs "$profile" "this") COMPREPLY=( $(compgen -W "${plugs}" -- ${cur}) ) @@ -87,4 +87,10 @@ _volt() { fi return 0 } + +if [ -n "$ZSH_VERSION" ]; then + autoload bashcompinit + bashcompinit +fi + complete -F _volt volt diff --git a/_contrib/completion/zsh b/_contrib/completion/zsh new file mode 100644 index 00000000..7cb2f68e --- /dev/null +++ b/_contrib/completion/zsh @@ -0,0 +1,19 @@ +#compdef volt + +# zsh completion wrapper for volt +# +# Based on git and tig's zsh completion scripts. +# git: https://git-scm.com +# tig: https://jonas.github.io/tig +# +# Copy or symlink this script and bash completion script as '_volt' and +# 'volt-completion.bash' to any directory in '$fpath'. + + +_volt () { + local e + e=$(dirname ${funcsourcetrace[1]%:*})/volt-completion.bash + if [ -f $e ]; then + . $e + fi +} diff --git a/config/config.go b/config/config.go index fc8feedf..1b4880bf 100644 --- a/config/config.go +++ b/config/config.go @@ -1,9 +1,9 @@ package config import ( - "fmt" - "github.com/BurntSushi/toml" + "github.com/pkg/errors" + "github.com/vim-volt/volt/pathutil" ) @@ -12,6 +12,7 @@ type Config struct { Alias map[string][]string `toml:"alias"` Build configBuild `toml:"build"` Get configGet `toml:"get"` + Edit configEdit `toml:"edit"` } // configBuild is a config for 'volt build'. @@ -25,6 +26,11 @@ type configGet struct { FallbackGitCmd *bool `toml:"fallback_git_cmd"` } +// configEdit is a config for 'volt edit'. +type configEdit struct { + Editor string `toml:"editor"` +} + const ( // SymlinkBuilder creates symlinks when 'volt build'. SymlinkBuilder = "symlink" @@ -43,6 +49,9 @@ func initialConfigTOML() *Config { CreateSkeletonPlugconf: &trueValue, FallbackGitCmd: &falseValue, }, + Edit: configEdit{ + Editor: "", + }, } } @@ -76,11 +85,14 @@ func merge(cfg, initCfg *Config) { if cfg.Get.FallbackGitCmd == nil { cfg.Get.FallbackGitCmd = initCfg.Get.FallbackGitCmd } + if cfg.Edit.Editor == "" { + cfg.Edit.Editor = initCfg.Edit.Editor + } } func validate(cfg *Config) error { if cfg.Build.Strategy != "symlink" && cfg.Build.Strategy != "copy" { - return fmt.Errorf("build.strategy is %q: valid values are %q or %q", cfg.Build.Strategy, "symlink", "copy") + return errors.Errorf("build.strategy is %q: valid values are %q or %q", cfg.Build.Strategy, "symlink", "copy") } return nil } diff --git a/fileutil/copyfile_linux.go b/fileutil/copyfile_linux.go index e4247b1e..75f15f13 100644 --- a/fileutil/copyfile_linux.go +++ b/fileutil/copyfile_linux.go @@ -31,9 +31,10 @@ package fileutil import ( - "fmt" "os" "syscall" + + "github.com/pkg/errors" ) // CopyFile copies the contents of the file named src to the file named @@ -63,7 +64,7 @@ func CopyFile(src, dst string, buf []byte, perm os.FileMode) error { for { n, err := syscall.Sendfile(wfd, rfd, nil, readsize) if err != nil { - return fmt.Errorf("sendfile(%q, %q) failed: %s", src, dst, err.Error()) + return errors.Errorf("sendfile(%q, %q) failed: %s", src, dst, err.Error()) } written += int64(n) if written >= fi.Size() { @@ -72,7 +73,7 @@ func CopyFile(src, dst string, buf []byte, perm os.FileMode) error { } } else { if _, err := syscall.Sendfile(wfd, rfd, nil, int(fi.Size())); err != nil { - return fmt.Errorf("sendfile(%q, %q) failed: %s", src, dst, err.Error()) + return errors.Errorf("sendfile(%q, %q) failed: %s", src, dst, err.Error()) } } return nil diff --git a/gitutil/gitutil.go b/gitutil/gitutil.go index 77c6d8cd..a5443d14 100644 --- a/gitutil/gitutil.go +++ b/gitutil/gitutil.go @@ -1,10 +1,10 @@ package gitutil import ( - "errors" - "fmt" "regexp" + "github.com/pkg/errors" + "github.com/vim-volt/volt/pathutil" git "gopkg.in/src-d/go-git.v4" "gopkg.in/src-d/go-git.v4/plumbing" @@ -109,7 +109,7 @@ func GetUpstreamRemote(r *git.Repository) (string, error) { subsec := cfg.Raw.Section("branch").Subsection(branch[1]) remote := subsec.Option("remote") if remote == "" { - return "", fmt.Errorf("gitconfig 'branch.%s.remote' is not found", subsec.Name) + return "", errors.Errorf("gitconfig 'branch.%s.remote' is not found", subsec.Name) } return remote, nil } diff --git a/httputil/httputil.go b/httputil/httputil.go index 9ab03021..0398d76f 100644 --- a/httputil/httputil.go +++ b/httputil/httputil.go @@ -1,7 +1,7 @@ package httputil import ( - "errors" + "github.com/pkg/errors" "io" "io/ioutil" "net/http" diff --git a/internal/testutil/testutil.go b/internal/testutil/testutil.go index 0b474987..27c53b8d 100644 --- a/internal/testutil/testutil.go +++ b/internal/testutil/testutil.go @@ -1,8 +1,8 @@ package testutil import ( - "errors" "fmt" + "github.com/pkg/errors" "io/ioutil" "os" "os/exec" diff --git a/lockjson/lockjson.go b/lockjson/lockjson.go index 90899890..cf3dab90 100644 --- a/lockjson/lockjson.go +++ b/lockjson/lockjson.go @@ -2,13 +2,13 @@ package lockjson import ( "encoding/json" - "errors" - "fmt" "io/ioutil" "os" "path/filepath" "strconv" + "github.com/pkg/errors" + "github.com/vim-volt/volt/logger" "github.com/vim-volt/volt/pathutil" ) @@ -112,7 +112,7 @@ func read(doLog bool) (*LockJSON, error) { // Validate lock.json err = validate(&lockJSON) if err != nil { - return nil, errors.New("validation failed: lock.json: " + err.Error()) + return nil, errors.Wrap(err, "validation failed: lock.json") } return &lockJSON, nil @@ -120,11 +120,11 @@ func read(doLog bool) (*LockJSON, error) { func validate(lockJSON *LockJSON) error { if lockJSON.Version < 1 { - return fmt.Errorf("lock.json version is '%d' (must be 1 or greater)", lockJSON.Version) + return errors.Errorf("lock.json version is '%d' (must be 1 or greater)", lockJSON.Version) } // Validate if volt can manipulate lock.json of this version if lockJSON.Version > lockJSONVersion { - return fmt.Errorf("this lock.json version is '%d' which volt cannot recognize. please upgrade volt to process this file", lockJSON.Version) + return errors.Errorf("this lock.json version is '%d' which volt cannot recognize. please upgrade volt to process this file", lockJSON.Version) } // Validate if missing required keys exist diff --git a/pathutil/pathutil.go b/pathutil/pathutil.go index a48890cb..ee34755b 100644 --- a/pathutil/pathutil.go +++ b/pathutil/pathutil.go @@ -1,7 +1,7 @@ package pathutil import ( - "errors" + "github.com/pkg/errors" "os" "os/exec" "path/filepath" diff --git a/plugconf/plugconf.go b/plugconf/plugconf.go index 5966474d..3e5da799 100644 --- a/plugconf/plugconf.go +++ b/plugconf/plugconf.go @@ -3,7 +3,6 @@ package plugconf import ( "bytes" "encoding/json" - "errors" "fmt" "io/ioutil" "path" @@ -12,6 +11,8 @@ import ( "sort" "strings" + "github.com/pkg/errors" + multierror "github.com/hashicorp/go-multierror" "github.com/vim-volt/volt/httputil" "github.com/vim-volt/volt/lockjson" @@ -392,7 +393,7 @@ func ParsePlugconf(file *ast.File, src []byte, path string) (*ParsedInfo, *Parse } case isProhibitedFuncName(ident.Name): parseErr.merr = multierror.Append(parseErr.merr, - fmt.Errorf( + errors.Errorf( "'%s' is prohibited function name. please use other function name", ident.Name)) default: functions = append(functions, string(extractBody(fn, src))) @@ -684,12 +685,14 @@ endfunction } if vimrcPath != "" || gvimrcPath != "" { - buf.WriteString("\n\n") + buf.WriteString("\n") if vimrcPath != "" { + buf.WriteString("\n") vimrcPath = strings.Replace(vimrcPath, "'", "''", -1) buf.WriteString("let $MYVIMRC = '" + vimrcPath + "'") } if gvimrcPath != "" { + buf.WriteString("\n") gvimrcPath = strings.Replace(gvimrcPath, "'", "''", -1) buf.WriteString("let $MYGVIMRC = '" + gvimrcPath + "'") } @@ -845,39 +848,37 @@ func FetchPlugconfTemplate(reposPath pathutil.ReposPath) (*Template, error) { return &Template{content}, nil } -const skeletonPlugconfOnLoadPre = `function! s:on_load_pre() - " Plugin configuration like the code written in vimrc. - " This configuration is executed *before* a plugin is loaded. +const skeletonPlugconfOnLoadPre = `" Plugin configuration like the code written in vimrc. +" This configuration is executed *before* a plugin is loaded. +function! s:on_load_pre() endfunction` -const skeletonPlugconfOnLoadPost = `function! s:on_load_post() - " Plugin configuration like the code written in vimrc. - " This configuration is executed *after* a plugin is loaded. +const skeletonPlugconfOnLoadPost = `" Plugin configuration like the code written in vimrc. +" This configuration is executed *after* a plugin is loaded. +function! s:on_load_post() endfunction` -const skeletonPlugconfLoadOn = `function! s:loaded_on() - " This function determines when a plugin is loaded. - " - " Possible values are: - " * 'start' (a plugin will be loaded at VimEnter event) - " * 'filetype=' (a plugin will be loaded at FileType event) - " * 'excmd=' (a plugin will be loaded at CmdUndefined event) - " and can be multiple values separated by comma. - " - " This function must contain 'return ""' code. - " (the argument of :return must be string literal) - +const skeletonPlugconfLoadOn = `" This function determines when a plugin is loaded. +" +" Possible values are: +" * 'start' (a plugin will be loaded at VimEnter event) +" * 'filetype=' (a plugin will be loaded at FileType event) +" * 'excmd=' (a plugin will be loaded at CmdUndefined event) +" and can be multiple values separated by comma. +" +" This function must contain 'return ""' code. +" (the argument of :return must be string literal) +function! s:loaded_on() return 'start' endfunction` -const skeletonPlugconfDepends = `function! s:depends() - " Dependencies of this plugin. - " The specified dependencies are loaded after this plugin is loaded. - " - " This function must contain 'return [, ...]' code. - " (the argument of :return must be list literal, and the elements are string) - " e.g. return ['github.com/tyru/open-browser.vim'] - +const skeletonPlugconfDepends = `" Dependencies of this plugin. +" The specified dependencies are loaded after this plugin is loaded. +" +" This function must contain 'return [, ...]' code. +" (the argument of :return must be list literal, and the elements are string) +" e.g. return ['github.com/tyru/open-browser.vim'] +function! s:depends() return [] endfunction` diff --git a/subcmd/builder/base.go b/subcmd/builder/base.go index d0d2b87b..6d4b63fa 100644 --- a/subcmd/builder/base.go +++ b/subcmd/builder/base.go @@ -1,7 +1,6 @@ package builder import ( - "errors" "fmt" "io" "os" @@ -9,6 +8,8 @@ import ( "path/filepath" "strings" + "github.com/pkg/errors" + "github.com/hashicorp/go-multierror" "github.com/vim-volt/volt/fileutil" "github.com/vim-volt/volt/lockjson" @@ -79,7 +80,7 @@ func (builder *BaseBuilder) installRCFile(profileName, srcRCFileName, dst string if !pathutil.Exists(src) { return nil } - return fmt.Errorf("'%s' is not an auto-generated file. please move to '%s' and re-run 'volt build'", dst, pathutil.RCDir(profileName)) + return errors.Errorf("'%s' is not an auto-generated file. please move to '%s' and re-run 'volt build'", dst, pathutil.RCDir(profileName)) } } @@ -175,7 +176,7 @@ func (builder *BaseBuilder) helptags(reposPath pathutil.ReposPath, vimExePath st logger.Debugf("Executing '%s %s' ...", vimExePath, strings.Join(vimArgs, " ")) err := exec.Command(vimExePath, vimArgs...).Run() if err != nil { - return errors.New("failed to make tags file: " + err.Error()) + return errors.Wrap(err, "failed to make tags file") } return nil } diff --git a/subcmd/builder/builder.go b/subcmd/builder/builder.go index 3730b783..adc557a6 100644 --- a/subcmd/builder/builder.go +++ b/subcmd/builder/builder.go @@ -1,7 +1,7 @@ package builder import ( - "errors" + "github.com/pkg/errors" "os" "github.com/vim-volt/volt/config" @@ -22,7 +22,7 @@ func Build(full bool) error { // Read config.toml cfg, err := config.Read() if err != nil { - return errors.New("could not read config.toml: " + err.Error()) + return errors.Wrap(err, "could not read config.toml") } // Get builder diff --git a/subcmd/builder/copy.go b/subcmd/builder/copy.go index b579f62e..5d079a2d 100644 --- a/subcmd/builder/copy.go +++ b/subcmd/builder/copy.go @@ -1,13 +1,13 @@ package builder import ( - "errors" - "fmt" "io/ioutil" "os" "path/filepath" "time" + "github.com/pkg/errors" + "github.com/hashicorp/go-multierror" "github.com/vim-volt/volt/fileutil" "github.com/vim-volt/volt/gitutil" @@ -145,7 +145,7 @@ func (builder *copyBuilder) copyReposList(buildReposMap map[pathutil.ReposPath]* n, err := builder.copyReposGit(&reposList[i], buildReposMap[reposList[i].Path], vimExePath, copyDone) if err != nil { copyDone <- actionReposResult{ - err: errors.New("failed to copy " + string(reposList[i].Type) + " repos: " + err.Error()), + err: errors.Wrap(err, "failed to copy "+string(reposList[i].Type)+" repos"), repos: &reposList[i], } } @@ -168,13 +168,13 @@ func (builder *copyBuilder) copyReposGit(repos *lockjson.Repos, buildRepos *buil // Open ~/volt/repos/{repos} r, err := git.PlainOpen(src) if err != nil { - return 0, errors.New("failed to open repository: " + err.Error()) + return 0, errors.Wrap(err, "failed to open repository") } // Show warning when HEAD and locked revision are different head, err := gitutil.GetHEADRepository(r) if err != nil { - return 0, fmt.Errorf("failed to get HEAD revision of %q: %s", src, err.Error()) + return 0, errors.Errorf("failed to get HEAD revision of %q: %s", src, err.Error()) } if head != repos.Version { logger.Warnf("%s: HEAD and locked revision are different", repos.Path) @@ -185,7 +185,7 @@ func (builder *copyBuilder) copyReposGit(repos *lockjson.Repos, buildRepos *buil cfg, err := r.Config() if err != nil { - return 0, errors.New("failed to get repository config: " + err.Error()) + return 0, errors.Wrap(err, "failed to get repository config") } isClean := false @@ -244,9 +244,9 @@ func (*copyBuilder) waitCopyRepos(copyDone chan actionReposResult, copyCount int if result.err != nil { merr = multierror.Append( merr, - errors.New( + errors.Wrap(result.err, "failed to copy repository '"+result.repos.Path.String()+ - "': "+result.err.Error())) + "'")) } else { err := callback(&result) if err != nil { @@ -305,9 +305,7 @@ func (*copyBuilder) waitRemoveRepos(removeDone chan actionReposResult, removeCou target = result.repos.Path.String() } merr = multierror.Append( - merr, errors.New( - "Failed to remove "+target+ - ": "+result.err.Error())) + merr, errors.Wrap(result.err, "Failed to remove "+target)) } else { callback(&result) } @@ -328,7 +326,7 @@ func (*copyBuilder) getLatestModTime(path string) (time.Time, error) { return nil }) if err != nil { - return time.Now(), errors.New("failed to readdir: " + err.Error()) + return time.Now(), errors.Wrap(err, "failed to readdir") } return mtime, nil } @@ -356,7 +354,7 @@ func (builder *copyBuilder) updateGitRepos(repos *lockjson.Repos, r *git.Reposit err := os.RemoveAll(dst) if err != nil { done <- actionReposResult{ - err: errors.New("failed to remove repository: " + err.Error()), + err: errors.Wrap(err, "failed to remove repository"), repos: repos, } return @@ -377,7 +375,7 @@ func (builder *copyBuilder) updateBareGitRepos(r *git.Repository, src, dst strin commitObj, err := r.CommitObject(commit) if err != nil { done <- actionReposResult{ - err: errors.New("failed to get HEAD commit object: " + err.Error()), + err: errors.Wrap(err, "failed to get HEAD commit object"), repos: repos, } return @@ -387,7 +385,7 @@ func (builder *copyBuilder) updateBareGitRepos(r *git.Repository, src, dst strin tree, err := r.TreeObject(commitObj.TreeHash) if err != nil { done <- actionReposResult{ - err: errors.New("failed to get tree " + commit.String() + ": " + err.Error()), + err: errors.Wrap(err, "failed to get tree "+commit.String()), repos: repos, } return @@ -398,12 +396,12 @@ func (builder *copyBuilder) updateBareGitRepos(r *git.Repository, src, dst strin err = tree.Files().ForEach(func(file *object.File) error { osMode, err := file.Mode.ToOSFileMode() if err != nil { - return errors.New("failed to convert file mode: " + err.Error()) + return errors.Wrap(err, "failed to convert file mode") } contents, err := file.Contents() if err != nil { - return errors.New("failed to get file contents: " + err.Error()) + return errors.Wrap(err, "failed to get file contents") } filename := filepath.Join(dst, file.Name) @@ -540,7 +538,7 @@ func (builder *copyBuilder) updateStaticRepos(repos *lockjson.Repos, vimExePath err := os.RemoveAll(dst) if err != nil { done <- actionReposResult{ - err: errors.New("failed to remove repository: " + err.Error()), + err: errors.Wrap(err, "failed to remove repository"), repos: repos, } return @@ -551,7 +549,7 @@ func (builder *copyBuilder) updateStaticRepos(repos *lockjson.Repos, vimExePath si, err := os.Stat(src) if err != nil { done <- actionReposResult{ - err: errors.New("failed to copy static directory: " + err.Error()), + err: errors.Wrap(err, "failed to copy static directory"), repos: repos, } return @@ -566,7 +564,7 @@ func (builder *copyBuilder) updateStaticRepos(repos *lockjson.Repos, vimExePath err = fileutil.TryLinkDir(src, dst, buf, si.Mode(), BuildModeInvalidType) if err != nil { done <- actionReposResult{ - err: errors.New("failed to copy static directory: " + err.Error()), + err: errors.Wrap(err, "failed to copy static directory"), repos: repos, } return diff --git a/subcmd/builder/symlink.go b/subcmd/builder/symlink.go index eb94e5e5..45c079d4 100644 --- a/subcmd/builder/symlink.go +++ b/subcmd/builder/symlink.go @@ -1,14 +1,14 @@ package builder import ( - "errors" - "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "runtime" + "github.com/pkg/errors" + "gopkg.in/src-d/go-git.v4" "github.com/vim-volt/volt/gitutil" @@ -33,7 +33,7 @@ func (builder *symlinkBuilder) Build(buildInfo *buildinfo.BuildInfo, buildReposM // Get current profile's repos list lockJSON, err := lockjson.Read() if err != nil { - return errors.New("could not read lock.json: " + err.Error()) + return errors.Wrap(err, "could not read lock.json") } reposList, err := lockJSON.GetCurrentReposList() if err != nil { @@ -128,7 +128,7 @@ func (builder *symlinkBuilder) installRepos(repos *lockjson.Repos, vimExePath st r, err := git.PlainOpen(src) if err != nil { done <- actionReposResult{ - err: fmt.Errorf("repository %q: %s", src, err.Error()), + err: errors.Errorf("repository %q: %s", src, err.Error()), } return } @@ -137,7 +137,7 @@ func (builder *symlinkBuilder) installRepos(repos *lockjson.Repos, vimExePath st head, err := gitutil.GetHEADRepository(r) if err != nil { done <- actionReposResult{ - err: fmt.Errorf("failed to get HEAD revision of %q: %s", src, err.Error()), + err: errors.Errorf("failed to get HEAD revision of %q: %s", src, err.Error()), } return } @@ -151,7 +151,7 @@ func (builder *symlinkBuilder) installRepos(repos *lockjson.Repos, vimExePath st cfg, err := r.Config() if err != nil { done <- actionReposResult{ - err: fmt.Errorf("failed to get repository config of %q: %s", src, err.Error()), + err: errors.Errorf("failed to get repository config of %q: %s", src, err.Error()), } return } diff --git a/subcmd/buildinfo/buildinfo.go b/subcmd/buildinfo/buildinfo.go index 281e06cf..3b316c51 100644 --- a/subcmd/buildinfo/buildinfo.go +++ b/subcmd/buildinfo/buildinfo.go @@ -2,7 +2,7 @@ package buildinfo import ( "encoding/json" - "errors" + "github.com/pkg/errors" "io/ioutil" "github.com/vim-volt/volt/lockjson" @@ -50,7 +50,7 @@ func Read() (*BuildInfo, error) { // Validate build-info.json err = buildInfo.validate() if err != nil { - return nil, errors.New("validation failed: build-info.json: " + err.Error()) + return nil, errors.Wrap(err, "validation failed: build-info.json") } return &buildInfo, nil @@ -60,7 +60,7 @@ func (buildInfo *BuildInfo) Write() error { // Validate build-info.json err := buildInfo.validate() if err != nil { - return errors.New("validation failed: build-info.json: " + err.Error()) + return errors.Wrap(err, "validation failed: build-info.json") } // Write to build-info.json diff --git a/subcmd/cmd.go b/subcmd/cmd.go index 9e1a7983..67a88f74 100644 --- a/subcmd/cmd.go +++ b/subcmd/cmd.go @@ -1,8 +1,8 @@ package subcmd import ( - "errors" "flag" + "github.com/pkg/errors" "os" "os/user" "runtime" @@ -61,7 +61,7 @@ func Run(args []string, cont RunnerFunc) *Error { c, exists := cmdMap[subCmd] if !exists { - return &Error{Code: 3, Msg: "Unknown command '" + subCmd + "'"} + return &Error{Code: 3, Msg: "unknown command '" + subCmd + "'"} } // Disallow executing the commands which may modify files in root priviledge @@ -78,7 +78,7 @@ func Run(args []string, cont RunnerFunc) *Error { func expandAlias(subCmd string, args []string) (string, []string, error) { cfg, err := config.Read() if err != nil { - return "", nil, errors.New("could not read config.toml: " + err.Error()) + return "", nil, errors.Wrap(err, "could not read config.toml") } if newArgs, exists := cfg.Alias[subCmd]; exists && len(newArgs) > 0 { subCmd = newArgs[0] @@ -97,11 +97,11 @@ func detectPriviledgedUser() error { } u, err := user.Current() if err != nil { - return errors.New("Cannot get current user: " + err.Error()) + return errors.Wrap(err, "cannot get current user") } if u.Uid == "0" { return errors.New( - "Cannot run this sub command with root priviledge. " + + "cannot run this sub command with root priviledge. " + "Please run as normal user") } return nil diff --git a/subcmd/disable.go b/subcmd/disable.go index c3177243..8ed15114 100644 --- a/subcmd/disable.go +++ b/subcmd/disable.go @@ -1,9 +1,9 @@ package subcmd import ( - "errors" "flag" "fmt" + "github.com/pkg/errors" "os" "github.com/vim-volt/volt/pathutil" diff --git a/subcmd/edit.go b/subcmd/edit.go new file mode 100644 index 00000000..85740065 --- /dev/null +++ b/subcmd/edit.go @@ -0,0 +1,221 @@ +package subcmd + +import ( + "errors" + "flag" + "fmt" + "os" + "os/exec" + + "github.com/vim-volt/volt/config" + "github.com/vim-volt/volt/lockjson" + "github.com/vim-volt/volt/logger" + "github.com/vim-volt/volt/pathutil" + "github.com/vim-volt/volt/subcmd/builder" +) + +func init() { + cmdMap["edit"] = &editCmd{} +} + +type editCmd struct { + helped bool + editor string +} + +func (cmd *editCmd) ProhibitRootExecution(args []string) bool { return true } + +func (cmd *editCmd) FlagSet() *flag.FlagSet { + fs := flag.NewFlagSet(os.Args[0], flag.ContinueOnError) + fs.SetOutput(os.Stdout) + fs.Usage = func() { + fmt.Print(` +Usage + volt edit [-help] [-e|--editor {editor}] {repository} [{repository2} ...] + +Quick example + $ volt edit tyru/caw.vim # will open the plugconf file for tyru/caw.vim for editing + +Description + Open the plugconf file(s) of one or more {repository} for editing. + + If the -e option was given, use the given editor for editing those files (unless it cannot be found) + + It also calls "volt build" afterwards if modifications were made to the plugconf file(s).` + "\n\n") + //fmt.Println("Options") + //fs.PrintDefaults() + fmt.Println() + cmd.helped = true + } + fs.StringVar(&cmd.editor, "editor", "", "Use the given editor for editing the plugconf files") + fs.StringVar(&cmd.editor, "e", "", "Use the given editor for editing the plugconf files") + return fs +} + +func (cmd *editCmd) Run(args []string) *Error { + reposPathList, err := cmd.parseArgs(args) + if err == ErrShowedHelp { + return nil + } + if err != nil { + return &Error{Code: 10, Msg: "Failed to parse args: " + err.Error()} + } + + hasChanges, err := cmd.doEdit(reposPathList) + if err != nil { + return &Error{Code: 15, Msg: "Failed to edit plugconf file: " + err.Error()} + } + + // Build opt dir + if hasChanges { + err = builder.Build(false) + if err != nil { + return &Error{Code: 12, Msg: "Could not build " + pathutil.VimVoltDir() + ": " + err.Error()} + } + } + + return nil +} + +func (cmd *editCmd) doEdit(reposPathList []pathutil.ReposPath) (bool, error) { + // Read lock.json + lockJSON, err := lockjson.Read() + if err != nil { + return false, err + } + + // Read config.toml + cfg, err := config.Read() + if err != nil { + return false, errors.New("could not read config.toml: " + err.Error()) + } + + editor, err := cmd.identifyEditor(cfg) + if err != nil || editor == "" { + return false, &Error{Code: 30, Msg: "No usable editor found"} + } + + changeWasMade := false + for _, reposPath := range reposPathList { + + // Edit plugconf file + plugconfPath := reposPath.Plugconf() + + // Install a new template if none exists + if !pathutil.Exists(plugconfPath) { + getCmd := new(getCmd) + logger.Debugf("Installing new plugconf for '%s'.", reposPath) + getCmd.downloadPlugconf(reposPath) + } + + // Remember modification time before opening the editor + info, err := os.Stat(plugconfPath) + if err != nil { + return false, err + } + mTimeBefore := info.ModTime() + + // Call the editor with the plugconf file + editorCmd := exec.Command(editor, plugconfPath) + editorCmd.Stdin = os.Stdin + editorCmd.Stdout = os.Stdout + if err = editorCmd.Run(); err != nil { + logger.Error("Error calling editor for '%s': %s", reposPath, err.Error) + continue + } + + // Get modification time after closing the editor + info, err = os.Stat(plugconfPath) + if err != nil { + return false, err + } + mTimeAfter := info.ModTime() + + // A change was made if the modification time was updated + changeWasMade = changeWasMade || mTimeAfter.After(mTimeBefore) + + // Remove repository from lock.json + err = lockJSON.Repos.RemoveAllReposPath(reposPath) + err2 := lockJSON.Profiles.RemoveAllReposPath(reposPath) + if err == nil || err2 == nil { + // ignore? + } + } + + // Write to lock.json + if err = lockJSON.Write(); err != nil { + return changeWasMade, err + } + return changeWasMade, nil +} + +func (cmd *editCmd) parseArgs(args []string) (pathutil.ReposPathList, error) { + fs := cmd.FlagSet() + fs.Parse(args) + if cmd.helped { + return nil, ErrShowedHelp + } + + if len(fs.Args()) == 0 { + fs.Usage() + return nil, errors.New("repository was not given") + } + + // Normalize repos path + reposPathList := make(pathutil.ReposPathList, 0, len(fs.Args())) + for _, arg := range fs.Args() { + reposPath, err := pathutil.NormalizeRepos(arg) + if err != nil { + return nil, err + } + reposPathList = append(reposPathList, reposPath) + } + + return reposPathList, nil +} + +func (cmd *editCmd) identifyEditor(cfg *config.Config) (string, error) { + editors := make([]string, 0, 6) + + // if an editor is specified as commandline argument, consider it + // as alternative + if cmd.editor != "" { + editors = append(editors, cmd.editor) + } + + // if an editor is configured in the config.toml, consider it as + // alternative + if cfg.Edit.Editor != "" { + editors = append(editors, cfg.Edit.Editor) + } + + vimExecutable, err := pathutil.VimExecutable() + if err != nil { + logger.Debug("No vim executable found in $PATH") + } else { + editors = append(editors, vimExecutable) + } + + // specifiy a fixed list of other alternatives + editors = append(editors, "$VISUAL", "sensible-editor", "$EDITOR") + + for _, editor := range editors { + // resolve content of environment variables + var editorName string + if editor[0] == '$' { + editorName = os.Getenv(editor[1:]) + } else { + editorName = editor + } + + path, err := exec.LookPath(editorName) + if err != nil { + logger.Debug(editorName + " not found in $PATH") + } else if path != "" { + logger.Debug("Using " + path + " as editor") + return editorName, nil + } + } + + return "", errors.New("No usable editor found") +} diff --git a/subcmd/enable.go b/subcmd/enable.go index e51c8186..bea7586a 100644 --- a/subcmd/enable.go +++ b/subcmd/enable.go @@ -1,9 +1,9 @@ package subcmd import ( - "errors" "flag" "fmt" + "github.com/pkg/errors" "os" "github.com/vim-volt/volt/pathutil" diff --git a/subcmd/get.go b/subcmd/get.go index b20796f7..924efc76 100644 --- a/subcmd/get.go +++ b/subcmd/get.go @@ -1,7 +1,6 @@ package subcmd import ( - "errors" "flag" "fmt" "io/ioutil" @@ -12,6 +11,8 @@ import ( "sort" "strings" + "github.com/pkg/errors" + "gopkg.in/src-d/go-git.v4" "github.com/vim-volt/volt/config" @@ -205,7 +206,7 @@ func (cmd *getCmd) doGet(reposPathList []pathutil.ReposPath, lockJSON *lockjson. // Read config.toml cfg, err := config.Read() if err != nil { - return errors.New("could not read config.toml: " + err.Error()) + return errors.Wrap(err, "could not read config.toml") } done := make(chan getParallelResult, len(reposPathList)) @@ -249,14 +250,14 @@ func (cmd *getCmd) doGet(reposPathList []pathutil.ReposPath, lockJSON *lockjson. // Write to lock.json err = lockJSON.Write() if err != nil { - return errors.New("could not write to lock.json: " + err.Error()) + return errors.Wrap(err, "could not write to lock.json") } } // Build ~/.vim/pack/volt dir err = builder.Build(false) if err != nil { - return errors.New("could not build " + pathutil.VimVoltDir() + ": " + err.Error()) + return errors.Wrap(err, "could not build "+pathutil.VimVoltDir()) } // Show results @@ -341,7 +342,7 @@ func (cmd *getCmd) installPlugin(reposPath pathutil.ReposPath, repos *lockjson.R // Get HEAD hash string fromHash, err = gitutil.GetHEAD(reposPath) if err != nil { - result := errors.New("failed to get HEAD commit hash: " + err.Error()) + result := errors.Wrap(err, "failed to get HEAD commit hash") done <- getParallelResult{ reposPath: reposPath, status: fmt.Sprintf(fmtInstallFailed, reposPath), @@ -369,7 +370,7 @@ func (cmd *getCmd) installPlugin(reposPath pathutil.ReposPath, repos *lockjson.R logger.Debug("Upgrading " + reposPath + " ...") err := cmd.upgradePlugin(reposPath, cfg) if err != git.NoErrAlreadyUpToDate && err != nil { - result := errors.New("failed to upgrade plugin: " + err.Error()) + result := errors.Wrap(err, "failed to upgrade plugin") done <- getParallelResult{ reposPath: reposPath, status: fmt.Sprintf(fmtUpgradeFailed, reposPath), @@ -387,7 +388,7 @@ func (cmd *getCmd) installPlugin(reposPath pathutil.ReposPath, repos *lockjson.R logger.Debug("Installing " + reposPath + " ...") err := cmd.clonePlugin(reposPath, cfg) if err != nil { - result := errors.New("failed to install plugin: " + err.Error()) + result := errors.Wrap(err, "failed to install plugin") logger.Debug("Rollbacking " + fullReposPath + " ...") err = cmd.removeDir(fullReposPath) if err != nil { @@ -412,7 +413,7 @@ func (cmd *getCmd) installPlugin(reposPath pathutil.ReposPath, repos *lockjson.R // Get HEAD hash string toHash, err = gitutil.GetHEAD(reposPath) if err != nil { - result := errors.New("failed to get HEAD commit hash: " + err.Error()) + result := errors.Wrap(err, "failed to get HEAD commit hash") if doInstall { logger.Debug("Rollbacking " + fullReposPath + " ...") err = cmd.removeDir(fullReposPath) @@ -454,7 +455,7 @@ func (cmd *getCmd) installPlugconf(reposPath pathutil.ReposPath, pluginResult *g logger.Debug("Installing plugconf " + reposPath + " ...") err := cmd.downloadPlugconf(reposPath) if err != nil { - result := errors.New("failed to install plugconf: " + err.Error()) + result := errors.Wrap(err, "failed to install plugconf") // TODO: Call cmd.removeDir() only when the repos *did not* exist previously // and was installed newly. // fullReposPath := reposPath.FullPath() @@ -487,7 +488,7 @@ func (*getCmd) removeDir(fullReposPath string) error { if pathutil.Exists(fullReposPath) { err := os.RemoveAll(fullReposPath) if err != nil { - return fmt.Errorf("rollback failed: cannot remove '%s'", fullReposPath) + return errors.Errorf("rollback failed: cannot remove '%s'", fullReposPath) } // Remove parent directories fileutil.RemoveDirs(filepath.Dir(fullReposPath)) @@ -552,7 +553,7 @@ func (cmd *getCmd) downloadPlugconf(reposPath pathutil.ReposPath) error { } content, merr := tmpl.Generate(path) if merr.ErrorOrNil() != nil { - return fmt.Errorf("parse error in fetched plugconf %s: %s", reposPath, merr.Error()) + return errors.Errorf("parse error in fetched plugconf %s: %s", reposPath, merr.Error()) } os.MkdirAll(filepath.Dir(path), 0755) err = ioutil.WriteFile(path, content, 0644) @@ -676,8 +677,11 @@ func (cmd *getCmd) getWorktreeChanges(r *git.Repository, before string) (bool, e func (cmd *getCmd) gitClone(cloneURL, dstDir string, cfg *config.Config) error { isBare := false r, err := git.PlainClone(dstDir, isBare, &git.CloneOptions{ - URL: cloneURL, - RecurseSubmodules: 10, + URL: cloneURL, + // TODO: Temporarily recursive clone is disabled, because go-git does + // not support relative submodule url in .gitmodules and it causes an + // error + RecurseSubmodules: 0, }) if err != nil { // When fallback_git_cmd is true and git command is installed, @@ -692,7 +696,7 @@ func (cmd *getCmd) gitClone(cloneURL, dstDir string, cfg *config.Config) error { } out, err := exec.Command("git", "clone", "--recursive", cloneURL, dstDir).CombinedOutput() if err != nil { - return fmt.Errorf("\"git clone --recursive %s %s\" failed, out=%s: %s", cloneURL, dstDir, string(out), err.Error()) + return errors.Errorf("\"git clone --recursive %s %s\" failed, out=%s: %s", cloneURL, dstDir, string(out), err.Error()) } } diff --git a/subcmd/get_test.go b/subcmd/get_test.go index a2ee3224..051f9842 100644 --- a/subcmd/get_test.go +++ b/subcmd/get_test.go @@ -2,8 +2,8 @@ package subcmd import ( "bytes" - "errors" "fmt" + "github.com/pkg/errors" "io/ioutil" "path/filepath" "strings" @@ -583,7 +583,7 @@ func gitCommitOne(reposPath pathutil.ReposPath) (prev plumbing.Hash, current plu filename := filepath.Join(reposPath.FullPath(), relPath) if err = ioutil.WriteFile(filename, content, 0644); err != nil { - err = errors.New("ioutil.WriteFile() failed: " + err.Error()) + err = errors.Wrap(err, "ioutil.WriteFile() failed") return } r, err := git.PlainOpen(reposPath.FullPath()) diff --git a/subcmd/help.go b/subcmd/help.go index 49bf679a..9b7b86a1 100644 --- a/subcmd/help.go +++ b/subcmd/help.go @@ -1,9 +1,9 @@ package subcmd import ( - "errors" "flag" "fmt" + "github.com/pkg/errors" "os" ) @@ -58,6 +58,9 @@ Command This is shortcut of: volt profile rm -current {repository} [{repository2} ...] + edit [-e|--editor {editor}] {repository} [{repository2} ...] + Open the plugconf file(s) of one or more {repository} for editing. + profile set {name} Set profile name diff --git a/subcmd/list.go b/subcmd/list.go index f3578547..af734e5e 100644 --- a/subcmd/list.go +++ b/subcmd/list.go @@ -2,9 +2,9 @@ package subcmd import ( "encoding/json" - "errors" "flag" "fmt" + "github.com/pkg/errors" "os" "text/template" @@ -141,7 +141,7 @@ func (cmd *listCmd) list(format string) error { // Read lock.json lockJSON, err := lockjson.Read() if err != nil { - return errors.New("failed to read lock.json: " + err.Error()) + return errors.Wrap(err, "failed to read lock.json") } // Parse template string t, err := template.New("volt").Funcs(cmd.funcMap(lockJSON)).Parse(format) diff --git a/subcmd/migrate.go b/subcmd/migrate.go index 0fe90a2c..8d22b00d 100644 --- a/subcmd/migrate.go +++ b/subcmd/migrate.go @@ -1,9 +1,9 @@ package subcmd import ( - "errors" "flag" "fmt" + "github.com/pkg/errors" "os" "github.com/vim-volt/volt/logger" diff --git a/subcmd/migrate/lockjson.go b/subcmd/migrate/lockjson.go index 0739c4a2..fb3e963b 100644 --- a/subcmd/migrate/lockjson.go +++ b/subcmd/migrate/lockjson.go @@ -1,7 +1,7 @@ package migrate import ( - "errors" + "github.com/pkg/errors" "github.com/vim-volt/volt/lockjson" "github.com/vim-volt/volt/transaction" @@ -35,7 +35,7 @@ func (*lockjsonMigrater) Migrate() error { // Read lock.json lockJSON, err := lockjson.ReadNoMigrationMsg() if err != nil { - return errors.New("could not read lock.json: " + err.Error()) + return errors.Wrap(err, "could not read lock.json") } // Begin transaction @@ -48,7 +48,7 @@ func (*lockjsonMigrater) Migrate() error { // Write to lock.json err = lockJSON.Write() if err != nil { - return errors.New("could not write to lock.json: " + err.Error()) + return errors.Wrap(err, "could not write to lock.json") } return nil } diff --git a/subcmd/migrate/migrater.go b/subcmd/migrate/migrater.go index d0c0197d..2e26ff20 100644 --- a/subcmd/migrate/migrater.go +++ b/subcmd/migrate/migrater.go @@ -1,7 +1,7 @@ package migrate import ( - "errors" + "github.com/pkg/errors" "sort" ) diff --git a/subcmd/migrate/plugconf-config-func.go b/subcmd/migrate/plugconf-config-func.go index 6033c783..73d44ab8 100644 --- a/subcmd/migrate/plugconf-config-func.go +++ b/subcmd/migrate/plugconf-config-func.go @@ -1,7 +1,7 @@ package migrate import ( - "errors" + "github.com/pkg/errors" "io/ioutil" "os" "path/filepath" @@ -43,7 +43,7 @@ func (*plugconfConfigMigrater) Migrate() error { // Read lock.json lockJSON, err := lockjson.ReadNoMigrationMsg() if err != nil { - return errors.New("could not read lock.json: " + err.Error()) + return errors.Wrap(err, "could not read lock.json") } results, parseErr := plugconf.ParseMultiPlugconf(lockJSON.Repos) @@ -98,7 +98,7 @@ func (*plugconfConfigMigrater) Migrate() error { // Build ~/.vim/pack/volt dir err = builder.Build(false) if err != nil { - return errors.New("could not build " + pathutil.VimVoltDir() + ": " + err.Error()) + return errors.Wrap(err, "could not build "+pathutil.VimVoltDir()) } return nil diff --git a/subcmd/profile.go b/subcmd/profile.go index 6fb4a6c5..6912cb21 100644 --- a/subcmd/profile.go +++ b/subcmd/profile.go @@ -1,11 +1,12 @@ package subcmd import ( - "errors" "flag" "fmt" "os" + "github.com/pkg/errors" + "github.com/hashicorp/go-multierror" "github.com/vim-volt/volt/lockjson" "github.com/vim-volt/volt/logger" @@ -155,7 +156,7 @@ func (cmd *profileCmd) parseArgs(args []string) ([]string, error) { func (*profileCmd) getCurrentProfile() (string, error) { lockJSON, err := lockjson.Read() if err != nil { - return "", errors.New("failed to read lock.json: " + err.Error()) + return "", errors.Wrap(err, "failed to read lock.json") } return lockJSON.CurrentProfileName, nil } @@ -177,12 +178,12 @@ func (cmd *profileCmd) doSet(args []string) error { // Read lock.json lockJSON, err := lockjson.Read() if err != nil { - return errors.New("failed to read lock.json: " + err.Error()) + return errors.Wrap(err, "failed to read lock.json") } // Exit if current profile is same as profileName if lockJSON.CurrentProfileName == profileName { - return fmt.Errorf("'%s' is current profile", profileName) + return errors.Errorf("'%s' is current profile", profileName) } // Create given profile unless the profile exists @@ -196,7 +197,7 @@ func (cmd *profileCmd) doSet(args []string) error { // Read lock.json again lockJSON, err = lockjson.Read() if err != nil { - return errors.New("failed to read lock.json: " + err.Error()) + return errors.Wrap(err, "failed to read lock.json") } if _, err = lockJSON.Profiles.FindByName(profileName); err != nil { return err @@ -224,7 +225,7 @@ func (cmd *profileCmd) doSet(args []string) error { // Build ~/.vim/pack/volt dir err = builder.Build(false) if err != nil { - return errors.New("could not build " + pathutil.VimVoltDir() + ": " + err.Error()) + return errors.Wrap(err, "could not build "+pathutil.VimVoltDir()) } return nil @@ -240,7 +241,7 @@ func (cmd *profileCmd) doShow(args []string) error { // Read lock.json lockJSON, err := lockjson.Read() if err != nil { - return errors.New("failed to read lock.json: " + err.Error()) + return errors.Wrap(err, "failed to read lock.json") } var profileName string @@ -249,7 +250,7 @@ func (cmd *profileCmd) doShow(args []string) error { } else { profileName = args[0] if lockJSON.Profiles.FindIndexByName(profileName) == -1 { - return fmt.Errorf("profile '%s' does not exist", profileName) + return errors.Errorf("profile '%s' does not exist", profileName) } } @@ -282,7 +283,7 @@ func (cmd *profileCmd) doNew(args []string) error { // Read lock.json lockJSON, err := lockjson.Read() if err != nil { - return errors.New("failed to read lock.json: " + err.Error()) + return errors.Wrap(err, "failed to read lock.json") } // Return error if profiles[]/name matches profileName @@ -325,7 +326,7 @@ func (cmd *profileCmd) doDestroy(args []string) error { // Read lock.json lockJSON, err := lockjson.Read() if err != nil { - return errors.New("failed to read lock.json: " + err.Error()) + return errors.Wrap(err, "failed to read lock.json") } // Begin transaction @@ -385,7 +386,7 @@ func (cmd *profileCmd) doRename(args []string) error { // Read lock.json lockJSON, err := lockjson.Read() if err != nil { - return errors.New("failed to read lock.json: " + err.Error()) + return errors.Wrap(err, "failed to read lock.json") } // Return error if profiles[]/name does not match oldName @@ -417,7 +418,7 @@ func (cmd *profileCmd) doRename(args []string) error { if pathutil.Exists(oldRCDir) { newRCDir := pathutil.RCDir(newName) if err = os.Rename(oldRCDir, newRCDir); err != nil { - return fmt.Errorf("could not rename %s to %s", oldRCDir, newRCDir) + return errors.Errorf("could not rename %s to %s", oldRCDir, newRCDir) } } @@ -436,13 +437,13 @@ func (cmd *profileCmd) doAdd(args []string) error { // Read lock.json lockJSON, err := lockjson.Read() if err != nil { - return errors.New("failed to read lock.json: " + err.Error()) + return errors.Wrap(err, "failed to read lock.json") } // Parse args profileName, reposPathList, err := cmd.parseAddArgs(lockJSON, "add", args) if err != nil { - return errors.New("failed to parse args: " + err.Error()) + return errors.Wrap(err, "failed to parse args") } if profileName == "-current" { @@ -468,7 +469,7 @@ func (cmd *profileCmd) doAdd(args []string) error { // Build ~/.vim/pack/volt dir err = builder.Build(false) if err != nil { - return errors.New("could not build " + pathutil.VimVoltDir() + ": " + err.Error()) + return errors.Wrap(err, "could not build "+pathutil.VimVoltDir()) } return nil @@ -478,13 +479,13 @@ func (cmd *profileCmd) doRm(args []string) error { // Read lock.json lockJSON, err := lockjson.Read() if err != nil { - return errors.New("failed to read lock.json: " + err.Error()) + return errors.Wrap(err, "failed to read lock.json") } // Parse args profileName, reposPathList, err := cmd.parseAddArgs(lockJSON, "rm", args) if err != nil { - return errors.New("failed to parse args: " + err.Error()) + return errors.Wrap(err, "failed to parse args") } if profileName == "-current" { @@ -512,7 +513,7 @@ func (cmd *profileCmd) doRm(args []string) error { // Build ~/.vim/pack/volt dir err = builder.Build(false) if err != nil { - return errors.New("could not build " + pathutil.VimVoltDir() + ": " + err.Error()) + return errors.Wrap(err, "could not build "+pathutil.VimVoltDir()) } return nil diff --git a/subcmd/rm.go b/subcmd/rm.go index f805b2fd..b2e4d309 100644 --- a/subcmd/rm.go +++ b/subcmd/rm.go @@ -1,13 +1,14 @@ package subcmd import ( - "errors" "flag" "fmt" "os" "path/filepath" "strings" + "github.com/pkg/errors" + "github.com/vim-volt/volt/fileutil" "github.com/vim-volt/volt/lockjson" "github.com/vim-volt/volt/logger" @@ -129,7 +130,7 @@ func (cmd *rmCmd) doRemove(reposPathList []pathutil.ReposPath) error { return err } if len(rdeps) > 0 { - return fmt.Errorf("cannot remove '%s' because it's depended by '%s'", + return errors.Errorf("cannot remove '%s' because it's depended by '%s'", reposPath, strings.Join(rdeps.Strings(), "', '")) } } diff --git a/subcmd/self_upgrade.go b/subcmd/self_upgrade.go index be65a8fd..00d86445 100644 --- a/subcmd/self_upgrade.go +++ b/subcmd/self_upgrade.go @@ -2,7 +2,6 @@ package subcmd import ( "encoding/json" - "errors" "flag" "fmt" "io" @@ -15,6 +14,8 @@ import ( "syscall" "time" + "github.com/pkg/errors" + "github.com/vim-volt/volt/httputil" "github.com/vim-volt/volt/logger" ) @@ -84,12 +85,12 @@ func (cmd *selfUpgradeCmd) parseArgs(args []string) error { func (cmd *selfUpgradeCmd) doCleanUp(ppidStr string) error { ppid, err := strconv.Atoi(ppidStr) if err != nil { - return errors.New("failed to parse VOLT_SELF_UPGRADE_PPID: " + err.Error()) + return errors.Wrap(err, "failed to parse VOLT_SELF_UPGRADE_PPID") } // Wait until the parent process exits if died := cmd.waitUntilParentExits(ppid); !died { - return fmt.Errorf("parent pid (%s) is keeping alive for long time", ppidStr) + return errors.Errorf("parent pid (%s) is keeping alive for long time", ppidStr) } // Remove old binary diff --git a/subcmd/version.go b/subcmd/version.go index 65f94623..2d8cde46 100644 --- a/subcmd/version.go +++ b/subcmd/version.go @@ -1,16 +1,16 @@ package subcmd import ( - "errors" "flag" "fmt" + "github.com/pkg/errors" "os" "regexp" "strconv" ) // This variable is not constant for testing (to change it temporarily) -var voltVersion = "v0.3.5" +var voltVersion = "v0.3.6-alpha" func init() { cmdMap["version"] = &versionCmd{} diff --git a/transaction/transaction.go b/transaction/transaction.go index 97c9bc23..c5f4ac4d 100644 --- a/transaction/transaction.go +++ b/transaction/transaction.go @@ -1,7 +1,7 @@ package transaction import ( - "errors" + "github.com/pkg/errors" "io/ioutil" "os" "path/filepath" @@ -19,7 +19,7 @@ func Create() error { // Create trx.lock parent directories err := os.MkdirAll(filepath.Dir(trxLockFile), 0755) if err != nil { - return errors.New("failed to begin transaction: " + err.Error()) + return errors.Wrap(err, "failed to begin transaction") } // Return error if the file exists @@ -30,13 +30,13 @@ func Create() error { // Write pid to trx.lock file err = ioutil.WriteFile(trxLockFile, ownPid, 0644) if err != nil { - return errors.New("failed to begin transaction: " + err.Error()) + return errors.Wrap(err, "failed to begin transaction") } // Read pid from trx.lock file pid, err := ioutil.ReadFile(trxLockFile) if err != nil { - return errors.New("failed to begin transaction: " + err.Error()) + return errors.Wrap(err, "failed to begin transaction") } if string(pid) != string(ownPid) { diff --git a/vendor/github.com/pkg/errors/.gitignore b/vendor/github.com/pkg/errors/.gitignore new file mode 100644 index 00000000..daf913b1 --- /dev/null +++ b/vendor/github.com/pkg/errors/.gitignore @@ -0,0 +1,24 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof diff --git a/vendor/github.com/pkg/errors/.travis.yml b/vendor/github.com/pkg/errors/.travis.yml new file mode 100644 index 00000000..588ceca1 --- /dev/null +++ b/vendor/github.com/pkg/errors/.travis.yml @@ -0,0 +1,11 @@ +language: go +go_import_path: github.com/pkg/errors +go: + - 1.4.3 + - 1.5.4 + - 1.6.2 + - 1.7.1 + - tip + +script: + - go test -v ./... diff --git a/vendor/github.com/pkg/errors/LICENSE b/vendor/github.com/pkg/errors/LICENSE new file mode 100644 index 00000000..835ba3e7 --- /dev/null +++ b/vendor/github.com/pkg/errors/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2015, Dave Cheney +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md new file mode 100644 index 00000000..273db3c9 --- /dev/null +++ b/vendor/github.com/pkg/errors/README.md @@ -0,0 +1,52 @@ +# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) + +Package errors provides simple error handling primitives. + +`go get github.com/pkg/errors` + +The traditional error handling idiom in Go is roughly akin to +```go +if err != nil { + return err +} +``` +which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. + +## Adding context to an error + +The errors.Wrap function returns a new error that adds context to the original error. For example +```go +_, err := ioutil.ReadAll(r) +if err != nil { + return errors.Wrap(err, "read failed") +} +``` +## Retrieving the cause of an error + +Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. +```go +type causer interface { + Cause() error +} +``` +`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: +```go +switch err := errors.Cause(err).(type) { +case *MyError: + // handle specifically +default: + // unknown error +} +``` + +[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). + +## Contributing + +We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high. + +Before proposing a change, please discuss your change by raising an issue. + +## Licence + +BSD-2-Clause diff --git a/vendor/github.com/pkg/errors/appveyor.yml b/vendor/github.com/pkg/errors/appveyor.yml new file mode 100644 index 00000000..a932eade --- /dev/null +++ b/vendor/github.com/pkg/errors/appveyor.yml @@ -0,0 +1,32 @@ +version: build-{build}.{branch} + +clone_folder: C:\gopath\src\github.com\pkg\errors +shallow_clone: true # for startup speed + +environment: + GOPATH: C:\gopath + +platform: + - x64 + +# http://www.appveyor.com/docs/installed-software +install: + # some helpful output for debugging builds + - go version + - go env + # pre-installed MinGW at C:\MinGW is 32bit only + # but MSYS2 at C:\msys64 has mingw64 + - set PATH=C:\msys64\mingw64\bin;%PATH% + - gcc --version + - g++ --version + +build_script: + - go install -v ./... + +test_script: + - set PATH=C:\gopath\bin;%PATH% + - go test -v ./... + +#artifacts: +# - path: '%GOPATH%\bin\*.exe' +deploy: off diff --git a/vendor/github.com/pkg/errors/bench_test.go b/vendor/github.com/pkg/errors/bench_test.go new file mode 100644 index 00000000..0416a3cb --- /dev/null +++ b/vendor/github.com/pkg/errors/bench_test.go @@ -0,0 +1,59 @@ +// +build go1.7 + +package errors + +import ( + "fmt" + "testing" + + stderrors "errors" +) + +func noErrors(at, depth int) error { + if at >= depth { + return stderrors.New("no error") + } + return noErrors(at+1, depth) +} +func yesErrors(at, depth int) error { + if at >= depth { + return New("ye error") + } + return yesErrors(at+1, depth) +} + +func BenchmarkErrors(b *testing.B) { + var toperr error + type run struct { + stack int + std bool + } + runs := []run{ + {10, false}, + {10, true}, + {100, false}, + {100, true}, + {1000, false}, + {1000, true}, + } + for _, r := range runs { + part := "pkg/errors" + if r.std { + part = "errors" + } + name := fmt.Sprintf("%s-stack-%d", part, r.stack) + b.Run(name, func(b *testing.B) { + var err error + f := yesErrors + if r.std { + f = noErrors + } + b.ReportAllocs() + for i := 0; i < b.N; i++ { + err = f(0, r.stack) + } + b.StopTimer() + toperr = err + }) + } +} diff --git a/vendor/github.com/pkg/errors/errors.go b/vendor/github.com/pkg/errors/errors.go new file mode 100644 index 00000000..842ee804 --- /dev/null +++ b/vendor/github.com/pkg/errors/errors.go @@ -0,0 +1,269 @@ +// Package errors provides simple error handling primitives. +// +// The traditional error handling idiom in Go is roughly akin to +// +// if err != nil { +// return err +// } +// +// which applied recursively up the call stack results in error reports +// without context or debugging information. The errors package allows +// programmers to add context to the failure path in their code in a way +// that does not destroy the original value of the error. +// +// Adding context to an error +// +// The errors.Wrap function returns a new error that adds context to the +// original error by recording a stack trace at the point Wrap is called, +// and the supplied message. For example +// +// _, err := ioutil.ReadAll(r) +// if err != nil { +// return errors.Wrap(err, "read failed") +// } +// +// If additional control is required the errors.WithStack and errors.WithMessage +// functions destructure errors.Wrap into its component operations of annotating +// an error with a stack trace and an a message, respectively. +// +// Retrieving the cause of an error +// +// Using errors.Wrap constructs a stack of errors, adding context to the +// preceding error. Depending on the nature of the error it may be necessary +// to reverse the operation of errors.Wrap to retrieve the original error +// for inspection. Any error value which implements this interface +// +// type causer interface { +// Cause() error +// } +// +// can be inspected by errors.Cause. errors.Cause will recursively retrieve +// the topmost error which does not implement causer, which is assumed to be +// the original cause. For example: +// +// switch err := errors.Cause(err).(type) { +// case *MyError: +// // handle specifically +// default: +// // unknown error +// } +// +// causer interface is not exported by this package, but is considered a part +// of stable public API. +// +// Formatted printing of errors +// +// All error values returned from this package implement fmt.Formatter and can +// be formatted by the fmt package. The following verbs are supported +// +// %s print the error. If the error has a Cause it will be +// printed recursively +// %v see %s +// %+v extended format. Each Frame of the error's StackTrace will +// be printed in detail. +// +// Retrieving the stack trace of an error or wrapper +// +// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are +// invoked. This information can be retrieved with the following interface. +// +// type stackTracer interface { +// StackTrace() errors.StackTrace +// } +// +// Where errors.StackTrace is defined as +// +// type StackTrace []Frame +// +// The Frame type represents a call site in the stack trace. Frame supports +// the fmt.Formatter interface that can be used for printing information about +// the stack trace of this error. For example: +// +// if err, ok := err.(stackTracer); ok { +// for _, f := range err.StackTrace() { +// fmt.Printf("%+s:%d", f) +// } +// } +// +// stackTracer interface is not exported by this package, but is considered a part +// of stable public API. +// +// See the documentation for Frame.Format for more details. +package errors + +import ( + "fmt" + "io" +) + +// New returns an error with the supplied message. +// New also records the stack trace at the point it was called. +func New(message string) error { + return &fundamental{ + msg: message, + stack: callers(), + } +} + +// Errorf formats according to a format specifier and returns the string +// as a value that satisfies error. +// Errorf also records the stack trace at the point it was called. +func Errorf(format string, args ...interface{}) error { + return &fundamental{ + msg: fmt.Sprintf(format, args...), + stack: callers(), + } +} + +// fundamental is an error that has a message and a stack, but no caller. +type fundamental struct { + msg string + *stack +} + +func (f *fundamental) Error() string { return f.msg } + +func (f *fundamental) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + if s.Flag('+') { + io.WriteString(s, f.msg) + f.stack.Format(s, verb) + return + } + fallthrough + case 's': + io.WriteString(s, f.msg) + case 'q': + fmt.Fprintf(s, "%q", f.msg) + } +} + +// WithStack annotates err with a stack trace at the point WithStack was called. +// If err is nil, WithStack returns nil. +func WithStack(err error) error { + if err == nil { + return nil + } + return &withStack{ + err, + callers(), + } +} + +type withStack struct { + error + *stack +} + +func (w *withStack) Cause() error { return w.error } + +func (w *withStack) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + if s.Flag('+') { + fmt.Fprintf(s, "%+v", w.Cause()) + w.stack.Format(s, verb) + return + } + fallthrough + case 's': + io.WriteString(s, w.Error()) + case 'q': + fmt.Fprintf(s, "%q", w.Error()) + } +} + +// Wrap returns an error annotating err with a stack trace +// at the point Wrap is called, and the supplied message. +// If err is nil, Wrap returns nil. +func Wrap(err error, message string) error { + if err == nil { + return nil + } + err = &withMessage{ + cause: err, + msg: message, + } + return &withStack{ + err, + callers(), + } +} + +// Wrapf returns an error annotating err with a stack trace +// at the point Wrapf is call, and the format specifier. +// If err is nil, Wrapf returns nil. +func Wrapf(err error, format string, args ...interface{}) error { + if err == nil { + return nil + } + err = &withMessage{ + cause: err, + msg: fmt.Sprintf(format, args...), + } + return &withStack{ + err, + callers(), + } +} + +// WithMessage annotates err with a new message. +// If err is nil, WithMessage returns nil. +func WithMessage(err error, message string) error { + if err == nil { + return nil + } + return &withMessage{ + cause: err, + msg: message, + } +} + +type withMessage struct { + cause error + msg string +} + +func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } +func (w *withMessage) Cause() error { return w.cause } + +func (w *withMessage) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + if s.Flag('+') { + fmt.Fprintf(s, "%+v\n", w.Cause()) + io.WriteString(s, w.msg) + return + } + fallthrough + case 's', 'q': + io.WriteString(s, w.Error()) + } +} + +// Cause returns the underlying cause of the error, if possible. +// An error value has a cause if it implements the following +// interface: +// +// type causer interface { +// Cause() error +// } +// +// If the error does not implement Cause, the original error will +// be returned. If the error is nil, nil will be returned without further +// investigation. +func Cause(err error) error { + type causer interface { + Cause() error + } + + for err != nil { + cause, ok := err.(causer) + if !ok { + break + } + err = cause.Cause() + } + return err +} diff --git a/vendor/github.com/pkg/errors/errors_test.go b/vendor/github.com/pkg/errors/errors_test.go new file mode 100644 index 00000000..1d8c6355 --- /dev/null +++ b/vendor/github.com/pkg/errors/errors_test.go @@ -0,0 +1,226 @@ +package errors + +import ( + "errors" + "fmt" + "io" + "reflect" + "testing" +) + +func TestNew(t *testing.T) { + tests := []struct { + err string + want error + }{ + {"", fmt.Errorf("")}, + {"foo", fmt.Errorf("foo")}, + {"foo", New("foo")}, + {"string with format specifiers: %v", errors.New("string with format specifiers: %v")}, + } + + for _, tt := range tests { + got := New(tt.err) + if got.Error() != tt.want.Error() { + t.Errorf("New.Error(): got: %q, want %q", got, tt.want) + } + } +} + +func TestWrapNil(t *testing.T) { + got := Wrap(nil, "no error") + if got != nil { + t.Errorf("Wrap(nil, \"no error\"): got %#v, expected nil", got) + } +} + +func TestWrap(t *testing.T) { + tests := []struct { + err error + message string + want string + }{ + {io.EOF, "read error", "read error: EOF"}, + {Wrap(io.EOF, "read error"), "client error", "client error: read error: EOF"}, + } + + for _, tt := range tests { + got := Wrap(tt.err, tt.message).Error() + if got != tt.want { + t.Errorf("Wrap(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want) + } + } +} + +type nilError struct{} + +func (nilError) Error() string { return "nil error" } + +func TestCause(t *testing.T) { + x := New("error") + tests := []struct { + err error + want error + }{{ + // nil error is nil + err: nil, + want: nil, + }, { + // explicit nil error is nil + err: (error)(nil), + want: nil, + }, { + // typed nil is nil + err: (*nilError)(nil), + want: (*nilError)(nil), + }, { + // uncaused error is unaffected + err: io.EOF, + want: io.EOF, + }, { + // caused error returns cause + err: Wrap(io.EOF, "ignored"), + want: io.EOF, + }, { + err: x, // return from errors.New + want: x, + }, { + WithMessage(nil, "whoops"), + nil, + }, { + WithMessage(io.EOF, "whoops"), + io.EOF, + }, { + WithStack(nil), + nil, + }, { + WithStack(io.EOF), + io.EOF, + }} + + for i, tt := range tests { + got := Cause(tt.err) + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("test %d: got %#v, want %#v", i+1, got, tt.want) + } + } +} + +func TestWrapfNil(t *testing.T) { + got := Wrapf(nil, "no error") + if got != nil { + t.Errorf("Wrapf(nil, \"no error\"): got %#v, expected nil", got) + } +} + +func TestWrapf(t *testing.T) { + tests := []struct { + err error + message string + want string + }{ + {io.EOF, "read error", "read error: EOF"}, + {Wrapf(io.EOF, "read error without format specifiers"), "client error", "client error: read error without format specifiers: EOF"}, + {Wrapf(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"}, + } + + for _, tt := range tests { + got := Wrapf(tt.err, tt.message).Error() + if got != tt.want { + t.Errorf("Wrapf(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want) + } + } +} + +func TestErrorf(t *testing.T) { + tests := []struct { + err error + want string + }{ + {Errorf("read error without format specifiers"), "read error without format specifiers"}, + {Errorf("read error with %d format specifier", 1), "read error with 1 format specifier"}, + } + + for _, tt := range tests { + got := tt.err.Error() + if got != tt.want { + t.Errorf("Errorf(%v): got: %q, want %q", tt.err, got, tt.want) + } + } +} + +func TestWithStackNil(t *testing.T) { + got := WithStack(nil) + if got != nil { + t.Errorf("WithStack(nil): got %#v, expected nil", got) + } +} + +func TestWithStack(t *testing.T) { + tests := []struct { + err error + want string + }{ + {io.EOF, "EOF"}, + {WithStack(io.EOF), "EOF"}, + } + + for _, tt := range tests { + got := WithStack(tt.err).Error() + if got != tt.want { + t.Errorf("WithStack(%v): got: %v, want %v", tt.err, got, tt.want) + } + } +} + +func TestWithMessageNil(t *testing.T) { + got := WithMessage(nil, "no error") + if got != nil { + t.Errorf("WithMessage(nil, \"no error\"): got %#v, expected nil", got) + } +} + +func TestWithMessage(t *testing.T) { + tests := []struct { + err error + message string + want string + }{ + {io.EOF, "read error", "read error: EOF"}, + {WithMessage(io.EOF, "read error"), "client error", "client error: read error: EOF"}, + } + + for _, tt := range tests { + got := WithMessage(tt.err, tt.message).Error() + if got != tt.want { + t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want) + } + } + +} + +// errors.New, etc values are not expected to be compared by value +// but the change in errors#27 made them incomparable. Assert that +// various kinds of errors have a functional equality operator, even +// if the result of that equality is always false. +func TestErrorEquality(t *testing.T) { + vals := []error{ + nil, + io.EOF, + errors.New("EOF"), + New("EOF"), + Errorf("EOF"), + Wrap(io.EOF, "EOF"), + Wrapf(io.EOF, "EOF%d", 2), + WithMessage(nil, "whoops"), + WithMessage(io.EOF, "whoops"), + WithStack(io.EOF), + WithStack(nil), + } + + for i := range vals { + for j := range vals { + _ = vals[i] == vals[j] // mustn't panic + } + } +} diff --git a/vendor/github.com/pkg/errors/example_test.go b/vendor/github.com/pkg/errors/example_test.go new file mode 100644 index 00000000..c1fc13e3 --- /dev/null +++ b/vendor/github.com/pkg/errors/example_test.go @@ -0,0 +1,205 @@ +package errors_test + +import ( + "fmt" + + "github.com/pkg/errors" +) + +func ExampleNew() { + err := errors.New("whoops") + fmt.Println(err) + + // Output: whoops +} + +func ExampleNew_printf() { + err := errors.New("whoops") + fmt.Printf("%+v", err) + + // Example output: + // whoops + // github.com/pkg/errors_test.ExampleNew_printf + // /home/dfc/src/github.com/pkg/errors/example_test.go:17 + // testing.runExample + // /home/dfc/go/src/testing/example.go:114 + // testing.RunExamples + // /home/dfc/go/src/testing/example.go:38 + // testing.(*M).Run + // /home/dfc/go/src/testing/testing.go:744 + // main.main + // /github.com/pkg/errors/_test/_testmain.go:106 + // runtime.main + // /home/dfc/go/src/runtime/proc.go:183 + // runtime.goexit + // /home/dfc/go/src/runtime/asm_amd64.s:2059 +} + +func ExampleWithMessage() { + cause := errors.New("whoops") + err := errors.WithMessage(cause, "oh noes") + fmt.Println(err) + + // Output: oh noes: whoops +} + +func ExampleWithStack() { + cause := errors.New("whoops") + err := errors.WithStack(cause) + fmt.Println(err) + + // Output: whoops +} + +func ExampleWithStack_printf() { + cause := errors.New("whoops") + err := errors.WithStack(cause) + fmt.Printf("%+v", err) + + // Example Output: + // whoops + // github.com/pkg/errors_test.ExampleWithStack_printf + // /home/fabstu/go/src/github.com/pkg/errors/example_test.go:55 + // testing.runExample + // /usr/lib/go/src/testing/example.go:114 + // testing.RunExamples + // /usr/lib/go/src/testing/example.go:38 + // testing.(*M).Run + // /usr/lib/go/src/testing/testing.go:744 + // main.main + // github.com/pkg/errors/_test/_testmain.go:106 + // runtime.main + // /usr/lib/go/src/runtime/proc.go:183 + // runtime.goexit + // /usr/lib/go/src/runtime/asm_amd64.s:2086 + // github.com/pkg/errors_test.ExampleWithStack_printf + // /home/fabstu/go/src/github.com/pkg/errors/example_test.go:56 + // testing.runExample + // /usr/lib/go/src/testing/example.go:114 + // testing.RunExamples + // /usr/lib/go/src/testing/example.go:38 + // testing.(*M).Run + // /usr/lib/go/src/testing/testing.go:744 + // main.main + // github.com/pkg/errors/_test/_testmain.go:106 + // runtime.main + // /usr/lib/go/src/runtime/proc.go:183 + // runtime.goexit + // /usr/lib/go/src/runtime/asm_amd64.s:2086 +} + +func ExampleWrap() { + cause := errors.New("whoops") + err := errors.Wrap(cause, "oh noes") + fmt.Println(err) + + // Output: oh noes: whoops +} + +func fn() error { + e1 := errors.New("error") + e2 := errors.Wrap(e1, "inner") + e3 := errors.Wrap(e2, "middle") + return errors.Wrap(e3, "outer") +} + +func ExampleCause() { + err := fn() + fmt.Println(err) + fmt.Println(errors.Cause(err)) + + // Output: outer: middle: inner: error + // error +} + +func ExampleWrap_extended() { + err := fn() + fmt.Printf("%+v\n", err) + + // Example output: + // error + // github.com/pkg/errors_test.fn + // /home/dfc/src/github.com/pkg/errors/example_test.go:47 + // github.com/pkg/errors_test.ExampleCause_printf + // /home/dfc/src/github.com/pkg/errors/example_test.go:63 + // testing.runExample + // /home/dfc/go/src/testing/example.go:114 + // testing.RunExamples + // /home/dfc/go/src/testing/example.go:38 + // testing.(*M).Run + // /home/dfc/go/src/testing/testing.go:744 + // main.main + // /github.com/pkg/errors/_test/_testmain.go:104 + // runtime.main + // /home/dfc/go/src/runtime/proc.go:183 + // runtime.goexit + // /home/dfc/go/src/runtime/asm_amd64.s:2059 + // github.com/pkg/errors_test.fn + // /home/dfc/src/github.com/pkg/errors/example_test.go:48: inner + // github.com/pkg/errors_test.fn + // /home/dfc/src/github.com/pkg/errors/example_test.go:49: middle + // github.com/pkg/errors_test.fn + // /home/dfc/src/github.com/pkg/errors/example_test.go:50: outer +} + +func ExampleWrapf() { + cause := errors.New("whoops") + err := errors.Wrapf(cause, "oh noes #%d", 2) + fmt.Println(err) + + // Output: oh noes #2: whoops +} + +func ExampleErrorf_extended() { + err := errors.Errorf("whoops: %s", "foo") + fmt.Printf("%+v", err) + + // Example output: + // whoops: foo + // github.com/pkg/errors_test.ExampleErrorf + // /home/dfc/src/github.com/pkg/errors/example_test.go:101 + // testing.runExample + // /home/dfc/go/src/testing/example.go:114 + // testing.RunExamples + // /home/dfc/go/src/testing/example.go:38 + // testing.(*M).Run + // /home/dfc/go/src/testing/testing.go:744 + // main.main + // /github.com/pkg/errors/_test/_testmain.go:102 + // runtime.main + // /home/dfc/go/src/runtime/proc.go:183 + // runtime.goexit + // /home/dfc/go/src/runtime/asm_amd64.s:2059 +} + +func Example_stackTrace() { + type stackTracer interface { + StackTrace() errors.StackTrace + } + + err, ok := errors.Cause(fn()).(stackTracer) + if !ok { + panic("oops, err does not implement stackTracer") + } + + st := err.StackTrace() + fmt.Printf("%+v", st[0:2]) // top two frames + + // Example output: + // github.com/pkg/errors_test.fn + // /home/dfc/src/github.com/pkg/errors/example_test.go:47 + // github.com/pkg/errors_test.Example_stackTrace + // /home/dfc/src/github.com/pkg/errors/example_test.go:127 +} + +func ExampleCause_printf() { + err := errors.Wrap(func() error { + return func() error { + return errors.Errorf("hello %s", fmt.Sprintf("world")) + }() + }(), "failed") + + fmt.Printf("%v", err) + + // Output: failed: hello world +} diff --git a/vendor/github.com/pkg/errors/format_test.go b/vendor/github.com/pkg/errors/format_test.go new file mode 100644 index 00000000..15fd7d89 --- /dev/null +++ b/vendor/github.com/pkg/errors/format_test.go @@ -0,0 +1,535 @@ +package errors + +import ( + "errors" + "fmt" + "io" + "regexp" + "strings" + "testing" +) + +func TestFormatNew(t *testing.T) { + tests := []struct { + error + format string + want string + }{{ + New("error"), + "%s", + "error", + }, { + New("error"), + "%v", + "error", + }, { + New("error"), + "%+v", + "error\n" + + "github.com/pkg/errors.TestFormatNew\n" + + "\t.+/github.com/pkg/errors/format_test.go:26", + }, { + New("error"), + "%q", + `"error"`, + }} + + for i, tt := range tests { + testFormatRegexp(t, i, tt.error, tt.format, tt.want) + } +} + +func TestFormatErrorf(t *testing.T) { + tests := []struct { + error + format string + want string + }{{ + Errorf("%s", "error"), + "%s", + "error", + }, { + Errorf("%s", "error"), + "%v", + "error", + }, { + Errorf("%s", "error"), + "%+v", + "error\n" + + "github.com/pkg/errors.TestFormatErrorf\n" + + "\t.+/github.com/pkg/errors/format_test.go:56", + }} + + for i, tt := range tests { + testFormatRegexp(t, i, tt.error, tt.format, tt.want) + } +} + +func TestFormatWrap(t *testing.T) { + tests := []struct { + error + format string + want string + }{{ + Wrap(New("error"), "error2"), + "%s", + "error2: error", + }, { + Wrap(New("error"), "error2"), + "%v", + "error2: error", + }, { + Wrap(New("error"), "error2"), + "%+v", + "error\n" + + "github.com/pkg/errors.TestFormatWrap\n" + + "\t.+/github.com/pkg/errors/format_test.go:82", + }, { + Wrap(io.EOF, "error"), + "%s", + "error: EOF", + }, { + Wrap(io.EOF, "error"), + "%v", + "error: EOF", + }, { + Wrap(io.EOF, "error"), + "%+v", + "EOF\n" + + "error\n" + + "github.com/pkg/errors.TestFormatWrap\n" + + "\t.+/github.com/pkg/errors/format_test.go:96", + }, { + Wrap(Wrap(io.EOF, "error1"), "error2"), + "%+v", + "EOF\n" + + "error1\n" + + "github.com/pkg/errors.TestFormatWrap\n" + + "\t.+/github.com/pkg/errors/format_test.go:103\n", + }, { + Wrap(New("error with space"), "context"), + "%q", + `"context: error with space"`, + }} + + for i, tt := range tests { + testFormatRegexp(t, i, tt.error, tt.format, tt.want) + } +} + +func TestFormatWrapf(t *testing.T) { + tests := []struct { + error + format string + want string + }{{ + Wrapf(io.EOF, "error%d", 2), + "%s", + "error2: EOF", + }, { + Wrapf(io.EOF, "error%d", 2), + "%v", + "error2: EOF", + }, { + Wrapf(io.EOF, "error%d", 2), + "%+v", + "EOF\n" + + "error2\n" + + "github.com/pkg/errors.TestFormatWrapf\n" + + "\t.+/github.com/pkg/errors/format_test.go:134", + }, { + Wrapf(New("error"), "error%d", 2), + "%s", + "error2: error", + }, { + Wrapf(New("error"), "error%d", 2), + "%v", + "error2: error", + }, { + Wrapf(New("error"), "error%d", 2), + "%+v", + "error\n" + + "github.com/pkg/errors.TestFormatWrapf\n" + + "\t.+/github.com/pkg/errors/format_test.go:149", + }} + + for i, tt := range tests { + testFormatRegexp(t, i, tt.error, tt.format, tt.want) + } +} + +func TestFormatWithStack(t *testing.T) { + tests := []struct { + error + format string + want []string + }{{ + WithStack(io.EOF), + "%s", + []string{"EOF"}, + }, { + WithStack(io.EOF), + "%v", + []string{"EOF"}, + }, { + WithStack(io.EOF), + "%+v", + []string{"EOF", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:175"}, + }, { + WithStack(New("error")), + "%s", + []string{"error"}, + }, { + WithStack(New("error")), + "%v", + []string{"error"}, + }, { + WithStack(New("error")), + "%+v", + []string{"error", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:189", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:189"}, + }, { + WithStack(WithStack(io.EOF)), + "%+v", + []string{"EOF", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:197", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:197"}, + }, { + WithStack(WithStack(Wrapf(io.EOF, "message"))), + "%+v", + []string{"EOF", + "message", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:205", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:205", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:205"}, + }, { + WithStack(Errorf("error%d", 1)), + "%+v", + []string{"error1", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:216", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:216"}, + }} + + for i, tt := range tests { + testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true) + } +} + +func TestFormatWithMessage(t *testing.T) { + tests := []struct { + error + format string + want []string + }{{ + WithMessage(New("error"), "error2"), + "%s", + []string{"error2: error"}, + }, { + WithMessage(New("error"), "error2"), + "%v", + []string{"error2: error"}, + }, { + WithMessage(New("error"), "error2"), + "%+v", + []string{ + "error", + "github.com/pkg/errors.TestFormatWithMessage\n" + + "\t.+/github.com/pkg/errors/format_test.go:244", + "error2"}, + }, { + WithMessage(io.EOF, "addition1"), + "%s", + []string{"addition1: EOF"}, + }, { + WithMessage(io.EOF, "addition1"), + "%v", + []string{"addition1: EOF"}, + }, { + WithMessage(io.EOF, "addition1"), + "%+v", + []string{"EOF", "addition1"}, + }, { + WithMessage(WithMessage(io.EOF, "addition1"), "addition2"), + "%v", + []string{"addition2: addition1: EOF"}, + }, { + WithMessage(WithMessage(io.EOF, "addition1"), "addition2"), + "%+v", + []string{"EOF", "addition1", "addition2"}, + }, { + Wrap(WithMessage(io.EOF, "error1"), "error2"), + "%+v", + []string{"EOF", "error1", "error2", + "github.com/pkg/errors.TestFormatWithMessage\n" + + "\t.+/github.com/pkg/errors/format_test.go:272"}, + }, { + WithMessage(Errorf("error%d", 1), "error2"), + "%+v", + []string{"error1", + "github.com/pkg/errors.TestFormatWithMessage\n" + + "\t.+/github.com/pkg/errors/format_test.go:278", + "error2"}, + }, { + WithMessage(WithStack(io.EOF), "error"), + "%+v", + []string{ + "EOF", + "github.com/pkg/errors.TestFormatWithMessage\n" + + "\t.+/github.com/pkg/errors/format_test.go:285", + "error"}, + }, { + WithMessage(Wrap(WithStack(io.EOF), "inside-error"), "outside-error"), + "%+v", + []string{ + "EOF", + "github.com/pkg/errors.TestFormatWithMessage\n" + + "\t.+/github.com/pkg/errors/format_test.go:293", + "inside-error", + "github.com/pkg/errors.TestFormatWithMessage\n" + + "\t.+/github.com/pkg/errors/format_test.go:293", + "outside-error"}, + }} + + for i, tt := range tests { + testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true) + } +} + +func TestFormatGeneric(t *testing.T) { + starts := []struct { + err error + want []string + }{ + {New("new-error"), []string{ + "new-error", + "github.com/pkg/errors.TestFormatGeneric\n" + + "\t.+/github.com/pkg/errors/format_test.go:315"}, + }, {Errorf("errorf-error"), []string{ + "errorf-error", + "github.com/pkg/errors.TestFormatGeneric\n" + + "\t.+/github.com/pkg/errors/format_test.go:319"}, + }, {errors.New("errors-new-error"), []string{ + "errors-new-error"}, + }, + } + + wrappers := []wrapper{ + { + func(err error) error { return WithMessage(err, "with-message") }, + []string{"with-message"}, + }, { + func(err error) error { return WithStack(err) }, + []string{ + "github.com/pkg/errors.(func·002|TestFormatGeneric.func2)\n\t" + + ".+/github.com/pkg/errors/format_test.go:333", + }, + }, { + func(err error) error { return Wrap(err, "wrap-error") }, + []string{ + "wrap-error", + "github.com/pkg/errors.(func·003|TestFormatGeneric.func3)\n\t" + + ".+/github.com/pkg/errors/format_test.go:339", + }, + }, { + func(err error) error { return Wrapf(err, "wrapf-error%d", 1) }, + []string{ + "wrapf-error1", + "github.com/pkg/errors.(func·004|TestFormatGeneric.func4)\n\t" + + ".+/github.com/pkg/errors/format_test.go:346", + }, + }, + } + + for s := range starts { + err := starts[s].err + want := starts[s].want + testFormatCompleteCompare(t, s, err, "%+v", want, false) + testGenericRecursive(t, err, want, wrappers, 3) + } +} + +func testFormatRegexp(t *testing.T, n int, arg interface{}, format, want string) { + got := fmt.Sprintf(format, arg) + gotLines := strings.SplitN(got, "\n", -1) + wantLines := strings.SplitN(want, "\n", -1) + + if len(wantLines) > len(gotLines) { + t.Errorf("test %d: wantLines(%d) > gotLines(%d):\n got: %q\nwant: %q", n+1, len(wantLines), len(gotLines), got, want) + return + } + + for i, w := range wantLines { + match, err := regexp.MatchString(w, gotLines[i]) + if err != nil { + t.Fatal(err) + } + if !match { + t.Errorf("test %d: line %d: fmt.Sprintf(%q, err):\n got: %q\nwant: %q", n+1, i+1, format, got, want) + } + } +} + +var stackLineR = regexp.MustCompile(`\.`) + +// parseBlocks parses input into a slice, where: +// - incase entry contains a newline, its a stacktrace +// - incase entry contains no newline, its a solo line. +// +// Detecting stack boundaries only works incase the WithStack-calls are +// to be found on the same line, thats why it is optionally here. +// +// Example use: +// +// for _, e := range blocks { +// if strings.ContainsAny(e, "\n") { +// // Match as stack +// } else { +// // Match as line +// } +// } +// +func parseBlocks(input string, detectStackboundaries bool) ([]string, error) { + var blocks []string + + stack := "" + wasStack := false + lines := map[string]bool{} // already found lines + + for _, l := range strings.Split(input, "\n") { + isStackLine := stackLineR.MatchString(l) + + switch { + case !isStackLine && wasStack: + blocks = append(blocks, stack, l) + stack = "" + lines = map[string]bool{} + case isStackLine: + if wasStack { + // Detecting two stacks after another, possible cause lines match in + // our tests due to WithStack(WithStack(io.EOF)) on same line. + if detectStackboundaries { + if lines[l] { + if len(stack) == 0 { + return nil, errors.New("len of block must not be zero here") + } + + blocks = append(blocks, stack) + stack = l + lines = map[string]bool{l: true} + continue + } + } + + stack = stack + "\n" + l + } else { + stack = l + } + lines[l] = true + case !isStackLine && !wasStack: + blocks = append(blocks, l) + default: + return nil, errors.New("must not happen") + } + + wasStack = isStackLine + } + + // Use up stack + if stack != "" { + blocks = append(blocks, stack) + } + return blocks, nil +} + +func testFormatCompleteCompare(t *testing.T, n int, arg interface{}, format string, want []string, detectStackBoundaries bool) { + gotStr := fmt.Sprintf(format, arg) + + got, err := parseBlocks(gotStr, detectStackBoundaries) + if err != nil { + t.Fatal(err) + } + + if len(got) != len(want) { + t.Fatalf("test %d: fmt.Sprintf(%s, err) -> wrong number of blocks: got(%d) want(%d)\n got: %s\nwant: %s\ngotStr: %q", + n+1, format, len(got), len(want), prettyBlocks(got), prettyBlocks(want), gotStr) + } + + for i := range got { + if strings.ContainsAny(want[i], "\n") { + // Match as stack + match, err := regexp.MatchString(want[i], got[i]) + if err != nil { + t.Fatal(err) + } + if !match { + t.Fatalf("test %d: block %d: fmt.Sprintf(%q, err):\ngot:\n%q\nwant:\n%q\nall-got:\n%s\nall-want:\n%s\n", + n+1, i+1, format, got[i], want[i], prettyBlocks(got), prettyBlocks(want)) + } + } else { + // Match as message + if got[i] != want[i] { + t.Fatalf("test %d: fmt.Sprintf(%s, err) at block %d got != want:\n got: %q\nwant: %q", n+1, format, i+1, got[i], want[i]) + } + } + } +} + +type wrapper struct { + wrap func(err error) error + want []string +} + +func prettyBlocks(blocks []string, prefix ...string) string { + var out []string + + for _, b := range blocks { + out = append(out, fmt.Sprintf("%v", b)) + } + + return " " + strings.Join(out, "\n ") +} + +func testGenericRecursive(t *testing.T, beforeErr error, beforeWant []string, list []wrapper, maxDepth int) { + if len(beforeWant) == 0 { + panic("beforeWant must not be empty") + } + for _, w := range list { + if len(w.want) == 0 { + panic("want must not be empty") + } + + err := w.wrap(beforeErr) + + // Copy required cause append(beforeWant, ..) modified beforeWant subtly. + beforeCopy := make([]string, len(beforeWant)) + copy(beforeCopy, beforeWant) + + beforeWant := beforeCopy + last := len(beforeWant) - 1 + var want []string + + // Merge two stacks behind each other. + if strings.ContainsAny(beforeWant[last], "\n") && strings.ContainsAny(w.want[0], "\n") { + want = append(beforeWant[:last], append([]string{beforeWant[last] + "((?s).*)" + w.want[0]}, w.want[1:]...)...) + } else { + want = append(beforeWant, w.want...) + } + + testFormatCompleteCompare(t, maxDepth, err, "%+v", want, false) + if maxDepth > 0 { + testGenericRecursive(t, err, want, list, maxDepth-1) + } + } +} diff --git a/vendor/github.com/pkg/errors/stack.go b/vendor/github.com/pkg/errors/stack.go new file mode 100644 index 00000000..6b1f2891 --- /dev/null +++ b/vendor/github.com/pkg/errors/stack.go @@ -0,0 +1,178 @@ +package errors + +import ( + "fmt" + "io" + "path" + "runtime" + "strings" +) + +// Frame represents a program counter inside a stack frame. +type Frame uintptr + +// pc returns the program counter for this frame; +// multiple frames may have the same PC value. +func (f Frame) pc() uintptr { return uintptr(f) - 1 } + +// file returns the full path to the file that contains the +// function for this Frame's pc. +func (f Frame) file() string { + fn := runtime.FuncForPC(f.pc()) + if fn == nil { + return "unknown" + } + file, _ := fn.FileLine(f.pc()) + return file +} + +// line returns the line number of source code of the +// function for this Frame's pc. +func (f Frame) line() int { + fn := runtime.FuncForPC(f.pc()) + if fn == nil { + return 0 + } + _, line := fn.FileLine(f.pc()) + return line +} + +// Format formats the frame according to the fmt.Formatter interface. +// +// %s source file +// %d source line +// %n function name +// %v equivalent to %s:%d +// +// Format accepts flags that alter the printing of some verbs, as follows: +// +// %+s path of source file relative to the compile time GOPATH +// %+v equivalent to %+s:%d +func (f Frame) Format(s fmt.State, verb rune) { + switch verb { + case 's': + switch { + case s.Flag('+'): + pc := f.pc() + fn := runtime.FuncForPC(pc) + if fn == nil { + io.WriteString(s, "unknown") + } else { + file, _ := fn.FileLine(pc) + fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file) + } + default: + io.WriteString(s, path.Base(f.file())) + } + case 'd': + fmt.Fprintf(s, "%d", f.line()) + case 'n': + name := runtime.FuncForPC(f.pc()).Name() + io.WriteString(s, funcname(name)) + case 'v': + f.Format(s, 's') + io.WriteString(s, ":") + f.Format(s, 'd') + } +} + +// StackTrace is stack of Frames from innermost (newest) to outermost (oldest). +type StackTrace []Frame + +func (st StackTrace) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + switch { + case s.Flag('+'): + for _, f := range st { + fmt.Fprintf(s, "\n%+v", f) + } + case s.Flag('#'): + fmt.Fprintf(s, "%#v", []Frame(st)) + default: + fmt.Fprintf(s, "%v", []Frame(st)) + } + case 's': + fmt.Fprintf(s, "%s", []Frame(st)) + } +} + +// stack represents a stack of program counters. +type stack []uintptr + +func (s *stack) Format(st fmt.State, verb rune) { + switch verb { + case 'v': + switch { + case st.Flag('+'): + for _, pc := range *s { + f := Frame(pc) + fmt.Fprintf(st, "\n%+v", f) + } + } + } +} + +func (s *stack) StackTrace() StackTrace { + f := make([]Frame, len(*s)) + for i := 0; i < len(f); i++ { + f[i] = Frame((*s)[i]) + } + return f +} + +func callers() *stack { + const depth = 32 + var pcs [depth]uintptr + n := runtime.Callers(3, pcs[:]) + var st stack = pcs[0:n] + return &st +} + +// funcname removes the path prefix component of a function's name reported by func.Name(). +func funcname(name string) string { + i := strings.LastIndex(name, "/") + name = name[i+1:] + i = strings.Index(name, ".") + return name[i+1:] +} + +func trimGOPATH(name, file string) string { + // Here we want to get the source file path relative to the compile time + // GOPATH. As of Go 1.6.x there is no direct way to know the compiled + // GOPATH at runtime, but we can infer the number of path segments in the + // GOPATH. We note that fn.Name() returns the function name qualified by + // the import path, which does not include the GOPATH. Thus we can trim + // segments from the beginning of the file path until the number of path + // separators remaining is one more than the number of path separators in + // the function name. For example, given: + // + // GOPATH /home/user + // file /home/user/src/pkg/sub/file.go + // fn.Name() pkg/sub.Type.Method + // + // We want to produce: + // + // pkg/sub/file.go + // + // From this we can easily see that fn.Name() has one less path separator + // than our desired output. We count separators from the end of the file + // path until it finds two more than in the function name and then move + // one character forward to preserve the initial path segment without a + // leading separator. + const sep = "/" + goal := strings.Count(name, sep) + 2 + i := len(file) + for n := 0; n < goal; n++ { + i = strings.LastIndex(file[:i], sep) + if i == -1 { + // not enough separators found, set i so that the slice expression + // below leaves file unmodified + i = -len(sep) + break + } + } + // get back to 0 or trim the leading separator + file = file[i+len(sep):] + return file +} diff --git a/vendor/github.com/pkg/errors/stack_test.go b/vendor/github.com/pkg/errors/stack_test.go new file mode 100644 index 00000000..510c27a9 --- /dev/null +++ b/vendor/github.com/pkg/errors/stack_test.go @@ -0,0 +1,292 @@ +package errors + +import ( + "fmt" + "runtime" + "testing" +) + +var initpc, _, _, _ = runtime.Caller(0) + +func TestFrameLine(t *testing.T) { + var tests = []struct { + Frame + want int + }{{ + Frame(initpc), + 9, + }, { + func() Frame { + var pc, _, _, _ = runtime.Caller(0) + return Frame(pc) + }(), + 20, + }, { + func() Frame { + var pc, _, _, _ = runtime.Caller(1) + return Frame(pc) + }(), + 28, + }, { + Frame(0), // invalid PC + 0, + }} + + for _, tt := range tests { + got := tt.Frame.line() + want := tt.want + if want != got { + t.Errorf("Frame(%v): want: %v, got: %v", uintptr(tt.Frame), want, got) + } + } +} + +type X struct{} + +func (x X) val() Frame { + var pc, _, _, _ = runtime.Caller(0) + return Frame(pc) +} + +func (x *X) ptr() Frame { + var pc, _, _, _ = runtime.Caller(0) + return Frame(pc) +} + +func TestFrameFormat(t *testing.T) { + var tests = []struct { + Frame + format string + want string + }{{ + Frame(initpc), + "%s", + "stack_test.go", + }, { + Frame(initpc), + "%+s", + "github.com/pkg/errors.init\n" + + "\t.+/github.com/pkg/errors/stack_test.go", + }, { + Frame(0), + "%s", + "unknown", + }, { + Frame(0), + "%+s", + "unknown", + }, { + Frame(initpc), + "%d", + "9", + }, { + Frame(0), + "%d", + "0", + }, { + Frame(initpc), + "%n", + "init", + }, { + func() Frame { + var x X + return x.ptr() + }(), + "%n", + `\(\*X\).ptr`, + }, { + func() Frame { + var x X + return x.val() + }(), + "%n", + "X.val", + }, { + Frame(0), + "%n", + "", + }, { + Frame(initpc), + "%v", + "stack_test.go:9", + }, { + Frame(initpc), + "%+v", + "github.com/pkg/errors.init\n" + + "\t.+/github.com/pkg/errors/stack_test.go:9", + }, { + Frame(0), + "%v", + "unknown:0", + }} + + for i, tt := range tests { + testFormatRegexp(t, i, tt.Frame, tt.format, tt.want) + } +} + +func TestFuncname(t *testing.T) { + tests := []struct { + name, want string + }{ + {"", ""}, + {"runtime.main", "main"}, + {"github.com/pkg/errors.funcname", "funcname"}, + {"funcname", "funcname"}, + {"io.copyBuffer", "copyBuffer"}, + {"main.(*R).Write", "(*R).Write"}, + } + + for _, tt := range tests { + got := funcname(tt.name) + want := tt.want + if got != want { + t.Errorf("funcname(%q): want: %q, got %q", tt.name, want, got) + } + } +} + +func TestTrimGOPATH(t *testing.T) { + var tests = []struct { + Frame + want string + }{{ + Frame(initpc), + "github.com/pkg/errors/stack_test.go", + }} + + for i, tt := range tests { + pc := tt.Frame.pc() + fn := runtime.FuncForPC(pc) + file, _ := fn.FileLine(pc) + got := trimGOPATH(fn.Name(), file) + testFormatRegexp(t, i, got, "%s", tt.want) + } +} + +func TestStackTrace(t *testing.T) { + tests := []struct { + err error + want []string + }{{ + New("ooh"), []string{ + "github.com/pkg/errors.TestStackTrace\n" + + "\t.+/github.com/pkg/errors/stack_test.go:172", + }, + }, { + Wrap(New("ooh"), "ahh"), []string{ + "github.com/pkg/errors.TestStackTrace\n" + + "\t.+/github.com/pkg/errors/stack_test.go:177", // this is the stack of Wrap, not New + }, + }, { + Cause(Wrap(New("ooh"), "ahh")), []string{ + "github.com/pkg/errors.TestStackTrace\n" + + "\t.+/github.com/pkg/errors/stack_test.go:182", // this is the stack of New + }, + }, { + func() error { return New("ooh") }(), []string{ + `github.com/pkg/errors.(func·009|TestStackTrace.func1)` + + "\n\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New + "github.com/pkg/errors.TestStackTrace\n" + + "\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New's caller + }, + }, { + Cause(func() error { + return func() error { + return Errorf("hello %s", fmt.Sprintf("world")) + }() + }()), []string{ + `github.com/pkg/errors.(func·010|TestStackTrace.func2.1)` + + "\n\t.+/github.com/pkg/errors/stack_test.go:196", // this is the stack of Errorf + `github.com/pkg/errors.(func·011|TestStackTrace.func2)` + + "\n\t.+/github.com/pkg/errors/stack_test.go:197", // this is the stack of Errorf's caller + "github.com/pkg/errors.TestStackTrace\n" + + "\t.+/github.com/pkg/errors/stack_test.go:198", // this is the stack of Errorf's caller's caller + }, + }} + for i, tt := range tests { + x, ok := tt.err.(interface { + StackTrace() StackTrace + }) + if !ok { + t.Errorf("expected %#v to implement StackTrace() StackTrace", tt.err) + continue + } + st := x.StackTrace() + for j, want := range tt.want { + testFormatRegexp(t, i, st[j], "%+v", want) + } + } +} + +func stackTrace() StackTrace { + const depth = 8 + var pcs [depth]uintptr + n := runtime.Callers(1, pcs[:]) + var st stack = pcs[0:n] + return st.StackTrace() +} + +func TestStackTraceFormat(t *testing.T) { + tests := []struct { + StackTrace + format string + want string + }{{ + nil, + "%s", + `\[\]`, + }, { + nil, + "%v", + `\[\]`, + }, { + nil, + "%+v", + "", + }, { + nil, + "%#v", + `\[\]errors.Frame\(nil\)`, + }, { + make(StackTrace, 0), + "%s", + `\[\]`, + }, { + make(StackTrace, 0), + "%v", + `\[\]`, + }, { + make(StackTrace, 0), + "%+v", + "", + }, { + make(StackTrace, 0), + "%#v", + `\[\]errors.Frame{}`, + }, { + stackTrace()[:2], + "%s", + `\[stack_test.go stack_test.go\]`, + }, { + stackTrace()[:2], + "%v", + `\[stack_test.go:225 stack_test.go:272\]`, + }, { + stackTrace()[:2], + "%+v", + "\n" + + "github.com/pkg/errors.stackTrace\n" + + "\t.+/github.com/pkg/errors/stack_test.go:225\n" + + "github.com/pkg/errors.TestStackTraceFormat\n" + + "\t.+/github.com/pkg/errors/stack_test.go:276", + }, { + stackTrace()[:2], + "%#v", + `\[\]errors.Frame{stack_test.go:225, stack_test.go:284}`, + }} + + for i, tt := range tests { + testFormatRegexp(t, i, tt.StackTrace, tt.format, tt.want) + } +}