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
|
package chatpb
// functions to import and export the protobuf
// data to and from config files
import (
"errors"
"os"
"path/filepath"
"go.wit.com/lib/protobuf/bugpb"
"go.wit.com/log"
)
// write to ~/.config/regex/ unless ENV{REGEX_HOME} is set
func (all *Books) ConfigSave() error {
if os.Getenv("REGEX_HOME") == "" {
homeDir, _ := os.UserHomeDir()
fullpath := filepath.Join(homeDir, ".config/regex")
os.Setenv("REGEX_HOME", fullpath)
}
if all == nil {
log.Warn("chatpb all == nil")
return errors.New("chatpb.Books.ConfigSave() all == nil")
}
log.Info("Books.ConfigSave()")
// --- Start of Fix ---
// Create a new, clean Books object to avoid marshaling a slice with nil entries.
cleanBooks := NewBooks() // Assuming NewBooks() initializes the struct correctly.
// Loop through the original books and append only the non-nil ones.
for _, book := range all.GetBooks() {
if book != nil {
cleanBooks.Books = append(cleanBooks.Books, book)
} else {
log.Warn("Found and skipped a nil book entry during Books.ConfigSave")
}
}
// --- End of Fix ---
data, err := cleanBooks.Marshal() // Marshal the clean object, not 'all'
if err != nil {
log.Info("chatpb proto.Marshal() failed len", len(data), err)
// The tryValidate logic might be less necessary now but kept for safety.
if err := cleanBooks.tryValidate(); err != nil {
return err
} else {
data, err = cleanBooks.Marshal() // Retry with the clean object
if err == nil {
log.Info("chatpb.Books.ConfigSave() pb.Marshal() worked after validation len", len(cleanBooks.Books), "books")
configWrite("regex.pb", data)
return nil
}
}
return err
}
filename := "book." + all.GetTitleUuid() + ".pb"
if err := configWrite(filename, data); err != nil {
log.Infof("chatpb.Books.ConfigSave() failed len(Books)=%d bytes=%d", len(cleanBooks.Books), len(data))
return err
}
return nil
}
func (all *Books) tryValidate() error {
err := bugpb.ValidateProtoUTF8(all)
if err != nil {
log.Printf("Protobuf UTF-8 validation failed: %v\n", err)
}
if err := bugpb.SanitizeProtoUTF8(all); err != nil {
log.Warn("Sanitation failed:", err)
// log.Fatalf("Sanitization failed: %v", err)
return err
}
return nil
}
|