-
Notifications
You must be signed in to change notification settings - Fork 24
/
apps.go
88 lines (75 loc) · 1.79 KB
/
apps.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
package autocomplete
import (
"encoding/gob"
"os"
"path/filepath"
"time"
"github.com/Scalingo/cli/config"
"github.com/Scalingo/go-scalingo/debug"
"github.com/Scalingo/go-scalingo"
"gopkg.in/errgo.v1"
)
type appsCache struct {
CreatedAt time.Time
Apps []*scalingo.App
}
var (
appsCacheFile = filepath.Join(config.C.ConfigDir, ".apps-cache")
appsCacheDuration = 30.0
errExpiredCache = errgo.New("apps has expired")
)
func appsList() ([]*scalingo.App, error) {
var (
err error
apps []*scalingo.App
)
apps, err = appsAutoCompleteCache()
if err != nil {
debug.Println("fail to get applications autocomplete cache make GET request", err)
c, err := config.ScalingoClient()
if err != nil {
return nil, errgo.Notef(err, "fail to get Scalingo client")
}
apps, err = c.AppsList()
if err != nil || len(apps) == 0 {
return nil, errgo.Mask(err)
}
err = writeAppsAutoCompleteCache(apps)
if err != nil {
debug.Println("fail to write applications autocomplete cache", err)
}
}
return apps, nil
}
func appsAutoCompleteCache() ([]*scalingo.App, error) {
fd, err := os.Open(appsCacheFile)
if err != nil {
return nil, errgo.Mask(err)
}
defer fd.Close()
var cache appsCache
err = gob.NewDecoder(fd).Decode(&cache)
if err != nil {
return nil, errgo.Mask(err)
}
if time.Now().Sub(cache.CreatedAt).Seconds() > appsCacheDuration {
return nil, errExpiredCache
}
return cache.Apps, nil
}
func writeAppsAutoCompleteCache(apps []*scalingo.App) error {
fd, err := os.OpenFile(appsCacheFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
if err != nil {
return errgo.Mask(err)
}
defer fd.Close()
cache := appsCache{
Apps: apps,
CreatedAt: time.Now(),
}
err = gob.NewEncoder(fd).Encode(&cache)
if err != nil {
return errgo.Mask(err)
}
return nil
}