summaryrefslogtreecommitdiff
path: root/internal/askcli/command_projects.go
blob: 26e407fb92d6429e1eae47bfbeb08788cda651c6 (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package askcli

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"sort"
)

type taskCommandRunner func(context.Context, string, []string, io.Reader, io.Writer, io.Writer) error

func (d *Dispatcher) handleProjects(ctx context.Context, args []string, stdout, stderr io.Writer) (int, error) {
	_ = args

	taskPath, err := d.projectTaskBinary()()
	if err != nil {
		return 1, fmt.Errorf("ask projects: task binary lookup failed: %w", err)
	}

	scopeFilter := taskScopeFilter(taskScopeFromContext(ctx))
	cmdArgs := append([]string{"rc.verbose=nothing", "rc.confirmation=off", scopeFilter, "status:pending", "export"}, args[1:]...)
	var outBuf bytes.Buffer
	err = d.projectTaskCommand()(ctx, taskPath, cmdArgs, nil, &outBuf, stderr)
	if err != nil {
		return exitCodeFor(err), fmt.Errorf("ask projects: task export failed: %w", err)
	}

	tasks, err := ParseTaskExport(&outBuf)
	if err != nil {
		fmt.Fprintf(stderr, "error: failed to parse task data: %v\n", err)
		return 1, nil
	}

	projectSet := make(map[string]struct{})
	for _, task := range tasks {
		if task.Status == "pending" && task.Start == "" && task.Project != "" {
			projectSet[task.Project] = struct{}{}
		}
	}

	projects := make([]string, 0, len(projectSet))
	for p := range projectSet {
		projects = append(projects, p)
	}
	sort.Strings(projects)

	if d.jsonOutput {
		data, err := json.Marshal(projects)
		if err != nil {
			fmt.Fprintf(stderr, "error: failed to marshal JSON: %v\n", err)
			return 1, nil
		}
		_, _ = stdout.Write(data)
		_, _ = io.WriteString(stdout, "\n")
		return 0, nil
	}

	for _, p := range projects {
		_, _ = io.WriteString(stdout, p+"\n")
	}
	return 0, nil
}

func (d *Dispatcher) projectTaskBinary() func() (string, error) {
	if d != nil && d.findTaskBinary != nil {
		return d.findTaskBinary
	}
	return findTaskBinary
}

func (d *Dispatcher) projectTaskCommand() taskCommandRunner {
	if d != nil && d.runTaskCommand != nil {
		return d.runTaskCommand
	}
	return runTaskCommand
}