implement publish sub-cmd of mailinglist-cli

This commit is contained in:
Brian Picciano 2021-08-10 13:07:14 -06:00
parent ca27cd6c67
commit ac5275353c
2 changed files with 47 additions and 9 deletions

View File

@ -19,12 +19,14 @@ type Cfg struct {
*flag.FlagSet *flag.FlagSet
hooks []func(ctx context.Context) error hooks []func(ctx context.Context) error
args []string
} }
// New initializes and returns a new instance of *Cfg. // New initializes and returns a new instance of *Cfg.
func New() *Cfg { func New() *Cfg {
return &Cfg{ return &Cfg{
FlagSet: flag.NewFlagSet("", flag.ExitOnError), FlagSet: flag.NewFlagSet("", flag.ExitOnError),
args: os.Args[1:],
} }
} }
@ -38,7 +40,7 @@ func (c *Cfg) OnInit(cb func(context.Context) error) {
// called. If one returns an error that error is returned and no further hooks // called. If one returns an error that error is returned and no further hooks
// are run. // are run.
func (c *Cfg) Init(ctx context.Context) error { func (c *Cfg) Init(ctx context.Context) error {
if err := c.FlagSet.Parse(os.Args[1:]); err != nil { if err := c.FlagSet.Parse(c.args); err != nil {
return err return err
} }
@ -50,3 +52,25 @@ func (c *Cfg) Init(ctx context.Context) error {
return nil return nil
} }
// SubCmd should be called _after_ Init. Init will have consumed all arguments
// up until the first non-flag argument. This non-flag argument is a
// sub-command, and is returned by this method. This method also resets Cfg's
// internal state so that new options can be added to it.
//
// If there is no sub-command following the initial set of flags then this will
// return empty string.
func (c *Cfg) SubCmd() string {
c.args = c.FlagSet.Args()
if len(c.args) == 0 {
return ""
}
subCmd := c.args[0]
c.FlagSet = flag.NewFlagSet(subCmd, flag.ExitOnError)
c.hooks = nil
c.args = c.args[1:]
return subCmd
}

View File

@ -68,14 +68,10 @@ func main() {
ml := mailinglist.New(mlParams) ml := mailinglist.New(mlParams)
_ = ml _ = ml
args := cfg.Args() subCmd := cfg.SubCmd()
if len(args) == 0 { ctx = mctx.Annotate(ctx, "subCmd", subCmd)
args = append(args, "")
}
action, args := args[0], args[1:] switch subCmd {
switch action {
case "list": case "list":
for it := mlStore.GetAll(); ; { for it := mlStore.GetAll(); ; {
email, err := it() email, err := it()
@ -94,7 +90,25 @@ func main() {
logger.Info(ctx, "next") logger.Info(ctx, "next")
} }
case "publish":
title := cfg.String("title", "", "Title of the post which was published")
url := cfg.String("url", "", "URL of the post which was published")
cfg.Init(ctx)
if *title == "" {
logger.Fatal(ctx, "-title is required")
} else if *url == "" {
logger.Fatal(ctx, "-url is required")
}
err := ml.Publish(*title, *url)
if err != nil {
loggerFatalErr(ctx, logger, "publishing", err)
}
default: default:
logger.Fatal(ctx, "invalid action") logger.Fatal(ctx, "invalid sub-command, must be list|publish")
} }
} }