chatpb/config.books.go

79 lines
2.2 KiB
Go

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
}