Factor out boiler plate code for PostRun in "ipfs filestore ls".
License: MIT Signed-off-by: Kevin Atkinson <k@kevina.org>
Kevin Atkinson committed
Aug 26, 2018 at 20:10 UTC
98e5999761bf97f9dba8487d70afcdca23540e24
2 files changed
+47
-30
core/commands/commands.go
+40
@@ -8,6 +8,7 @@ package commands
8
import (
9
"fmt"
10
"io"
11
+ "os"
12
"sort"
13
"strings"
14
@@ -149,3 +150,42 @@ func unwrapOutput(i interface{}) (interface{}, error) {
150
151
return <-ch, nil
152
}
153
+
154
+type nonFatalError string
155
+
156
+// streamRes is a helper function to stream results, that possibly
157
+// contain with non-fatal, the helper function is allowed to panic on
158
+// internal errors
159
+func streamRes(procVal func(interface{}, io.Writer) nonFatalError) func(cmds.Response, cmds.ResponseEmitter) error {
160
+ return func(res cmds.Response, re cmds.ResponseEmitter) (err error) {
161
+ defer func() {
162
+ if r := recover(); r != nil {
163
+ err = fmt.Errorf("internal error: %v", r)
164
+ }
165
+ re.Close()
166
+ }()
167
+
168
+ var errors bool
169
+ for {
170
+ v, err := res.Next()
171
+ if err != nil {
172
+ if err == io.EOF {
173
+ break
174
+ }
175
+ return err
176
+ }
177
+
178
+ errorMsg := procVal(v, os.Stdout)
179
+
180
+ if errorMsg != "" {
181
+ errors = true
182
+ fmt.Fprintf(os.Stderr, "%s\n", errorMsg)
183
+ }
184
+ }
185
+
186
+ if errors {
187
+ return fmt.Errorf("errors while displaying some entries")
188
+ }
189
+ return nil
190
+ }
191
+}
core/commands/filestore.go
+7
-30
@@ -4,7 +4,6 @@ import (
4
"context"
5
"fmt"
6
"io"
7
- "os"
7
8
oldCmds "github.com/ipfs/go-ipfs/commands"
9
lgc "github.com/ipfs/go-ipfs/commands/legacy"
@@ -73,36 +72,14 @@ The output is:
72
return res.Emit(out)
73
},
74
PostRun: cmds.PostRunMap{
76
- cmds.CLI: func(res cmds.Response, re cmds.ResponseEmitter) error {
77
- var errors bool
78
- for {
79
- v, err := res.Next()
80
- if err != nil {
81
- if err == io.EOF {
82
- break
83
- }
84
- return err
85
- }
86
-
87
- r, ok := v.(*filestore.ListRes)
88
- if !ok {
89
- return e.New(e.TypeErr(r, v))
90
- }
91
-
92
- if r.ErrorMsg != "" {
93
- errors = true
94
- fmt.Fprintf(os.Stderr, "%s\n", r.ErrorMsg)
95
- } else {
96
- fmt.Fprintf(os.Stdout, "%s\n", r.FormatLong())
97
- }
98
- }
99
-
100
- if errors {
101
- return fmt.Errorf("errors while displaying some entries")
75
+ cmds.CLI: streamRes(func(v interface{}, out io.Writer) nonFatalError {
76
+ r := v.(*filestore.ListRes)
77
+ if r.ErrorMsg != "" {
78
+ return nonFatalError(r.ErrorMsg)
79
}
103
-
104
- return nil
105
- },
80
+ fmt.Fprintf(out, "%s\n", r.FormatLong())
81
+ return ""
82
+ }),
83
},
84
Type: filestore.ListRes{},
85
}