12 langSource = "datagen/region/region_codes.csv"
13 outputFileName = "region_code_info.go"
21 func decodeRegion() *[]reg {
24 csvfile, err := os.Open(langSource)
32 reader := csv.NewReader(csvfile)
33 // there are no empty fields
34 reader.FieldsPerRecord = 2
36 rawCSVdata, err := reader.ReadAll()
42 // move raw CSV data to struct
46 for _, v := range rawCSVdata {
49 rows = append(rows, row)
54 func generateSwitch(d []reg) (string, error) {
55 out := `// generated by "go generate"; DO NOT EDIT
64 // RegionCodeInfo returns the English regional name that
65 // corresponds to the ISO 3166-1 alpha-2 region codes.
66 // Region codes should always be uppercase, and this is enforced.
67 // E.g. "US" is valid, but "us" is not.
68 func RegionCodeInfo(s string) (region string, err error) {
70 // codes have to be two characters long
73 errors.New("ISO 3166-1 alpha-2 region codes must be 2 characters long")
78 out += fmt.Sprintf("\nswitch s[0] {\n\ncase %q:\nswitch s[1]{\n", c1)
80 // check that the code is exactly 2 characters long
81 if !isCodeValid(r.code) {
82 return "", fmt.Errorf("The code %q is not 2 characters long", r.code)
84 // new first letter of code
88 out += fmt.Sprintf("}\n\ncase %q:\nswitch s[1]{\n", c1)
90 out += fmt.Sprintf("case %q:\nreturn %q, nil\n", r.code[1], r.name)
96 fmt.Errorf("%q is not a valid ISO 3166-1 alpha-2 region code", s)
102 func isCodeValid(s string) bool {
106 if s[0] < 'A' || s[0] > 'Z' || s[1] < 'A' || s[1] > 'Z' {
112 func writeFile(s, fileName string) error {
115 err := ioutil.WriteFile(fileName, b, 0644)
117 return errors.New("Couldn't write the file")
123 rows := decodeRegion()
124 res, _ := generateSwitch(*rows)
125 err := writeFile(res, outputFileName)
129 fmt.Println("region_code_info.go generated")