Skip to content

Commit

Permalink
refactor: improved ux of multibase command
Browse files Browse the repository at this point in the history
  • Loading branch information
lidel committed Jul 1, 2021
1 parent 509b2a0 commit 27bf745
Showing 1 changed file with 36 additions and 7 deletions.
43 changes: 36 additions & 7 deletions core/commands/multibase.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package commands

import (
"bytes"
"fmt"
"io/ioutil"
"strings"

Expand All @@ -17,6 +18,7 @@ var MbaseCmd = &cmds.Command{
Subcommands: map[string]*cmds.Command{
"encode": mbaseEncodeCmd,
"decode": mbaseDecodeCmd,
"list": basesCmd,
},
Extra: CreateCmdExtras(SetDoesNotUseRepo(true)),
}
Expand All @@ -27,7 +29,21 @@ const (

var mbaseEncodeCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Encode file or stdin into multibase string",
Tagline: "Encode data into multibase string",
LongDescription: `
This command expects a file name or data provided via stdin.
By default it will use URL-safe base64url encoding,
but one can customize used base with -b:
> echo hello | ipfs multibase encode -b base16 > output_file
> cat output_file
f68656c6c6f0a
> echo hello > input_file
> ipfs multibase encode -b base16 input_file
f68656c6c6f0a
`,
},
Arguments: []cmds.Argument{
cmds.FileArg("file", true, false, "data to encode").EnableStdin(),
Expand All @@ -47,11 +63,11 @@ var mbaseEncodeCmd = &cmds.Command{
files := req.Files.Entries()
file, err := cmdenv.GetFileArg(files)
if err != nil {
return err
return fmt.Errorf("failed to access file: %w", err)
}
buf, err := ioutil.ReadAll(file)
if err != nil {
return err
return fmt.Errorf("failed to read file contents: %w", err)
}
encoded := encoder.Encode(buf)
reader := strings.NewReader(encoded)
Expand All @@ -61,7 +77,20 @@ var mbaseEncodeCmd = &cmds.Command{

var mbaseDecodeCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Decode multibase string to stdout",
Tagline: "Decode multibase string",
LongDescription: `
This command expects multibase inside of a file or via stdin:
> echo -n hello | ipfs multibase encode -b base16 > file
> cat file
f68656c6c6f
> ipfs multibase decode file
hello
> cat file | ipfs multibase decode
hello
`,
},
Arguments: []cmds.Argument{
cmds.FileArg("encoded_file", true, false, "encoded data to decode").EnableStdin(),
Expand All @@ -73,15 +102,15 @@ var mbaseDecodeCmd = &cmds.Command{
files := req.Files.Entries()
file, err := cmdenv.GetFileArg(files)
if err != nil {
return err
return fmt.Errorf("failed to access file: %w", err)
}
encoded_data, err := ioutil.ReadAll(file)
if err != nil {
return err
return fmt.Errorf("failed to read file contents: %w", err)
}
_, data, err := mbase.Decode(string(encoded_data))
if err != nil {
return err
return fmt.Errorf("failed to decode multibase: %w", err)
}
reader := bytes.NewReader(data)
return resp.Emit(reader)
Expand Down

0 comments on commit 27bf745

Please sign in to comment.