Skip to content

Instantly share code, notes, and snippets.

@fatih
Created November 16, 2017 19:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fatih/2141f0ab201f55fb37f4104649ea6577 to your computer and use it in GitHub Desktop.
Save fatih/2141f0ab201f55fb37f4104649ea6577 to your computer and use it in GitHub Desktop.
Wordpress captions to Hugo shortcodes. This is a terrible hack, not performant. Only here for reference
package main
import (
"fmt"
"io/ioutil"
"log"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
)
func main() {
if err := realMain(); err != nil {
log.Fatalln(err)
}
}
func realMain() error {
dir, err := os.Getwd()
if err != nil {
return err
}
files, err := ioutil.ReadDir(dir)
if err != nil {
return err
}
re := regexp.MustCompile(`!\[.*\]\((.*?)\)(.*?)\[\/caption`)
reURL := regexp.MustCompile(`!\[.*?\]\((.*?)\)`)
for _, f := range files {
if filepath.Ext(f.Name()) == ".go" {
continue
}
if f.Name() == "images" {
continue
}
out, err := ioutil.ReadFile(f.Name())
if err != nil {
return err
}
content := strings.Split(string(out), "\n")
for i, line := range content {
link := ""
caption := ""
splitted := re.FindStringSubmatch(line)
if len(splitted) == 3 {
caption = strings.TrimSpace(splitted[2])
}
links := reURL.FindStringSubmatch(line)
if len(links) == 2 {
link = links[1]
}
if link == "" {
continue
}
u, err := url.Parse(link)
if err != nil {
return err
}
path := u.Path
imageName := filepath.Base(path)
imagePath := fmt.Sprintf(filepath.Join("/images/", imageName))
finalLine := fmt.Sprintf(`{{< figure src="%s" >}}`, imagePath)
if caption != "" {
finalLine = fmt.Sprintf(`{{< figure src="%s" caption="%s" >}}`, imagePath, caption)
}
content[i] = finalLine
}
final := strings.Join(content, "\n")
err = ioutil.WriteFile(f.Name(), []byte(final), 0644)
if err != nil {
return err
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment