|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "io" |
| 6 | + "os" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "github.com/spf13/cobra" |
| 10 | + "github.com/yosev/coda" |
| 11 | +) |
| 12 | + |
| 13 | +var jsonCmd = &cobra.Command{ |
| 14 | + Use: "j <coda script as json>", |
| 15 | + Args: cobra.ExactArgs(1), |
| 16 | + DisableFlagsInUseLine: true, |
| 17 | + Short: "coda script as json", |
| 18 | + Run: jsonS, |
| 19 | +} |
| 20 | + |
| 21 | +var jsonFileCmd = &cobra.Command{ |
| 22 | + Use: "jj <coda script as json file>", |
| 23 | + Args: cobra.ExactArgs(1), |
| 24 | + DisableFlagsInUseLine: true, |
| 25 | + Example: `coda jj script.coda.json`, |
| 26 | + Short: "coda script as json file", |
| 27 | + Run: jsonF, |
| 28 | +} |
| 29 | + |
| 30 | +func init() { |
| 31 | + rootCmd.AddCommand(jsonCmd) |
| 32 | + rootCmd.AddCommand(jsonFileCmd) |
| 33 | +} |
| 34 | + |
| 35 | +func jsonS(cmd *cobra.Command, args []string) { |
| 36 | + input := args[0] |
| 37 | + if args[0] == "-" { |
| 38 | + b, err := io.ReadAll(os.Stdin) |
| 39 | + if err != nil { |
| 40 | + fmt.Printf("failed to read from stdin: %v\n", err) |
| 41 | + os.Exit(1) |
| 42 | + } |
| 43 | + input = string(b) |
| 44 | + } |
| 45 | + executeJ(input) |
| 46 | +} |
| 47 | + |
| 48 | +func jsonF(cmd *cobra.Command, args []string) { |
| 49 | + f, err := os.ReadFile(args[0]) |
| 50 | + if err != nil { |
| 51 | + fmt.Printf("failed to read json file: %v\n", err) |
| 52 | + os.Exit(1) |
| 53 | + } |
| 54 | + |
| 55 | + script := string(f) |
| 56 | + |
| 57 | + // remove shebang if present |
| 58 | + if strings.HasPrefix(script, "#!") { |
| 59 | + script = strings.SplitN(script, "\n", 2)[1] |
| 60 | + } |
| 61 | + |
| 62 | + executeJ(script) |
| 63 | +} |
| 64 | + |
| 65 | +func executeJ(j string) { |
| 66 | + c, err := coda.New().FromJson(j) |
| 67 | + if err != nil { |
| 68 | + fmt.Fprintf(os.Stderr, "failed to initiate coda from json file: %v\n", err) |
| 69 | + os.Exit(1) |
| 70 | + } |
| 71 | + |
| 72 | + err = c.Run() |
| 73 | + if err != nil { |
| 74 | + fmt.Fprintf(os.Stderr, "error: %v\n", err) |
| 75 | + os.Exit(1) |
| 76 | + } |
| 77 | + |
| 78 | + b, err := c.Marshal() |
| 79 | + if err != nil { |
| 80 | + fmt.Fprintf(os.Stderr, "failed to marshal coda script: %v\n", err) |
| 81 | + os.Exit(1) |
| 82 | + } |
| 83 | + |
| 84 | + fmt.Println(string(b)) |
| 85 | +} |
0 commit comments