-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlabels.go
91 lines (74 loc) · 2 KB
/
labels.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
// labels.go - Helpers for getting/creating a label.
package main
import (
"fmt"
"google.golang.org/api/gmail/v1"
)
// We cache the labels which are available to avoid the need to
// make too many HTTP-calls.
var labels2ID map[string]string
var id2Labels map[string]string
// loadLabels fetches all the labels available, and populates our
// caches. We cache on name=>id, and id=>name to allow lookups in
// both directions.
func loadLabels() error {
// Create our maps
labels2ID = make(map[string]string)
id2Labels = make(map[string]string)
// Get the existing labels, if any.
r, err := srv.Users.Labels.List("me").Do()
if err != nil {
return err
}
// Store each one in our local map/cache.
for _, label := range r.Labels {
labels2ID[label.Name] = label.Id
id2Labels[label.Id] = label.Name
}
return nil
}
// getLabelID returns the ID of a label, creating it if it is absent.
func getLabelID(srv *gmail.Service, name string) (string, error) {
//
// Get the list of labels if we've not done so.
//
if len(labels2ID) == 0 {
err := loadLabels()
if err != nil {
return "", err
}
}
// If the list of labels contains the one we want then return the ID.
found := labels2ID[name]
if len(found) > 0 {
return found, nil
}
// Otherwise we need to create the label.
req := &gmail.Label{Name: name}
created, err := srv.Users.Labels.Create("me", req).Do()
if err != nil {
return "", err
}
// Store the ID for next time, and return it.
labels2ID[name] = created.Id
id2Labels[created.Id] = name
return created.Id, nil
}
// getLabelByID returns the human readable label, by ID
func getLabelByID(srv *gmail.Service, id string) (string, error) {
//
// Get the list of labels if we've not done so.
//
if len(labels2ID) == 0 {
err := loadLabels()
if err != nil {
return "", err
}
}
// If the list of labels contains the one we want then return the ID.
found := id2Labels[id]
if len(found) > 0 {
return found, nil
}
return "", fmt.Errorf("failed to lookup label ID %s", id)
}