Skip to content

Commit

Permalink
Add hyperlink template function (#72)
Browse files Browse the repository at this point in the history
Relates to cli/cli#6179
  • Loading branch information
heaths authored Sep 19, 2022
1 parent a7df5ee commit 802b578
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
10 changes: 10 additions & 0 deletions pkg/template/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ func (t *Template) Parse(tmpl string) error {
templateFuncs := map[string]interface{}{
"autocolor": colorFunc,
"color": colorFunc,
"hyperlink": hyperlinkFunc,
"join": joinFunc,
"pluck": pluckFunc,
"tablerender": func() (string, error) {
Expand Down Expand Up @@ -233,3 +234,12 @@ func truncateMultiline(maxWidth int, s string) string {
}
return text.Truncate(maxWidth, s)
}

func hyperlinkFunc(link, text string) string {
if text == "" {
text = link
}

// See https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
return fmt.Sprintf("\x1b]8;;%s\x1b\\%s\x1b]8;;\x1b\\", link, text)
}
16 changes: 16 additions & 0 deletions pkg/template/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,22 @@ func TestExecute(t *testing.T) {
},
wantErr: true,
},
{
name: "hyperlink enabled",
args: args{
json: strings.NewReader(`{"link":"https://github.com"}`),
template: `{{ hyperlink .link "" }}`,
},
wantW: "\x1b]8;;https://github.com\x1b\\https://github.com\x1b]8;;\x1b\\",
},
{
name: "hyperlink with text enabled",
args: args{
json: strings.NewReader(`{"link":"https://github.com","text":"GitHub"}`),
template: `{{ hyperlink .link .text }}`,
},
wantW: "\x1b]8;;https://github.com\x1b\\GitHub\x1b]8;;\x1b\\",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down

0 comments on commit 802b578

Please sign in to comment.