-
-
Notifications
You must be signed in to change notification settings - Fork 33
/
search.go
66 lines (56 loc) · 1.39 KB
/
search.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
package main
import (
"fmt"
"io"
"sort"
"strings"
"github.com/tkuchiki/go-timezone"
)
// Zone search results
type ZoneSearchResults map[string]*timezone.TzInfo
// List of zones sorted alphabetically.
func (zsr ZoneSearchResults) SortedNames() []string {
sorted := make([]string, 0, len(zsr))
for name := range zsr {
sorted = append(sorted, name)
}
sort.Strings(sorted)
return sorted
}
// Print formatted ZoneSearchResults to the chosen Writer ; typically
// os.Stdout.
func (zsr ZoneSearchResults) Print(w io.Writer) {
sorted := zsr.SortedNames()
for i := range sorted {
name := sorted[i]
ti := zsr[name]
fmt.Fprintf(w, "%5s (%s) :: %s\n",
ti.ShortStandard(),
ti.StandardOffsetHHMM(),
name)
}
}
// Find zones matching a query. An empty query string returns all zones.
func SearchZones(q string) ZoneSearchResults {
// TODO Each call to timezone.New() allocs a fresh list of timezones:
// for now, avoid calling SearchZones too much.
t := timezone.New()
filter := q != ""
matches := map[string]*timezone.TzInfo{}
for abbr, zones := range t.Timezones() {
for _, name := range zones {
if filter &&
!strings.Contains(strings.ToLower(name), q) &&
!strings.Contains(strings.ToLower(abbr), q) {
continue
}
ti, err := t.GetTzInfo(name)
// That should not happen too often.
if err != nil {
panic(err)
}
matches[name] = ti
}
}
return matches
}