diff --git a/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go b/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go index a0ecd38..3c540bf 100644 --- a/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go +++ b/src/github.com/matrix-org/go-neb/services/wikipedia/wikipedia.go @@ -7,15 +7,18 @@ import ( "io/ioutil" "net/http" "net/url" + "strconv" "strings" log "github.com/Sirupsen/logrus" + "github.com/jaytaylor/html2text" "github.com/matrix-org/go-neb/types" "github.com/matrix-org/gomatrix" ) // ServiceType of the Wikipedia service const ServiceType = "wikipedia" +const maxExtractLength = 1024 // Max length of extract string in bytes var httpClient = &http.Client{} @@ -81,9 +84,25 @@ func (s *Service) cmdWikipediaSearch(client *gomatrix.Client, roomID, userID str }, nil } + extractText, err := html2text.FromString(searchResultPage.Extract) + if err != nil { + return gomatrix.TextMessage{ + MsgType: "m.notice", + Body: "Failed to convert extract to plain text - " + err.Error(), + }, nil + } + + // Truncate the extract text, if necessary + if len(extractText) > maxExtractLength { + extractText = extractText[:maxExtractLength] + "..." + } + + // Add a link to the bottom of the extract + extractText += "\n" + "http://en.wikipedia.org/?curid=" + strconv.FormatInt(searchResultPage.PageID, 10) + return gomatrix.TextMessage{ MsgType: "m.notice", - Body: searchResultPage.Extract, + Body: extractText, }, nil } @@ -122,12 +141,18 @@ func (s *Service) text2Wikipedia(query string) (*wikipediaPage, error) { // log.Info(response2String(res)) if err := json.NewDecoder(res.Body).Decode(&searchResults); err != nil { return nil, fmt.Errorf("ERROR - %s", err.Error()) - } else if len(searchResults.Pages) < 1 { + } else if len(searchResults.Query.Pages) < 1 { return nil, fmt.Errorf("No articles found") } - // Return only the first search result - return &searchResults.Pages[0], nil + // Return only the first search result with an extract + for _, page := range searchResults.Query.Pages { + if page.Extract != "" { + return &page, nil + } + } + + return nil, fmt.Errorf("No articles with extracts found") } // response2String returns a string representation of an HTTP response body diff --git a/vendor/manifest b/vendor/manifest index 3070089..1bf7484 100644 --- a/vendor/manifest +++ b/vendor/manifest @@ -129,6 +129,12 @@ "revision": "d02018f006d98f58512bf3adfc171d88d17626df", "branch": "master" }, + { + "importpath": "github.com/jaytaylor/html2text", + "repository": "https://github.com/jaytaylor/html2text", + "revision": "24f9b0f63599c6bbecc3b773636b54f8d302db67", + "branch": "master" + }, { "importpath": "github.com/matrix-org/dugong", "repository": "https://github.com/matrix-org/dugong", diff --git a/vendor/src/github.com/jaytaylor/html2text/LICENSE b/vendor/src/github.com/jaytaylor/html2text/LICENSE new file mode 100644 index 0000000..24dc4ab --- /dev/null +++ b/vendor/src/github.com/jaytaylor/html2text/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jay Taylor + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/vendor/src/github.com/jaytaylor/html2text/README.md b/vendor/src/github.com/jaytaylor/html2text/README.md new file mode 100644 index 0000000..ac11247 --- /dev/null +++ b/vendor/src/github.com/jaytaylor/html2text/README.md @@ -0,0 +1,116 @@ +# html2text + +[![Documentation](https://godoc.org/github.com/jaytaylor/html2text?status.svg)](https://godoc.org/github.com/jaytaylor/html2text) +[![Build Status](https://travis-ci.org/jaytaylor/html2text.svg?branch=master)](https://travis-ci.org/jaytaylor/html2text) +[![Report Card](https://goreportcard.com/badge/github.com/jaytaylor/html2text)](https://goreportcard.com/report/github.com/jaytaylor/html2text) + +### Converts HTML into text + + +## Introduction + +Ensure your emails are readable by all! + +Turns HTML into raw text, useful for sending fancy HTML emails with a equivalently nicely formatted TXT document as a fallback (e.g. for people who don't allow HTML emails or have other display issues). + +html2text is a simple golang package for rendering HTML into plaintext. + +There are still lots of improvements to be had, but FWIW this has worked fine for my [basic] HTML-2-text needs. + +It requires go 1.x or newer ;) + + +## Download the package + +```bash +go get github.com/jaytaylor/html2text +``` + +## Example usage + +```go +package main + +import ( + "fmt" + + "github.com/jaytaylor/html2text" +) + +func main() { + inputHtml := ` + + + My Mega Service + + + + + + + +

