From bade3895da20899165e5cfe6a0ce4f585edd5466 Mon Sep 17 00:00:00 2001 From: Yasuhiro Matsumoto Date: Thu, 20 Apr 2017 14:14:25 +0900 Subject: [PATCH] add --template flag for stream command close #30 --- cmd/mstdn/cmd_stream.go | 30 +++++++++++++++++++++++++++++- cmd/mstdn/main.go | 12 ++++++++---- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/cmd/mstdn/cmd_stream.go b/cmd/mstdn/cmd_stream.go index b37fd86..c922667 100644 --- a/cmd/mstdn/cmd_stream.go +++ b/cmd/mstdn/cmd_stream.go @@ -7,6 +7,7 @@ import ( "os" "os/signal" "strings" + "text/template" "github.com/mattn/go-mastodon" "github.com/urfave/cli" @@ -20,9 +21,35 @@ type SimpleJSON struct { Content string `json:"content"` } +func checkFlag(f ...bool) bool { + n := 0 + for _, on := range f { + if on { + n++ + } + } + return n > 1 +} + func cmdStream(c *cli.Context) error { asJSON := c.Bool("json") asSimpleJSON := c.Bool("simplejson") + asFormat := c.String("template") + + if checkFlag(asJSON, asSimpleJSON, asFormat != "") { + return errors.New("cannot speicify two or three options in --json/--simplejson/--template") + } + tx, err := template.New("mstdn").Funcs(template.FuncMap{ + "nl": func(s string) string { + return s + "\n" + }, + "text": func(s string) string { + return textContent(s) + }, + }).Parse(asFormat) + if err != nil { + return err + } client := c.App.Metadata["client"].(*mastodon.Client) config := c.App.Metadata["config"].(*mastodon.Config) @@ -33,7 +60,6 @@ func cmdStream(c *cli.Context) error { signal.Notify(sc, os.Interrupt) var q chan mastodon.Event - var err error t := c.String("type") if t == "public" { @@ -72,6 +98,8 @@ func cmdStream(c *cli.Context) error { Content: textContent(t.Status.Content), }) } + } else if asFormat != "" { + tx.ExecuteTemplate(c.App.Writer, "mstdn", e) } else { switch t := e.(type) { case *mastodon.UpdateEvent: diff --git a/cmd/mstdn/main.go b/cmd/mstdn/main.go index 9acf5ac..ca268c6 100644 --- a/cmd/mstdn/main.go +++ b/cmd/mstdn/main.go @@ -202,18 +202,22 @@ func makeApp() *cli.App { Name: "stream", Usage: "stream statuses", Flags: []cli.Flag{ + cli.StringFlag{ + Name: "type", + Usage: "stream type (public,public/local,user:NAME,hashtag:TAG)", + }, cli.BoolFlag{ Name: "json", Usage: "output JSON", }, - cli.StringFlag{ - Name: "type", - Usage: "straem type (public,public/local,user:NAME,hashtag:TAG)", - }, cli.BoolFlag{ Name: "simplejson", Usage: "output simple JSON", }, + cli.StringFlag{ + Name: "template", + Usage: "output with tamplate format", + }, }, Action: cmdStream, },