1
0
mirror of https://github.com/ipfs/kubo.git synced 2025-06-27 07:57:30 +08:00

Factor out boiler plate code for PostRun in "ipfs filestore ls".

License: MIT
Signed-off-by: Kevin Atkinson <k@kevina.org>
This commit is contained in:
Kevin Atkinson
2018-08-26 20:10:19 -04:00
parent 30b861bc5a
commit 98e5999761
2 changed files with 47 additions and 30 deletions

View File

@ -8,6 +8,7 @@ package commands
import (
"fmt"
"io"
"os"
"sort"
"strings"
@ -149,3 +150,42 @@ func unwrapOutput(i interface{}) (interface{}, error) {
return <-ch, nil
}
type nonFatalError string
// streamRes is a helper function to stream results, that possibly
// contain with non-fatal, the helper function is allowed to panic on
// internal errors
func streamRes(procVal func(interface{}, io.Writer) nonFatalError) func(cmds.Response, cmds.ResponseEmitter) error {
return func(res cmds.Response, re cmds.ResponseEmitter) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("internal error: %v", r)
}
re.Close()
}()
var errors bool
for {
v, err := res.Next()
if err != nil {
if err == io.EOF {
break
}
return err
}
errorMsg := procVal(v, os.Stdout)
if errorMsg != "" {
errors = true
fmt.Fprintf(os.Stderr, "%s\n", errorMsg)
}
}
if errors {
return fmt.Errorf("errors while displaying some entries")
}
return nil
}
}

View File

@ -4,7 +4,6 @@ import (
"context"
"fmt"
"io"
"os"
oldCmds "github.com/ipfs/go-ipfs/commands"
lgc "github.com/ipfs/go-ipfs/commands/legacy"
@ -73,36 +72,14 @@ The output is:
return res.Emit(out)
},
PostRun: cmds.PostRunMap{
cmds.CLI: func(res cmds.Response, re cmds.ResponseEmitter) error {
var errors bool
for {
v, err := res.Next()
if err != nil {
if err == io.EOF {
break
}
return err
}
r, ok := v.(*filestore.ListRes)
if !ok {
return e.New(e.TypeErr(r, v))
}
if r.ErrorMsg != "" {
errors = true
fmt.Fprintf(os.Stderr, "%s\n", r.ErrorMsg)
} else {
fmt.Fprintf(os.Stdout, "%s\n", r.FormatLong())
}
cmds.CLI: streamRes(func(v interface{}, out io.Writer) nonFatalError {
r := v.(*filestore.ListRes)
if r.ErrorMsg != "" {
return nonFatalError(r.ErrorMsg)
}
if errors {
return fmt.Errorf("errors while displaying some entries")
}
return nil
},
fmt.Fprintf(out, "%s\n", r.FormatLong())
return ""
}),
},
Type: filestore.ListRes{},
}