summaryrefslogtreecommitdiff
path: root/internal/cli/start.go
blob: 9e66e0022952061d30e0cf9cb740ef2234664153 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package cli

import (
	"encoding/json"
	"fmt"
	"io"
	"net/url"

	"github.com/spf13/cobra"
)

func newStartCmd() *cobra.Command {
	var serverURL string

	cmd := &cobra.Command{
		Use:   "start <task-id>",
		Short: "Queue a task for execution via the running server",
		Args:  cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			return startTask(serverURL, args[0])
		},
	}

	cmd.Flags().StringVar(&serverURL, "server", "http://localhost:8484", "claudomator server URL")
	return cmd
}

func startTask(serverURL, id string) error {
	url := fmt.Sprintf("%s/api/tasks/%s/run", serverURL, url.PathEscape(id))
	resp, err := httpClient.Post(url, "application/json", nil) //nolint:noctx
	if err != nil {
		return fmt.Errorf("POST %s: %w", url, err)
	}
	defer resp.Body.Close()

	raw, _ := io.ReadAll(resp.Body)
	var body map[string]string
	if err := json.Unmarshal(raw, &body); err != nil {
		return fmt.Errorf("server returned invalid JSON (status %d): %s", resp.StatusCode, string(raw))
	}

	if resp.StatusCode >= 300 {
		return fmt.Errorf("server returned %d: %s", resp.StatusCode, body["error"])
	}

	fmt.Printf("Queued task %s\n", id)
	return nil
}