1
0
mirror of https://github.com/ipfs/kubo.git synced 2025-06-26 23:53:19 +08:00

Merge pull request #5562 from kjzz/zkj/offline-test

add offline id test #4978 and refactor command code
This commit is contained in:
Steven Allen
2018-10-05 11:20:29 -07:00
committed by GitHub
26 changed files with 439 additions and 213 deletions

View File

@ -14,6 +14,10 @@ import (
"gx/ipfs/QmSP88ryZkHSRn1fnngAaV2Vcn63WUJzAavnRM9CVdU1Ky/go-ipfs-cmdkit"
)
const (
verboseOptionName = "v"
)
var ActiveReqsCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "List commands run on this IPFS node.",
@ -25,7 +29,7 @@ Lists running and recently run commands.
res.SetOutput(req.InvocContext().ReqLog.Report())
},
Options: []cmdkit.Option{
cmdkit.BoolOption("verbose", "v", "Print extra information."),
cmdkit.BoolOption("verbose", verboseOptionName, "Print extra information."),
},
Subcommands: map[string]*cmds.Command{
"clear": clearInactiveCmd,
@ -44,7 +48,7 @@ Lists running and recently run commands.
}
buf := new(bytes.Buffer)
verbose, _, _ := res.Request().Option("v").Bool()
verbose, _, _ := res.Request().Option(verboseOptionName).Bool()
w := tabwriter.NewWriter(buf, 4, 4, 2, ' ', 0)
if verbose {

View File

@ -32,6 +32,10 @@ var BitswapCmd = &cmds.Command{
},
}
const (
peerOptionName = "peer"
)
var showWantlistCmd = &oldcmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Show blocks currently on the wantlist.",
@ -39,7 +43,7 @@ var showWantlistCmd = &oldcmds.Command{
Print out all blocks currently on the bitswap wantlist for the local peer.`,
},
Options: []cmdkit.Option{
cmdkit.StringOption("peer", "p", "Specify which peer to show wantlist for. Default: self."),
cmdkit.StringOption(peerOptionName, "p", "Specify which peer to show wantlist for. Default: self."),
},
Type: KeyList{},
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.`,
return
}
pstr, found, err := req.Option("peer").String()
pstr, found, err := req.Option(peerOptionName).String()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return

View File

