summaryrefslogtreecommitdiff
path: root/config.books.go
diff options
context:
space:
mode:
authorJeff Carr <[email protected]>2025-09-03 01:23:01 -0500
committerJeff Carr <[email protected]>2025-09-03 01:23:01 -0500
commit60ef1deb90eafd1741f231ddbc19f48b6199061b (patch)
tree6b97f4a8ff730097f4ef54750703078421acfef9 /config.books.go
parent1aaa1d0e0743acc62b41e65b7547a53de5a399bf (diff)
Diffstat (limited to 'config.books.go')
-rw-r--r--config.books.go78
1 files changed, 78 insertions, 0 deletions
diff --git a/config.books.go b/config.books.go
new file mode 100644
index 0000000..8717540
--- /dev/null
+++ b/config.books.go
@@ -0,0 +1,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
+}