forked from andreaskoch/allmark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rewritelinks.go
66 lines (50 loc) · 1.53 KB
/
rewritelinks.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright 2015 Andreas Koch. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package postprocessor
import (
"github.com/andreaskoch/allmark/common/paths"
"github.com/andreaskoch/allmark/common/route"
"github.com/andreaskoch/allmark/model"
"fmt"
"regexp"
"strings"
)
var (
htmlLinkPattern = regexp.MustCompile(`(src|href)="([^"]+)"`)
)
func rewireLinks(pathProvider paths.Pather, base route.Route, files []*model.File, html string) string {
allMatches := htmlLinkPattern.FindAllStringSubmatch(html, -1)
for _, matches := range allMatches {
if len(matches) != 3 {
continue
}
// components
originalText := strings.TrimSpace(matches[0])
linkType := strings.TrimSpace(matches[1])
filePath := strings.TrimSpace(matches[2])
fileRoute := route.Combine(base, route.NewFromRequest(filePath))
path := fileRoute.Value()
// get matching file
matchingFile := getMatchingFiles(path, files)
// skip if no matching files are found
if matchingFile == nil {
continue
}
// assemble the new link path
matchingFilePath := pathProvider.Path(matchingFile.Route().Value())
// assemble the new link
newLinkText := fmt.Sprintf("%s=\"%s\"", linkType, matchingFilePath)
// replace the old text
html = strings.Replace(html, originalText, newLinkText, -1)
}
return html
}
func getMatchingFiles(path string, files []*model.File) *model.File {
for _, file := range files {
if file.Route().IsMatch(path) {
return file
}
}
return nil
}