Fix: title cant be updated

Doesn't make sense because the first thing it does is to search by title in disk
The md won't be found
This commit is contained in:
Óscar M. Lage 2024-10-11 22:48:21 +02:00
parent 28ffc9c77b
commit c9a30a3767
2 changed files with 27 additions and 3 deletions

View File

@ -25,12 +25,29 @@ func LoadBooks() ([]Book, error) {
return books, nil
}
func ProcessBooks(books []Book) error {
func ProcessBooks(books []Book, update bool) error {
fmt.Printf(" B O O K S\n")
utils.Sep()
for _, book := range books {
fmt.Printf("Title: %s, Author: %s, ID: %s\n", book.Title, book.Author, book.ID)
// If we're updating, the process is a bit different
if update {
outputDir := os.Getenv("MARKDOWN_OUTPUT_BOOKS_DIR")
mdFilePath := filepath.Join(outputDir, fmt.Sprintf("%s.md", utils.Sluggify(book.Title)))
frontmatter, content, err := utils.LoadMarkdown(mdFilePath)
if err != nil {
fmt.Printf(" ! Error loading markdown frontmatter for book %s: %v\n", book.Title, err)
continue
}
updatedFrontmatter := updateFrontmatterWithYAML(frontmatter, book)
err = utils.SaveUpdatedMarkdown(mdFilePath, updatedFrontmatter, content)
if err != nil {
fmt.Printf(" ! Error saving updated markdown for book %s: %v\n", book.Title, err)
continue
}
}
// If we dont have ID, search movie by Title and get the ID
if book.ID == "" {
err := SearchBookByTitle(book.Title, &book)
@ -85,3 +102,12 @@ func generateBookMarkdown(book Book) error {
return utils.GenerateMarkdown(templatePath, outputPath, data)
}
// Helper function to update only YAML fields that exist in both the frontmatter and YAML data
func updateFrontmatterWithYAML(frontmatter utils.FrontMatter, book Book) utils.FrontMatter {
// Update fields (adapt based on your actual Book struct)
frontmatter.Progress = book.Progress
frontmatter.Date = book.Date
frontmatter.Rate = book.Rate
return frontmatter
}

View File

@ -97,14 +97,12 @@ func SaveUpdatedMarkdown(filepath string, frontmatter FrontMatter, content strin
// Define regex patterns to match specific fields in the frontmatter
fieldPatterns := map[string]string{
"title": fmt.Sprintf(`(?m)^title: "(.*)"`),
"progress": fmt.Sprintf(`(?m)^progress: "(.*)"`),
"date": fmt.Sprintf(`(?m)^date: (\d+)$`),
"rate": fmt.Sprintf(`(?m)^rate: (\d+\.?\d*)$`),
}
// Replace the relevant fields in the frontmatter using regex substitution
fileContent = updateFieldInFrontmatter(fileContent, "title", frontmatter.Title, fieldPatterns["title"])
fileContent = updateFieldInFrontmatter(fileContent, "progress", frontmatter.Progress, fieldPatterns["progress"])
fileContent = updateFieldInFrontmatter(fileContent, "date", fmt.Sprintf("%d", frontmatter.Date), fieldPatterns["date"])
fileContent = updateFieldInFrontmatterFloat(fileContent, "rate", frontmatter.Rate, fieldPatterns["rate"])