Skip to content

Commit 3dc0ce7

Browse files
committed
refactor all command code
License: MIT Signed-off-by: Kejie Zhang <[email protected]>
1 parent 70ebea5 commit 3dc0ce7

25 files changed

+415
-213
lines changed

core/commands/active.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@ import (
1414
"gx/ipfs/QmSP88ryZkHSRn1fnngAaV2Vcn63WUJzAavnRM9CVdU1Ky/go-ipfs-cmdkit"
1515
)
1616

17+
const (
18+
verboseOptionName = "v"
19+
)
20+
1721
var ActiveReqsCmd = &cmds.Command{
1822
Helptext: cmdkit.HelpText{
1923
Tagline: "List commands run on this IPFS node.",
@@ -25,7 +29,7 @@ Lists running and recently run commands.
2529
res.SetOutput(req.InvocContext().ReqLog.Report())
2630
},
2731
Options: []cmdkit.Option{
28-
cmdkit.BoolOption("verbose", "v", "Print extra information."),
32+
cmdkit.BoolOption("verbose", verboseOptionName, "Print extra information."),
2933
},
3034
Subcommands: map[string]*cmds.Command{
3135
"clear": clearInactiveCmd,
@@ -44,7 +48,7 @@ Lists running and recently run commands.
4448
}
4549
buf := new(bytes.Buffer)
4650

47-
verbose, _, _ := res.Request().Option("v").Bool()
51+
verbose, _, _ := res.Request().Option(verboseOptionName).Bool()
4852

4953
w := tabwriter.NewWriter(buf, 4, 4, 2, ' ', 0)
5054
if verbose {

core/commands/bitswap.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,14 +32,18 @@ var BitswapCmd = &cmds.Command{
3232
},
3333
}
3434

35+
const (
36+
peerOptionName = "peer"
37+
)
38+
3539
var showWantlistCmd = &oldcmds.Command{
3640
Helptext: cmdkit.HelpText{
3741
Tagline: "Show blocks currently on the wantlist.",
3842
ShortDescription: `
3943
Print out all blocks currently on the bitswap wantlist for the local peer.`,
4044
},
4145
Options: []cmdkit.Option{
42-
cmdkit.StringOption("peer", "p", "Specify which peer to show wantlist for. Default: self."),
46+
cmdkit.StringOption(peerOptionName, "p", "Specify which peer to show wantlist for. Default: self."),
4347
},
4448
Type: KeyList{},
4549
Run: func(req oldcmds.Request, res oldcmds.Response) {
@@ -60,7 +64,7 @@ Print out all blocks currently on the bitswap wantlist for the local peer.`,
6064
return
6165
}
6266

63-
pstr, found, err := req.Option("peer").String()
67+
pstr, found, err := req.Option(peerOptionName).String()
6468
if err != nil {
6569
res.SetError(err, cmdkit.ErrNormal)
6670
return

core/commands/block.go

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,12 @@ It outputs to stdout, and <key> is a base58 encoded multihash.
126126
},
127127
}
128128

129+
const (
130+
blockFormatOptionName = "format"
131+
mhtypeOptionName = "mhtype"
132+
mhlenOptionName = "mhlen"
133+
)
134+
129135
var blockPutCmd = &cmds.Command{
130136
Helptext: cmdkit.HelpText{
131137
Tagline: "Store input as an IPFS block.",
@@ -142,9 +148,9 @@ than 'sha2-256' or format to anything other than 'v0' will result in CIDv1.
142148
cmdkit.FileArg("data", true, false, "The data to be stored as an IPFS block.").EnableStdin(),
143149
},
144150
Options: []cmdkit.Option{
145-
cmdkit.StringOption("format", "f", "cid format for blocks to be created with."),
146-
cmdkit.StringOption("mhtype", "multihash hash function").WithDefault("sha2-256"),
147-
cmdkit.IntOption("mhlen", "multihash hash length").WithDefault(-1),
151+
cmdkit.StringOption(blockFormatOptionName, "f", "cid format for blocks to be created with."),
152+
cmdkit.StringOption(mhtypeOptionName, "multihash hash function").WithDefault("sha2-256"),
153+
cmdkit.IntOption(mhlenOptionName, "multihash hash length").WithDefault(-1),
148154
},
149155
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
150156
api, err := cmdenv.GetApi(env)
@@ -157,18 +163,18 @@ than 'sha2-256' or format to anything other than 'v0' will result in CIDv1.
157163
return err
158164
}
159165

160-
mhtype, _ := req.Options["mhtype"].(string)
166+
mhtype, _ := req.Options[mhtypeOptionName].(string)
161167
mhtval, ok := mh.Names[mhtype]
162168
if !ok {
163169
return fmt.Errorf("unrecognized multihash function: %s", mhtype)
164170
}
165171

166-
mhlen, ok := req.Options["mhlen"].(int)
172+
mhlen, ok := req.Options[mhlenOptionName].(int)
167173
if !ok {
168174
return errors.New("missing option \"mhlen\"")
169175
}
170176

171-
format, formatSet := req.Options["format"].(string)
177+
format, formatSet := req.Options[blockFormatOptionName].(string)
172178
if !formatSet {
173179
if mhtval != mh.SHA2_256 || (mhlen != -1 && mhlen != 32) {
174180
format = "protobuf"
@@ -200,6 +206,11 @@ than 'sha2-256' or format to anything other than 'v0' will result in CIDv1.
200206
Type: BlockStat{},
201207
}
202208

209+
const (
210+
forceOptionName = "force"
211+
blockQuietOptionName = "quiet"
212+
)
213+
203214
var blockRmCmd = &cmds.Command{
204215
Helptext: cmdkit.HelpText{
205216
Tagline: "Remove IPFS block(s).",
@@ -212,17 +223,17 @@ It takes a list of base58 encoded multihashes to remove.
212223
cmdkit.StringArg("hash", true, true, "Bash58 encoded multihash of block(s) to remove."),
213224
},
214225
Options: []cmdkit.Option{
215-
cmdkit.BoolOption("force", "f", "Ignore nonexistent blocks."),
216-
cmdkit.BoolOption("quiet", "q", "Write minimal output."),
226+
cmdkit.BoolOption(forceOptionName, "f", "Ignore nonexistent blocks."),
227+
cmdkit.BoolOption(blockQuietOptionName, "q", "Write minimal output."),
217228
},
218229
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
219230
api, err := cmdenv.GetApi(env)
220231
if err != nil {
221232
return err
222233
}
223234

224-
force, _ := req.Options["force"].(bool)
225-
quiet, _ := req.Options["quiet"].(bool)
235+
force, _ := req.Options[forceOptionName].(bool)
236+
quiet, _ := req.Options[blockQuietOptionName].(bool)
226237

227238
// TODO: use batching coreapi when done
228239
for _, b := range req.Arguments {

core/commands/bootstrap.go

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,10 @@ Running 'ipfs bootstrap' with no arguments will run 'ipfs bootstrap list'.
4040
},
4141
}
4242

43+
const (
44+
defaultOptionName = "default"
45+
)
46+
4347
var bootstrapAddCmd = &cmds.Command{
4448
Helptext: cmdkit.HelpText{
4549
Tagline: "Add peers to the bootstrap list.",
@@ -53,14 +57,14 @@ in the bootstrap list).
5357
},
5458

5559
Options: []cmdkit.Option{
56-
cmdkit.BoolOption("default", "Add default bootstrap nodes. (Deprecated, use 'default' subcommand instead)"),
60+
cmdkit.BoolOption(defaultOptionName, "Add default bootstrap nodes. (Deprecated, use 'default' subcommand instead)"),
5761
},
5862
Subcommands: map[string]*cmds.Command{
5963
"default": bootstrapAddDefaultCmd,
6064
},
6165

6266
Run: func(req cmds.Request, res cmds.Response) {
63-
deflt, _, err := req.Option("default").Bool()
67+
deflt, _, err := req.Option(defaultOptionName).Bool()
6468
if err != nil {
6569
res.SetError(err, cmdkit.ErrNormal)
6670
return
@@ -191,6 +195,10 @@ in the bootstrap list).`,
191195
},
192196
}
193197

198+
const (
199+
bootstrapAllOptionName = "all"
200+
)
201+
194202
var bootstrapRemoveCmd = &cmds.Command{
195203
Helptext: cmdkit.HelpText{
196204
Tagline: "Remove peers from the bootstrap list.",
@@ -202,13 +210,13 @@ var bootstrapRemoveCmd = &cmds.Command{
202210
cmdkit.StringArg("peer", false, true, peerOptionDesc).EnableStdin(),
203211
},
204212
Options: []cmdkit.Option{
205-
cmdkit.BoolOption("all", "Remove all bootstrap peers. (Deprecated, use 'all' subcommand)"),
213+
cmdkit.BoolOption(bootstrapAllOptionName, "Remove all bootstrap peers. (Deprecated, use 'all' subcommand)"),
206214
},
207215
Subcommands: map[string]*cmds.Command{
208216
"all": bootstrapRemoveAllCmd,
209217
},
210218
Run: func(req cmds.Request, res cmds.Response) {
211-
all, _, err := req.Option("all").Bool()
219+
all, _, err := req.Option(bootstrapAllOptionName).Bool()
212220
if err != nil {
213221
res.SetError(err, cmdkit.ErrNormal)
214222
return

core/commands/cat.go

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,11 @@ import (
1313
cmds "gx/ipfs/QmXTmUCBtDUrzDYVzASogLiNph7EBuYqEgPL7QoHNMzUnz/go-ipfs-cmds"
1414
)
1515

16-
const progressBarMinSize = 1024 * 1024 * 8 // show progress bar for outputs > 8MiB
16+
const (
17+
progressBarMinSize = 1024 * 1024 * 8 // show progress bar for outputs > 8MiB
18+
offsetOptionName = "offset"
19+
lengthOptionName = "length"
20+
)
1721

1822
var CatCmd = &cmds.Command{
1923
Helptext: cmdkit.HelpText{
@@ -25,8 +29,8 @@ var CatCmd = &cmds.Command{
2529
cmdkit.StringArg("ipfs-path", true, true, "The path to the IPFS object(s) to be outputted.").EnableStdin(),
2630
},
2731
Options: []cmdkit.Option{
28-
cmdkit.IntOption("offset", "o", "Byte offset to begin reading from."),
29-
cmdkit.IntOption("length", "l", "Maximum number of bytes to read."),
32+
cmdkit.IntOption(offsetOptionName, "o", "Byte offset to begin reading from."),
33+
cmdkit.IntOption(lengthOptionName, "l", "Maximum number of bytes to read."),
3034
},
3135
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
3236
node, err := cmdenv.GetNode(env)
@@ -45,12 +49,12 @@ var CatCmd = &cmds.Command{
4549
}
4650
}
4751

48-
offset, _ := req.Options["offset"].(int)
52+
offset, _ := req.Options[offsetOptionName].(int)
4953
if offset < 0 {
5054
return fmt.Errorf("cannot specify negative offset")
5155
}
5256

53-
max, found := req.Options["length"].(int)
57+
max, found := req.Options[lengthOptionName].(int)
5458
if err != nil {
5559
return err
5660
}

core/commands/cid.go

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@ var CidCmd = &cmds.Command{
3131
},
3232
}
3333

34+
const (
35+
cidFormatOptionName = "f"
36+
cidVerisonOptionName = "v"
37+
cidMultibaseOptionName = "b"
38+
)
39+
3440
var cidFmtCmd = &cmds.Command{
3541
Helptext: cmdkit.HelpText{
3642
Tagline: "Format and convert a CID in various useful ways.",
@@ -44,14 +50,14 @@ The optional format string is a printf style format string:
4450
cmdkit.StringArg("cid", true, true, "Cids to format.").EnableStdin(),
4551
},
4652
Options: []cmdkit.Option{
47-
cmdkit.StringOption("f", "Printf style format string.").WithDefault("%s"),
48-
cmdkit.StringOption("v", "CID version to convert to."),
49-
cmdkit.StringOption("b", "Multibase to display CID in."),
53+
cmdkit.StringOption(cidFormatOptionName, "Printf style format string.").WithDefault("%s"),
54+
cmdkit.StringOption(cidVerisonOptionName, "CID version to convert to."),
55+
cmdkit.StringOption(cidMultibaseOptionName, "Multibase to display CID in."),
5056
},
5157
Run: func(req *cmds.Request, resp cmds.ResponseEmitter, env cmds.Environment) error {
52-
fmtStr, _ := req.Options["f"].(string)
53-
verStr, _ := req.Options["v"].(string)
54-
baseStr, _ := req.Options["b"].(string)
58+
fmtStr, _ := req.Options[cidFormatOptionName].(string)
59+
verStr, _ := req.Options[cidVerisonOptionName].(string)
60+
baseStr, _ := req.Options[cidMultibaseOptionName].(string)
5561

5662
opts := cidFormatOpts{}
5763

@@ -216,13 +222,18 @@ type CodeAndName struct {
216222
Name string
217223
}
218224

225+
const (
226+
prefixOptionName = "prefix"
227+
numericOptionName = "numeric"
228+
)
229+
219230
var basesCmd = &cmds.Command{
220231
Helptext: cmdkit.HelpText{
221232
Tagline: "List available multibase encodings.",
222233
},
223234
Options: []cmdkit.Option{
224-
cmdkit.BoolOption("prefix", "also include the single leter prefixes in addition to the code"),
225-
cmdkit.BoolOption("numeric", "also include numeric codes"),
235+
cmdkit.BoolOption(prefixOptionName, "also include the single leter prefixes in addition to the code"),
236+
cmdkit.BoolOption(numericOptionName, "also include numeric codes"),
226237
},
227238
Run: func(req *cmds.Request, resp cmds.ResponseEmitter, env cmds.Environment) error {
228239
var res []CodeAndName
@@ -235,8 +246,8 @@ var basesCmd = &cmds.Command{
235246
},
236247
Encoders: cmds.EncoderMap{
237248
cmds.Text: cmds.MakeEncoder(func(req *cmds.Request, w io.Writer, val0 interface{}) error {
238-
prefixes, _ := req.Options["prefix"].(bool)
239-
numeric, _ := req.Options["numeric"].(bool)
249+
prefixes, _ := req.Options[prefixOptionName].(bool)
250+
numeric, _ := req.Options[numericOptionName].(bool)
240251
val, ok := val0.([]CodeAndName)
241252
if !ok {
242253
return e.TypeErr(val, val0)
@@ -265,12 +276,16 @@ var basesCmd = &cmds.Command{
265276
Type: []CodeAndName{},
266277
}
267278

279+
const (
280+
codecsNumericOptionName = "numeric"
281+
)
282+
268283
var codecsCmd = &cmds.Command{
269284
Helptext: cmdkit.HelpText{
270285
Tagline: "List available CID codecs.",
271286
},
272287
Options: []cmdkit.Option{
273-
cmdkit.BoolOption("numeric", "also include numeric codes"),
288+
cmdkit.BoolOption(codecsNumericOptionName, "also include numeric codes"),
274289
},
275290
Run: func(req *cmds.Request, resp cmds.ResponseEmitter, env cmds.Environment) error {
276291
var res []CodeAndName
@@ -283,7 +298,7 @@ var codecsCmd = &cmds.Command{
283298
},
284299
Encoders: cmds.EncoderMap{
285300
cmds.Text: cmds.MakeEncoder(func(req *cmds.Request, w io.Writer, val0 interface{}) error {
286-
numeric, _ := req.Options["numeric"].(bool)
301+
numeric, _ := req.Options[codecsNumericOptionName].(bool)
287302
val, ok := val0.([]CodeAndName)
288303
if !ok {
289304
return e.TypeErr(val, val0)

core/commands/config.go

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@ type ConfigField struct {
2525
Value interface{}
2626
}
2727

28+
const (
29+
configBoolOptionName = "bool"
30+
configJsonOptionName = "json"
31+
)
32+
2833
var ConfigCmd = &cmds.Command{
2934
Helptext: cmdkit.HelpText{
3035
Tagline: "Get and set ipfs config values.",
@@ -54,8 +59,8 @@ Set the value of the 'Datastore.Path' key:
5459
cmdkit.StringArg("value", false, false, "The value to set the config entry to."),
5560
},
5661
Options: []cmdkit.Option{
57-
cmdkit.BoolOption("bool", "Set a boolean value."),
58-
cmdkit.BoolOption("json", "Parse stringified JSON."),
62+
cmdkit.BoolOption(configBoolOptionName, "Set a boolean value."),
63+
cmdkit.BoolOption(configJsonOptionName, "Parse stringified JSON."),
5964
},
6065
Run: func(req cmds.Request, res cmds.Response) {
6166
args := req.Arguments()
@@ -87,7 +92,7 @@ Set the value of the 'Datastore.Path' key:
8792
if len(args) == 2 {
8893
value := args[1]
8994

90-
if parseJson, _, _ := req.Option("json").Bool(); parseJson {
95+
if parseJson, _, _ := req.Option(configJsonOptionName).Bool(); parseJson {
9196
var jsonVal interface{}
9297
if err := json.Unmarshal([]byte(value), &jsonVal); err != nil {
9398
err = fmt.Errorf("failed to unmarshal json. %s", err)
@@ -96,7 +101,7 @@ Set the value of the 'Datastore.Path' key:
96101
}
97102

98103
output, err = setConfig(r, key, jsonVal)
99-
} else if isbool, _, _ := req.Option("bool").Bool(); isbool {
104+
} else if isbool, _, _ := req.Option(configBoolOptionName).Bool(); isbool {
100105
output, err = setConfig(r, key, value == "true")
101106
} else {
102107
output, err = setConfig(r, key, value)

0 commit comments

Comments
 (0)