Wordpress captions to Hugo shortcodes. This is a terrible hack, not performant. Only here for reference
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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