govote/cmd/new.go

109 lines
2.7 KiB
Go
Raw Normal View History

2024-05-12 22:47:24 +00:00
package cmd
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
"time"
"code.c-base.org/baccenfutter/govote/store"
"code.c-base.org/baccenfutter/govote/utils"
"code.c-base.org/baccenfutter/govote/voting/quorum"
"code.c-base.org/baccenfutter/govote/voting/threshold"
"github.com/urfave/cli/v2"
)
var newCmd = &cli.Command{
2024-05-13 08:45:38 +00:00
Name: "new",
Usage: " Create a voting",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "deadline",
Usage: "Duration for which this voting is open",
Aliases: []string{"D"},
Value: "1m",
},
&cli.StringFlag{
Name: "quorum",
Usage: "Minimum required number of participants",
Aliases: []string{"Q"},
Value: "SIMPLE",
},
&cli.StringFlag{
Name: "threshold",
Usage: "Minimum number of positive votes",
Aliases: []string{"T"},
Value: "SIMPLE",
},
&cli.StringFlag{
Name: "electors",
Usage: "Comma-separated list of eligible electors or empty if anyone can vote",
Aliases: []string{"E"},
},
&cli.BoolFlag{
Name: "anonymous",
Usage: "Public visibility of votes.",
Aliases: []string{"A"},
Value: false,
},
},
Action: func(ctx *cli.Context) error {
deadline := ctx.String("deadline")
deadlineNum := fmt.Sprintf("%s", deadline[:len(deadline)-1])
deadlineUnit := fmt.Sprintf("%s", deadline[len(deadline)-1:])
2024-05-12 22:47:24 +00:00
2024-05-13 08:45:38 +00:00
deadlineInt, err := strconv.Atoi(deadlineNum)
if err != nil {
return err
}
2024-05-12 22:47:24 +00:00
2024-05-13 08:45:38 +00:00
if !strings.Contains("mhd", deadlineUnit) {
return fmt.Errorf("invalid deadline unit '%s'. use one of: [ m | d | h ]", deadlineUnit)
}
2024-05-12 22:47:24 +00:00
2024-05-13 08:45:38 +00:00
var d time.Time
switch deadlineUnit {
case "m", "":
d = time.Now().UTC().Add(time.Duration(deadlineInt) * time.Minute).Round(time.Second)
case "h":
d = time.Now().UTC().Add(time.Duration(deadlineInt) * time.Hour).Round(time.Second)
case "d":
d = time.Now().UTC().Add(time.Duration(deadlineInt) * time.Hour * 24).Round(time.Second)
default:
panic("this code should never be reached")
}
2024-05-12 22:47:24 +00:00
2024-05-13 08:45:38 +00:00
var (
q quorum.Quorum
t threshold.Threshold
)
if q, err = quorum.FromString(ctx.String("quorum")); err != nil {
return err
}
if t, err = threshold.FromString(ctx.String("threshold")); err != nil {
return err
}
e := strings.Split(ctx.String("electors"), " ")
a := ctx.Bool("anonymous")
2024-05-12 22:47:24 +00:00
2024-05-13 08:45:38 +00:00
var r = ""
if ctx.Args().Len() == 0 {
fmt.Print("Give your referendum a concise name or subject: ")
inputReader := bufio.NewReader(os.Stdin)
r, _ = inputReader.ReadString('\n')
r = r[:len(r)-1]
} else {
r = strings.Join(ctx.Args().Slice(), " ")
}
2024-05-12 22:47:24 +00:00
2024-05-13 08:45:38 +00:00
id := utils.GenerateRandomString(11)
if err := store.NewVoting(string(id), r, d, q, t, e, a); err != nil {
return err
}
fmt.Println(string(id))
return nil
},
2024-05-12 22:47:24 +00:00
}