Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HCL relative_url() function #361

Merged
merged 10 commits into from
Oct 28, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions eval/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,7 @@ func newFunctionsMap() map[string]function.Function {
"json_decode": stdlib.JSONDecodeFunc,
"json_encode": stdlib.JSONEncodeFunc,
"merge": lib.MergeFunc,
"relative_url": lib.RelativeUrlFunc,
"to_lower": stdlib.LowerFunc,
"to_upper": stdlib.UpperFunc,
"unixtime": lib.UnixtimeFunc,
Expand Down
50 changes: 50 additions & 0 deletions eval/lib/relative_url.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package lib
johakoch marked this conversation as resolved.
Show resolved Hide resolved

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

"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
)

var (
// https://datatracker.ietf.org/doc/html/rfc3986#page-50
regexParseURL = regexp.MustCompile(`^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?`)
RelativeUrlFunc = newRelativeUrlFunction()
)

func newRelativeUrlFunction() function.Function {
return function.New(&function.Spec{
Params: []function.Parameter{{
Name: "s",
Type: cty.String,
}},
Type: function.StaticReturnType(cty.String),
Impl: func(args []cty.Value, _ cty.Type) (ret cty.Value, err error) {
absURL := strings.TrimSpace(args[0].AsString())

if !strings.HasPrefix(absURL, "/") && !strings.HasPrefix(absURL, "http://") && !strings.HasPrefix(absURL, "https://") {
return cty.StringVal(""), fmt.Errorf("invalid url given: '%s'", absURL)
johakoch marked this conversation as resolved.
Show resolved Hide resolved
}

// Do not use the result of url.ParseRequestURI() above,
// to preserve the URL encoding, e.g. in the query.
if _, err := url.Parse(absURL); err != nil {
return cty.StringVal(""), err
}

// The regexParseURL garanties the len of 10 in the result.
urlParts := regexParseURL.FindStringSubmatch(absURL)
johakoch marked this conversation as resolved.
Show resolved Hide resolved

// The path must begin w/ a slash.
if !strings.HasPrefix(urlParts[5], "/") {
urlParts[5] = "/" + urlParts[5]
}

return cty.StringVal(urlParts[5] + urlParts[6] + urlParts[8]), nil
},
})
}