Original post

Hi I've written the quick and dirty script below to "migrate" from the current frontmatter structure to a new structure.

Here's the script:

“` package main

import ( "bytes" "fmt" "io/ioutil" "log"

"github.com/BurntSushi/toml" 

)

type oldFrontMatter struct { Name string Compensation string Currency string }

type NewFrontMatter struct { Name string toml:"full_name" Salary string toml:"salary" Currency string toml:"currency" UnitText string toml:"unit_text" }

var contentPath = "contents/"

func main() { // get a list of markdown files files, err := ioutil.ReadDir(contentPath) if err != nil { log.Fatal(err) }

// read each markdown file and get TOML front matter block for _, file := range files { contents, err := ioutil.ReadFile(contentPath + file.Name()) if err != nil { log.Fatal(err) } // remove the "+++" identifier and parse the TOML data data := removeTOMLIdentifier(contents) // decode TOML keys mapping them to oldFM struct field names var oldFM OldFrontMatter if _, err := toml.Decode(string(data), &oldFM); err != nil { log.Fatal(err) } // migrate from oldFrontMatter to NewFrontMatter var newFM NewFrontMatter newFM.Name = oldFM.Name newFM.Salary = oldFM.Compensation newFM.Currency = oldFM.Currency currency := newFM.Currency if len(currency) > 0 { newFM.UnitText = "blah" } else { newFM.UnitText = "" } // create TOML front matter block buf := new(bytes.Buffer) buf.WriteString("+++n") if err := toml.NewEncoder(buf).Encode(newFM); err != nil { log.Fatal(err) } buf.WriteString("+++") fmt.Println(buf) } 

} “`

Here's an example markdown file with old frontmatter:

“` +++ name = testname compensation = "10000" currency = "USD" +++

Some content here.

More content. “`

Here's what the markdown file should look like after running the script above new frontmatter:

“` +++ name = testname salary = "10000" currency = "USD" unit_text = "blah +++

Some content here.

More content. “`

I'm having the following issue:

The script fails at this line if _, err := toml.Decode(string(data), &oldFM); err != nil { if the markdown file has a body, e.g. "Some content here.". I understand that it's because the body is not valid TOML. However, I'm not sure how to "split" the frontmatter from the body, so that only the frontmatter is decoded and migrated to the new structure.

I know the script is not the best but I just need this for a one off processing of ~200 markdown files and doing the changes manually would suck 🙂

Is there a simple way to accomplish this? Thanks in advance.

submitted by /u/Express-Confusion-11
[link] [comments]