summaryrefslogtreecommitdiffstats
path: root/client/go/cmd/target.go
blob: 8b0cc4ee51a8596469978cc98fca7bd9effc27d5 (plain) (blame)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// Models a target for Vespa commands
// author: bratseth

package cmd

import (
	"log"
	"strings"

	"github.com/spf13/cobra"
)

const (
	applicationFlag = "application"
	targetFlag      = "target"
	cloudApi        = "https://api.vespa-external.aws.oath.cloud:4443"
)

var (
	targetArg      string
	applicationArg string
)

type target struct {
	deploy   string
	query    string
	document string
}

type context int32

const (
	deployContext   context = 0
	queryContext    context = 1
	documentContext context = 2
)

func addTargetFlag(command *cobra.Command) {
	command.PersistentFlags().StringVarP(&targetArg, targetFlag, "t", "local", "The name or URL of the recipient of this command")
	bindFlagToConfig(targetFlag, command)
}

func addApplicationFlag(command *cobra.Command) {
	command.PersistentFlags().StringVarP(&applicationArg, applicationFlag, "a", "", "The application name to use for deployment")
	bindFlagToConfig(applicationFlag, command)
}

func deployTarget() string {
	return getTarget(deployContext).deploy
}

func queryTarget() string {
	return getTarget(queryContext).query
}

func documentTarget() string {
	return getTarget(documentContext).document
}

func getApplication() string {
	app, err := getOption(applicationFlag)
	if err != nil {
		log.Fatalf("a valid application must be specified")
	}
	return app
}

func getTargetType() string {
	target, err := getOption(targetFlag)
	if err != nil {
		log.Fatalf("a valid target must be specified")
	}
	return target
}

func getTarget(targetContext context) *target {
	targetValue := getTargetType()
	if strings.HasPrefix(targetValue, "http") {
		// TODO: Add default ports if missing
		switch targetContext {
		case deployContext:
			return &target{
				deploy: targetValue,
			}
		case queryContext:
			return &target{
				query: targetValue,
			}
		case documentContext:
			return &target{
				document: targetValue,
			}
		}
	}

	// Otherwise, target is a name

	if targetValue == "" || targetValue == "local" {
		return &target{
			deploy:   "http://127.0.0.1:19071",
			query:    "http://127.0.0.1:8080",
			document: "http://127.0.0.1:8080",
		}
	}

	if targetValue == "cloud" {
		return &target{deploy: cloudApi}
	}

	log.Printf("Unknown target '%s': Use %s, %s or an URL", color.Red(targetValue), color.Cyan("local"), color.Cyan("cloud"))
	return nil
}