Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Go初心者がGoでコマンドラインツールの作成に挑戦した話

2,537 views

Published on

Go初心者がGoでコマンドラインツールの作成に挑戦した話
Yuki Haneda / BizReach.inc / 2017.11.2

Published in: Engineering
  • Be the first to comment

Go初心者がGoでコマンドラインツールの作成に挑戦した話

  1. 1. 

  2. 2. $ brant info | pbcopy
  3. 3. ## ( ) $ mkdir test && cd test $ go get github.com/spf13/cobra/cobra ## $ cat 'author: Yuki Haneda' > ~/.cobra.yaml $ cat 'license: MIT' >> ~/.cobra.yaml # viper( ) $ cobra init --viper=false
  4. 4. $ tree . !"" LICENSE !"" cmd #   %"" root.go %"" main.go
  5. 5. package main import "bitbucket.org/ap8322/misc/cobra/cmd" func main() { cmd.Execute() }
  6. 6. // hogeCmd represents the hoge command var hogeCmd = &cobra.Command{ Use: "hoge", Short: " ", Long: ` `, Run: func(cmd *cobra.Command, args []string) { // }, }
  7. 7. func init() { // // config }
  8. 8. # $ cobra add hoge # .go $ ls cmd hoge.go root.go
  9. 9. // hogeCmd represents the hoge command var hogeCmd = &cobra.Command{ Use: "hoge", Short: " ", Long: ` `, Run: func(cmd *cobra.Command, args []string) { // }, }
  10. 10.
  11. 11. var Conf Config type Config struct { Core CoreConfig Jira JiraConfig } type CoreConfig struct { Editor string `toml:"editor"` TicketCache string `toml:"ticketcache"` SelectCmd string `toml:"selectcmd"` } type JiraConfig struct { Host string `toml:"host"` UserName string `toml:"username"` Password string `toml:"password"` Jql string `toml:"jql"` }
  12. 12. file := "/tmp" f, err := os.Create(file) if err != nil { return err } toml.NewEncoder(f).Encode(conf)
  13. 13. var tickets Tickets type Tickets struct { Tickets []Ticket `toml:"Tickets"` } type Ticket struct { ID string `toml:"id"` Title string `toml:"title"` Description string `toml:"description"` }
  14. 14. file := "/tmp" if _, err := toml.DecodeFile(cache, tickets); err != nil { return err }
  15. 15. func (conf *Config) Load(file string) error {...}
  16. 16. err := exec.Command("ls", "-la").Run() // command := "ls -la" cmd = exec.Command("sh", "-c", command).Run()
  17. 17. // func run(command string, r io.Reader, w io.Writer) error { var cmd *exec.Cmd if runtime.GOOS == "windows" { cmd = exec.Command("cmd", "/c", command) } else { cmd = exec.Command("sh", "-c", command) } cmd.Stderr = os.Stderr cmd.Stdout = w cmd.Stdin = r return cmd.Run() }
  18. 18. $ cobra add conf
  19. 19. func editFile(command, file string) error { command += " " + file // return run(command, os.Stdin, os.Stdout) }
  20. 20. func conf(cmd *cobra.Command, args []string) error { // config editor := config.Conf.Core.Editor return editFile(editor, configFile) }
  21. 21. // list fzf list := `first line second line third line` var buf bytes.Buffer // if err := run("fzf", strings.NewReader(list), &buf); err != nil { return nil }

×