Browse Source

Added plaintext renderer

Benton Edmondson 2 years ago
parent
commit
c7b09539de
3 changed files with 58 additions and 1 deletions
  1. 22 0
      plaintext/plaintext.go
  2. 34 0
      plaintext/plaintext_test.go
  3. 2 1
      render/render.go

+ 22 - 0
plaintext/plaintext.go

@@ -0,0 +1,22 @@
+package plaintext
+
+import (
+	"regexp"
+	"mimicry/style"
+)
+
+func Render(text string) (string, error) {
+	/*
+		Oversimplistic URL regexp based on RFC 3986, Appendix A
+		It matches:
+			<scheme>://<hierarchy>
+		Where
+			<scheme> is ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
+			<hierarchy> is any of the characters listed in Appendix A:
+				A-Z a-z 0-9 - . ? # / @ : [ ] % _ ~ ! $ & ' ( ) * + , ; =
+	*/
+	
+	url := regexp.MustCompile(`[A-Za-z][A-Za-z0-9+\-.]*://[A-Za-z0-9.?#/@:%_~!$&'()*+,;=\[\]\-]+`)
+
+	return url.ReplaceAllStringFunc(text, style.Link), nil
+}

+ 34 - 0
plaintext/plaintext_test.go

@@ -0,0 +1,34 @@
+package plaintext
+
+import (
+	"testing"
+	"mimicry/style"
+)
+
+func assertEqual(expected string, output string, t *testing.T) {
+	if expected != output {
+		t.Fatalf("Expected `%s` not `%s`\n", expected, output)
+	}
+}
+
+func TestBasic(t *testing.T) {
+	input := `Yes, Jim, I found it under "http://www.w3.org/Addressing/",
+but you can probably pick it up from <ftp://foo.example.com/rfc/>.
+Note the warning in <http://www.ics.uci.edu/pub/ietf/uri/historical.html#WARNING>.`
+	output, err := Render(input)
+	if err != nil {
+		panic(err)
+	}
+
+	expected := `Yes, Jim, I found it under "` +
+		style.Link("http://www.w3.org/Addressing/") +
+		`",
+but you can probably pick it up from <` +
+		style.Link("ftp://foo.example.com/rfc/") +
+		`>.
+Note the warning in <` +
+		style.Link("http://www.ics.uci.edu/pub/ietf/uri/historical.html#WARNING") +
+		`>.`
+
+	assertEqual(expected, output, t)
+}

+ 2 - 1
render/render.go

@@ -5,6 +5,7 @@ import (
 	"errors"
 	"fmt"
 	"mimicry/hypertext"
+	"mimicry/plaintext"
 )
 
 // TODO: need to actually parse mediaType, not use `Contains`
@@ -12,7 +13,7 @@ func Render(text string, mediaType string) (string, error) {
 	fmt.Println("started render")
 	switch {
 	case strings.Contains(mediaType, "text/plain"): 
-		return text, nil
+		return plaintext.Render(text)
 	case strings.Contains(mediaType, "text/html"):
 		return hypertext.Render(text)
 	default: