Mercurial > hg > Members > anatofuz > aragane
view cmd/cbc2c.go @ 0:7369b027b56e
inti project
author | anatofuz <anatofuz@cr.ie.u-ryukyu.ac.jp> |
---|---|
date | Tue, 02 Jun 2020 16:41:46 +0900 |
parents | |
children | 46d33184b0d0 |
line wrap: on
line source
package cmd import ( "errors" "fmt" "os" "os/exec" "strings" "github.com/spf13/cobra" ) func newCbc2cCmd() *cobra.Command { cmd := &cobra.Command{ Use: "cbc2c [file]", Short: "dump path the converted C file of CbC.", Args: cobra.ExactArgs(1), RunE: cbc2c, } cmd.AddCommand(newCbc2cEditorCmd()) return cmd } func cbc2c(cmd *cobra.Command, args []string) error { cfile, err := cbcfile2cfilepath(args[0]) if err != nil { return fmt.Errorf("failed cbc2c command %v", err) } fmt.Fprintln(cmd.OutOrStdout(), cfile) return nil } func cbcfile2cfilepath(arg string) (string, error) { cbcfilePath := arg if !fileExists(cbcfilePath) { return "", errors.New("failed nout found files") } var idx int if idx = strings.LastIndex(cbcfilePath, ".cbc"); idx == -1 { return "", errors.New("failed nout found cbc files") } var b strings.Builder b.Grow(32) b.WriteString("c/") b.WriteString(cbcfilePath[0:idx]) b.WriteString(".c") return b.String(), nil } func newCbc2cEditorCmd() *cobra.Command { cmd := &cobra.Command{ Use: "editor [file]", Short: "open editor the converted C file of CbC", Args: cobra.ExactArgs(1), RunE: cbc2cEditor, } return cmd } func cbc2cEditor(cmd *cobra.Command, args []string) error { cfile, err := cbcfile2cfilepath(args[0]) if err != nil { return fmt.Errorf("failed cbc2c command %v", err) } if editor, ok := os.LookupEnv("EDITOR"); ok { editoCMD := exec.Command(editor, cfile) editoCMD.Stdin = cmd.InOrStdin() editoCMD.Stdout = cmd.OutOrStdout() editoCMD.Stderr = cmd.ErrOrStderr() return editoCMD.Run() } return errors.New("failed lookup $EDITOR") } func fileExists(filename string) bool { info, err := os.Stat(filename) if os.IsNotExist(err) { return false } return !info.IsDir() }