Skip to content

Instantly share code, notes, and snippets.

@conoro
Created July 10, 2016 09:52
Show Gist options
  • Save conoro/d1fe27a4e09702ccdaf9728e78f1cbf6 to your computer and use it in GitHub Desktop.
Save conoro/d1fe27a4e09702ccdaf9728e78f1cbf6 to your computer and use it in GitHub Desktop.
Add a slug field to every post in Hugo to avoid periods and caps in urls
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
)
func main() {
searchDir := "."
fileList := []string{}
err := filepath.Walk(searchDir, func(path string, f os.FileInfo, err error) error {
fileList = append(fileList, path)
return nil
})
if err != nil {
fmt.Println(err)
}
var re = regexp.MustCompile("[^a-z0-9]+")
for _, file := range fileList {
var slug string
//fmt.Println(file)
if len(file) >= 3 {
slug = strings.Trim(re.ReplaceAllString(strings.ToLower(file[:len(file)-3]), "-"), "-")
fmt.Println(slug)
input, err := ioutil.ReadFile(file)
if err != nil {
log.Fatalln(err)
}
lines := strings.Split(string(input), "\n")
slugline := "slug: \"" + slug + "\""
lines2 := []string{}
for i, line := range lines {
lines2 = append(lines2, line)
if i == 1 {
lines2 = append(lines2, slugline)
}
}
output := strings.Join(lines2, "\n")
err = ioutil.WriteFile(file, []byte(output), 0644)
if err != nil {
log.Fatalln(err)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment