forked from jaypipes/pcidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
discover.go
83 lines (76 loc) · 1.65 KB
/
discover.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
//
// Use and distribution licensed under the Apache license version 2.
//
// See the COPYING file in the root project directory for full text.
//
package pcidb
import (
"bufio"
"compress/gzip"
"io"
"net/http"
"os"
"path/filepath"
)
const (
PCIIDS_URI = "https://pci-ids.ucw.cz/v2.2/pci.ids.gz"
)
func (db *PCIDB) load(ctx *context) error {
var foundPath string
for _, fp := range ctx.searchPaths {
if _, err := os.Stat(fp); err == nil {
foundPath = fp
break
}
}
if foundPath == "" {
// OK, so we didn't find any host-local copy of the pci-ids DB file. Let's
// try fetching it from the network and storing it
if err := cacheDBFile(ctx.cachePath); err != nil {
return err
}
foundPath = ctx.cachePath
}
f, err := os.Open(foundPath)
if err != nil {
return err
}
defer f.Close()
scanner := bufio.NewScanner(f)
return parseDBFile(db, scanner)
}
func ensureDir(fp string) error {
fpDir := filepath.Dir(fp)
if _, err := os.Stat(fpDir); os.IsNotExist(err) {
err = os.MkdirAll(fpDir, os.ModePerm)
if err != nil {
return err
}
}
return nil
}
// Pulls down the latest copy of the pci-ids file from the network and stores
// it in the local host filesystem
func cacheDBFile(cacheFilePath string) error {
ensureDir(cacheFilePath)
response, err := http.Get(PCIIDS_URI)
if err != nil {
return err
}
defer response.Body.Close()
f, err := os.Create(cacheFilePath)
if err != nil {
return err
}
defer f.Close()
// write the gunzipped contents to our local cache file
zr, err := gzip.NewReader(response.Body)
if err != nil {
return err
}
defer zr.Close()
if _, err = io.Copy(f, zr); err != nil {
return err
}
return err
}