-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
109 lines (82 loc) · 1.84 KB
/
context.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
package main
import (
"io/ioutil"
"log"
"encoding/json"
"github.com/fsnotify/fsnotify"
)
type Context struct {
context string
Channel chan string
}
func NewContext() *Context {
context := new(Context)
context.Channel = make(chan string)
return context
}
func (self *Context) readContext(fn string) error {
var conf struct {
CurrentContext string
}
content, err := ioutil.ReadFile(fn)
if err != nil{
return err
}
err = json.Unmarshal(content, &conf)
if err != nil {
return err
}
switch conf.CurrentContext {
case "":
self.context = "default"
default:
self.context = conf.CurrentContext
}
return nil
}
func (self *Context) watch(fn string) {
log.Println(fn)
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
return
}
err = watcher.Add(fn)
if err != nil {
log.Fatal(err)
return
}
err = self.readContext(fn)
if err != nil {
log.Fatal(err)
return
}
self.Channel <- self.context
defer watcher.Close()
for {
select {
case event, ok := <-watcher.Events:
if !ok {
log.Fatal("watcher.Events ok? ", ok)
}
if event.Has(fsnotify.Remove) || event.Has(fsnotify.Rename) {
watcher.Remove(fn)
watcher.Add(fn)
}
// Immediately read the context even after a Remove or Rename
// event has happened because fsnotify is (presumably) too slow
// to react to the quick remove-create-write of the docker cli
// when the context is being changed.
err = self.readContext(fn)
if err != nil {
log.Println("self.readContext(fn) err = ", err)
}
self.Channel <- self.context
case err, ok := <-watcher.Errors:
if !ok {
log.Fatal("watcher.Events ok? ", ok)
}
log.Fatal("watcher.Events err = ", err)
}
}
}