Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lotus-shed: add math command #3568

Merged
merged 1 commit into from
Sep 5, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cmd/lotus-shed/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func main() {
miscCmd,
mpoolCmd,
genesisVerifyCmd,
mathCmd,
}

app := &cli.App{
Expand Down
103 changes: 103 additions & 0 deletions cmd/lotus-shed/math.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package main

import (
"bufio"
"fmt"
"io"
"os"
"strings"

"github.com/urfave/cli/v2"

"github.com/filecoin-project/lotus/chain/types"
)

var mathCmd = &cli.Command{
Name: "math",
Usage: "utility commands around doing math on a list of numbers",
Subcommands: []*cli.Command{
mathSumCmd,
},
}

func readLargeNumbers(i io.Reader) ([]types.BigInt, error) {
list := []types.BigInt{}
reader := bufio.NewReader(i)

exit := false
for {
if exit {
break
}

line, err := reader.ReadString('\n')
if err != nil && err != io.EOF {
break
}
if err == io.EOF {
exit = true
}

line = strings.Trim(line, "\n")

if len(line) == 0 {
continue
}

value, err := types.BigFromString(line)
if err != nil {
return []types.BigInt{}, fmt.Errorf("failed to parse line: %s", line)
}

list = append(list, value)
}

return list, nil
}

var mathSumCmd = &cli.Command{
Name: "sum",
Usage: "Sum numbers",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "avg",
Value: false,
Usage: "Print the average instead of the sum",
},
&cli.StringFlag{
Name: "format",
Value: "raw",
Usage: "format the number in a more readable way [fil,bytes2,bytes10]",
},
},
Action: func(cctx *cli.Context) error {
list, err := readLargeNumbers(os.Stdin)
if err != nil {
return err
}

val := types.NewInt(0)
for _, value := range list {
val = types.BigAdd(val, value)
}

if cctx.Bool("avg") {
val = types.BigDiv(val, types.NewInt(uint64(len(list))))
}

switch cctx.String("format") {
case "byte2":
fmt.Printf("%s\n", types.SizeStr(val))
case "byte10":
fmt.Printf("%s\n", types.DeciStr(val))
case "fil":
fmt.Printf("%s\n", types.FIL(val))
case "raw":
fmt.Printf("%s\n", val)
default:
return fmt.Errorf("Unknown format")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably better to use some factory method producer thingy so that we can get these error before reading all the numbers 🤷‍♂️

}

return nil
},
}