Repository: knative-sandbox/kn-plugin-func
Pull request #1249 (2022-09-14 20:38:31)

fix: wrong-error-message-reported-in-command-func-templates-repository
Fixes: https://github.com/knative-sandbox/kn-plugin-func/issues/1206
```release-notes
fixes a bug in the display of repository urls in the event of an error
```

knative-prow[bot]: [APPROVALNOTIFIER] This PR is **NOT APPROVED**

This pull-request has been approved by: *<a href="https://github.com/knative-sandbox/kn-plugin-func/pull/1249#" title="Author self-approved">grafvonb</a>*
**Once this PR has been reviewed and has the lgtm label**, please assign navidshaikh for approval by writing `/assign @navidshaikh` in a comment. For more information see:[The Kubernetes Code Review Process](https://git.k8s.io/community/contributors/guide/owners.md#the-code-review-process).

The full list of commands accepted by this bot can be found [here](https://go.k8s.io/bot-commands?repo=knative-sandbox%2Fkn-plugin-func).

<details open>
Needs approval from an approver in each of these files:

- **[OWNERS](https://github.com/knative-sandbox/kn-plugin-func/blob/main/OWNERS)**

Approvers can indicate their approval by writing `/approve` in a comment
Approvers can cancel approval by writing `/approve cancel` in a comment
</details>
<!-- META={"approvers":["navidshaikh"]} -->
codecov[bot]: # [Codecov](https://codecov.io/gh/knative-sandbox/kn-plugin-func/pull/1249?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative-sandbox) Report
> Merging [#1249](https://codecov.io/gh/knative-sandbox/kn-plugin-func/pull/1249?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative-sandbox) (d41121d) into [main](https://codecov.io/gh/knative-sandbox/kn-plugin-func/commit/155b6f158f7c0360b7c80fc52e8f297661ff616f?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative-sandbox) (155b6f1) will **decrease** coverage by `0.01%`.
> The diff coverage is `66.66%`.

```diff
@@            Coverage Diff             @@
##             main    #1249      +/-   ##
==========================================
- Coverage   46.38%   46.37%   -0.02%     
==========================================
  Files          71       71              
  Lines       10029    10038       +9     
==========================================
+ Hits         4652     4655       +3     
- Misses       4975     4979       +4     
- Partials      402      404       +2     
```


| [Impacted Files](https://codecov.io/gh/knative-sandbox/kn-plugin-func/pull/1249?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative-sandbox) | Coverage Δ | |
|---|---|---|
| [cmd/client.go](https://codecov.io/gh/knative-sandbox/kn-plugin-func/pull/1249/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative-sandbox#diff-Y21kL2NsaWVudC5nbw==) | `78.82% <ø> (ø)` | |
| [cmd/templates.go](https://codecov.io/gh/knative-sandbox/kn-plugin-func/pull/1249/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative-sandbox#diff-Y21kL3RlbXBsYXRlcy5nbw==) | `81.50% <66.66%> (-0.98%)` | :arrow_down: |
| [s2i/builder.go](https://codecov.io/gh/knative-sandbox/kn-plugin-func/pull/1249/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative-sandbox#diff-czJpL2J1aWxkZXIuZ28=) | `61.04% <0.00%> (-1.21%)` | :arrow_down: |

Help us with your feedback. Take ten seconds to tell us [how you rate us](https://about.codecov.io/nps?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative-sandbox). Have a feature suggestion? [Share it here.](https://app.codecov.io/gh/feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative-sandbox)

grafvonb: @lance ready for review 
salaboy: this looks good to me, but I guess that we will wait for @lance blessing on this one
lkingland: /lgtm
knative-prow[bot]: [APPROVALNOTIFIER] This PR is **APPROVED**

This pull-request has been approved by: *<a href="https://github.com/knative-sandbox/kn-plugin-func/pull/1249#" title="Author self-approved">grafvonb</a>*, *<a href="https://github.com/knative-sandbox/kn-plugin-func/pull/1249#pullrequestreview-1112185497" title="LGTM">lkingland</a>*

The full list of commands accepted by this bot can be found [here](https://go.k8s.io/bot-commands?repo=knative-sandbox%2Fkn-plugin-func).

The pull request process is described [here](https://git.k8s.io/community/contributors/guide/owners.md#the-code-review-process)

<details >
Needs approval from an approver in each of these files:

- ~~[OWNERS](https://github.com/knative-sandbox/kn-plugin-func/blob/main/OWNERS)~~ [lkingland]

Approvers can indicate their approval by writing `/approve` in a comment
Approvers can cancel approval by writing `/approve cancel` in a comment
</details>
<!-- META={"approvers":[]} -->

Patch:
diff --git a/cmd/client.go b/cmd/client.go
index 039a804d..97b20476 100644
--- a/cmd/client.go
+++ b/cmd/client.go
@@ -34,7 +34,7 @@ type ClientConfig struct {
 // for use by commands.
 // See the NewClient constructor which is the fully populated ClientFactory used
 // by commands by default.
-// See NewClientFactory which constructs a minimal CientFactory for use
+// See NewClientFactory which constructs a minimal ClientFactory for use
 // during testing.
 type ClientFactory func(ClientConfig, ...fn.Option) (*fn.Client, func())
 
@@ -52,7 +52,7 @@ func NewClientFactory(n func() *fn.Client) ClientFactory {
 // NewClient constructs an fn.Client with the majority of
 // the concrete implementations set.  Provide additional Options to this constructor
 // to override or augment as needed, or override the ClientFactory passed to
-// commands entirely to mock for testing. Note the reutrned cleanup function.
+// commands entirely to mock for testing. Note the returned cleanup function.
 // 'Namespace' is optional.  If not provided (see DefaultNamespace commentary),
 // the currently configured is used.
 // 'Verbose' indicates the system should write out a higher amount of logging.
diff --git a/cmd/templates.go b/cmd/templates.go
index d7b1174d..c0829426 100644
--- a/cmd/templates.go
+++ b/cmd/templates.go
@@ -4,6 +4,7 @@ import (
 	"encoding/json"
 	"errors"
 	"fmt"
+	"net/http"
 	"os"
 	"strings"
 	"text/tabwriter"
@@ -14,6 +15,9 @@ import (
 	fn "knative.dev/kn-plugin-func"
 )
 
+// ErrTemplateRepoDoesNotExist is a sentinel error if a template repository responds with 404 status code
+var ErrTemplateRepoDoesNotExist = errors.New("template repo does not exist")
+
 func NewTemplatesCmd(newClient ClientFactory) *cobra.Command {
 	cmd := &cobra.Command{
 		Use:   "templates",
@@ -60,7 +64,7 @@ EXAMPLES
 		PreRunE: bindEnv("json", "repository"),
 	}
 
-	cmd.Flags().BoolP("json", "", false, "Set output to JSON format. (Env: $FUNC_JSON)")
+	cmd.Flags().Bool("json", false, "Set output to JSON format. (Env: $FUNC_JSON)")
 	cmd.Flags().StringP("repository", "r", "", "URI to a specific repository to consider (Env: $FUNC_REPOSITORY)")
 
 	cmd.SetHelpFunc(defaultTemplatedHelp)
@@ -79,13 +83,25 @@ func runTemplates(cmd *cobra.Command, args []string, newClient ClientFactory) (e
 		return
 	}
 
+	// Simple ping to the repo to avoid subsequent errors from http package if it does not exist
+	if cfg.Repository != "" {
+		res, err := http.Get(cfg.Repository)
+		if err != nil {
+			return err
+		}
+		defer res.Body.Close()
+		if res.StatusCode == http.StatusNotFound {
+			return ErrTemplateRepoDoesNotExist
+		}
+	}
+
 	// Client which will provide data
 	client, done := newClient(ClientConfig{Verbose: cfg.Verbose},
 		fn.WithRepository(cfg.Repository),             // Use exactly this repo OR
 		fn.WithRepositoriesPath(cfg.RepositoriesPath)) // Path on disk to installed repos
 	defer done()
 
-	// For a singl language runtime
+	// For a single language runtime
 	// -------------------
 	if len(args) == 1 {
 		templates, err := client.Templates().List(args[0])
@@ -105,7 +121,7 @@ func runTemplates(cmd *cobra.Command, args []string, newClient ClientFactory) (e
 		}
 		return nil
 	} else if len(args) > 1 {
-		return errors.New("unexpected extra arguments.")
+		return errors.New("unexpected extra arguments")
 	}
 
 	// All language runtimes


Test patch:
diff --git a/cmd/templates_test.go b/cmd/templates_test.go
index 3ff10fa1..b1da35d9 100644
--- a/cmd/templates_test.go
+++ b/cmd/templates_test.go
@@ -1,8 +1,11 @@
 package cmd
 
 import (
+	"errors"
 	"testing"
 
+	"gotest.tools/v3/assert"
+
 	fn "knative.dev/kn-plugin-func"
 	. "knative.dev/kn-plugin-func/testing"
 )
@@ -140,3 +143,24 @@ http`
 	}
 
 }
+
+func TestTemplates_ErrTemplateRepoDoesNotExist(t *testing.T) {
+	defer t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+	cmd := NewTemplatesCmd(NewClientFactory(func() *fn.Client {
+		return fn.New()
+	}))
+	cmd.SetArgs([]string{"--repository", "https://github.com/boson-project/repo-does-not-exist"})
+	err := cmd.Execute()
+	assert.Assert(t, err != nil)
+	assert.Assert(t, errors.Is(err, ErrTemplateRepoDoesNotExist))
+}
+
+func TestTemplates_WrongRepositoryUrl(t *testing.T) {
+	defer t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+	cmd := NewTemplatesCmd(NewClientFactory(func() *fn.Client {
+		return fn.New()
+	}))
+	cmd.SetArgs([]string{"--repository", "wrong://github.com/boson-project/repo-does-not-exist"})
+	err := cmd.Execute()
+	assert.Assert(t, err != nil)
+}