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
|
package config
// loads from the users .cache/ dir
//
// GOAL: always work. When in doubt, delete things in ~/.cache/
// RULE: always use raw .pb files, never human readable .text or .json files
//
// deletes files when versions don't match
// deletes files when filenames can't be set
// deletes anything that doesn't work
//
// This is important to avoid unmarshalling garbage protobuf data
import (
"errors"
"fmt"
"os"
"go.wit.com/lib/env"
"google.golang.org/protobuf/proto"
)
// loads foo.proto from ~/.cache/<appname>/foo.pb
func LoadCacheDir(pb proto.Message) error {
appname, err := env.GetAppname() // already configured by your application
if err != nil {
return err
}
err = LoadCacheDirByAppname(pb, appname)
return err
}
// loads foo.proto from ~/.cache/<appname>/foo.pb
func LoadCacheDirByAppname(pb proto.Message, appname string) error {
protoname, err := GetProtobufName(pb) // defined in the foo.proto file
if err != nil {
return err
}
err = CreateCacheDirPB(pb, appname, protoname)
return err
}
// checks the UUID and Version of the .pb file
func CreateCacheDirPB(pb proto.Message, dirname string, filename string) error {
// Get ~/.cache/dirname/filename.text
fullname := MakeCacheFilename(dirname, filename)
_, err := SetFilename(pb, fullname)
if err != nil {
fmt.Println("lib/config PB file does not support Filename")
}
newver, curver, err := VersionCheckFile(pb, fullname)
_, _ = newver, curver
if err == nil {
// everything is fine. Versions match. load file
err = LoadFromFilename(pb, fullname)
return err
}
if errors.Is(err, os.ErrNotExist) {
// file is new, create the file
err = SaveToFilename(pb, fullname)
return err
}
// some other bad error
return err
}
// checks the UUID and Version of the .pb file
func ForceCreateCacheDirPB(pb proto.Message, dirname string, filename string) error {
// Get ~/.cache/dirname/filename.text
fullname := MakeCacheFilename(dirname, filename)
_, err := SetFilename(pb, fullname)
if err != nil {
fmt.Println("lib/config PB file does not support Filename")
}
newver, curver, err := VersionCheckFile(pb, fullname)
_, _ = newver, curver
if err == nil {
// everything is fine. Versions match. load file
err = LoadFromFilename(pb, fullname)
if err == nil {
return nil
}
fmt.Printf("lib/config Load() %s failed. Removing file. (%v)\n", fullname, err)
}
if !errors.Is(err, os.ErrNotExist) {
// Version Check failed.
err = os.Remove(fullname)
if err != nil {
fmt.Printf("lib/config os.Remove() %s failed (%v)\n", fullname, err)
}
}
// if there is any err, recreate the file
err = SaveToFilename(pb, fullname)
return err
}
|