-
Notifications
You must be signed in to change notification settings - Fork 90
/
region.go
120 lines (114 loc) · 2.62 KB
/
region.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package cfaws
import (
"fmt"
"strconv"
"strings"
)
const DefaultRegion = "us-east-1"
// ExpandRegion takes a string and attemps to expand it into a fully formed region e.g ue1 -> us-east-1
//
// If region is an empty string, the DefaultRegion is returned
//
// ExpandRegion does not attempt to fully validate regions and may produce regions which do not exist, for example as2 -> ap-south-2 which is not a valid region
func ExpandRegion(region string) (string, error) {
// Region could come in one of three formats:
// 1. No region specified
if region == "" {
return DefaultRegion, nil
}
// 2. A fully-qualified region. Assume that if there's one dash, it's valid.
if strings.Contains(region, "-") {
return region, nil
}
var major, minor, num string
idx := 1 // Number of characters consumed from region
// 3. Otherwise, we have a shortened region, like ue1
if len(region) < 2 {
return "", fmt.Errorf("region too short, needs at least two characters (eg ue)")
}
// Region might be one or two letters
switch region[0] {
case 'u':
major = "us"
if region[1] == 'g' {
major = "us-gov"
idx += 1
} else if region[1] == 's' {
// This will break if us-southeast-1 is ever created
idx += 1
}
case 'e':
major = "eu"
if region[1] == 'u' {
idx += 1
}
case 'a':
major = "ap"
if region[1] == 'f' {
major = "af"
idx += 1
} else if region[1] == 'p' {
idx += 1
}
case 'c':
major = "ca"
if region[1] == 'n' {
major = "cn"
idx += 1
} else if region[1] == 'a' {
idx += 1
}
case 'm':
major = "me"
// This will break if me-east-1 is ever created
if region[1] == 'e' {
idx += 1
}
case 's':
major = "sa"
if region[1] == 'a' {
idx += 1
}
default:
return "", fmt.Errorf("unknown region major (hint: try using the first letter of the region)")
}
region = region[idx:]
idx = 1
// Location might be one or two letters (n, nw)
switch region[0] {
case 'n', 's':
if region[0] == 'n' {
minor = "north"
} else {
minor = "south"
}
if len(region) > 1 {
if region[1] == 'w' {
minor += "west"
idx += 1
} else if region[1] == 'e' {
minor += "east"
idx += 1
}
}
case 'e':
minor = "east"
case 'w':
minor = "west"
case 'c':
minor = "central"
default:
return "", fmt.Errorf("unknown region minor in %s (found major: %s)", region, major)
}
region = region[idx:]
if len(region) > 0 {
_, err := strconv.Atoi(region)
if err != nil {
return "", fmt.Errorf("unknown region number in %s (found major: %s, minor: %s)", region, major, minor)
}
num = region
} else {
num = "1"
}
return fmt.Sprintf("%s-%s-%s", major, minor, num), nil
}