Small Go tool to convert Github markdown (plus HTML and Hugo shortcodes) to Gemini text files.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.0 KiB

// md2gmi 0.1.0
// gryffyn[at]neveris[dot]one
package main
import (
"io/ioutil"
"os"
"regexp"
"github.com/alexflint/go-arg"
)
func ifile(filename string) (string, error) {
content, err := ioutil.ReadFile(filename)
str := string(content)
return str, err
}
func ofile(filename, str string) error {
err := ioutil.WriteFile(filename, []byte(str), os.FileMode.Perm(0644))
return err
}
// Converts .md to .gmi using regexes
// Supports citations, html tags, and hyperlinks
func md2gmi(md string) string {
// defines regexes and compiles them
reg_html := regexp.MustCompile(`<.+?>.+?<\/.+?>`)
reg_cite := regexp.MustCompile(`\[\^.+?\]\(.+?\)`)
reg_hugo := regexp.MustCompile(`(?s)\+{3}.+?\+{3}`)
reg_shcd := regexp.MustCompile(`{{(.*<.*>.*|.*%.*%.*)}}\n?`)
// deletes hugo and html tags
gm := reg_html.ReplaceAllString(md, "${1}")
gm_0 := reg_hugo.ReplaceAllString(gm, "${1}")
gm_1 := reg_cite.ReplaceAllString(gm_0, "${1}")
gm_2 := reg_shcd.ReplaceAllString(gm_1, "${1}")
// re-does links
reg_link := regexp.MustCompile(`\[(?P<name>.+?)\]\((?P<url>.+?)\)`)
res := reg_link.ReplaceAllStringFunc(gm_2, func(m string) string {
parts := reg_link.FindStringSubmatch(m)
return "\n=> " + parts[2] + " " + parts[1] + "\n"
})
return res
}
func inout(in, out string) error {
md, err := ifile(in)
res := md2gmi(md)
err = ofile(out, res)
return err
}
func main() {
var args struct {
Input string `arg:"positional" help:"input markdown file (.md)"`
Output string `arg:"positional" help:"output gemtext file (.gmi)"`
V bool `arg:"-V" help:"Version"`
}
parse := arg.MustParse(&args)
if args.Input == "" && args.Output == "" && args.V {
println("md2gmi 0.1.0\nby gryffyn")
return
} else if args.Input == "" && args.Output == "" && !(args.V) {
parse.Fail("You must provide both INPUT and OUTPUT.")
} else if args.Output == "" && !(args.V) {
parse.Fail("You must provide both INPUT and OUTPUT.")
}
err := inout(args.Input, args.Output)
if err != nil {
panic(err)
}
}