@ -126,6 +126,12 @@ It outputs to stdout, and <key> is a base58 encoded multihash.
},
}
const (
blockFormatOptionName = "format"
mhtypeOptionName = "mhtype"
mhlenOptionName = "mhlen"
)
var blockPutCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
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.
cmdkit.FileArg("data", true, false, "The data to be stored as an IPFS block.").EnableStdin(),
},
Options: []cmdkit.Option{
cmdkit.StringOption("format", "f", "cid format for blocks to be created with."),
cmdkit.StringOption("mhtype", "multihash hash function").WithDefault("sha2-256"),
cmdkit.IntOption("mhlen", "multihash hash length").WithDefault(-1),
cmdkit.StringOption(blockFormatOptionName, "f", "cid format for blocks to be created with."),
cmdkit.StringOption(mhtypeOptionName, "multihash hash function").WithDefault("sha2-256"),
cmdkit.IntOption(mhlenOptionName, "multihash hash length").WithDefault(-1),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
api, err := cmdenv.GetApi(env)
@ -157,18 +163,18 @@ than 'sha2-256' or format to anything other than 'v0' will result in CIDv1.
return err
}
mhtype, _ := req.Options["mhtype"].(string)
mhtype, _ := req.Options[mhtypeOptionName].(string)
mhtval, ok := mh.Names[mhtype]
if !ok {
return fmt.Errorf("unrecognized multihash function: %s", mhtype)
}
mhlen, ok := req.Options["mhlen"].(int)
mhlen, ok := req.Options[mhlenOptionName].(int)
if !ok {
return errors.New("missing option \"mhlen\"")
}
format, formatSet := req.Options["format"].(string)
format, formatSet := req.Options[blockFormatOptionName].(string)
if !formatSet {
if mhtval != mh.SHA2_256 || (mhlen != -1 && mhlen != 32) {
format = "protobuf"
@ -200,6 +206,11 @@ than 'sha2-256' or format to anything other than 'v0' will result in CIDv1.
Type: BlockStat{},
}
const (
forceOptionName = "force"
blockQuietOptionName = "quiet"
)
var blockRmCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Remove IPFS block(s).",
@ -212,8 +223,8 @@ It takes a list of base58 encoded multihashes to remove.
cmdkit.StringArg("hash", true, true, "Bash58 encoded multihash of block(s) to remove."),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("force", "f", "Ignore nonexistent blocks."),
cmdkit.BoolOption("quiet", "q", "Write minimal output."),
cmdkit.BoolOption(forceOptionName, "f", "Ignore nonexistent blocks."),
cmdkit.BoolOption(blockQuietOptionName, "q", "Write minimal output."),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
api, err := cmdenv.GetApi(env)
@ -221,8 +232,8 @@ It takes a list of base58 encoded multihashes to remove.
return err
}
force, _ := req.Options["force"].(bool)
quiet, _ := req.Options["quiet"].(bool)
force, _ := req.Options[forceOptionName].(bool)
quiet, _ := req.Options[blockQuietOptionName].(bool)
// TODO: use batching coreapi when done
for _, b := range req.Arguments {

View File

@ -40,6 +40,10 @@ Running 'ipfs bootstrap' with no arguments will run 'ipfs bootstrap list'.
},
}
const (
defaultOptionName = "default"
)
var bootstrapAddCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Add peers to the bootstrap list.",
@ -53,14 +57,14 @@ in the bootstrap list).
},
Options: []cmdkit.Option{
cmdkit.BoolOption("default", "Add default bootstrap nodes. (Deprecated, use 'default' subcommand instead)"),
cmdkit.BoolOption(defaultOptionName, "Add default bootstrap nodes. (Deprecated, use 'default' subcommand instead)"),
},
Subcommands: map[string]*cmds.Command{
"default": bootstrapAddDefaultCmd,
},
Run: func(req cmds.Request, res cmds.Response) {
deflt, _, err := req.Option("default").Bool()
deflt, _, err := req.Option(defaultOptionName).Bool()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
@ -191,6 +195,10 @@ in the bootstrap list).`,
},
}
const (
bootstrapAllOptionName = "all"
)
var bootstrapRemoveCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Remove peers from the bootstrap list.",
@ -202,13 +210,13 @@ var bootstrapRemoveCmd = &cmds.Command{
cmdkit.StringArg("peer", false, true, peerOptionDesc).EnableStdin(),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("all", "Remove all bootstrap peers. (Deprecated, use 'all' subcommand)"),
cmdkit.BoolOption(bootstrapAllOptionName, "Remove all bootstrap peers. (Deprecated, use 'all' subcommand)"),
},
Subcommands: map[string]*cmds.Command{
"all": bootstrapRemoveAllCmd,
},
Run: func(req cmds.Request, res cmds.Response) {
all, _, err := req.Option("all").Bool()
all, _, err := req.Option(bootstrapAllOptionName).Bool()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return

View File

@ -13,7 +13,11 @@ import (
cmds "gx/ipfs/QmXTmUCBtDUrzDYVzASogLiNph7EBuYqEgPL7QoHNMzUnz/go-ipfs-cmds"
)
const progressBarMinSize = 1024 * 1024 * 8 // show progress bar for outputs > 8MiB
const (
progressBarMinSize = 1024 * 1024 * 8 // show progress bar for outputs > 8MiB
offsetOptionName = "offset"
lengthOptionName = "length"
)
var CatCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
@ -25,8 +29,8 @@ var CatCmd = &cmds.Command{
cmdkit.StringArg("ipfs-path", true, true, "The path to the IPFS object(s) to be outputted.").EnableStdin(),
},
Options: []cmdkit.Option{
cmdkit.IntOption("offset", "o", "Byte offset to begin reading from."),
cmdkit.IntOption("length", "l", "Maximum number of bytes to read."),
cmdkit.IntOption(offsetOptionName, "o", "Byte offset to begin reading from."),
cmdkit.IntOption(lengthOptionName, "l", "Maximum number of bytes to read."),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
node, err := cmdenv.GetNode(env)
@ -45,12 +49,12 @@ var CatCmd = &cmds.Command{
}
}
offset, _ := req.Options["offset"].(int)
offset, _ := req.Options[offsetOptionName].(int)
if offset < 0 {
return fmt.Errorf("cannot specify negative offset")
}
max, found := req.Options["length"].(int)
max, found := req.Options[lengthOptionName].(int)
if err != nil {
return err
}

View File

@ -31,6 +31,12 @@ var CidCmd = &cmds.Command{
},
}
const (
cidFormatOptionName = "f"
cidVerisonOptionName = "v"
cidMultibaseOptionName = "b"
)
var cidFmtCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Format and convert a CID in various useful ways.",
@ -44,14 +50,14 @@ The optional format string is a printf style format string:
cmdkit.StringArg("cid", true, true, "Cids to format.").EnableStdin(),
},
Options: []cmdkit.Option{
cmdkit.StringOption("f", "Printf style format string.").WithDefault("%s"),
cmdkit.StringOption("v", "CID version to convert to."),
cmdkit.StringOption("b", "Multibase to display CID in."),
cmdkit.StringOption(cidFormatOptionName, "Printf style format string.").WithDefault("%s"),
cmdkit.StringOption(cidVerisonOptionName, "CID version to convert to."),
cmdkit.StringOption(cidMultibaseOptionName, "Multibase to display CID in."),
},
Run: func(req *cmds.Request, resp cmds.ResponseEmitter, env cmds.Environment) error {
fmtStr, _ := req.Options["f"].(string)
verStr, _ := req.Options["v"].(string)
baseStr, _ := req.Options["b"].(string)
fmtStr, _ := req.Options[cidFormatOptionName].(string)
verStr, _ := req.Options[cidVerisonOptionName].(string)
baseStr, _ := req.Options[cidMultibaseOptionName].(string)
opts := cidFormatOpts{}
@ -216,13 +222,18 @@ type CodeAndName struct {
Name string
}
const (
prefixOptionName = "prefix"
numericOptionName = "numeric"
)
var basesCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "List available multibase encodings.",
},
Options: []cmdkit.Option{
cmdkit.BoolOption("prefix", "also include the single leter prefixes in addition to the code"),
cmdkit.BoolOption("numeric", "also include numeric codes"),
cmdkit.BoolOption(prefixOptionName, "also include the single leter prefixes in addition to the code"),
cmdkit.BoolOption(numericOptionName, "also include numeric codes"),
},
Run: func(req *cmds.Request, resp cmds.ResponseEmitter, env cmds.Environment) error {
var res []CodeAndName
@ -235,8 +246,8 @@ var basesCmd = &cmds.Command{
},
Encoders: cmds.EncoderMap{
cmds.Text: cmds.MakeEncoder(func(req *cmds.Request, w io.Writer, val0 interface{}) error {
prefixes, _ := req.Options["prefix"].(bool)
numeric, _ := req.Options["numeric"].(bool)
prefixes, _ := req.Options[prefixOptionName].(bool)
numeric, _ := req.Options[numericOptionName].(bool)
val, ok := val0.([]CodeAndName)
if !ok {
return e.TypeErr(val, val0)
@ -265,12 +276,16 @@ var basesCmd = &cmds.Command{
Type: []CodeAndName{},
}
const (
codecsNumericOptionName = "numeric"
)
var codecsCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "List available CID codecs.",
},
Options: []cmdkit.Option{
cmdkit.BoolOption("numeric", "also include numeric codes"),
cmdkit.BoolOption(codecsNumericOptionName, "also include numeric codes"),
},
Run: func(req *cmds.Request, resp cmds.ResponseEmitter, env cmds.Environment) error {
var res []CodeAndName
@ -283,7 +298,7 @@ var codecsCmd = &cmds.Command{
},
Encoders: cmds.EncoderMap{
cmds.Text: cmds.MakeEncoder(func(req *cmds.Request, w io.Writer, val0 interface{}) error {
numeric, _ := req.Options["numeric"].(bool)
numeric, _ := req.Options[codecsNumericOptionName].(bool)
val, ok := val0.([]CodeAndName)
if !ok {
return e.TypeErr(val, val0)

View File

@ -25,6 +25,11 @@ type ConfigField struct {
Value interface{}
}
const (
configBoolOptionName = "bool"
configJSONOptionName = "json"
)
var ConfigCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Get and set ipfs config values.",
@ -54,8 +59,8 @@ Set the value of the 'Datastore.Path' key:
cmdkit.StringArg("value", false, false, "The value to set the config entry to."),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("bool", "Set a boolean value."),
cmdkit.BoolOption("json", "Parse stringified JSON."),
cmdkit.BoolOption(configBoolOptionName, "Set a boolean value."),
cmdkit.BoolOption(configJSONOptionName, "Parse stringified JSON."),
},
Run: func(req cmds.Request, res cmds.Response) {
args := req.Arguments()
@ -87,7 +92,7 @@ Set the value of the 'Datastore.Path' key:
if len(args) == 2 {
value := args[1]
if parseJson, _, _ := req.Option("json").Bool(); parseJson {
if parseJSON, _, _ := req.Option(configJSONOptionName).Bool(); parseJSON {
var jsonVal interface{}
if err := json.Unmarshal([]byte(value), &jsonVal); err != nil {
err = fmt.Errorf("failed to unmarshal json. %s", err)
@ -96,7 +101,7 @@ Set the value of the 'Datastore.Path' key:
}
output, err = setConfig(r, key, jsonVal)
} else if isbool, _, _ := req.Option("bool").Bool(); isbool {
} else if isbool, _, _ := req.Option(configBoolOptionName).Bool(); isbool {
output, err = setConfig(r, key, value == "true")
} else {
output, err = setConfig(r, key, value)

View File

@ -44,6 +44,10 @@ var DhtCmd = &cmds.Command{
},
}
const (
dhtVerboseOptionName = "v"
)
var queryDhtCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Find the closest Peer IDs to a given Peer ID by querying the DHT.",
@ -54,7 +58,7 @@ var queryDhtCmd = &cmds.Command{
cmdkit.StringArg("peerID", true, true, "The peerID to run the query against."),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("verbose", "v", "Print extra information."),
cmdkit.BoolOption("verbose", dhtVerboseOptionName, "Print extra information."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
@ -128,7 +132,7 @@ var queryDhtCmd = &cmds.Command{
return nil, e.TypeErr(obj, v)
}
verbose, _, _ := res.Request().Option("v").Bool()
verbose, _, _ := res.Request().Option(dhtVerboseOptionName).Bool()
buf := new(bytes.Buffer)
printEvent(obj, buf, verbose, pfm)
@ -139,6 +143,10 @@ var queryDhtCmd = &cmds.Command{
Type: notif.QueryEvent{},
}
const (
numProvidersOptionName = "num-providers"
)
var findProvidersDhtCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Find peers that can provide a specific value, given a key.",
@ -149,8 +157,8 @@ var findProvidersDhtCmd = &cmds.Command{
cmdkit.StringArg("key", true, true, "The key to find providers for."),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("verbose", "v", "Print extra information."),
cmdkit.IntOption("num-providers", "n", "The number of providers to find.").WithDefault(20),
cmdkit.BoolOption("verbose", dhtVerboseOptionName, "Print extra information."),
cmdkit.IntOption(numProvidersOptionName, "n", "The number of providers to find.").WithDefault(20),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
@ -164,7 +172,7 @@ var findProvidersDhtCmd = &cmds.Command{
return
}
numProviders, _, err := res.Request().Option("num-providers").Int()
numProviders, _, err := res.Request().Option(numProvidersOptionName).Int()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
@ -232,7 +240,7 @@ var findProvidersDhtCmd = &cmds.Command{
}
return func(res cmds.Response) (io.Reader, error) {
verbose, _, _ := res.Request().Option("v").Bool()
verbose, _, _ := res.Request().Option(dhtVerboseOptionName).Bool()
v, err := unwrapOutput(res.Output())
if err != nil {
return nil, err
@ -252,6 +260,10 @@ var findProvidersDhtCmd = &cmds.Command{
Type: notif.QueryEvent{},
}
const (
recursiveOptionName = "recursive"
)
var provideRefDhtCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Announce to the network that you are providing given values.",
@ -261,8 +273,8 @@ var provideRefDhtCmd = &cmds.Command{
cmdkit.StringArg("key", true, true, "The key[s] to send provide records for.").EnableStdin(),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("verbose", "v", "Print extra information."),
cmdkit.BoolOption("recursive", "r", "Recursively provide entire graph."),
cmdkit.BoolOption("verbose", dhtVerboseOptionName, "Print extra information."),
cmdkit.BoolOption(recursiveOptionName, "r", "Recursively provide entire graph."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
@ -281,7 +293,7 @@ var provideRefDhtCmd = &cmds.Command{
return
}
rec, _, _ := req.Option("recursive").Bool()
rec, _, _ := req.Option(recursiveOptionName).Bool()
var cids []cid.Cid
for _, arg := range req.Arguments() {
@ -349,7 +361,7 @@ var provideRefDhtCmd = &cmds.Command{
}
return func(res cmds.Response) (io.Reader, error) {
verbose, _, _ := res.Request().Option("v").Bool()
verbose, _, _ := res.Request().Option(dhtVerboseOptionName).Bool()
v, err := unwrapOutput(res.Output())
if err != nil {
return nil, err
@ -414,7 +426,7 @@ var findPeerDhtCmd = &cmds.Command{
cmdkit.StringArg("peerID", true, true, "The ID of the peer to search for."),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("verbose", "v", "Print extra information."),
cmdkit.BoolOption("verbose", dhtVerboseOptionName, "Print extra information."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
@ -480,7 +492,7 @@ var findPeerDhtCmd = &cmds.Command{
}
return func(res cmds.Response) (io.Reader, error) {
verbose, _, _ := res.Request().Option("v").Bool()
verbose, _, _ := res.Request().Option(dhtVerboseOptionName).Bool()
v, err := unwrapOutput(res.Output())
if err != nil {
return nil, err
@ -519,7 +531,7 @@ Different key types can specify other 'best' rules.
cmdkit.StringArg("key", true, true, "The key to find a value for."),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("verbose", "v", "Print extra information."),
cmdkit.BoolOption("verbose", dhtVerboseOptionName, "Print extra information."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
@ -584,7 +596,7 @@ Different key types can specify other 'best' rules.
}
return func(res cmds.Response) (io.Reader, error) {
verbose, _, _ := res.Request().Option("v").Bool()
verbose, _, _ := res.Request().Option(dhtVerboseOptionName).Bool()
v, err := unwrapOutput(res.Output())
if err != nil {
return nil, err
@ -633,7 +645,7 @@ NOTE: A value may not exceed 2048 bytes.
cmdkit.StringArg("value", true, false, "The value to store.").EnableStdin(),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("verbose", "v", "Print extra information."),
cmdkit.BoolOption("verbose", dhtVerboseOptionName, "Print extra information."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
@ -697,7 +709,7 @@ NOTE: A value may not exceed 2048 bytes.
}
return func(res cmds.Response) (io.Reader, error) {
verbose, _, _ := res.Request().Option("v").Bool()
verbose, _, _ := res.Request().Option(dhtVerboseOptionName).Bool()
v, err := unwrapOutput(res.Output())
if err != nil {
return nil, err

View File

@ -13,6 +13,10 @@ import (
"gx/ipfs/QmSP88ryZkHSRn1fnngAaV2Vcn63WUJzAavnRM9CVdU1Ky/go-ipfs-cmdkit"
)
const (
dnsRecursiveOptionName = "recursive"
)
var DNSCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Resolve DNS links.",
@ -51,11 +55,11 @@ The resolver can recursively resolve:
cmdkit.StringArg("domain-name", true, false, "The domain-name name to resolve.").EnableStdin(),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("recursive", "r", "Resolve until the result is not a DNS link."),
cmdkit.BoolOption(dnsRecursiveOptionName, "r", "Resolve until the result is not a DNS link."),
},
Run: func(req cmds.Request, res cmds.Response) {
recursive, _, _ := req.Option("recursive").Bool()
recursive, _, _ := req.Option(dnsRecursiveOptionName).Bool()
name := req.Arguments()[0]
resolver := namesys.NewDNSResolver()

View File

@ -69,8 +69,13 @@ operations.
},
}
var cidVersionOption = cmdkit.IntOption("cid-version", "cid-ver", "Cid version to use. (experimental)")
var hashOption = cmdkit.StringOption("hash", "Hash function to use. Will set Cid version to 1 if used. (experimental)")
const (
filesCidVersionOptionName = "cid-version"
filesHashOptionName = "hash"
)
var cidVersionOption = cmdkit.IntOption(filesCidVersionOptionName, "cid-ver", "Cid version to use. (experimental)")
var hashOption = cmdkit.StringOption(filesHashOptionName, "Hash function to use. Will set Cid version to 1 if used. (experimental)")
var errFormat = errors.New("format was set by multiple options. Only one format option is allowed")
@ -85,11 +90,16 @@ type statOutput struct {
SizeLocal uint64 `json:",omitempty"`
}
const defaultStatFormat = `<hash>
const (
defaultStatFormat = `<hash>
Size: <size>
CumulativeSize: <cumulsize>
ChildBlocks: <childs>
Type: <type>`
filesFormatOptionName = "format"
filesSizeOptionName = "size"
filesWithLocalOptionName = "with-local"
)
var filesStatCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
@ -100,11 +110,11 @@ var filesStatCmd = &cmds.Command{
cmdkit.StringArg("path", true, false, "Path to node to stat."),
},
Options: []cmdkit.Option{
cmdkit.StringOption("format", "Print statistics in given format. Allowed tokens: "+
cmdkit.StringOption(filesFormatOptionName, "Print statistics in given format. Allowed tokens: "+
"<hash> <size> <cumulsize> <type> <childs>. Conflicts with other format options.").WithDefault(defaultStatFormat),
cmdkit.BoolOption("hash", "Print only hash. Implies '--format=<hash>'. Conflicts with other format options."),
cmdkit.BoolOption("size", "Print only size. Implies '--format=<cumulsize>'. Conflicts with other format options."),
cmdkit.BoolOption("with-local", "Compute the amount of the dag that is local, and if possible the total size"),
cmdkit.BoolOption(filesHashOptionName, "Print only hash. Implies '--format=<hash>'. Conflicts with other format options."),
cmdkit.BoolOption(filesSizeOptionName, "Print only size. Implies '--format=<cumulsize>'. Conflicts with other format options."),
cmdkit.BoolOption(filesWithLocalOptionName, "Compute the amount of the dag that is local, and if possible the total size"),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
@ -128,7 +138,7 @@ var filesStatCmd = &cmds.Command{
return err
}
withLocal, _ := req.Options["with-local"].(bool)
withLocal, _ := req.Options[filesWithLocalOptionName].(bool)
var dagserv ipld.DAGService
if withLocal {
@ -199,9 +209,9 @@ func moreThanOne(a, b, c bool) bool {
func statGetFormatOptions(req *cmds.Request) (string, error) {
hash, _ := req.Options["hash"].(bool)
size, _ := req.Options["size"].(bool)
format, _ := req.Options["format"].(string)
hash, _ := req.Options[filesHashOptionName].(bool)
size, _ := req.Options[filesSizeOptionName].(bool)
format, _ := req.Options[filesFormatOptionName].(string)
if moreThanOne(hash, size, format != defaultStatFormat) {
return "", errFormat
@ -380,6 +390,11 @@ type filesLsOutput struct {
Entries []mfs.NodeListing
}
const (
longOptionName = "l"
dontSortOptionName = "U"
)
var filesLsCmd = &oldcmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "List directories in the local mutable namespace.",
@ -405,8 +420,8 @@ Examples:
cmdkit.StringArg("path", false, false, "Path to show listing for. Defaults to '/'."),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("l", "Use long listing format."),
cmdkit.BoolOption("U", "Do not sort; list entries in directory order."),
cmdkit.BoolOption(longOptionName, "Use long listing format."),
cmdkit.BoolOption(dontSortOptionName, "Do not sort; list entries in directory order."),
},
Run: func(req oldcmds.Request, res oldcmds.Response) {
var arg string
@ -435,7 +450,7 @@ Examples:
return
}
long, _, _ := req.Option("l").Bool()
long, _, _ := req.Option(longOptionName).Bool()
switch fsn := fsn.(type) {
case *mfs.Directory:
@ -502,14 +517,14 @@ Examples:
buf := new(bytes.Buffer)
noSort, _, _ := res.Request().Option("U").Bool()
noSort, _, _ := res.Request().Option(dontSortOptionName).Bool()
if !noSort {
sort.Slice(out.Entries, func(i, j int) bool {
return strings.Compare(out.Entries[i].Name, out.Entries[j].Name) < 0
})
}
long, _, _ := res.Request().Option("l").Bool()
long, _, _ := res.Request().Option(longOptionName).Bool()
for _, o := range out.Entries {
if long {
fmt.Fprintf(buf, "%s\t%s\t%d\n", o.Name, o.Hash, o.Size)
@ -523,6 +538,11 @@ Examples:
Type: filesLsOutput{},
}
const (
filesOffsetOptionName = "offset"
filesCountOptionName = "count"
)
var filesReadCmd = &oldcmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Read a file in a given mfs.",
@ -541,8 +561,8 @@ Examples:
cmdkit.StringArg("path", true, false, "Path to file to be read."),
},
Options: []cmdkit.Option{
cmdkit.IntOption("offset", "o", "Byte offset to begin reading from."),
cmdkit.IntOption("count", "n", "Maximum number of bytes to read."),
cmdkit.IntOption(filesOffsetOptionName, "o", "Byte offset to begin reading from."),
cmdkit.IntOption(filesCountOptionName, "n", "Maximum number of bytes to read."),
},
Run: func(req oldcmds.Request, res oldcmds.Response) {
n, err := req.InvocContext().GetNode()
@ -577,7 +597,7 @@ Examples:
defer rfd.Close()
offset, _, err := req.Option("offset").Int()
offset, _, err := req.Option(offsetOptionName).Int()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
@ -605,7 +625,7 @@ Examples:
}
var r io.Reader = &contextReaderWrapper{R: rfd, ctx: req.Context()}
count, found, err := req.Option("count").Int()
count, found, err := req.Option(filesCountOptionName).Int()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
@ -680,6 +700,14 @@ Example:
},
}
const (
filesCreateOptionName = "create"
filesParentsOptionName = "parents"
filesTruncateOptionName = "truncate"
filesRawLeavesOptionName = "raw-leaves"
filesFlushOptionName = "flush"
)
var filesWriteCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Write to a mutable file in a given filesystem.",
@ -719,12 +747,12 @@ stat' on the file or any of its ancestors.
cmdkit.FileArg("data", true, false, "Data to write.").EnableStdin(),
},
Options: []cmdkit.Option{
cmdkit.IntOption("offset", "o", "Byte offset to begin writing at."),
cmdkit.BoolOption("create", "e", "Create the file if it does not exist."),
cmdkit.BoolOption("parents", "p", "Make parent directories as needed."),
cmdkit.BoolOption("truncate", "t", "Truncate the file to size zero before writing."),
cmdkit.IntOption("count", "n", "Maximum number of bytes to read."),
cmdkit.BoolOption("raw-leaves", "Use raw blocks for newly created leaf nodes. (experimental)"),
cmdkit.IntOption(filesOffsetOptionName, "o", "Byte offset to begin writing at."),
cmdkit.BoolOption(filesCreateOptionName, "e", "Create the file if it does not exist."),
cmdkit.BoolOption(filesParentsOptionName, "p", "Make parent directories as needed."),
cmdkit.BoolOption(filesTruncateOptionName, "t", "Truncate the file to size zero before writing."),
cmdkit.IntOption(filesCountOptionName, "n", "Maximum number of bytes to read."),
cmdkit.BoolOption(filesRawLeavesOptionName, "Use raw blocks for newly created leaf nodes. (experimental)"),
cidVersionOption,
hashOption,
},
@ -734,11 +762,11 @@ stat' on the file or any of its ancestors.
return err
}
create, _ := req.Options["create"].(bool)
mkParents, _ := req.Options["parents"].(bool)
trunc, _ := req.Options["truncate"].(bool)
flush, _ := req.Options["flush"].(bool)
rawLeaves, rawLeavesDef := req.Options["raw-leaves"].(bool)
create, _ := req.Options[filesCreateOptionName].(bool)
mkParents, _ := req.Options[filesParentsOptionName].(bool)
trunc, _ := req.Options[filesTruncateOptionName].(bool)
flush, _ := req.Options[filesFlushOptionName].(bool)
rawLeaves, rawLeavesDef := req.Options[filesRawLeavesOptionName].(bool)
prefix, err := getPrefixNew(req)
if err != nil {
@ -750,7 +778,7 @@ stat' on the file or any of its ancestors.
return err
}
offset, _ := req.Options["offset"].(int)
offset, _ := req.Options[filesOffsetOptionName].(int)
if offset < 0 {
return fmt.Errorf("cannot have negative write offset")
}
@ -792,7 +820,7 @@ stat' on the file or any of its ancestors.
}
}
count, countfound := req.Options["count"].(int)
count, countfound := req.Options[filesCountOptionName].(int)
if countfound && count < 0 {
return fmt.Errorf("cannot have negative byte count")
}
@ -840,7 +868,7 @@ Examples:
cmdkit.StringArg("path", true, false, "Path to dir to make."),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("parents", "p", "No error if existing, make parent directories as needed."),
cmdkit.BoolOption(filesParentsOptionName, "p", "No error if existing, make parent directories as needed."),
cidVersionOption,
hashOption,
},
@ -851,14 +879,14 @@ Examples:
return
}
dashp, _, _ := req.Option("parents").Bool()
dashp, _, _ := req.Option(filesParentsOptionName).Bool()
dirtomake, err := checkPath(req.Arguments()[0])
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
flush, _, _ := req.Option("flush").Bool()
flush, _, _ := req.Option(filesFlushOptionName).Bool()
prefix, err := getPrefix(req)
if err != nil {
@ -940,7 +968,7 @@ Change the cid version or hash function of the root node of a given path.
path = req.Arguments()[0]
}
flush, _, _ := req.Option("flush").Bool()
flush, _, _ := req.Option(filesFlushOptionName).Bool()
prefix, err := getPrefix(req)
if err != nil {
@ -1096,8 +1124,8 @@ Remove files or directories.
}
func getPrefixNew(req *cmds.Request) (cid.Builder, error) {
cidVer, cidVerSet := req.Options["cid-version"].(int)
hashFunStr, hashFunSet := req.Options["hash"].(string)
cidVer, cidVerSet := req.Options[filesCidVersionOptionName].(int)
hashFunStr, hashFunSet := req.Options[filesHashOptionName].(string)
if !cidVerSet && !hashFunSet {
return nil, nil
@ -1125,8 +1153,8 @@ func getPrefixNew(req *cmds.Request) (cid.Builder, error) {
}
func getPrefix(req oldcmds.Request) (cid.Builder, error) {
cidVer, cidVerSet, _ := req.Option("cid-version").Int()
hashFunStr, hashFunSet, _ := req.Option("hash").String()
cidVer, cidVerSet, _ := req.Option(filesCidVersionOptionName).Int()
hashFunStr, hashFunSet, _ := req.Option(filesHashOptionName).String()
if !cidVerSet && !hashFunSet {
return nil, nil

View File

@ -28,6 +28,10 @@ var FileStoreCmd = &cmds.Command{
},
}
const (
fileOrderOptionName = "file-order"
)
var lsFileStore = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "List objects in filestore.",
@ -46,7 +50,7 @@ The output is:
cmdkit.StringArg("obj", false, true, "Cid of objects to list."),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("file-order", "sort the results based on the path of the backing file"),
cmdkit.BoolOption(fileOrderOptionName, "sort the results based on the path of the backing file"),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
_, fs, err := getFilestore(env)
@ -62,7 +66,7 @@ The output is:
return res.Emit(out)
}
fileOrder, _ := req.Options["file-order"].(bool)
fileOrder, _ := req.Options[fileOrderOptionName].(bool)
next, err := filestore.ListAll(fs, fileOrder)
if err != nil {
return err
@ -112,7 +116,7 @@ For ERROR entries the error will also be printed to stderr.
cmdkit.StringArg("obj", false, true, "Cid of objects to verify."),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("file-order", "verify the objects based on the order of the backing file"),
cmdkit.BoolOption(fileOrderOptionName, "verify the objects based on the order of the backing file"),
},
Run: func(req oldCmds.Request, res oldCmds.Response) {
_, fs, err := getFilestore(req.InvocContext())
@ -127,7 +131,7 @@ For ERROR entries the error will also be printed to stderr.
})
res.SetOutput(out)
} else {
fileOrder, _, _ := req.Option("file-order").Bool()
fileOrder, _, _ := req.Option(fileOrderOptionName).Bool()
next, err := filestore.VerifyAll(fs, fileOrder)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)