Welcome to your new account on my service!

+ +

+ Here is some more information: + +

+

+ + + ` + + text, err := html2text.FromString(inputHtml) + if err != nil { + panic(err) + } + fmt.Println(text) +} +``` + +Output: +``` +Mega Service ( http://mymegaservice.com/ ) + +****************************************** +Welcome to your new account on my service! +****************************************** + +Here is some more information: + +* Link 1: Example.com ( https://example.com ) +* Link 2: Example2.com ( https://example2.com ) +* Something else +``` + + +## Unit-tests + +Running the unit-tests is straightforward and standard: + +```bash +go test +``` + + +# License + +Permissive MIT license. + + +## Contact + +You are more than welcome to open issues and send pull requests if you find a bug or want a new feature. + +If you appreciate this library please feel free to drop me a line and tell me! It's always nice to hear from people who have benefitted from my work. + +Email: jay at (my github username).com + +Twitter: [@jtaylor](https://twitter.com/jtaylor) + diff --git a/vendor/src/github.com/jaytaylor/html2text/html2text.go b/vendor/src/github.com/jaytaylor/html2text/html2text.go new file mode 100644 index 0000000..8933fbe --- /dev/null +++ b/vendor/src/github.com/jaytaylor/html2text/html2text.go @@ -0,0 +1,304 @@ +package html2text + +import ( + "bytes" + "io" + "regexp" + "strings" + "unicode" + + "golang.org/x/net/html" + "golang.org/x/net/html/atom" +) + +var ( + spacingRe = regexp.MustCompile(`[ \r\n\t]+`) + newlineRe = regexp.MustCompile(`\n\n+`) +) + +type textifyTraverseCtx struct { + Buf bytes.Buffer + + prefix string + blockquoteLevel int + lineLength int + endsWithSpace bool + endsWithNewline bool + justClosedDiv bool +} + +func (ctx *textifyTraverseCtx) traverse(node *html.Node) error { + switch node.Type { + + default: + return ctx.traverseChildren(node) + + case html.TextNode: + data := strings.Trim(spacingRe.ReplaceAllString(node.Data, " "), " ") + return ctx.emit(data) + + case html.ElementNode: + + ctx.justClosedDiv = false + switch node.DataAtom { + case atom.Br: + return ctx.emit("\n") + + case atom.H1, atom.H2, atom.H3: + subCtx := textifyTraverseCtx{} + if err := subCtx.traverseChildren(node); err != nil { + return err + } + + str := subCtx.Buf.String() + dividerLen := 0 + for _, line := range strings.Split(str, "\n") { + if lineLen := len([]rune(line)); lineLen-1 > dividerLen { + dividerLen = lineLen - 1 + } + } + divider := "" + if node.DataAtom == atom.H1 { + divider = strings.Repeat("*", dividerLen) + } else { + divider = strings.Repeat("-", dividerLen) + } + + if node.DataAtom == atom.H3 { + return ctx.emit("\n\n" + str + "\n" + divider + "\n\n") + } + return ctx.emit("\n\n" + divider + "\n" + str + "\n" + divider + "\n\n") + + case atom.Blockquote: + ctx.blockquoteLevel++ + ctx.prefix = strings.Repeat(">", ctx.blockquoteLevel) + " " + if err := ctx.emit("\n"); err != nil { + return err + } + if ctx.blockquoteLevel == 1 { + if err := ctx.emit("\n"); err != nil { + return err + } + } + if err := ctx.traverseChildren(node); err != nil { + return err + } + ctx.blockquoteLevel-- + ctx.prefix = strings.Repeat(">", ctx.blockquoteLevel) + if ctx.blockquoteLevel > 0 { + ctx.prefix += " " + } + return ctx.emit("\n\n") + + case atom.Div: + if ctx.lineLength > 0 { + if err := ctx.emit("\n"); err != nil { + return err + } + } + if err := ctx.traverseChildren(node); err != nil { + return err + } + var err error + if ctx.justClosedDiv == false { + err = ctx.emit("\n") + } + ctx.justClosedDiv = true + return err + + case atom.Li: + if err := ctx.emit("* "); err != nil { + return err + } + + if err := ctx.traverseChildren(node); err != nil { + return err + } + + return ctx.emit("\n") + + case atom.B, atom.Strong: + subCtx := textifyTraverseCtx{} + subCtx.endsWithSpace = true + if err := subCtx.traverseChildren(node); err != nil { + return err + } + str := subCtx.Buf.String() + return ctx.emit("*" + str + "*") + + case atom.A: + // If image is the only child, take its alt text as the link text + if img := node.FirstChild; img != nil && node.LastChild == img && img.DataAtom == atom.Img { + if altText := getAttrVal(img, "alt"); altText != "" { + ctx.emit(altText) + } + } else if err := ctx.traverseChildren(node); err != nil { + return err + } + + hrefLink := "" + if attrVal := getAttrVal(node, "href"); attrVal != "" { + attrVal = ctx.normalizeHrefLink(attrVal) + if attrVal != "" { + hrefLink = "( " + attrVal + " )" + } + } + + return ctx.emit(hrefLink) + + case atom.P, atom.Ul, atom.Table: + if err := ctx.emit("\n\n"); err != nil { + return err + } + + if err := ctx.traverseChildren(node); err != nil { + return err + } + + return ctx.emit("\n\n") + + case atom.Tr: + if err := ctx.traverseChildren(node); err != nil { + return err + } + + return ctx.emit("\n") + + case atom.Style, atom.Script, atom.Head: + // Ignore the subtree + return nil + + default: + return ctx.traverseChildren(node) + } + } +} + +func (ctx *textifyTraverseCtx) traverseChildren(node *html.Node) error { + for c := node.FirstChild; c != nil; c = c.NextSibling { + if err := ctx.traverse(c); err != nil { + return err + } + } + + return nil +} + +func (ctx *textifyTraverseCtx) emit(data string) error { + if len(data) == 0 { + return nil + } + lines := ctx.breakLongLines(data) + var err error + for _, line := range lines { + runes := []rune(line) + startsWithSpace := unicode.IsSpace(runes[0]) + if !startsWithSpace && !ctx.endsWithSpace { + ctx.Buf.WriteByte(' ') + ctx.lineLength++ + } + ctx.endsWithSpace = unicode.IsSpace(runes[len(runes)-1]) + for _, c := range line { + _, err = ctx.Buf.WriteString(string(c)) + if err != nil { + return err + } + ctx.lineLength++ + if c == '\n' { + ctx.lineLength = 0 + if ctx.prefix != "" { + _, err = ctx.Buf.WriteString(ctx.prefix) + if err != nil { + return err + } + } + } + } + } + return nil +} + +func (ctx *textifyTraverseCtx) breakLongLines(data string) []string { + // only break lines when we are in blockquotes + if ctx.blockquoteLevel == 0 { + return []string{data} + } + var ret []string + runes := []rune(data) + l := len(runes) + existing := ctx.lineLength + if existing >= 74 { + ret = append(ret, "\n") + existing = 0 + } + for l+existing > 74 { + i := 74 - existing + for i >= 0 && !unicode.IsSpace(runes[i]) { + i-- + } + if i == -1 { + // no spaces, so go the other way + i = 74 - existing + for i < l && !unicode.IsSpace(runes[i]) { + i++ + } + } + ret = append(ret, string(runes[:i])+"\n") + for i < l && unicode.IsSpace(runes[i]) { + i++ + } + runes = runes[i:] + l = len(runes) + existing = 0 + } + if len(runes) > 0 { + ret = append(ret, string(runes)) + } + return ret +} + +func (ctx *textifyTraverseCtx) normalizeHrefLink(link string) string { + link = strings.TrimSpace(link) + link = strings.TrimPrefix(link, "mailto:") + return link +} + +func getAttrVal(node *html.Node, attrName string) string { + for _, attr := range node.Attr { + if attr.Key == attrName { + return attr.Val + } + } + + return "" +} + +func FromHtmlNode(doc *html.Node) (string, error) { + ctx := textifyTraverseCtx{ + Buf: bytes.Buffer{}, + } + if err := ctx.traverse(doc); err != nil { + return "", err + } + + text := strings.TrimSpace(newlineRe.ReplaceAllString( + strings.Replace(ctx.Buf.String(), "\n ", "\n", -1), "\n\n")) + return text, nil + +} + +func FromReader(reader io.Reader) (string, error) { + doc, err := html.Parse(reader) + if err != nil { + return "", err + } + return FromHtmlNode(doc) +} + +func FromString(input string) (string, error) { + text, err := FromReader(strings.NewReader(input)) + if err != nil { + return "", err + } + return text, nil +} diff --git a/vendor/src/github.com/jaytaylor/html2text/html2text_test.go b/vendor/src/github.com/jaytaylor/html2text/html2text_test.go new file mode 100644 index 0000000..c55aa3e --- /dev/null +++ b/vendor/src/github.com/jaytaylor/html2text/html2text_test.go @@ -0,0 +1,630 @@ +package html2text + +import ( + "fmt" + "regexp" + "testing" +) + +func TestStrippingWhitespace(t *testing.T) { + testCases := []struct { + input string + output string + }{ + { + "test text", + "test text", + }, + { + " \ttext\ntext\n", + "text text", + }, + { + " \na \n\t \n \n a \t", + "a a", + }, + { + "test text", + "test text", + }, + { + "test    text ", + "test    text", + }, + } + + for _, testCase := range testCases { + assertString(t, testCase.input, testCase.output) + } +} + +func TestParagraphsAndBreaks(t *testing.T) { + testCases := []struct { + input string + output string + }{ + { + "Test text", + "Test text", + }, + { + "Test text
", + "Test text", + }, + { + "Test text
Test", + "Test text\nTest", + }, + { + "

