Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ endif
govet:
ifneq ($(HAS_SERVER),)
@echo Running govet
@# Workaroung because you can't install binaries without adding them to go.mod
@# Workaround because you can't install binaries without adding them to go.mod
env GO111MODULE=off $(GO) get golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow
$(GO) vet ./server/...
$(GO) vet -vettool=$(GOPATH)/bin/shadow ./server/...
Expand Down Expand Up @@ -154,7 +154,7 @@ endif

## Extract strings for translation from the source code.
.PHONY: i18n-extract
i18n-extract:
i18n-extract:
ifneq ($(HAS_WEBAPP),)
@[[ -d $(MM_UTILITIES_DIR) ]] || echo "You must clone github.com/mattermost/mattermost-utilities repo in .. to use this command"
@[[ -d $(MM_UTILITIES_DIR) ]] && cd $(MM_UTILITIES_DIR) && npm install && npm run babel && node mmjstool/build/index.js i18n extract-webapp --webapp-dir ../mattermost-plugin-demo/webapp
Expand Down
6 changes: 6 additions & 0 deletions plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@
"display_name": "Enable Private Repositories",
"type": "bool",
"help_text": "(Optional) Allow the plugin to work with private repositories. When enabled, existing users must reconnect their accounts to gain access to private repositories. Affected users will be notified by the plugin once private repositories are enabled."
},
{
"key": "EnableCodePreview",
"display_name": "Enable Code Previews",
"type": "bool",
"help_text": "(Optional) Allow the plugin to expand permalinks to github files with an actual preview of the linked file."
}
],
"footer": "* To report an issue, make a suggestion or a contribution, [check the repository](https://github.com/mattermost/mattermost-plugin-github)."
Expand Down
1 change: 1 addition & 0 deletions server/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ type configuration struct {
EnterpriseBaseURL string
EnterpriseUploadURL string
PluginsDirectory string
EnableCodePreview bool
}

// Clone shallow copies the configuration. Your implementation may require a deep copy if
Expand Down
2 changes: 1 addition & 1 deletion server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ import (
)

func main() {
plugin.ClientMain(&Plugin{})
plugin.ClientMain(NewPlugin())
}
149 changes: 149 additions & 0 deletions server/permalinks.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
package main

import (
"context"
"encoding/hex"
"strings"
"time"

"github.com/google/go-github/v25/github"
)

// maxPermalinkReplacements sets the maximum limit to the number of
// permalink replacements that can be performed on a single message.
const maxPermalinkReplacements = 10
Comment thread
agnivade marked this conversation as resolved.
Resolved

const permalinkReqTimeout = 5 * time.Second

// maxPreviewLines sets the maximum number of preview lines that will be shown
// while replacing a permalink.
const maxPreviewLines = 10

// permalinkLineContext shows the number of lines before and after to show
// if the link points to a single line.
const permalinkLineContext = 3

// replacement holds necessary info to replace github permalinks
// in messages with a code preview block.
type replacement struct {
index int // index of the permalink in the string
word string // the permalink
permalinkInfo struct { // holds the necessary metadata of a permalink
haswww string
commit string
user string
repo string
path string
line string
}
}

// getReplacements returns the permalink replacements that needs to be performed
// on a message. The returned slice is sorted by the index in ascending order.
func (p *Plugin) getReplacements(msg string) []replacement {
// find the permalinks from the msg using a regex
matches := p.githubPermalinkRegex.FindAllStringSubmatch(msg, -1)
indices := p.githubPermalinkRegex.FindAllStringIndex(msg, -1)
var replacements []replacement
for i, m := range matches {
// have a limit on the number of replacements to do
if i > maxPermalinkReplacements {
break
}
word := m[0]
index := indices[i][0]
r := replacement{
index: index,
word: word,
}
// ignore if the word is inside a link
if isInsideLink(msg, index) {
continue
}
// populate the permalinkInfo with the extracted groups of the regex
for j, name := range p.githubPermalinkRegex.SubexpNames() {
if j == 0 {
continue
}
switch name {
case "haswww":
r.permalinkInfo.haswww = m[j]
case "user":
r.permalinkInfo.user = m[j]
case "repo":
r.permalinkInfo.repo = m[j]
case "commit":
r.permalinkInfo.commit = m[j]
case "path":
r.permalinkInfo.path = m[j]
case "line":
r.permalinkInfo.line = m[j]
}
}
replacements = append(replacements, r)
}
return replacements
}

// makeReplacements perform the given replacements on the msg and returns
// the new msg. The replacements slice needs to be sorted by the index in ascending order.
func (p *Plugin) makeReplacements(msg string, replacements []replacement, ghClient *github.Client) string {
// iterating the slice in reverse to preserve the replacement indices.
for i := len(replacements) - 1; i >= 0; i-- {
r := replacements[i]
// quick bailout if the commit hash is not proper.
if _, err := hex.DecodeString(r.permalinkInfo.commit); err != nil {
p.API.LogError("bad git commit hash in permalink", "error", err.Error(), "hash", r.permalinkInfo.commit)
continue
}

// get the file contents
opts := github.RepositoryContentGetOptions{
Ref: r.permalinkInfo.commit,
}
// TODO: make all of these requests concurrently.
reqctx, cancel := context.WithTimeout(context.Background(), permalinkReqTimeout)
fileContent, _, _, err := ghClient.Repositories.GetContents(reqctx,
Comment thread
agnivade marked this conversation as resolved.
Resolved
r.permalinkInfo.user, r.permalinkInfo.repo, r.permalinkInfo.path, &opts)
defer cancel()
if err != nil {
p.API.LogError("error while fetching file contents", "error", err.Error(), "path", r.permalinkInfo.path)
continue
}
// this is not a file, ignore.
if fileContent == nil {
p.API.LogWarn("permalink is not a file", "file", r.permalinkInfo.path)
continue
}
decoded, err := fileContent.GetContent()
if err != nil {
p.API.LogError("error while decoding file contents", "error", err.Error(), "path", r.permalinkInfo.path)
continue
}

// get the required lines.
start, end := getLineNumbers(r.permalinkInfo.line)
// bad anchor tag, ignore.
if start == -1 || end == -1 {
continue
}
isTruncated := false
if end-start > maxPreviewLines {
end = start + maxPreviewLines
isTruncated = true
Comment thread
agnivade marked this conversation as resolved.
Resolved
}
lines, err := filterLines(decoded, start, end)
if err != nil {
p.API.LogError("error while filtering lines", "error", err.Error(), "path", r.permalinkInfo.path)
}
if lines == "" {
p.API.LogError("line numbers out of range. Skipping.", "file", r.permalinkInfo.path, "start", start, "end", end)
continue
}
final := getCodeMarkdown(r.permalinkInfo.user, r.permalinkInfo.repo, r.permalinkInfo.path, r.word, lines, isTruncated)

// replace word in msg starting from r.index only once.
msg = msg[:r.index] + strings.Replace(msg[r.index:], r.word, final, 1)
Comment thread
agnivade marked this conversation as resolved.
Resolved
}
return msg
}
Loading