84 lines
1.7 KiB
Go
84 lines
1.7 KiB
Go
package main
|
|
|
|
import (
|
|
_ "embed"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"io/ioutil"
|
|
"os"
|
|
"regexp"
|
|
"strings"
|
|
)
|
|
|
|
func _main(o opts) error {
|
|
t, err := ioutil.ReadAll(o.In)
|
|
if err != nil {
|
|
return fmt.Errorf("could not read from stdin: %w", err)
|
|
}
|
|
|
|
r := regexp.MustCompile(`\(LINK ([^ ]+?) (.+?)\)`)
|
|
mms := r.FindAllSubmatch(t, -1)
|
|
|
|
if mms == nil {
|
|
fmt.Fprintf(o.Out, string(t))
|
|
return nil
|
|
}
|
|
|
|
output := string(t)
|
|
footer := ""
|
|
|
|
for ix, ms := range mms {
|
|
rawLink := string(ms[0])
|
|
link := string(ms[1])
|
|
title := string(ms[2])
|
|
switch o.Mode {
|
|
case "html":
|
|
output = strings.ReplaceAll(output, rawLink,
|
|
fmt.Sprintf("<a href=\"%s\">%s</a>", link, title))
|
|
case "gopher":
|
|
output = strings.ReplaceAll(output, rawLink, fmt.Sprintf("%s[%d]", title, ix))
|
|
linkType := "i"
|
|
if strings.HasPrefix(link, "http") {
|
|
linkType = "h"
|
|
}
|
|
footer += fmt.Sprintf("%s[%d]: %s %s\n", linkType, ix, title, link)
|
|
case "gemini":
|
|
output = strings.ReplaceAll(output, rawLink, fmt.Sprintf("%s[%d]", title, ix))
|
|
footer += fmt.Sprintf("=> %s [%d]: %s\n", link, ix, title)
|
|
}
|
|
}
|
|
|
|
if footer != "" {
|
|
output = output + "\n\n" + footer
|
|
}
|
|
|
|
fmt.Fprintf(o.Out, output)
|
|
|
|
return nil
|
|
}
|
|
|
|
type opts struct {
|
|
In io.Reader
|
|
Out io.Writer
|
|
Mode string
|
|
}
|
|
|
|
func main() {
|
|
var modeFlag = flag.String("mode", "", "one of html, gopher, gemini.")
|
|
flag.Parse()
|
|
if *modeFlag == "" || (*modeFlag != "html" && *modeFlag != "gopher" && *modeFlag != "gemini") {
|
|
fmt.Fprintln(os.Stderr, "--mode must be specified and one of: html, gopher, gemini")
|
|
os.Exit(1)
|
|
}
|
|
o := opts{
|
|
In: os.Stdin,
|
|
Out: os.Stdout,
|
|
Mode: *modeFlag,
|
|
}
|
|
if err := _main(o); err != nil {
|
|
fmt.Fprintln(os.Stderr, err.Error())
|
|
os.Exit(2)
|
|
}
|
|
}
|