cmds: rm old lib
License: MIT Signed-off-by: Overbool <overbool.xu@gmail.com>
Overbool committed
Nov 21, 2018 at 18:58 UTC
a7485994d79e3d9061553b435557ed2e154b9ab2
10 files changed
+7
-901
commands/command.go
deleted
-68
@@ -1,68 +0,0 @@
1
-/*
2
-Package commands provides an API for defining and parsing commands.
3
-
4
-Supporting nested commands, options, arguments, etc. The commands
5
-package also supports a collection of marshallers for presenting
6
-output to the user, including text, JSON, and XML marshallers.
7
-*/
8
-
9
-package commands
10
-
11
-import (
12
- "io"
13
-
14
- logging "gx/ipfs/QmcuXC5cxs79ro2cUuHs4HQ2bkDLJUYokwL8aivcX6HW3C/go-log"
15
- cmdkit "gx/ipfs/Qmde5VP1qUkyQXKCfmEUA7bP64V2HAptbJ7phuPp7jXWwg/go-ipfs-cmdkit"
16
-)
17
-
18
-var log = logging.Logger("command")
19
-
20
-// Function is the type of function that Commands use.
21
-// It reads from the Request, and writes results to the Response.
22
-type Function func(Request, Response)
23
-
24
-// Marshaler is a function that takes in a Response, and returns an io.Reader
25
-// (or an error on failure)
26
-type Marshaler func(Response) (io.Reader, error)
27
-
28
-// MarshalerMap is a map of Marshaler functions, keyed by EncodingType
29
-// (or an error on failure)
30
-type MarshalerMap map[EncodingType]Marshaler
31
-
32
-// Command is a runnable command, with input arguments and options (flags).
33
-// It can also have Subcommands, to group units of work into sets.
34
-type Command struct {
35
- Options []cmdkit.Option
36
- Arguments []cmdkit.Argument
37
- PreRun func(req Request) error
38
-
39
- // Run is the function that processes the request to generate a response.
40
- // Note that when executing the command over the HTTP API you can only read
41
- // after writing when using multipart requests. The request body will not be
42
- // available for reading after the HTTP connection has been written to.
43
- Run Function
44
- PostRun Function
45
- Marshalers map[EncodingType]Marshaler
46
- Helptext cmdkit.HelpText
47
-
48
- // External denotes that a command is actually an external binary.
49
- // fewer checks and validations will be performed on such commands.
50
- External bool
51
-
52
- // Type describes the type of the output of the Command's Run Function.
53
- // In precise terms, the value of Type is an instance of the return type of
54
- // the Run Function.
55
- //
56
- // ie. If command Run returns &Block{}, then Command.Type == &Block{}
57
- Type interface{}
58
- Subcommands map[string]*Command
59
-}
60
-
61
-// Subcommand returns the subcommand with the given id
62
-func (c *Command) Subcommand(id string) *Command {
63
- return c.Subcommands[id]
64
-}
65
-
66
-func ClientError(msg string) error {
67
- return &cmdkit.Error{Code: cmdkit.ErrClient, Message: msg}
68
-}
commands/context.go
renamed
+6
-17
@@ -11,11 +11,13 @@ import (
11
coreiface "github.com/ipfs/go-ipfs/core/coreapi/interface"
12
13
config "gx/ipfs/QmXctaABKwgzmQgNM4bucMJf7zJnxxvhmPM1Pw95dxUfB5/go-ipfs-config"
14
- files "gx/ipfs/QmZMWMvWMVKCbHetJ4RgndbuEF1io2UpUxwQwtNjtYPzSC/go-ipfs-files"
14
"gx/ipfs/Qma6uuSyjkecGhMFFLfzyJDPyoDtNJSHJNweDccZhaWkgU/go-ipfs-cmds"
16
- "gx/ipfs/Qmde5VP1qUkyQXKCfmEUA7bP64V2HAptbJ7phuPp7jXWwg/go-ipfs-cmdkit"
15
+ logging "gx/ipfs/QmcuXC5cxs79ro2cUuHs4HQ2bkDLJUYokwL8aivcX6HW3C/go-log"
16
)
17
18
+var log = logging.Logger("command")
19
+
20
+// Context represents request context
21
type Context struct {
22
Online bool
23
ConfigRoot string
@@ -55,9 +57,9 @@ func (c *Context) GetNode() (*core.IpfsNode, error) {
57
return c.node, err
58
}
59
58
-// GetApi returns CoreAPI instance backed by ipfs node.
60
+// GetAPI returns CoreAPI instance backed by ipfs node.
61
// It may construct the node with the provided function
60
-func (c *Context) GetApi() (coreiface.CoreAPI, error) {
62
+func (c *Context) GetAPI() (coreiface.CoreAPI, error) {
63
if c.api == nil {
64
n, err := c.GetNode()
65
if err != nil {
@@ -109,16 +111,3 @@ func (c *Context) Close() {
111
c.node.Close()
112
}
113
}
112
-
113
-// Request represents a call to a command from a consumer
114
-type Request interface {
115
- Path() []string
116
- Option(name string) *cmdkit.OptionValue
117
- Options() cmdkit.OptMap
118
- Arguments() []string
119
- StringArguments() []string
120
- Files() files.File
121
- Context() context.Context
122
- InvocContext() *Context
123
- Command() *Command
124
-}
commands/legacy/command.go
deleted
-68
@@ -1,68 +0,0 @@
1
-package legacy
2
-
3
-import (
4
- "io"
5
-
6
- oldcmds "github.com/ipfs/go-ipfs/commands"
7
-
8
- "gx/ipfs/Qma6uuSyjkecGhMFFLfzyJDPyoDtNJSHJNweDccZhaWkgU/go-ipfs-cmds"
9
- logging "gx/ipfs/QmcuXC5cxs79ro2cUuHs4HQ2bkDLJUYokwL8aivcX6HW3C/go-log"
10
-)
11
-
12
-var log = logging.Logger("cmds/lgc")
13
-
14
-// NewCommand returns a Command from an oldcmds.Command
15
-func NewCommand(oldcmd *oldcmds.Command) *cmds.Command {
16
- if oldcmd == nil {
17
- return nil
18
- }
19
- var cmd *cmds.Command
20
-
21
- cmd = &cmds.Command{
22
- Options: oldcmd.Options,
23
- Arguments: oldcmd.Arguments,
24
- Helptext: oldcmd.Helptext,
25
- External: oldcmd.External,
26
- Type: oldcmd.Type,
27
-
28
- Subcommands: make(map[string]*cmds.Command),
29
- }
30
-
31
- if oldcmd.Run != nil {
32
- cmd.Run = func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) error {
33
- oldReq := &requestWrapper{req, OldContext(env)}
34
- res := &fakeResponse{req: oldReq, re: re, wait: make(chan struct{})}
35
-
36
- errCh := make(chan error)
37
- go res.Send(errCh)
38
-
39
- oldcmd.Run(oldReq, res)
40
- return <-errCh
41
- }
42
- }
43
-
44
- if oldcmd.PreRun != nil {
45
- cmd.PreRun = func(req *cmds.Request, env cmds.Environment) error {
46
- oldReq := &requestWrapper{req, OldContext(env)}
47
- return oldcmd.PreRun(oldReq)
48
- }
49
- }
50
-
51
- for name, sub := range oldcmd.Subcommands {
52
- cmd.Subcommands[name] = NewCommand(sub)
53
- }
54
-
55
- cmd.Encoders = make(cmds.EncoderMap)
56
-
57
- for encType, m := range oldcmd.Marshalers {
58
- cmd.Encoders[cmds.EncodingType(encType)] = func(m oldcmds.Marshaler, encType oldcmds.EncodingType) func(req *cmds.Request) func(io.Writer) cmds.Encoder {
59
- return func(req *cmds.Request) func(io.Writer) cmds.Encoder {
60
- return func(w io.Writer) cmds.Encoder {
61
- return NewMarshalerEncoder(req, m, w)
62
- }
63
- }
64
- }(m, encType)
65
- }
66
-
67
- return cmd
68
-}
commands/legacy/legacy.go
deleted
-57
@@ -1,57 +0,0 @@
1
-package legacy
2
-
3
-import (
4
- "io"
5
- "runtime/debug"
6
-
7
- "gx/ipfs/Qma6uuSyjkecGhMFFLfzyJDPyoDtNJSHJNweDccZhaWkgU/go-ipfs-cmds"
8
-
9
- oldcmds "github.com/ipfs/go-ipfs/commands"
10
-)
11
-
12
-// MarshalerEncoder implements Encoder from a Marshaler
13
-type MarshalerEncoder struct {
14
- m oldcmds.Marshaler
15
- w io.Writer
16
- req *cmds.Request
17
-}
18
-
19
-// NewMarshalerEncoder returns a new MarshalerEncoder
20
-func NewMarshalerEncoder(req *cmds.Request, m oldcmds.Marshaler, w io.Writer) *MarshalerEncoder {
21
- me := &MarshalerEncoder{
22
- m: m,
23
- w: w,
24
- req: req,
25
- }
26
-
27
- return me
28
-}
29
-
30
-// Encode encodes v onto the io.Writer w using Marshaler m, with both m and w passed in NewMarshalerEncoder
31
-func (me *MarshalerEncoder) Encode(v interface{}) error {
32
- re, res := cmds.NewChanResponsePair(me.req)
33
- go re.Emit(v)
34
-
35
- r, err := me.m(&responseWrapper{Response: res})
36
- if err != nil {
37
- return err
38
- }
39
- if r == nil {
40
- // behave like empty reader
41
- return nil
42
- }
43
-
44
- _, err = io.Copy(me.w, r)
45
- return err
46
-}
47
-
48
-// OldContext tries to cast the environment as a legacy command context,
49
-// returning nil on failure.
50
-func OldContext(env interface{}) *oldcmds.Context {
51
- ctx, ok := env.(*oldcmds.Context)
52
- if !ok {
53
- log.Errorf("OldContext: env passed is not %T but %T\n%s", ctx, env, debug.Stack())
54
- }
55
-
56
- return ctx
57
-}
commands/legacy/legacy_test.go
deleted
-215
@@ -1,215 +0,0 @@
1
-package legacy
2
-
3
-import (
4
- "bytes"
5
- "context"
6
- "io"
7
- "testing"
8
-
9
- oldcmds "github.com/ipfs/go-ipfs/commands"
10
- cmds "gx/ipfs/Qma6uuSyjkecGhMFFLfzyJDPyoDtNJSHJNweDccZhaWkgU/go-ipfs-cmds"
11
- cmdkit "gx/ipfs/Qmde5VP1qUkyQXKCfmEUA7bP64V2HAptbJ7phuPp7jXWwg/go-ipfs-cmdkit"
12
-)
13
-
14
-type WriteNopCloser struct {
15
- io.Writer
16
-}
17
-
18
-func (wc WriteNopCloser) Close() error {
19
- return nil
20
-}
21
-
22
-func TestNewCommand(t *testing.T) {
23
- root := &cmds.Command{
24
- Subcommands: map[string]*cmds.Command{
25
- "test": NewCommand(&oldcmds.Command{
26
- Run: func(req oldcmds.Request, res oldcmds.Response) {
27
- res.SetOutput("Test.")
28
- },
29
- Marshalers: map[oldcmds.EncodingType]oldcmds.Marshaler{
30
- oldcmds.Text: func(res oldcmds.Response) (io.Reader, error) {
31
- ch, ok := res.Output().(<-chan interface{})
32
- if !ok {
33
- t.Fatalf("output is not <-chan interface{} but %T", ch)
34
- }
35
-
36
- v := <-ch
37
- str, ok := v.(string)
38
- if !ok {
39
- t.Fatalf("read value is not string but %T", v)
40
- }
41
-
42
- buf := bytes.NewBuffer(nil)
43
- _, err := io.WriteString(buf, str)
44
- if err != nil {
45
- t.Fatal(err)
46
- }
47
-
48
- return buf, nil
49
- },
50
- },
51
- Subcommands: map[string]*oldcmds.Command{
52
- "sub": &oldcmds.Command{
53
- Options: []cmdkit.Option{
54
- cmdkit.NewOption(cmdkit.String, "test", "t", "some random test flag"),
55
- },
56
- },
57
- },
58
- }),
59
- },
60
- }
61
-
62
- path := []string{"test"}
63
- req, err := cmds.NewRequest(context.TODO(), path, nil, nil, nil, root)
64
- if err != nil {
65
- t.Fatal(err)
66
- }
67
-
68
- buf := bytes.NewBuffer(nil)
69
-
70
- // test calling "test" command
71
- testCmd := root.Subcommands["test"]
72
-
73
- re, err := cmds.NewWriterResponseEmitter(WriteNopCloser{buf}, req)
74
- if err != nil {
75
- t.Fatal(err)
76
- }
77
-
78
- var env oldcmds.Context
79
-
80
- root.Call(req, re, &env)
81
-
82
- expected := `"Test."
83
-`
84
-
85
- if buf.String() != expected {
86
- t.Fatalf("expected string %#v but got %#v", expected, buf.String())
87
- }
88
-
89
- // test getting subcommand
90
- subCmd := testCmd.Subcommands["sub"]
91
- if subCmd == nil {
92
- t.Fatal("got nil subcommand")
93
- }
94
-
95
- if nOpts := len(subCmd.Options); nOpts != 1 {
96
- t.Fatalf("subcommand has %v options, expected 1", nOpts)
97
- }
98
-
99
- opt := subCmd.Options[0]
100
-
101
- if nNames := len(opt.Names()); nNames != 2 {
102
- t.Fatalf("option has %v names, expected 2", nNames)
103
- }
104
-
105
- names := opt.Names()
106
- if names[0] != "test" {
107
- t.Fatalf("option has name %q, expected %q", names[0], "test")
108
- }
109
-
110
- if names[1] != "t" {
111
- t.Fatalf("option has name %q, expected %q", names[1], "t")
112
- }
113
-}
114
-
115
-func TestPipePair(t *testing.T) {
116
- cmd := NewCommand(&oldcmds.Command{Type: "string"})
117
-
118
- req, err := cmds.NewRequest(context.TODO(), nil, nil, nil, nil, cmd)
119
- if err != nil {
120
- t.Fatal(err)
121
- }
122
-
123
- r, w := io.Pipe()
124
- re, err := cmds.NewWriterResponseEmitter(w, req)
125
- if err != nil {
126
- t.Fatal(err)
127
- }
128
- res, err := cmds.NewReaderResponse(r, req)
129
- if err != nil {
130
- t.Fatal(err)
131
- }
132
-
133
- wait := make(chan interface{})
134
-
135
- expect := "abc"
136
- go func() {
137
- err := re.Emit(expect)
138
- if err != nil {
139
- t.Fatal(err)
140
- }
141
-
142
- err = re.Close()
143
- if err != nil {
144
- t.Fatal(err)
145
- }
146
-
147
- close(wait)
148
- }()
149
-
150
- v, err := res.Next()
151
- if err != nil {
152
- t.Fatal(err)
153
- }
154
- str, ok := v.(*string)
155
- if !ok {
156
- t.Fatalf("expected type %T but got %T", expect, v)
157
- }
158
- if *str != expect {
159
- t.Fatalf("expected value %#v but got %#v", expect, v)
160
- }
161
-
162
- _, err = res.Next()
163
- if err != io.EOF {
164
- t.Fatal("expected io.EOF, got:", err)
165
- }
166
-
167
- <-wait
168
-}
169
-
170
-func TestChanPair(t *testing.T) {
171
- cmd := NewCommand(&oldcmds.Command{Type: "string"})
172
-
173
- req, err := cmds.NewRequest(context.TODO(), nil, nil, nil, nil, cmd)
174
- if err != nil {
175
- t.Fatal(err)
176
- }
177
-
178
- re, res := cmds.NewChanResponsePair(req)
179
-
180
- wait := make(chan interface{})
181
-
182
- expect := "abc"
183
- go func() {
184
- err := re.Emit(expect)
185
- if err != nil {
186
- t.Fatal(err)
187
- }
188
-
189
- err = re.Close()
190
- if err != nil {
191
- t.Fatal(err)
192
- }
193
-
194
- close(wait)
195
- }()
196
-
197
- v, err := res.Next()
198
- if err != nil {
199
- t.Fatal(err)
200
- }
201
- str, ok := v.(string)
202
- if !ok {
203
- t.Fatalf("expected type %T but got %T", expect, v)
204
- }
205
- if str != expect {
206
- t.Fatalf("expected value %#v but got %#v", expect, v)
207
- }
208
-
209
- _, err = res.Next()
210
- if err != io.EOF {
211
- t.Fatal("expected io.EOF, got:", err)
212
- }
213
-
214
- <-wait
215
-}
commands/legacy/request.go
deleted
-196
@@ -1,196 +0,0 @@
1
-package legacy
2
-
3
-import (
4
- "context"
5
- "fmt"
6
- "io"
7
- "os"
8
- "reflect"
9
-
10
- files "gx/ipfs/QmZMWMvWMVKCbHetJ4RgndbuEF1io2UpUxwQwtNjtYPzSC/go-ipfs-files"
11
- "gx/ipfs/Qma6uuSyjkecGhMFFLfzyJDPyoDtNJSHJNweDccZhaWkgU/go-ipfs-cmds"
12
- "gx/ipfs/Qmde5VP1qUkyQXKCfmEUA7bP64V2HAptbJ7phuPp7jXWwg/go-ipfs-cmdkit"
13
-
14
- oldcmds "github.com/ipfs/go-ipfs/commands"
15
-)
16
-
17
-// requestWrapper implements a oldcmds.Request from an Request
18
-type requestWrapper struct {
19
- req *cmds.Request
20
- ctx *oldcmds.Context
21
-}
22
-
23
-func (r *requestWrapper) String() string {
24
- return fmt.Sprintf("{%v, %v}", r.req, r.ctx)
25
-}
26
-
27
-func (r *requestWrapper) GoString() string {
28
- return fmt.Sprintf("lgc.Request{%#v, %#v}", r.req, r.ctx)
29
-}
30
-
31
-// InvocContext retuns the invocation context of the oldcmds.Request.
32
-// It is faked using OldContext().
33
-func (r *requestWrapper) InvocContext() *oldcmds.Context {
34
- return r.ctx
35
-}
36
-
37
-// SetInvocContext sets the invocation context. First the context is converted
38
-// to a Context using NewContext().
39
-func (r *requestWrapper) SetInvocContext(ctx oldcmds.Context) {
40
- r.ctx = &ctx
41
-}
42
-
43
-// Command is an empty stub.
44
-func (r *requestWrapper) Command() *oldcmds.Command { return nil }
45
-
46
-func (r *requestWrapper) Arguments() []string {
47
- cmdArgs := r.req.Command.Arguments
48
- reqArgs := r.req.Arguments
49
-
50
- // TODO figure out the exaclt policy for when to use these automatically
51
- // TODO once that's done, change the log.Debug below to log.Error
52
- // read arguments from body if we don't have all of them or the command has variadic arguemnts
53
- if len(reqArgs) < len(cmdArgs) ||
54
- len(cmdArgs) > 0 && cmdArgs[len(cmdArgs)-1].Variadic {
55
- err := r.req.ParseBodyArgs()
56
- if err != nil {
57
- log.Debug("error reading arguments from stdin: ", err)
58
- }
59
- }
60
- return r.req.Arguments
61
-}
62
-
63
-func (r *requestWrapper) Context() context.Context {
64
- return r.req.Context
65
-}
66
-
67
-func (r *requestWrapper) ConvertOptions() error {
68
- return convertOptions(r.req)
69
-}
70
-
71
-func (r *requestWrapper) Files() files.File {
72
- return r.req.Files
73
-}
74
-
75
-func (r *requestWrapper) Option(name string) *cmdkit.OptionValue {
76
- var option cmdkit.Option
77
-
78
- optDefs, err := r.req.Root.GetOptions(r.req.Path)
79
- if err != nil {
80
- return &cmdkit.OptionValue{}
81
- }
82
- for _, def := range optDefs {
83
- for _, optName := range def.Names() {
84
- if name == optName {
85
- option = def
86
- break
87
- }
88
- }
89
- }
90
- if option == nil {
91
- return nil
92
- }
93
-
94
- // try all the possible names, break if we find a value
95
- for _, n := range option.Names() {
96
- val, found := r.req.Options[n]
97
- if found {
98
- return &cmdkit.OptionValue{
99
- Value: val,
100
- ValueFound: found,
101
- Def: option,
102
- }
103
- }
104
- }
105
-
106
- return &cmdkit.OptionValue{
107
- Value: option.Default(),
108
- ValueFound: false,
109
- Def: option,
110
- }
111
-}
112
-
113
-func (r *requestWrapper) Options() cmdkit.OptMap {
114
- return r.req.Options
115
-}
116
-
117
-func (r *requestWrapper) Path() []string {
118
- return r.req.Path
119
-}
120
-
121
-func (r *requestWrapper) SetArguments(args []string) {
122
- r.req.Arguments = args
123
-}
124
-
125
-func (r *requestWrapper) SetFiles(f files.File) {
126
- r.req.Files = f
127
-}
128
-
129
-func (r *requestWrapper) SetOption(name string, v interface{}) {
130
- r.req.SetOption(name, v)
131
-}
132
-
133
-func (r *requestWrapper) SetOptions(om cmdkit.OptMap) error {
134
- r.req.Options = om
135
- return convertOptions(r.req)
136
-}
137
-
138
-func (r *requestWrapper) Stdin() io.Reader {
139
- return os.Stdin
140
-}
141
-
142
-func (r *requestWrapper) StringArguments() []string {
143
- return r.req.Arguments
144
-}
145
-
146
-func (r *requestWrapper) Values() map[string]interface{} {
147
- return nil
148
-}
149
-
150
-// copied from go-ipfs-cmds/request.go
151
-func convertOptions(req *cmds.Request) error {
152
- optDefSlice := req.Command.Options
153
-
154
- optDefs := make(map[string]cmdkit.Option)
155
- for _, def := range optDefSlice {
156
- for _, name := range def.Names() {
157
- optDefs[name] = def
158
- }
159
- }
160
-
161
- for k, v := range req.Options {
162
- opt, ok := optDefs[k]
163
- if !ok {
164
- continue
165
- }
166
-
167
- kind := reflect.TypeOf(v).Kind()
168
- if kind != opt.Type() {
169
- if str, ok := v.(string); ok {
170
- val, err := opt.Parse(str)
171
- if err != nil {
172
- value := fmt.Sprintf("value %q", v)
173
- if len(str) == 0 {
174
- value = "empty value"
175
- }
176
- return fmt.Errorf("could not convert %q to type %q (for option %q)",
177
- value, opt.Type().String(), "-"+k)
178
- }
179
- req.Options[k] = val
180
-
181
- } else {
182
- return fmt.Errorf("option %q should be type %q, but got type %q",
183
- k, opt.Type().String(), kind.String())
184
- }
185
- }
186
-
187
- for _, name := range opt.Names() {
188
- if _, ok := req.Options[name]; name != k && ok {
189
- return fmt.Errorf("duplicate command options were provided (%q and %q)",
190
- k, name)
191
- }
192
- }
193
- }
194
-
195
- return nil
196
-}
commands/legacy/response.go
deleted
-207
@@ -1,207 +0,0 @@
1
-package legacy
2
-
3
-import (
4
- "context"
5
- "io"
6
- "os"
7
- "reflect"
8
- "sync"
9
-
10
- "gx/ipfs/Qma6uuSyjkecGhMFFLfzyJDPyoDtNJSHJNweDccZhaWkgU/go-ipfs-cmds"
11
- "gx/ipfs/Qmde5VP1qUkyQXKCfmEUA7bP64V2HAptbJ7phuPp7jXWwg/go-ipfs-cmdkit"
12
-
13
- oldcmds "github.com/ipfs/go-ipfs/commands"
14
-)
15
-
16
-// responseWrapper wraps Response and implements olcdms.Response.
17
-// It embeds a Response so some methods are taken from that.
18
-type responseWrapper struct {
19
- cmds.Response
20
-
21
- out interface{}
22
-}
23
-
24
-// Request returns a (faked) oldcmds.Request
25
-func (rw *responseWrapper) Request() oldcmds.Request {
26
- return &requestWrapper{rw.Response.Request(), nil}
27
-}
28
-
29
-// Output returns either a <-chan interface{} on which you can receive the
30
-// emitted values, or an emitted io.Reader
31
-func (rw *responseWrapper) Output() interface{} {
32
- //if not called before
33
- if rw.out == nil {
34
- // get first emitted value
35
- x, err := rw.Next()
36
- if err != nil {
37
- ch := make(chan interface{})
38
- log.Error(err)
39
- close(ch)
40
- return (<-chan interface{})(ch)
41
- }
42
- if e, ok := x.(*cmdkit.Error); ok {
43
- ch := make(chan interface{})
44
- log.Error(e)
45
- close(ch)
46
- return (<-chan interface{})(ch)
47
- }
48
-
49
- switch v := x.(type) {
50
- case io.Reader:
51
- // if it's a reader, set it
52
- rw.out = v
53
- case cmds.Single:
54
- rw.out = v.Value
55
- default:
56
- // if it is something else, create a channel and copy values from next in there
57
- ch := make(chan interface{})
58
- rw.out = (<-chan interface{})(ch)
59
-
60
- go func() {
61
- defer close(ch)
62
- ch <- v
63
-
64
- for {
65
- v, err := rw.Next()
66
-
67
- if err == io.EOF || err == context.Canceled {
68
- return
69
- }
70
- if err != nil {
71
- log.Error(err)
72
- return
73
- }
74
-
75
- ch <- v
76
- }
77
- }()
78
- }
79
- }
80
-
81
- // if we have it already, return existing value
82
- return rw.out
83
-}
84
-
85
-// SetError is an empty stub
86
-func (rw *responseWrapper) SetError(error, cmdkit.ErrorType) {}
87
-
88
-// SetOutput is an empty stub
89
-func (rw *responseWrapper) SetOutput(interface{}) {}
90
-
91
-// SetLength is an empty stub
92
-func (rw *responseWrapper) SetLength(uint64) {}
93
-
94
-// SetCloser is an empty stub
95
-func (rw *responseWrapper) SetCloser(io.Closer) {}
96
-
97
-// Close is an empty stub
98
-func (rw *responseWrapper) Close() error { return nil }
99
-
100
-// Marshal is an empty stub
101
-func (rw *responseWrapper) Marshal() (io.Reader, error) { return nil, nil }
102
-
103
-// Reader is an empty stub
104
-func (rw *responseWrapper) Reader() (io.Reader, error) { return nil, nil }
105
-
106
-// Stdout returns os.Stdout
107
-func (rw *responseWrapper) Stdout() io.Writer { return os.Stdout }
108
-
109
-// Stderr returns os.Stderr
110
-func (rw *responseWrapper) Stderr() io.Writer { return os.Stderr }
111
-
112
-// fakeResponse implements oldcmds.Response and takes a ResponseEmitter
113
-type fakeResponse struct {
114
- req oldcmds.Request
115
- re cmds.ResponseEmitter
116
- out interface{}
117
- wait chan struct{}
118
- once sync.Once
119
-}
120
-
121
-// Send emits the value(s) stored in r.out on the ResponseEmitter
122
-func (r *fakeResponse) Send(errCh chan<- error) {
123
- defer close(errCh)
124
-
125
- out := r.Output()
126
-
127
- // don't emit nil or Single{nil}
128
- if out == nil || out == (cmds.Single{Value: nil}) {
129
- return
130
- }
131
-
132
- errCh <- r.re.Emit(out)
133
- return
134
-}
135
-
136
-// Request returns the oldcmds.Request that belongs to this Response
137
-func (r *fakeResponse) Request() oldcmds.Request {
138
- return r.req
139
-}
140
-
141
-// SetError forwards the call to the underlying ResponseEmitter
142
-func (r *fakeResponse) SetError(err error, code cmdkit.ErrorType) {
143
- defer r.once.Do(func() { close(r.wait) })
144
- r.re.CloseWithError(cmdkit.Errorf(code, err.Error()))
145
-}
146
-
147
-// Error is an empty stub
148
-func (r *fakeResponse) Error() *cmdkit.Error {
149
- return nil
150
-}
151
-
152
-// SetOutput sets the output variable to the passed value
153
-func (r *fakeResponse) SetOutput(v interface{}) {
154
- t := reflect.TypeOf(v)
155
- _, isReader := v.(io.Reader)
156
-
157
- if t != nil && t.Kind() != reflect.Chan && !isReader {
158
- v = cmds.Single{Value: v}
159
- }
160
-
161
- r.out = v
162
- r.once.Do(func() { close(r.wait) })
163
-}
164
-
165
-// Output returns the output variable
166
-func (r *fakeResponse) Output() interface{} {
167
- <-r.wait
168
- return r.out
169
-}
170
-
171
-// SetLength forwards the call to the underlying ResponseEmitter
172
-func (r *fakeResponse) SetLength(l uint64) {
173
- r.re.SetLength(l)
174
-}
175
-
176
-// Length is an empty stub
177
-func (r *fakeResponse) Length() uint64 {
178
- return 0
179
-}
180
-
181
-// Close forwards the call to the underlying ResponseEmitter
182
-func (r *fakeResponse) Close() error {
183
- return r.re.Close()
184
-}
185
-
186
-// SetCloser is an empty stub
187
-func (r *fakeResponse) SetCloser(io.Closer) {}
188
-
189
-// Reader is an empty stub
190
-func (r *fakeResponse) Reader() (io.Reader, error) {
191
- return nil, nil
192
-}
193
-
194
-// Marshal is an empty stub
195
-func (r *fakeResponse) Marshal() (io.Reader, error) {
196
- return nil, nil
197
-}
198
-
199
-// Stdout returns os.Stdout
200
-func (r *fakeResponse) Stdout() io.Writer {
201
- return os.Stdout
202
-}
203
-
204
-// Stderr returns os.Stderr
205
-func (r *fakeResponse) Stderr() io.Writer {
206
- return os.Stderr
207
-}
commands/reqlog.go
-17
@@ -1,7 +1,6 @@
1
package commands
2
3
import (
4
- "strings"
4
"sync"
5
"time"
6
)
@@ -34,22 +33,6 @@ type ReqLog struct {
33
keep time.Duration
34
}
35
37
-// Add creates a ReqLogEntry from a request and adds it to the log
38
-func (rl *ReqLog) Add(req Request) *ReqLogEntry {
39
- rle := &ReqLogEntry{
40
- StartTime: time.Now(),
41
- Active: true,
42
- Command: strings.Join(req.Path(), "/"),
43
- Options: req.Options(),
44
- Args: req.StringArguments(),
45
- ID: rl.nextID,
46
- log: rl,
47
- }
48
-
49
- rl.AddEntry(rle)
50
- return rle
51
-}
52
-
36
// AddEntry adds an entry to the log
37
func (rl *ReqLog) AddEntry(rle *ReqLogEntry) {
38
rl.lock.Lock()
commands/response.go
deleted
-55
@@ -1,55 +0,0 @@
1
-package commands
2
-
3
-import (
4
- "io"
5
-
6
- cmdkit "gx/ipfs/Qmde5VP1qUkyQXKCfmEUA7bP64V2HAptbJ7phuPp7jXWwg/go-ipfs-cmdkit"
7
-)
8
-
9
-// ErrorType signfies a category of errors
10
-type ErrorType uint
11
-
12
-// EncodingType defines a supported encoding
13
-type EncodingType string
14
-
15
-// Supported EncodingType constants.
16
-const (
17
- JSON = "json"
18
- XML = "xml"
19
- Protobuf = "protobuf"
20
- Text = "text"
21
- // TODO: support more encoding types
22
-)
23
-
24
-// Response is the result of a command request. Handlers write to the response,
25
-// setting Error or Value. Response is returned to the client.
26
-type Response interface {
27
- Request() Request
28
-
29
- // Set/Return the response Error
30
- SetError(err error, code cmdkit.ErrorType)
31
- Error() *cmdkit.Error
32
-
33
- // Sets/Returns the response value
34
- SetOutput(interface{})
35
- Output() interface{}
36
-
37
- // Sets/Returns the length of the output
38
- SetLength(uint64)
39
- Length() uint64
40
-
41
- // underlying http connections need to be cleaned up, this is for that
42
- Close() error
43
- SetCloser(io.Closer)
44
-
45
- // Marshal marshals out the response into a buffer. It uses the EncodingType
46
- // on the Request to chose a Marshaler (Codec).
47
- Marshal() (io.Reader, error)
48
-
49
- // Gets a io.Reader that reads the marshalled output
50
- Reader() (io.Reader, error)
51
-
52
- // Gets Stdout and Stderr, for writing to console without using SetOutput
53
- Stdout() io.Writer
54
- Stderr() io.Writer
55
-}
core/commands/cmdenv/env.go
+1
-1
@@ -28,7 +28,7 @@ func GetApi(env cmds.Environment) (coreiface.CoreAPI, error) {
28
return nil, fmt.Errorf("expected env to be of type %T, got %T", ctx, env)
29
}
30
31
- return ctx.GetApi()
31
+ return ctx.GetAPI()
32
}
33
34
// GetConfig extracts the config from the environment.