Fix: field replacement with quotes

This commit is contained in:
Óscar M. Lage 2024-10-14 13:43:41 +02:00
parent c7bc40ba33
commit ad98329552

View File

@ -17,6 +17,7 @@ type FrontMatter struct {
Title string `yaml:"title"` Title string `yaml:"title"`
Rate float64 `yaml:"rate"` Rate float64 `yaml:"rate"`
Progress string `yaml:"progress"` Progress string `yaml:"progress"`
Episode string `yaml:"episode"`
Date string `yaml:"date"` Date string `yaml:"date"`
} }
@ -95,16 +96,17 @@ func SaveUpdatedMarkdown(filepath string, frontmatter FrontMatter, content strin
// Convert file content to string // Convert file content to string
fileContent := string(fileBytes) fileContent := string(fileBytes)
// Define regex patterns to match specific fields in the frontmatter
fieldPatterns := map[string]string{ fieldPatterns := map[string]string{
"progress": fmt.Sprintf(`(?m)^progress: "(.*)"`), "progress": `(?m)^progress: "(.*)%"$`,
"date": fmt.Sprintf(`(?m)^date: (\d+)$`), "episode": `(?m)^episode: "(.*)"$`,
"rate": fmt.Sprintf(`(?m)^rate: (\d+\.?\d*)$`), "date": `(?m)^date: "(.*)"$`,
"rate": `(?m)^rate: (\d+\.?\d*)$`,
} }
// Replace the relevant fields in the frontmatter using regex substitution // Fields replacement
fileContent = updateFieldInFrontmatter(fileContent, "progress", frontmatter.Progress, fieldPatterns["progress"]) fileContent = updateFieldInFrontmatter(fileContent, "progress", fmt.Sprintf("\"%s\"", frontmatter.Progress), fieldPatterns["progress"])
fileContent = updateFieldInFrontmatter(fileContent, "date", fmt.Sprintf("%d", frontmatter.Date), fieldPatterns["date"]) fileContent = updateFieldInFrontmatter(fileContent, "episode", fmt.Sprintf("\"%s\"", frontmatter.Episode), fieldPatterns["episode"])
fileContent = updateFieldInFrontmatter(fileContent, "date", fmt.Sprintf("\"%s\"", frontmatter.Date), fieldPatterns["date"])
fileContent = updateFieldInFrontmatterFloat(fileContent, "rate", frontmatter.Rate, fieldPatterns["rate"]) fileContent = updateFieldInFrontmatterFloat(fileContent, "rate", frontmatter.Rate, fieldPatterns["rate"])
// Write the updated content back to the file // Write the updated content back to the file
@ -116,11 +118,9 @@ func SaveUpdatedMarkdown(filepath string, frontmatter FrontMatter, content strin
return nil return nil
} }
// Helper function to update a specific field in the frontmatter func updateFieldInFrontmatter(content, field, newValue, pattern string) string {
func updateFieldInFrontmatter(fileContent, field, newValue, pattern string) string {
re := regexp.MustCompile(pattern) re := regexp.MustCompile(pattern)
updatedContent := re.ReplaceAllString(fileContent, fmt.Sprintf("%s: \"%s\"", field, newValue)) return re.ReplaceAllString(content, fmt.Sprintf("%s: %s", field, newValue))
return updatedContent
} }
// Helper function to update a float64 field in the frontmatter (for numerical values like rate) // Helper function to update a float64 field in the frontmatter (for numerical values like rate)