View File

@ -24,6 +24,13 @@ import (
var ErrInvalidCompressionLevel = errors.New("compression level must be between 1 and 9")
const (
outputOptionName = "output"
archiveOptionName = "archive"
compressOptionName = "compress"
compressionLevelOptionName = "compression-level"
)
var GetCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Download IPFS objects.",
@ -44,10 +51,10 @@ may also specify the level of compression by specifying '-l=<1-9>'.
cmdkit.StringArg("ipfs-path", true, false, "The path to the IPFS object(s) to be outputted.").EnableStdin(),
},
Options: []cmdkit.Option{
cmdkit.StringOption("output", "o", "The path where the output should be stored."),
cmdkit.BoolOption("archive", "a", "Output a TAR archive."),
cmdkit.BoolOption("compress", "C", "Compress the output with GZIP compression."),
cmdkit.IntOption("compression-level", "l", "The level of compression (1-9)."),
cmdkit.StringOption(outputOptionName, "o", "The path where the output should be stored."),
cmdkit.BoolOption(archiveOptionName, "a", "Output a TAR archive."),
cmdkit.BoolOption(compressOptionName, "C", "Compress the output with GZIP compression."),
cmdkit.IntOption(compressionLevelOptionName, "l", "The level of compression (1-9)."),
},
PreRun: func(req *cmds.Request, env cmds.Environment) error {
_, err := getCompressOptions(req)
@ -84,7 +91,7 @@ may also specify the level of compression by specifying '-l=<1-9>'.
return err
}
archive, _ := req.Options["archive"].(bool)
archive, _ := req.Options[archiveOptionName].(bool)
reader, err := uarchive.DagArchive(ctx, dn, p.String(), node.DAG, archive, cmplvl)
if err != nil {
return err
@ -113,7 +120,7 @@ may also specify the level of compression by specifying '-l=<1-9>'.
return err
}
archive, _ := req.Options["archive"].(bool)
archive, _ := req.Options[archiveOptionName].(bool)
gw := getWriter{
Out: os.Stdout,
@ -165,7 +172,7 @@ func makeProgressBar(out io.Writer, l int64) *pb.ProgressBar {
}
func getOutPath(req *cmds.Request) string {
outPath, _ := req.Options["output"].(string)
outPath, _ := req.Options[outputOptionName].(string)
if outPath == "" {
trimmed := strings.TrimRight(req.Arguments[0], "/")
_, outPath = filepath.Split(trimmed)
@ -233,8 +240,8 @@ func (gw *getWriter) writeExtracted(r io.Reader, fpath string) error {
}
func getCompressOptions(req *cmds.Request) (int, error) {
cmprs, _ := req.Options["compress"].(bool)
cmplvl, cmplvlFound := req.Options["compression-level"].(int)
cmprs, _ := req.Options[compressOptionName].(bool)
cmplvl, cmplvlFound := req.Options[compressionLevelOptionName].(int)
switch {
case !cmprs:
return gzip.NoCompression, nil

View File

@ -37,6 +37,10 @@ type IdOutput struct {
ProtocolVersion string
}
const (
formatOptionName = "format"
)
var IDCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Show ipfs node id info.",
@ -60,7 +64,7 @@ EXAMPLE:
cmdkit.StringArg("peerid", false, false, "Peer.ID of node to look up."),
},
Options: []cmdkit.Option{
cmdkit.StringOption("format", "f", "Optional output format."),
cmdkit.StringOption(formatOptionName, "f", "Optional output format."),
},
Run: func(req cmds.Request, res cmds.Response) {
node, err := req.InvocContext().GetNode()
@ -126,7 +130,7 @@ EXAMPLE:
return nil, e.TypeErr(val, v)
}
format, found, err := res.Request().Option("format").String()
format, found, err := res.Request().Option(formatOptionName).String()
if err != nil {
return nil, err
}

View File

@ -55,13 +55,18 @@ type KeyRenameOutput struct {
Overwrite bool
}
const (
keyStoreTypeOptionName = "type"
keyStoreSizeOptionName = "size"
)
var keyGenCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Create a new keypair",
},
Options: []cmdkit.Option{
cmdkit.StringOption("type", "t", "type of the key to create [rsa, ed25519]"),
cmdkit.IntOption("size", "s", "size of the key to generate"),
cmdkit.StringOption(keyStoreTypeOptionName, "t", "type of the key to create [rsa, ed25519]"),
cmdkit.IntOption(keyStoreSizeOptionName, "s", "size of the key to generate"),
},
Arguments: []cmdkit.Argument{
cmdkit.StringArg("name", true, false, "name of key to create"),
@ -72,7 +77,7 @@ var keyGenCmd = &cmds.Command{
return err
}
typ, f := req.Options["type"].(string)
typ, f := req.Options[keyStoreTypeOptionName].(string)
if !f {
return fmt.Errorf("please specify a key type with --type")
}
@ -84,7 +89,7 @@ var keyGenCmd = &cmds.Command{
opts := []options.KeyGenerateOption{options.Key.Type(typ)}
size, sizefound := req.Options["size"].(int)
size, sizefound := req.Options[keyStoreSizeOptionName].(int)
if sizefound {
opts = append(opts, options.Key.Size(size))
}
@ -146,6 +151,10 @@ var keyListCmd = &cmds.Command{
Type: KeyOutputList{},
}
const (
keyStoreForceOptionName = "force"
)
var keyRenameCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Rename a keypair",
@ -155,7 +164,7 @@ var keyRenameCmd = &cmds.Command{
cmdkit.StringArg("newName", true, false, "new name of the key"),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("force", "f", "Allow to overwrite an existing key."),
cmdkit.BoolOption(keyStoreForceOptionName, "f", "Allow to overwrite an existing key."),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
api, err := cmdenv.GetApi(env)
@ -165,7 +174,7 @@ var keyRenameCmd = &cmds.Command{
name := req.Arguments[0]
newName := req.Arguments[1]
force, _ := req.Options["force"].(bool)
force, _ := req.Options[keyStoreForceOptionName].(bool)
key, overwritten, err := api.Key().Rename(req.Context, name, newName, options.Key.Force(force))
if err != nil {

View File

@ -36,6 +36,11 @@ type LsOutput struct {
Objects []LsObject
}
const (
lsHeadersOptionNameTime = "headers"
lsResolveTypeOptionName = "resolve-type"
)
var LsCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "List directory contents for Unix filesystem objects.",
@ -53,8 +58,8 @@ The JSON output contains type information.
cmdkit.StringArg("ipfs-path", true, true, "The path to the IPFS object(s) to list links from.").EnableStdin(),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("headers", "v", "Print table headers (Hash, Size, Name)."),
cmdkit.BoolOption("resolve-type", "Resolve linked objects to find out their types.").WithDefault(true),
cmdkit.BoolOption(lsHeadersOptionNameTime, "v", "Print table headers (Hash, Size, Name)."),
cmdkit.BoolOption(lsResolveTypeOptionName, "Resolve linked objects to find out their types.").WithDefault(true),
},
Run: func(req cmds.Request, res cmds.Response) {
nd, err := req.InvocContext().GetNode()
@ -70,12 +75,12 @@ The JSON output contains type information.
}
// get options early -> exit early in case of error
if _, _, err := req.Option("headers").Bool(); err != nil {
if _, _, err := req.Option(lsHeadersOptionNameTime).Bool(); err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
resolve, _, err := req.Option("resolve-type").Bool()
resolve, _, err := req.Option(lsResolveTypeOptionName).Bool()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
@ -178,7 +183,7 @@ The JSON output contains type information.
return nil, err
}
headers, _, _ := res.Request().Option("headers").Bool()
headers, _, _ := res.Request().Option(lsHeadersOptionNameTime).Bool()
output, ok := v.(*LsOutput)
if !ok {
return nil, e.TypeErr(output, v)

View File

@ -53,10 +53,6 @@ type P2PStreamsOutput struct {
const (
allowCustomProtocolOptionName = "allow-custom-protocol"
allOptionName = "all"
protocolOptionName = "protocol"
listenAddressOptionName = "listen-address"
targetAddressOptionName = "target-address"
)
var resolveTimeout = 10 * time.Second
@ -258,12 +254,16 @@ func forwardLocal(ctx context.Context, p *p2p.P2P, ps pstore.Peerstore, proto pr
return err
}
const (
p2pHeadersOptionName = "headers"
)
var p2pLsCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "List active p2p listeners.",
},
Options: []cmdkit.Option{
cmdkit.BoolOption("headers", "v", "Print table headers (Protocol, Listen, Target)."),
cmdkit.BoolOption(p2pHeadersOptionName, "v", "Print table headers (Protocol, Listen, Target)."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := p2pGetNode(req)
@ -304,7 +304,7 @@ var p2pLsCmd = &cmds.Command{
return nil, err
}
headers, _, _ := res.Request().Option("headers").Bool()
headers, _, _ := res.Request().Option(p2pHeadersOptionName).Bool()
list := v.(*P2PLsOutput)
buf := new(bytes.Buffer)
w := tabwriter.NewWriter(buf, 1, 2, 1, ' ', 0)
@ -322,15 +322,22 @@ var p2pLsCmd = &cmds.Command{
},
}
const (
p2pAllOptionName = "all"
p2pProtocolOptionName = "protocol"
p2pListenAddressOptionName = "listen-address"
p2pTargetAddressOptionName = "target-address"
)
var p2pCloseCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Stop listening for new connections to forward.",
},
Options: []cmdkit.Option{
cmdkit.BoolOption(allOptionName, "a", "Close all listeners."),
cmdkit.StringOption(protocolOptionName, "p", "Match protocol name"),
cmdkit.StringOption(listenAddressOptionName, "l", "Match listen address"),
cmdkit.StringOption(targetAddressOptionName, "t", "Match target address"),
cmdkit.BoolOption(p2pAllOptionName, "a", "Close all listeners."),
cmdkit.StringOption(p2pProtocolOptionName, "p", "Match protocol name"),
cmdkit.StringOption(p2pListenAddressOptionName, "l", "Match listen address"),
cmdkit.StringOption(p2pTargetAddressOptionName, "t", "Match target address"),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := p2pGetNode(req)
@ -339,10 +346,10 @@ var p2pCloseCmd = &cmds.Command{
return
}
closeAll, _, _ := req.Option(allOptionName).Bool()
protoOpt, p, _ := req.Option(protocolOptionName).String()
listenOpt, l, _ := req.Option(listenAddressOptionName).String()
targetOpt, t, _ := req.Option(targetAddressOptionName).String()
closeAll, _, _ := req.Option(p2pAllOptionName).Bool()
protoOpt, p, _ := req.Option(p2pProtocolOptionName).String()
listenOpt, l, _ := req.Option(p2pListenAddressOptionName).String()
targetOpt, t, _ := req.Option(p2pTargetAddressOptionName).String()
proto := protocol.ID(protoOpt)
@ -428,7 +435,7 @@ var p2pStreamLsCmd = &cmds.Command{
Tagline: "List active p2p streams.",
},
Options: []cmdkit.Option{
cmdkit.BoolOption("headers", "v", "Print table headers (ID, Protocol, Local, Remote)."),
cmdkit.BoolOption(p2pHeadersOptionName, "v", "Print table headers (ID, Protocol, Local, Remote)."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := p2pGetNode(req)
@ -462,7 +469,7 @@ var p2pStreamLsCmd = &cmds.Command{
return nil, err
}
headers, _, _ := res.Request().Option("headers").Bool()
headers, _, _ := res.Request().Option(p2pHeadersOptionName).Bool()
list := v.(*P2PStreamsOutput)
buf := new(bytes.Buffer)
w := tabwriter.NewWriter(buf, 1, 2, 1, ' ', 0)
@ -488,7 +495,7 @@ var p2pStreamCloseCmd = &cmds.Command{
cmdkit.StringArg("id", false, false, "Stream identifier"),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("all", "a", "Close all streams."),
cmdkit.BoolOption(p2pAllOptionName, "a", "Close all streams."),
},
Run: func(req cmds.Request, res cmds.Response) {
res.SetOutput(nil)
@ -499,7 +506,7 @@ var p2pStreamCloseCmd = &cmds.Command{
return
}
closeAll, _, _ := req.Option("all").Bool()
closeAll, _, _ := req.Option(p2pAllOptionName).Bool()
var handlerID uint64
if !closeAll {

View File

@ -46,6 +46,11 @@ type AddPinOutput struct {
Progress int `json:",omitempty"`
}
const (
pinRecursiveOptionName = "recursive"
pinProgressOptionName = "progress"
)
var addPinCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Pin objects to local storage.",
@ -56,8 +61,8 @@ var addPinCmd = &cmds.Command{
cmdkit.StringArg("ipfs-path", true, true, "Path to object(s) to be pinned.").EnableStdin(),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("recursive", "r", "Recursively pin the object linked to by the specified object(s).").WithDefault(true),
cmdkit.BoolOption("progress", "Show progress"),
cmdkit.BoolOption(pinRecursiveOptionName, "r", "Recursively pin the object linked to by the specified object(s).").WithDefault(true),
cmdkit.BoolOption(pinProgressOptionName, "Show progress"),
},
Type: AddPinOutput{},
Run: func(req cmds.Request, res cmds.Response) {
@ -76,12 +81,12 @@ var addPinCmd = &cmds.Command{
defer n.Blockstore.PinLock().Unlock()
// set recursive flag
recursive, _, err := req.Option("recursive").Bool()
recursive, _, err := req.Option(pinRecursiveOptionName).Bool()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
showProgress, _, _ := req.Option("progress").Bool()
showProgress, _, _ := req.Option(pinProgressOptionName).Bool()
if !showProgress {
added, err := corerepo.Pin(n, api, req.Context(), req.Arguments(), recursive)
@ -188,7 +193,7 @@ collected if needed. (By default, recursively. Use -r=false for direct pins.)
cmdkit.StringArg("ipfs-path", true, true, "Path to object(s) to be unpinned.").EnableStdin(),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("recursive", "r", "Recursively unpin the object linked to by the specified object(s).").WithDefault(true),
cmdkit.BoolOption(pinRecursiveOptionName, "r", "Recursively unpin the object linked to by the specified object(s).").WithDefault(true),
},
Type: PinOutput{},
Run: func(req cmds.Request, res cmds.Response) {
@ -205,7 +210,7 @@ collected if needed. (By default, recursively. Use -r=false for direct pins.)
}
// set recursive flag
recursive, _, err := req.Option("recursive").Bool()
recursive, _, err := req.Option(pinRecursiveOptionName).Bool()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
@ -240,6 +245,11 @@ collected if needed. (By default, recursively. Use -r=false for direct pins.)
},
}
const (
pinTypeOptionName = "type"
pinQuietOptionName = "quiet"
)
var listPinCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "List objects pinned to local storage.",
@ -288,8 +298,8 @@ Example:
cmdkit.StringArg("ipfs-path", false, true, "Path to object(s) to be listed."),
},
Options: []cmdkit.Option{
cmdkit.StringOption("type", "t", "The type of pinned keys to list. Can be \"direct\", \"indirect\", \"recursive\", or \"all\".").WithDefault("all"),
cmdkit.BoolOption("quiet", "q", "Write just hashes of objects."),
cmdkit.StringOption(pinTypeOptionName, "t", "The type of pinned keys to list. Can be \"direct\", \"indirect\", \"recursive\", or \"all\".").WithDefault("all"),
cmdkit.BoolOption(pinQuietOptionName, "q", "Write just hashes of objects."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
@ -304,7 +314,7 @@ Example:
return
}
typeStr, _, err := req.Option("type").String()
typeStr, _, err := req.Option(pinTypeOptionName).String()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
@ -340,7 +350,7 @@ Example:
return nil, err
}
quiet, _, err := res.Request().Option("quiet").Bool()
quiet, _, err := res.Request().Option(pinQuietOptionName).Bool()
if err != nil {
return nil, err
}
@ -362,6 +372,10 @@ Example:
},
}
const (
pinUnpinOptionName = "unpin"
)
var updatePinCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Update a recursive pin",
@ -377,7 +391,7 @@ new pin and removing the old one.
cmdkit.StringArg("to-path", true, false, "Path to new object to be pinned."),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("unpin", "Remove the old pin.").WithDefault(true),
cmdkit.BoolOption(pinUnpinOptionName, "Remove the old pin.").WithDefault(true),
},
Type: PinOutput{},
Run: func(req cmds.Request, res cmds.Response) {
@ -387,7 +401,7 @@ new pin and removing the old one.
return
}
unpin, _, err := req.Option("unpin").Bool()
unpin, _, err := req.Option(pinUnpinOptionName).Bool()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
@ -431,13 +445,17 @@ new pin and removing the old one.
},
}
const (
pinVerboseOptionName = "verbose"
)
var verifyPinCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Verify that recursive pins are complete.",
},
Options: []cmdkit.Option{
cmdkit.BoolOption("verbose", "Also write the hashes of non-broken pins."),
cmdkit.BoolOption("quiet", "q", "Write just hashes of broken pins."),
cmdkit.BoolOption(pinVerboseOptionName, "Also write the hashes of non-broken pins."),
cmdkit.BoolOption(pinQuietOptionName, "q", "Write just hashes of broken pins."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
@ -446,8 +464,8 @@ var verifyPinCmd = &cmds.Command{
return
}
verbose, _, _ := res.Request().Option("verbose").Bool()
quiet, _, _ := res.Request().Option("quiet").Bool()
verbose, _, _ := res.Request().Option(pinVerboseOptionName).Bool()
quiet, _, _ := res.Request().Option(pinQuietOptionName).Bool()
if verbose && quiet {
res.SetError(fmt.Errorf("the --verbose and --quiet options can not be used at the same time"), cmdkit.ErrNormal)
@ -464,7 +482,7 @@ var verifyPinCmd = &cmds.Command{
Type: PinVerifyRes{},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
quiet, _, _ := res.Request().Option("quiet").Bool()
quiet, _, _ := res.Request().Option(pinQuietOptionName).Bool()
out, err := unwrapOutput(res.Output())
if err != nil {

View File

@ -27,6 +27,10 @@ type PingResult struct {
Text string
}
const (
pingCountOptionName = "count"
)
// ErrPingSelf is returned when the user attempts to ping themself.
var ErrPingSelf = errors.New("error: can't ping self")
@ -43,7 +47,7 @@ trip latency information.
cmdkit.StringArg("peer ID", true, true, "ID of peer to be pinged.").EnableStdin(),
},
Options: []cmdkit.Option{
cmdkit.IntOption("count", "n", "Number of ping messages to send.").WithDefault(10),
cmdkit.IntOption(pingCountOptionName, "n", "Number of ping messages to send.").WithDefault(10),
},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
@ -97,7 +101,7 @@ trip latency information.
n.Peerstore.AddAddr(peerID, addr, pstore.TempAddrTTL) // temporary
}
numPings, _, err := req.Option("count").Int()
numPings, _, err := req.Option(pingCountOptionName).Int()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return

View File

@ -44,6 +44,10 @@ To use, the daemon must be run with '--enable-pubsub-experiment'.
},
}
const (
pubsubDiscoverOptionName = "discover"
)
var PubsubSubCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Subscribe to messages on a given topic.",
@ -72,7 +76,7 @@ This command outputs data in the following encodings:
cmdkit.StringArg("topic", true, false, "String name of topic to subscribe to."),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("discover", "try to discover other peers subscribed to the same topic"),
cmdkit.BoolOption(pubsubDiscoverOptionName, "try to discover other peers subscribed to the same topic"),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
n, err := cmdenv.GetNode(env)
@ -96,7 +100,7 @@ This command outputs data in the following encodings:
}
defer sub.Cancel()
discover, _ := req.Options["discover"].(bool)
discover, _ := req.Options[pubsubDiscoverOptionName].(bool)
if discover {
go func() {
blk := blocks.NewBlock([]byte("floodsub:" + topic))

View File

@ -22,6 +22,14 @@ type KeyList struct {
Keys []cid.Cid
}
const (
refsFormatOptionName = "format"
refsEdgesOptionName = "edges"
refsUniqueOptionName = "unique"
refsRecursiveOptionName = "recursive"
refsMaxDepthOptionName = "max-depth"
)
// KeyListTextMarshaler outputs a KeyList as plaintext, one key per line
func KeyListTextMarshaler(res cmds.Response) (io.Reader, error) {
out, err := unwrapOutput(res.Output())
@ -60,11 +68,11 @@ NOTE: List all references recursively by using the flag '-r'.
cmdkit.StringArg("ipfs-path", true, true, "Path to the object(s) to list refs from.").EnableStdin(),
},
Options: []cmdkit.Option{
cmdkit.StringOption("format", "Emit edges with given format. Available tokens: <src> <dst> <linkname>.").WithDefault("<dst>"),
cmdkit.BoolOption("edges", "e", "Emit edge format: `<from> -> <to>`."),
cmdkit.BoolOption("unique", "u", "Omit duplicate refs from output."),
cmdkit.BoolOption("recursive", "r", "Recursively list links of child nodes."),
cmdkit.IntOption("max-depth", "Only for recursive refs, limits fetch and listing to the given depth").WithDefault(-1),
cmdkit.StringOption(refsFormatOptionName, "Emit edges with given format. Available tokens: <src> <dst> <linkname>.").WithDefault("<dst>"),
cmdkit.BoolOption(refsEdgesOptionName, "e", "Emit edge format: `<from> -> <to>`."),
cmdkit.BoolOption(refsUniqueOptionName, "u", "Omit duplicate refs from output."),
cmdkit.BoolOption(refsRecursiveOptionName, "r", "Recursively list links of child nodes."),
cmdkit.IntOption(refsMaxDepthOptionName, "Only for recursive refs, limits fetch and listing to the given depth").WithDefault(-1),
},
Run: func(req cmds.Request, res cmds.Response) {
ctx := req.Context()
@ -74,19 +82,19 @@ NOTE: List all references recursively by using the flag '-r'.
return
}
unique, _, err := req.Option("unique").Bool()
unique, _, err := req.Option(refsUniqueOptionName).Bool()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
recursive, _, err := req.Option("recursive").Bool()
recursive, _, err := req.Option(refsRecursiveOptionName).Bool()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
maxDepth, _, err := req.Option("max-depth").Int()
maxDepth, _, err := req.Option(refsMaxDepthOptionName).Int()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
@ -96,13 +104,13 @@ NOTE: List all references recursively by using the flag '-r'.
maxDepth = 1 // write only direct refs
}
format, _, err := req.Option("format").String()
format, _, err := req.Option(refsFormatOptionName).String()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
edges, _, err := req.Option("edges").Bool()
edges, _, err := req.Option(refsEdgesOptionName).Bool()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return

View File

@ -51,6 +51,11 @@ type GcResult struct {
Error string `json:",omitempty"`
}
const (
repoStreamErrorsOptionName = "stream-errors"
repoQuietOptionName = "quiet"
)
var repoGcCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Perform a garbage collection sweep on the repo.",
@ -61,8 +66,8 @@ order to reclaim hard disk space.
`,
},
Options: []cmdkit.Option{
cmdkit.BoolOption("stream-errors", "Stream errors."),
cmdkit.BoolOption("quiet", "q", "Write minimal output."),
cmdkit.BoolOption(repoStreamErrorsOptionName, "Stream errors."),
cmdkit.BoolOption(repoQuietOptionName, "q", "Write minimal output."),
},
Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) error {
n, err := cmdenv.GetNode(env)
@ -70,7 +75,7 @@ order to reclaim hard disk space.
return err
}
streamErrors, _ := req.Options["stream-errors"].(bool)
streamErrors, _ := req.Options[repoStreamErrorsOptionName].(bool)
gcOutChan := corerepo.GarbageCollectAsync(n, req.Context)
@ -101,7 +106,7 @@ order to reclaim hard disk space.
Type: GcResult{},
Encoders: cmds.EncoderMap{
cmds.Text: cmds.MakeEncoder(func(req *cmds.Request, w io.Writer, v interface{}) error {
quiet, _ := req.Options["quiet"].(bool)
quiet, _ := req.Options[repoQuietOptionName].(bool)
obj, ok := v.(*GcResult)
if !ok {
@ -124,6 +129,11 @@ order to reclaim hard disk space.
},
}
const (
repoSizeOnlyOptionName = "size-only"
repoHumanOptionName = "human"
)
var repoStatCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Get stats for the currently used repo.",
@ -139,8 +149,8 @@ Version string The repo version.
`,
},
Options: []cmdkit.Option{
cmdkit.BoolOption("size-only", "Only report RepoSize and StorageMax."),
cmdkit.BoolOption("human", "Output sizes in MiB."),
cmdkit.BoolOption(repoSizeOnlyOptionName, "Only report RepoSize and StorageMax."),
cmdkit.BoolOption(repoHumanOptionName, "Output sizes in MiB."),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
n, err := cmdenv.GetNode(env)
@ -148,7 +158,7 @@ Version string The repo version.
return err
}
sizeOnly, _ := req.Options["size-only"].(bool)
sizeOnly, _ := req.Options[repoSizeOnlyOptionName].(bool)
if sizeOnly {
sizeStat, err := corerepo.RepoSize(req.Context, n)
if err != nil {
@ -178,8 +188,8 @@ Version string The repo version.
wtr := tabwriter.NewWriter(w, 0, 0, 1, ' ', 0)
defer wtr.Flush()
human, _ := req.Options["human"].(bool)
sizeOnly, _ := req.Options["size-only"].(bool)
human, _ := req.Options[repoHumanOptionName].(bool)
sizeOnly, _ := req.Options[repoSizeOnlyOptionName].(bool)
printSize := func(name string, size uint64) {
sizeInMiB := size / (1024 * 1024)
@ -360,7 +370,7 @@ var repoVersionCmd = &oldcmds.Command{
},
Options: []cmdkit.Option{
cmdkit.BoolOption("quiet", "q", "Write minimal output."),
cmdkit.BoolOption(repoQuietOptionName, "q", "Write minimal output."),
},
Run: func(req oldcmds.Request, res oldcmds.Response) {
res.SetOutput(&RepoVersion{

View File

@ -20,6 +20,12 @@ import (
"gx/ipfs/QmXTmUCBtDUrzDYVzASogLiNph7EBuYqEgPL7QoHNMzUnz/go-ipfs-cmds"
)
const (
resolveRecursiveOptionName = "recursive"
resolveDhtRecordCountOptionName = "dht-record-count"
resolveDhtTimeoutOptionName = "dht-timeout"
)
var ResolveCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Resolve the value of names to IPFS.",
@ -64,9 +70,9 @@ Resolve the value of an IPFS DAG path:
cmdkit.StringArg("name", true, false, "The name to resolve.").EnableStdin(),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("recursive", "r", "Resolve until the result is an IPFS name."),
cmdkit.IntOption("dht-record-count", "dhtrc", "Number of records to request for DHT resolution."),
cmdkit.StringOption("dht-timeout", "dhtt", "Max time to collect values during DHT resolution eg \"30s\". Pass 0 for no timeout."),
cmdkit.BoolOption(resolveRecursiveOptionName, "r", "Resolve until the result is an IPFS name."),
cmdkit.IntOption(resolveDhtRecordCountOptionName, "dhtrc", "Number of records to request for DHT resolution."),
cmdkit.StringOption(resolveDhtTimeoutOptionName, "dhtt", "Max time to collect values during DHT resolution eg \"30s\". Pass 0 for no timeout."),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
api, err := cmdenv.GetApi(env)
@ -87,12 +93,12 @@ Resolve the value of an IPFS DAG path:
}
name := req.Arguments[0]
recursive, _ := req.Options["recursive"].(bool)
recursive, _ := req.Options[resolveRecursiveOptionName].(bool)
// the case when ipns is resolved step by step
if strings.HasPrefix(name, "/ipns/") && !recursive {
rc, rcok := req.Options["dht-record-count"].(uint)
dhtt, dhttok := req.Options["dht-timeout"].(string)
rc, rcok := req.Options[resolveDhtRecordCountOptionName].(uint)
dhtt, dhttok := req.Options[resolveDhtTimeoutOptionName].(string)
ropts := []options.NameResolveOption{
options.Name.ResolveOption(nsopts.Depth(1)),
}

View File

@ -33,6 +33,13 @@ for your IPFS node.`,
},
}
const (
statPeerOptionName = "peer"
statProtoOptionName = "proto"
statPollOptionName = "poll"
statIntervalOptionName = "interval"
)
var statBwCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Print ipfs bandwidth information.",
@ -71,10 +78,10 @@ Example:
`,
},
Options: []cmdkit.Option{
cmdkit.StringOption("peer", "p", "Specify a peer to print bandwidth for."),
cmdkit.StringOption("proto", "t", "Specify a protocol to print bandwidth for."),
cmdkit.BoolOption("poll", "Print bandwidth at an interval."),
cmdkit.StringOption("interval", "i", `Time interval to wait between updating output, if 'poll' is true.
cmdkit.StringOption(statPeerOptionName, "p", "Specify a peer to print bandwidth for."),
cmdkit.StringOption(statProtoOptionName, "t", "Specify a protocol to print bandwidth for."),
cmdkit.BoolOption(statPollOptionName, "Print bandwidth at an interval."),
cmdkit.StringOption(statIntervalOptionName, "i", `Time interval to wait between updating output, if 'poll' is true.
This accepts durations such as "300s", "1.5h" or "2h45m". Valid time units are:
"ns", "us" (or "µs"), "ms", "s", "m", "h".`).WithDefault("1s"),
@ -95,7 +102,7 @@ Example:
return fmt.Errorf("bandwidth reporter disabled in config")
}
pstr, pfound := req.Options["peer"].(string)
pstr, pfound := req.Options[statPeerOptionName].(string)
tstr, tfound := req.Options["proto"].(string)
if pfound && tfound {
return cmdkit.Errorf(cmdkit.ErrClient, "please only specify peer OR protocol")
@ -110,13 +117,13 @@ Example:
pid = checkpid
}
timeS, _ := req.Options["interval"].(string)
timeS, _ := req.Options[statIntervalOptionName].(string)
interval, err := time.ParseDuration(timeS)
if err != nil {
return err
}
doPoll, _ := req.Options["poll"].(bool)
doPoll, _ := req.Options[statPollOptionName].(bool)
for {
if pfound {
stats := nd.Reporter.GetBandwidthForPeer(pid)
@ -142,7 +149,7 @@ Example:
Type: metrics.Stats{},
PostRun: cmds.PostRunMap{
cmds.CLI: func(res cmds.Response, re cmds.ResponseEmitter) error {
polling, _ := res.Request().Options["poll"].(bool)
polling, _ := res.Request().Options[statPollOptionName].(bool)
if polling {
fmt.Fprintln(os.Stdout, "Total Up Total Down Rate Up Rate Down")

View File

@ -52,6 +52,13 @@ ipfs peers in the internet.
},
}
const (
swarmVerboseOptionName = "verbose"
swarmStreamsOptionName = "streams"
swarmLatencyOptionName = "latency"
swarmDirectionOptionName = "direction"
)
var swarmPeersCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "List peers with open connections.",
@ -60,10 +67,10 @@ var swarmPeersCmd = &cmds.Command{
`,
},
Options: []cmdkit.Option{
cmdkit.BoolOption("verbose", "v", "display all extra information"),
cmdkit.BoolOption("streams", "Also list information about open streams for each peer"),
cmdkit.BoolOption("latency", "Also list information about latency to each peer"),
cmdkit.BoolOption("direction", "Also list information about the direction of connection"),
cmdkit.BoolOption(swarmVerboseOptionName, "v", "display all extra information"),
cmdkit.BoolOption(swarmStreamsOptionName, "Also list information about open streams for each peer"),
cmdkit.BoolOption(swarmLatencyOptionName, "Also list information about latency to each peer"),
cmdkit.BoolOption(swarmDirectionOptionName, "Also list information about the direction of connection"),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
api, err := cmdenv.GetApi(env)
@ -71,10 +78,10 @@ var swarmPeersCmd = &cmds.Command{
return err
}
verbose, _ := req.Options["verbose"].(bool)
latency, _ := req.Options["latency"].(bool)
streams, _ := req.Options["streams"].(bool)
direction, _ := req.Options["direction"].(bool)
verbose, _ := req.Options[swarmVerboseOptionName].(bool)
latency, _ := req.Options[swarmLatencyOptionName].(bool)
streams, _ := req.Options[swarmStreamsOptionName].(bool)
direction, _ := req.Options[swarmDirectionOptionName].(bool)
conns, err := api.Swarm().Peers(req.Context)
if err != nil {

View File

@ -22,6 +22,13 @@ type VersionOutput struct {
Golang string
}
const (
versionNumberOptionName = "number"
versionCommitOptionName = "commit"
versionRepoOptionName = "repo"
versionAllOptionName = "all"
)
var VersionCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Show ipfs version information.",
@ -29,10 +36,10 @@ var VersionCmd = &cmds.Command{
},
Options: []cmdkit.Option{
cmdkit.BoolOption("number", "n", "Only show the version number."),
cmdkit.BoolOption("commit", "Show the commit hash."),
cmdkit.BoolOption("repo", "Show repo version."),
cmdkit.BoolOption("all", "Show all version information"),
cmdkit.BoolOption(versionNumberOptionName, "n", "Only show the version number."),
cmdkit.BoolOption(versionCommitOptionName, "Show the commit hash."),
cmdkit.BoolOption(versionRepoOptionName, "Show repo version."),
cmdkit.BoolOption(versionAllOptionName, "Show all version information"),
},
Run: func(req cmds.Request, res cmds.Response) {
res.SetOutput(&VersionOutput{
@ -55,7 +62,7 @@ var VersionCmd = &cmds.Command{
return nil, e.TypeErr(version, v)
}
repo, _, err := res.Request().Option("repo").Bool()
repo, _, err := res.Request().Option(versionRepoOptionName).Bool()
if err != nil {
return nil, err
}
@ -64,7 +71,7 @@ var VersionCmd = &cmds.Command{
return strings.NewReader(version.Repo + "\n"), nil
}
commit, _, err := res.Request().Option("commit").Bool()
commit, _, err := res.Request().Option(versionCommitOptionName).Bool()
commitTxt := ""
if err != nil {
return nil, err
@ -73,7 +80,7 @@ var VersionCmd = &cmds.Command{
commitTxt = "-" + version.Commit
}
number, _, err := res.Request().Option("number").Bool()
number, _, err := res.Request().Option(versionNumberOptionName).Bool()
if err != nil {
return nil, err
}
@ -81,7 +88,7 @@ var VersionCmd = &cmds.Command{
return strings.NewReader(fmt.Sprintln(version.Version + commitTxt)), nil
}
all, _, err := res.Request().Option("all").Bool()
all, _, err := res.Request().Option(versionAllOptionName).Bool()
if err != nil {
return nil, err
}

View File

@ -59,5 +59,29 @@ test_expect_success "ipfs daemon --offline --mount fails - #2995" '
test_fsh cat daemon_err
'
test_launch_ipfs_daemon --offline
test_expect_success "'ipfs name resolve' succeeds after ipfs id when daemon offline" '
PEERID=`ipfs id --format="<id>"` &&
test_check_peerid "${PEERID}" &&
ipfs name publish --allow-offline -Q "/ipfs/$HASH_WELCOME_DOCS" >publish_out
'
test_expect_success "pubrmlish --quieter output looks good" '
echo "${PEERID}" >expected1 &&
test_cmp expected1 publish_out
'
test_expect_success "'ipfs name resolve' succeeds" '
ipfs name resolve "$PEERID" >output
'
test_expect_success "resolve output looks good" '
printf "/ipfs/%s\n" "$HASH_WELCOME_DOCS" >expected2 &&
test_cmp expected2 output
'
test_kill_ipfs_daemon
test_done