package main import ( "encoding/json" "fmt" "os" "path/filepath" "strings" "time" "gitea.lab.audasmedia.com.au/sam/artemis_control/internal/adb" "gitea.lab.audasmedia.com.au/sam/artemis_control/internal/recipe" ) // recipesDir is where hand-editable recipes live. func recipesDir() string { if d := os.Getenv("ARTEMIS_RECIPES"); d != "" { return d } return "recipes" } // runLogPath is the JSON-lines action log (FR-10). func runLogPath() string { if p := os.Getenv("ARTEMIS_LOG"); p != "" { return p } return filepath.Join("logs", "runs.jsonl") } func cmdRecipes(args []string) error { recipes, err := recipe.List(recipesDir()) if err != nil { return err } for _, r := range recipes { fmt.Printf("%-16s %s\n", r.Task, r.Description) } return nil } // cmdRun runs a named recipe: artemis run spotify_play query="Rolling Stones". func cmdRun(r *adb.Runner, args []string) error { if len(args) < 1 { return fmt.Errorf("usage: artemis run [name=value ...]") } task := args[0] params := map[string]string{} for _, kv := range args[1:] { name, value, ok := strings.Cut(kv, "=") if !ok { return fmt.Errorf("parameter %q must be name=value", kv) } params[strings.TrimSpace(name)] = value } rec, err := recipe.Find(recipesDir(), task) if err != nil { return err } if missing := rec.MissingParams(params); len(missing) > 0 { return fmt.Errorf("recipe %s needs %s", task, strings.Join(missing, ", ")) } var res *recipe.RunResult err = ensurePhone(r, func() error { res = recipe.Run(r, rec, recipe.Options{Params: params, Log: os.Stdout}) if logErr := appendRunLog(runLogPath(), res); logErr != nil { fmt.Fprintf(os.Stderr, "artemis: could not write the run log: %v\n", logErr) } if !res.OK { return fmt.Errorf("%s", res.Error) } return nil }) fmt.Printf("\n%s\n", summaryLine(task, res)) return err } func summaryLine(task string, res *recipe.RunResult) string { if res == nil { return "task " + task + " did not run" } steps := len(res.Steps) if res.OK { return fmt.Sprintf("ok: %s ran %d steps in %s", task, steps, res.Duration.Round(time.Millisecond)) } return fmt.Sprintf("failed: %s stopped at step %d in %s: %s", task, steps, res.Duration.Round(time.Millisecond), res.Error) } // appendRunLog adds one JSON line per run: task, params, steps, result and // duration (FR-10). func appendRunLog(path string, res *recipe.RunResult) error { if res == nil { return nil } if dir := filepath.Dir(path); dir != "" && dir != "." { if err := os.MkdirAll(dir, 0o755); err != nil { return err } } f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) if err != nil { return err } defer f.Close() entry := struct { Time string `json:"time"` *recipe.RunResult }{Time: time.Now().Format(time.RFC3339), RunResult: res} raw, err := json.Marshal(entry) if err != nil { return err } _, err = f.Write(append(raw, '\n')) return err }