govote/cmd/new.go
2024-05-13 10:45:38 +02:00

109 lines
2.7 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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{
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:])
deadlineInt, err := strconv.Atoi(deadlineNum)
if err != nil {
return err
}
if !strings.Contains("mhd", deadlineUnit) {
return fmt.Errorf("invalid deadline unit '%s'. use one of: [ m | d | h ]", deadlineUnit)
}
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")
}
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")
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(), " ")
}
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
},
}