1package flaghelpers
2
3import (
4	"errors"
5	"fmt"
6	"strings"
7
8	"github.com/jessevdk/go-flags"
9
10	"github.com/concourse/concourse/fly/rc"
11)
12
13type JobFlag struct {
14	PipelineName string
15	JobName      string
16}
17
18func (job *JobFlag) UnmarshalFlag(value string) error {
19	vs := strings.SplitN(value, "/", -1)
20
21	if len(vs) != 2 {
22		return errors.New("argument format should be <pipeline>/<job>")
23	}
24
25	job.PipelineName = vs[0]
26	job.JobName = vs[1]
27
28	return nil
29}
30
31func (flag *JobFlag) Complete(match string) []flags.Completion {
32	fly := parseFlags()
33
34	target, err := rc.LoadTarget(fly.Target, false)
35	if err != nil {
36		return []flags.Completion{}
37	}
38
39	err = target.Validate()
40	if err != nil {
41		return []flags.Completion{}
42	}
43
44	team := target.Team()
45	comps := []flags.Completion{}
46	vs := strings.SplitN(match, "/", 2)
47
48	if len(vs) == 1 {
49		pipelines, err := team.ListPipelines()
50		if err != nil {
51			return comps
52		}
53
54		for _, pipeline := range pipelines {
55			if strings.HasPrefix(pipeline.Name, vs[0]) {
56				comps = append(comps, flags.Completion{Item: pipeline.Name + "/"})
57			}
58		}
59	} else if len(vs) == 2 {
60		jobs, err := team.ListJobs(vs[0])
61		if err != nil {
62			return comps
63		}
64
65		for _, job := range jobs {
66			if strings.HasPrefix(job.Name, vs[1]) {
67				comps = append(comps, flags.Completion{Item: fmt.Sprintf("%s/%s", vs[0], job.Name)})
68			}
69		}
70	}
71
72	return comps
73}
74