package generate import ( "encoding/json" "fmt" "io/ioutil" "strconv" "strings" "time" "github.com/pkg/errors" "github.com/spf13/cobra" "tildegit.org/PigeonProtocolConsortium/pigeongo/internal/codec" ) const ( outStdout = "stdout" outFile = "file" outGoGen = "go-generate" errMsgParsingSeq = "there was ana error parsing the sequence" errMsgEmptyFilePath = "required file path is empty" errMsgWritingFile = "there was an error writing the file" errMsgMissingGoPkg = "required go package name is empty" ) var ( goGenTmp = `// Auto generated // By: tildegit.org/PigeonProtocolConsortium/pigeongo/internal/cmd/lipsenq // On: %s package %s var GeneratedLipmaaLayerSequences = []uint{%v} ` seqConf = struct { Layer, Depth uint Sequences []uint FilePath string GoGenPackageName string Format string }{} seqCmd = cobra.Command{ Use: "sequences", Short: "Generate Lipmaa Layer Sequences", Run: func(cmd *cobra.Command, args []string) { seq := codec.CalculateLipmaaLayerSequence( seqConf.Layer, seqConf.Depth, seqConf.Sequences, ) seqBuff, err := json.Marshal(seq) if err != nil { exitWithErrMsg(cmd, fmt.Sprintf("%v: %v", errMsgParsingSeq, err.Error())) } switch seqConf.Format { case outGoGen: if seqConf.GoGenPackageName == "" { exitWithErrMsg(cmd, errMsgMissingGoPkg) break } var seqStr []string for _, s := range seq { seqStr = append(seqStr, strconv.Itoa(int(s))) } goGenTmp := fmt.Sprintf( goGenTmp, time.Now().UTC(), seqConf.GoGenPackageName, strings.Join(seqStr, ","), ) if seqConf.FilePath == "" { fmt.Println(goGenTmp) break } if err := writeToFile(seqConf.FilePath, []byte(goGenTmp)); err != nil { exitWithErrMsg(cmd, err.Error()) break } case outFile: if err := writeToFile(seqConf.FilePath, seqBuff); err != nil { exitWithErrMsg(cmd, err.Error()) } default: fmt.Println(seq) } }, } ) func exitWithErrMsg(cmd *cobra.Command, msg string) { fmt.Printf("\nError: %s\n\n", msg) cmd.Help() } func writeToFile(p string, d []byte) error { if p == "" { return errors.New(errMsgEmptyFilePath) } if err := ioutil.WriteFile(p, d, 0644); err != nil { return errors.Wrap(err, errMsgWritingFile) } return nil } func init() { seqCmd.Flags().UintVarP(&seqConf.Layer, "layer", "l", uint(1), "The layer that you would like to start the sequence generation from") seqCmd.Flags().UintVarP(&seqConf.Depth, "depth", "d", uint(1), "The Layer that you would like to stop the sequence generation at") seqCmd.Flags().UintSliceVarP(&seqConf.Sequences, "sequences", "s", []uint{0}, "A list of sequences that you'de like to start with") seqCmd.Flags().StringVarP(&seqConf.Format, "format", "f", outStdout, "The kind of format you want") seqCmd.Flags().StringVarP(&seqConf.FilePath, "output", "o", "", "Where you want to output written to") seqCmd.Flags().StringVarP(&seqConf.GoGenPackageName, "go-package", "g", "", "A package name for the go-generate format") }