diff --git a/main.go b/main.go index 3919d3e..4d972cf 100644 --- a/main.go +++ b/main.go @@ -1,14 +1,17 @@ package main import ( + "bufio" "bytes" "fmt" "io" + "io/ioutil" "log" "os" "path/filepath" "regexp" "strings" + "time" "github.com/fsnotify/fsnotify" "github.com/gosimple/slug" @@ -98,6 +101,23 @@ func processModifiedFile(filePath, directory, destDir string) { // Copy modified file to the new destination newFilePath := filepath.Join(newDir, "index.md") + + // Check if the file already has frontmatter + hasFrontmatter, err := checkFrontmatter(filePath) + if err != nil { + fmt.Println("Error checking frontmatter:", err) + return + } + + // If the file doesn't have frontmatter, add it + if !hasFrontmatter { + err = addFrontmatter(filePath, fileName) + if err != nil { + fmt.Println("Error adding frontmatter:", err) + return + } + } + err = copyFile(filePath, newFilePath) if err != nil { fmt.Println("Error copying file:", err) @@ -112,6 +132,51 @@ func processModifiedFile(filePath, directory, destDir string) { } } +// Function to check if the file already has frontmatter +func checkFrontmatter(filePath string) (bool, error) { + file, err := os.Open(filePath) + if err != nil { + return false, err + } + defer file.Close() + + scanner := bufio.NewScanner(file) + for scanner.Scan() { + line := scanner.Text() + if line == "---" { + return true, nil + } + } + + return false, nil +} + +// Function to add frontmatter to the file +func addFrontmatter(filePath, title string) error { + // Read the content of the original file + content, err := ioutil.ReadFile(filePath) + if err != nil { + return err + } + + // Create a new temporary file with the frontmatter added + tempFilePath := filePath + ".tmp" + frontmatter := fmt.Sprintf("---\ntitle: %s\ndate: %s\ndraft: false\ntags: micropost\n---\n\n", title, time.Now().Format("2006-01-02 15:04:05 -0700")) + err = ioutil.WriteFile(tempFilePath, []byte(frontmatter+string(content)), os.ModePerm) + if err != nil { + return err + } + + // Replace the original file with the temporary file + fmt.Println("Rename:", tempFilePath, filePath) + err = os.Rename(tempFilePath, filePath) + if err != nil { + return err + } + + return nil +} + func copyFile(src, dst string) error { sourceFile, err := os.Open(src) if err != nil {