/
completer_deviceId_inventory.go
60 lines (55 loc) · 1.54 KB
/
completer_deviceId_inventory.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
package sorashell
import (
"encoding/json"
"fmt"
"github.com/c-bata/go-prompt"
"strings"
"time"
)
// naive cache which holds inventory devices data for inventoryDeviceIDFilterSuggestions
var inventoryDevicesCache []prompt.Suggest
func (s *SoracomCompleter) inventoryDeviceIDFilterSuggestions(word string) []prompt.Suggest {
c := make(chan []prompt.Suggest, 1024)
if len(inventoryDevicesCache) == 0 {
go getInventoryDevices(c, s.worker)
select {
case res := <-c:
inventoryDevicesCache = res
case <-time.After(10 * time.Second):
return []prompt.Suggest{{
Text: "Downloading device information in background",
Description: "Hit space to see latest",
}}
}
}
return filterFunc(inventoryDevicesCache, word, filterTextOrDescriptionFuzzy)
}
var getInventoryDevices = func(c chan<- []prompt.Suggest, worker *SoracomWorker) {
var r []prompt.Suggest
result := worker.Execute("devices list --fetch-all")
if err := json.NewDecoder(strings.NewReader(result)).Decode(&inventoryDevices); err != nil {
c <- []prompt.Suggest{{
Text: "Error while running 'devices list --fetch-all'",
Description: err.Error(),
}}
}
for _, device := range inventoryDevices {
online := "offline"
if device.Online {
online = "online"
}
r = append(r, prompt.Suggest{
Text: device.DeviceID,
Description: fmt.Sprintf("%-14s | %-8s | %-8s | %-15s | %15s | %15s | %s",
trunc(device.Endpoint, 14),
device.Status,
online,
device.Imei,
device.Imsi,
device.IPAddress,
device.Manufacturer,
),
})
}
c <- r
}