From 98e5999761bf97f9dba8487d70afcdca23540e24 Mon Sep 17 00:00:00 2001 From: Kevin Atkinson Date: Sun, 26 Aug 2018 20:10:19 -0400 Subject: [PATCH] Factor out boiler plate code for PostRun in "ipfs filestore ls". License: MIT Signed-off-by: Kevin Atkinson --- core/commands/commands.go | 40 ++++++++++++++++++++++++++++++++++++++ core/commands/filestore.go | 37 +++++++---------------------------- 2 files changed, 47 insertions(+), 30 deletions(-) diff --git a/core/commands/commands.go b/core/commands/commands.go index 51c707c6e..a89b279f7 100644 --- a/core/commands/commands.go +++ b/core/commands/commands.go @@ -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 + } +} diff --git a/core/commands/filestore.go b/core/commands/filestore.go index a45e01ef9..deb7520d2 100644 --- a/core/commands/filestore.go +++ b/core/commands/filestore.go @@ -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{}, }