Fix: field replacement with quotes

main
Óscar M. Lage 2024-10-14 13:43:41 +02:00
parent c7bc40ba33
commit ad98329552
1 changed files with 11 additions and 11 deletions

View File

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