Test text

", + "Test text", + }, + { + "

Test text

Test text

", + "Test text\n\nTest text", + }, + { + "\n

Test text

\n\n\n\t

Test text

\n", + "Test text\n\nTest text", + }, + { + "\n

Test text
Test text

\n", + "Test text\nTest text", + }, + { + "\n

Test text
\tTest text

\n", + "Test text\nTest text", + }, + { + "Test text

Test text", + "Test text\n\nTest text", + }, + } + + for _, testCase := range testCases { + assertString(t, testCase.input, testCase.output) + } +} + +func TestTables(t *testing.T) { + testCases := []struct { + input string + output string + }{ + { + "
", + "", + }, + { + "
cell1cell2
", + "cell1 cell2", + }, + { + "
row1
row2
", + "row1\nrow2", + }, + { + ` + + +
cell1-1cell1-2
cell2-1cell2-2
`, + "cell1-1 cell1-2\ncell2-1 cell2-2", + }, + { + "_
cell
_", + "_\n\ncell\n\n_", + }, + } + + for _, testCase := range testCases { + assertString(t, testCase.input, testCase.output) + } +} + +func TestStrippingLists(t *testing.T) { + testCases := []struct { + input string + output string + }{ + { + "", + "", + }, + { + "_", + "* item\n\n_", + }, + { + "
  • item 1
  • item 2
  • \n_", + "* item 1\n* item 2\n_", + }, + { + "
  • item 1
  • \t\n
  • item 2
  • item 3
  • \n_", + "* item 1\n* item 2\n* item 3\n_", + }, + } + + for _, testCase := range testCases { + assertString(t, testCase.input, testCase.output) + } +} + +func TestLinks(t *testing.T) { + testCases := []struct { + input string + output string + }{ + { + ``, + ``, + }, + { + ``, + ``, + }, + { + ``, + `( http://example.com/ )`, + }, + { + `Link`, + `Link`, + }, + { + `Link`, + `Link ( http://example.com/ )`, + }, + { + `Link`, + `Link ( http://example.com/ )`, + }, + { + "\n\tLink\n\t", + `Link ( http://example.com/ )`, + }, + { + "Contact Us", + `Contact Us ( contact@example.org )`, + }, + { + "Link", + `Link ( http://example.com:80/~user?aaa=bb&c=d,e,f#foo )`, + }, + { + "Link", + `Link ( http://example.com/ )`, + }, + { + " Link ", + `Link ( http://example.com/ )`, + }, + { + "Link A Link B", + `Link A ( http://example.com/a/ ) Link B ( http://example.com/b/ )`, + }, + { + "Link", + `Link ( %%LINK%% )`, + }, + { + "Link", + `Link ( [LINK] )`, + }, + { + "Link", + `Link ( {LINK} )`, + }, + { + "Link", + `Link ( [[!unsubscribe]] )`, + }, + { + "

    This is link1 and link2 is next.

    ", + `This is link1 ( http://www.google.com ) and link2 ( http://www.google.com ) is next.`, + }, + } + + for _, testCase := range testCases { + assertString(t, testCase.input, testCase.output) + } +} + +func TestImageAltTags(t *testing.T) { + testCases := []struct { + input string + output string + }{ + { + ``, + ``, + }, + { + ``, + ``, + }, + { + `Example`, + ``, + }, + { + `Example`, + ``, + }, + // Images do matter if they are in a link + { + `Example`, + `Example ( http://example.com/ )`, + }, + { + `Example`, + `Example ( http://example.com/ )`, + }, + { + `Example`, + `Example ( http://example.com/ )`, + }, + { + `Example`, + `Example ( http://example.com/ )`, + }, + } + + for _, testCase := range testCases { + assertString(t, testCase.input, testCase.output) + } +} + +func TestHeadings(t *testing.T) { + testCases := []struct { + input string + output string + }{ + { + "

    Test

    ", + "****\nTest\n****", + }, + { + "\t

    \nTest

    ", + "****\nTest\n****", + }, + { + "\t

    \nTest line 1
    Test 2

    ", + "***********\nTest line 1\nTest 2\n***********", + }, + { + "

    Test

    Test

    ", + "****\nTest\n****\n\n****\nTest\n****", + }, + { + "

    Test

    ", + "----\nTest\n----", + }, + { + "

    Test

    ", + "****************************\nTest ( http://example.com/ )\n****************************", + }, + { + "

    Test

    ", + "Test\n----", + }, + } + + for _, testCase := range testCases { + assertString(t, testCase.input, testCase.output) + } + +} + +func TestBold(t *testing.T) { + testCases := []struct { + input string + output string + }{ + { + "Test", + "*Test*", + }, + { + "\tTest ", + "*Test*", + }, + { + "\tTest line 1
    Test 2
    ", + "*Test line 1\nTest 2*", + }, + { + "Test Test", + "*Test* *Test*", + }, + } + + for _, testCase := range testCases { + assertString(t, testCase.input, testCase.output) + } + +} + +func TestDiv(t *testing.T) { + testCases := []struct { + input string + output string + }{ + { + "
    Test
    ", + "Test", + }, + { + "\t
    Test
    ", + "Test", + }, + { + "
    Test line 1
    Test 2
    ", + "Test line 1\nTest 2", + }, + { + "Test 1
    Test 2
    Test 3
    Test 4", + "Test 1\nTest 2\nTest 3\nTest 4", + }, + } + + for _, testCase := range testCases { + assertString(t, testCase.input, testCase.output) + } + +} + +func TestBlockquotes(t *testing.T) { + testCases := []struct { + input string + output string + }{ + { + "
    level 0
    level 1
    level 2
    level 1
    level 0
    ", + "level 0\n> \n> level 1\n> \n>> level 2\n> \n> level 1\n\nlevel 0", + }, + { + "
    Test
    Test", + "> \n> Test\n\nTest", + }, + { + "\t
    \nTest
    ", + "> \n> Test\n>", + }, + { + "\t
    \nTest line 1
    Test 2
    ", + "> \n> Test line 1\n> Test 2", + }, + { + "
    Test
    Test
    Other Test", + "> \n> Test\n\n> \n> Test\n\nOther Test", + }, + { + "
    Lorem ipsum Commodo id consectetur pariatur ea occaecat minim aliqua ad sit consequat quis ex commodo Duis incididunt eu mollit consectetur fugiat voluptate dolore in pariatur in commodo occaecat Ut occaecat velit esse labore aute quis commodo non sit dolore officia Excepteur cillum amet cupidatat culpa velit labore ullamco dolore mollit elit in aliqua dolor irure do
    ", + "> \n> Lorem ipsum Commodo id consectetur pariatur ea occaecat minim aliqua ad\n> sit consequat quis ex commodo Duis incididunt eu mollit consectetur fugiat\n> voluptate dolore in pariatur in commodo occaecat Ut occaecat velit esse\n> labore aute quis commodo non sit dolore officia Excepteur cillum amet\n> cupidatat culpa velit labore ullamco dolore mollit elit in aliqua dolor\n> irure do", + }, + { + "
    LoremipsumCommodoidconsecteturpariatureaoccaecatminimaliquaadsitconsequatquisexcommodoDuisincididunteumollitconsecteturfugiatvoluptatedoloreinpariaturincommodooccaecatUtoccaecatvelitesselaboreautequiscommodononsitdoloreofficiaExcepteurcillumametcupidatatculpavelitlaboreullamcodoloremollitelitinaliquadoloriruredo
    ", + "> \n> Lorem *ipsum* *Commodo* *id* *consectetur* *pariatur* *ea* *occaecat* *minim*\n> *aliqua* *ad* *sit* *consequat* *quis* *ex* *commodo* *Duis* *incididunt* *eu*\n> *mollit* *consectetur* *fugiat* *voluptate* *dolore* *in* *pariatur* *in* *commodo*\n> *occaecat* *Ut* *occaecat* *velit* *esse* *labore* *aute* *quis* *commodo*\n> *non* *sit* *dolore* *officia* *Excepteur* *cillum* *amet* *cupidatat* *culpa*\n> *velit* *labore* *ullamco* *dolore* *mollit* *elit* *in* *aliqua* *dolor* *irure*\n> *do*", + }, + } + + for _, testCase := range testCases { + assertString(t, testCase.input, testCase.output) + } + +} + +func TestIgnoreStylesScriptsHead(t *testing.T) { + testCases := []struct { + input string + output string + }{ + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + "", + "", + }, + { + `Title`, + "", + }, + } + + for _, testCase := range testCases { + assertString(t, testCase.input, testCase.output) + } +} + +func TestText(t *testing.T) { + testCases := []struct { + input string + expr string + }{ + { + `
  • + New repository +
  • `, + `\* New repository \( /new \)`, + }, + { + `hi + +
    + + hello google +

    + test

    List:

    + + +`, + `hi +hello google \( https://google.com \) + +test + +List: + +\* Foo \( foo \) +\* Barsoap \( http://www.microshwhat.com/bar/soapy \) +\* Baz`, + }, + // Malformed input html. + { + `hi + + hello google + + test

    List:

    + + + `, + `hi hello google \( https://google.com \) test + +List: + +\* Foo \( foo \) +\* Bar \( /\n[ \t]+bar/baz \) +\* Baz`, + }, + } + + for _, testCase := range testCases { + assertRegexp(t, testCase.input, testCase.expr) + } +} + +type StringMatcher interface { + MatchString(string) bool + String() string +} + +type RegexpStringMatcher string + +func (m RegexpStringMatcher) MatchString(str string) bool { + return regexp.MustCompile(string(m)).MatchString(str) +} +func (m RegexpStringMatcher) String() string { + return string(m) +} + +type ExactStringMatcher string + +func (m ExactStringMatcher) MatchString(str string) bool { + return string(m) == str +} +func (m ExactStringMatcher) String() string { + return string(m) +} + +func assertRegexp(t *testing.T, input string, outputRE string) { + assertPlaintext(t, input, RegexpStringMatcher(outputRE)) +} + +func assertString(t *testing.T, input string, output string) { + assertPlaintext(t, input, ExactStringMatcher(output)) +} + +func assertPlaintext(t *testing.T, input string, matcher StringMatcher) { + text, err := FromString(input) + if err != nil { + t.Error(err) + } + if !matcher.MatchString(text) { + t.Errorf("Input did not match expression\n"+ + "Input:\n>>>>\n%s\n<<<<\n\n"+ + "Output:\n>>>>\n%s\n<<<<\n\n"+ + "Expected output:\n>>>>\n%s\n<<<<\n\n", + input, text, matcher.String()) + } else { + t.Logf("input:\n\n%s\n\n\n\noutput:\n\n%s\n", input, text) + } +} + +func Example() { + inputHtml := ` + + + My Mega Service + + + + + + + +

    Welcome to your new account on my service!

    + +

    + Here is some more information: + +

    +

    + + + ` + + text, err := FromString(inputHtml) + if err != nil { + panic(err) + } + fmt.Println(text) + + // Output: + // Mega Service ( http://mymegaservice.com/ ) + // + // ****************************************** + // Welcome to your new account on my service! + // ****************************************** + // + // Here is some more information: + // + // * Link 1: Example.com ( https://example.com ) + // * Link 2: Example2.com ( https://example2.com ) + // * Something else +}