Skip to content

Commit

Permalink
simplify the EncodePath method
Browse files Browse the repository at this point in the history
The results of the old code were a bit different but this version is
still compliant to the webdav rfc:
https://datatracker.ietf.org/doc/html/rfc4918#section-8.3.1.
It is also a whole lot faster.
  • Loading branch information
David Christofas committed Apr 4, 2022
1 parent 9f90ce1 commit 7763278
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 30 deletions.
30 changes: 1 addition & 29 deletions internal/http/services/owncloud/ocdav/net/net.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@
package net

import (
"fmt"
"net/url"
"regexp"
"strings"

"github.com/pkg/errors"
Expand Down Expand Up @@ -69,37 +67,11 @@ func (d Depth) String() string {
return string(d)
}

// replaceAllStringSubmatchFunc is taken from 'Go: Replace String with Regular Expression Callback'
// see: https://elliotchance.medium.com/go-replace-string-with-regular-expression-callback-f89948bad0bb
func replaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func([]string) string) string {
result := ""
lastIndex := 0
for _, v := range re.FindAllSubmatchIndex([]byte(str), -1) {
groups := []string{}
for i := 0; i < len(v); i += 2 {
groups = append(groups, str[v[i]:v[i+1]])
}
result += str[lastIndex:v[0]] + repl(groups)
lastIndex = v[1]
}
return result + str[lastIndex:]
}

var hrefre = regexp.MustCompile(`([^A-Za-z0-9_\-.~()/:@!$])`)

// EncodePath encodes the path of a url.
//
// slashes (/) are treated as path-separators.
// ported from https://github.com/sabre-io/http/blob/bb27d1a8c92217b34e778ee09dcf79d9a2936e84/lib/functions.php#L369-L379
func EncodePath(path string) string {
return replaceAllStringSubmatchFunc(hrefre, path, func(groups []string) string {
b := groups[1]
var sb strings.Builder
for i := 0; i < len(b); i++ {
sb.WriteString(fmt.Sprintf("%%%x", b[i]))
}
return sb.String()
})
return (&url.URL{Path: path}).EscapedPath()
}

// ParseDepth parses the depth header value defined in https://tools.ietf.org/html/rfc4918#section-9.1
Expand Down
2 changes: 1 addition & 1 deletion internal/http/services/owncloud/ocdav/net/net_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ var _ = Describe("Net", func() {
Describe("EncodePath", func() {
It("encodes paths", func() {
Expect(net.EncodePath("foo")).To(Equal("foo"))
Expect(net.EncodePath("/some/path/Folder %^*(#1)")).To(Equal("/some/path/Folder%20%25%5e%2a(%231)"))
Expect(net.EncodePath("/some/path/Folder %^*(#1)")).To(Equal("/some/path/Folder%20%25%5E%2A%28%231%29"))
})

/*
Expand Down

0 comments on commit 7763278

Please sign in to comment.