Skip to content

Commit

Permalink
Merge pull request #14 from rneatherway/links
Browse files Browse the repository at this point in the history
Convert <a|b> links to markdown
  • Loading branch information
rneatherway authored Jul 1, 2022
2 parents ca7974f + 4d9656c commit 4b84ef1
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 8 deletions.
29 changes: 21 additions & 8 deletions internal/markdown/markdown.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
)

var userRE = regexp.MustCompile("<@[A-Z0-9]+>")
var linkRE = regexp.MustCompile(`<(https?://[^|>]+)\|([^>]+)>`)

type UserProvider interface {
UsernameForID(string) (string, error)
Expand Down Expand Up @@ -60,6 +61,22 @@ func parseUnixTimestamp(s string) (*time.Time, error) {
return &result, nil
}

func convert(client UserProvider, b *strings.Builder, s string) error {
text, err := interpolateUsers(client, s)
if err != nil {
return err
}

text = linkRE.ReplaceAllString(text, "[$2]($1)")

for _, line := range strings.Split(text, "\n") {
// TODO: Might be a good idea to escape 'line'
fmt.Fprintf(b, "> %s\n", line)
}

return nil
}

func FromMessages(client *slackclient.SlackClient, history *slackclient.HistoryResponse) (string, error) {
b := &strings.Builder{}
messages := history.Messages
Expand Down Expand Up @@ -101,21 +118,17 @@ func FromMessages(client *slackclient.SlackClient, history *slackclient.HistoryR
msgTimes[message.Ts].Format("2006-01-02 15:04"))

if message.Text != "" {
text, err := interpolateUsers(client, message.Text)
err = convert(client, b, message.Text)
if err != nil {
return "", err
}

for _, line := range strings.Split(text, "\n") {
// TODO: Might be a good idea to escape 'line'
fmt.Fprintf(b, "> %s\n", line)
}
}

// These seem to be mostly bot messages so far. Perhaps we should just skip them?
for _, a := range message.Attachments {
for _, line := range strings.Split(a.Text, "\n") {
fmt.Fprintf(b, "> %s\n", line)
err = convert(client, b, a.Text)
if err != nil {
return "", err
}
}

Expand Down
17 changes: 17 additions & 0 deletions internal/markdown/markdown_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,20 @@ func TestInterpolateUsers(t *testing.T) {
}
}
}

func TestLinkify(t *testing.T) {
table := [][]string{
{"Hello <https://example.com|text> end", "Hello [text](https://example.com) end"},
{"Hello <https://example.com|text> end and here is another link <http://github.com|GitHub!!> go check it out", "Hello [text](https://example.com) end and here is another link [GitHub!!](http://github.com) go check it out"},
}

for _, test := range table {
input := test[0]
expected := test[1]
actual := linkRE.ReplaceAllString(input, "[$2]($1)")

if actual != expected {
t.Errorf("expected %q, actual %q", expected, actual)
}
}
}

0 comments on commit 4b84ef1

Please sign in to comment.