/
data_source_application.go
101 lines (83 loc) · 2.37 KB
/
data_source_application.go
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
package vultr
import (
"errors"
"fmt"
"regexp"
"github.com/JamesClonk/vultr/lib"
"github.com/hashicorp/terraform/helper/schema"
)
func dataSourceApplication() *schema.Resource {
return &schema.Resource{
Read: dataSourceApplicationRead,
Schema: map[string]*schema.Schema{
"filter": dataSourceFiltersSchema(),
"name_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validateRegex,
},
"deploy_name": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"short_name": {
Type: schema.TypeString,
Computed: true,
},
"surcharge": {
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func dataSourceApplicationRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Client)
filters, filtersOk := d.GetOk("filter")
nameRegex, nameRegexOk := d.GetOk("name_regex")
if !filtersOk && !nameRegexOk {
return fmt.Errorf("One of %q and %q must be provided", "filter", "name_regex")
}
applications, err := client.GetApplications()
if err != nil {
return fmt.Errorf("Error getting applications: %v", err)
}
if filtersOk {
filter := filterFromSet(filters.(*schema.Set))
var filteredApplications []lib.Application
for _, application := range applications {
m := structToMap(application)
if filter.F(m) {
filteredApplications = append(filteredApplications, application)
}
}
applications = filteredApplications
}
if nameRegexOk {
var filteredApplications []lib.Application
r := regexp.MustCompile(nameRegex.(string))
for _, application := range applications {
if r.MatchString(application.Name) {
filteredApplications = append(filteredApplications, application)
}
}
applications = filteredApplications
}
if len(applications) < 1 {
return errors.New("The query for applications returned no results. Please modify the search criteria and try again")
}
if len(applications) > 1 {
return fmt.Errorf("The query for applications returned %d results. Please make the search criteria more specific and try again", len(applications))
}
d.SetId(applications[0].ID)
d.Set("deploy_name", applications[0].DeployName)
d.Set("name", applications[0].Name)
d.Set("short_name", applications[0].ShortName)
d.Set("surcharge", applications[0].Surcharge)
return nil
}