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

Add index list command #537

Merged
merged 7 commits into from
Mar 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
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
62 changes: 62 additions & 0 deletions cmd/krew/cmd/index.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright 2019 The Kubernetes Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
"os"

"github.com/pkg/errors"
"github.com/spf13/cobra"

"sigs.k8s.io/krew/internal/index/indexoperations"
"sigs.k8s.io/krew/pkg/constants"
)

// indexCmd represents the index command
var indexCmd = &cobra.Command{
Use: "index",
Short: "Manage custom plugin indexes",
Long: "Manage which repositories are used to discover and install plugins from.",
Args: cobra.NoArgs,
Hidden: true, // TODO(chriskim06) remove this once multi-index is enabled
}

var indexListCmd = &cobra.Command{
Use: "list",
Short: "List configured indexes",
Long: `Print a list of configured indexes.

This command prints a list of indexes. It shows the name and the remote URL for
each configured index in table format.`,
Args: cobra.NoArgs,
RunE: func(_ *cobra.Command, _ []string) error {
indexes, err := indexoperations.ListIndexes(paths.IndexBase())
if err != nil {
return errors.Wrap(err, "failed to list indexes")
}
var rows [][]string
for _, index := range indexes {
rows = append(rows, []string{index.Name, index.URL})
}
return printTable(os.Stdout, []string{"INDEX", "URL"}, rows)
},
}

func init() {
if _, ok := os.LookupEnv(constants.EnableMultiIndexSwitch); ok {
indexCmd.AddCommand(indexListCmd)
rootCmd.AddCommand(indexCmd)
}
}
20 changes: 13 additions & 7 deletions internal/gitutil/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ func EnsureCloned(uri, destinationPath string) error {
if ok, err := IsGitCloned(destinationPath); err != nil {
return err
} else if !ok {
return exec("", "clone", "-v", uri, destinationPath)
_, err = Exec("", "clone", "-v", uri, destinationPath)
return err
}
return nil
}
Expand All @@ -49,15 +50,15 @@ func IsGitCloned(gitPath string) (bool, error) {
// and also will create a pristine working directory by removing
// untracked files and directories.
func updateAndCleanUntracked(destinationPath string) error {
if err := exec(destinationPath, "fetch", "-v"); err != nil {
if _, err := Exec(destinationPath, "fetch", "-v"); err != nil {
return errors.Wrapf(err, "fetch index at %q failed", destinationPath)
}

if err := exec(destinationPath, "reset", "--hard", "@{upstream}"); err != nil {
if _, err := Exec(destinationPath, "reset", "--hard", "@{upstream}"); err != nil {
return errors.Wrapf(err, "reset index at %q failed", destinationPath)
}

err := exec(destinationPath, "clean", "-xfd")
_, err := Exec(destinationPath, "clean", "-xfd")
return errors.Wrapf(err, "clean index at %q failed", destinationPath)
}

Expand All @@ -69,7 +70,12 @@ func EnsureUpdated(uri, destinationPath string) error {
return updateAndCleanUntracked(destinationPath)
}

func exec(pwd string, args ...string) error {
// GetRemoteURL returns the url of the remote origin
func GetRemoteURL(dir string) (string, error) {
return Exec(dir, "config", "--get", "remote.origin.url")
}

func Exec(pwd string, args ...string) (string, error) {
klog.V(4).Infof("Going to run git %s", strings.Join(args, " "))
cmd := osexec.Command("git", args...)
cmd.Dir = pwd
Expand All @@ -80,7 +86,7 @@ func exec(pwd string, args ...string) error {
}
cmd.Stdout, cmd.Stderr = w, w
if err := cmd.Run(); err != nil {
return errors.Wrapf(err, "command execution failure, output=%q", buf.String())
return "", errors.Wrapf(err, "command execution failure, output=%q", buf.String())
}
return nil
return strings.TrimSpace(buf.String()), nil
}
54 changes: 54 additions & 0 deletions internal/index/indexoperations/index.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Copyright 2019 The Kubernetes Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package indexoperations

import (
"io/ioutil"
"path/filepath"

"github.com/pkg/errors"

"sigs.k8s.io/krew/internal/gitutil"
)

// Index describes the name and URL of a configured index.
type Index struct {
Name string
URL string
}

// ListIndexes returns a slice of Index objects. The path argument is used as
// the base path of the index.
func ListIndexes(path string) ([]Index, error) {
dirs, err := ioutil.ReadDir(path)
if err != nil {
return nil, errors.Wrapf(err, "failed to read directory %s", path)
}

indexes := []Index{}
for _, dir := range dirs {
indexName := dir.Name()
remote, err := gitutil.GetRemoteURL(filepath.Join(path, indexName))
if err != nil {
return nil, errors.Wrapf(err, "failed to list the remote URL for index %s", indexName)
}

indexes = append(indexes, Index{
Name: indexName,
URL: remote,
})
}
return indexes, nil
}
66 changes: 66 additions & 0 deletions internal/index/indexoperations/index_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Copyright 2019 The Kubernetes Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package indexoperations

import (
"os"
"path/filepath"
"testing"

"github.com/google/go-cmp/cmp"

"sigs.k8s.io/krew/internal/environment"
"sigs.k8s.io/krew/internal/gitutil"
"sigs.k8s.io/krew/internal/testutil"
)

func TestListIndexes(t *testing.T) {
tmpDir, cleanup := testutil.NewTempDir(t)
defer cleanup()

wantIndexes := []Index{
{
Name: "custom",
URL: "https://github.com/custom/index.git",
},
{
Name: "default",
URL: "https://github.com/default/index.git",
},
}

for _, index := range wantIndexes {
path := tmpDir.Path("index/" + index.Name)
if err := os.MkdirAll(path, os.ModePerm); err != nil {
t.Fatalf("cannot create directory %q: %s", filepath.Dir(path), err)
}
_, err := gitutil.Exec(path, "init")
if err != nil {
t.Fatalf("error initializing git repo: %s", err)
}
_, err = gitutil.Exec(path, "remote", "add", "origin", index.URL)
if err != nil {
t.Fatalf("error setting remote origin: %s", err)
}
}

gotIndexes, err := ListIndexes(environment.NewPaths(tmpDir.Root()).IndexBase())
if err != nil {
t.Errorf("error listing indexes: %v", err)
}
if diff := cmp.Diff(wantIndexes, gotIndexes); diff != "" {
t.Errorf("output does not match: %s", diff)
}
}