Skip to content

Commit 4be7678

Browse files
authored
adds autoload of registries list and pull registry (#19)
with this commit the cli when run will auto create a default registry list if one does not exist it will also pull down all configured registry files in the list if none yet are pulled. [#16]
1 parent f8f15e2 commit 4be7678

File tree

6 files changed

+144
-23
lines changed

6 files changed

+144
-23
lines changed

internal/commands/pull.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"io/ioutil"
77

88
"github.com/open-policy-agent/conftest/downloader"
9+
"github.com/policy-hub/policy-hub-cli/pkg/helpers"
910
"github.com/policy-hub/policy-hub-cli/pkg/metaconfig"
1011
"github.com/spf13/cobra"
1112
)
@@ -20,7 +21,7 @@ func newPullCommand() *cobra.Command {
2021
},
2122
}
2223

23-
cmd.Flags().StringVarP(&c.Repository, "repository", "r", "metadata/registries.yml", "Location of the repository to search.")
24+
cmd.Flags().StringVarP(&c.Repository, "repository", "r", helpers.DefaultMetaDataFile(), "Location of the repository to search.")
2425

2526
return cmd
2627
}

internal/commands/search.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"io/ioutil"
66
"os"
77

8+
"github.com/policy-hub/policy-hub-cli/pkg/helpers"
89
"github.com/policy-hub/policy-hub-cli/pkg/metaconfig"
910
"github.com/policy-hub/policy-hub-cli/pkg/search"
1011
"github.com/spf13/cobra"
@@ -20,7 +21,7 @@ func newSearchCommand() *cobra.Command {
2021
},
2122
}
2223

23-
cmd.Flags().StringVarP(&c.Repository, "repository", "r", "metadata/registries.yml", "Location of the repository to search.")
24+
cmd.Flags().StringVarP(&c.Repository, "repository", "r", helpers.DefaultMetaDataFile(), "Location of the repository to search.")
2425

2526
return cmd
2627
}
@@ -37,7 +38,7 @@ func (c *searchConfig) run(query string) error {
3738

3839
e, err := search.Load()
3940
defer e.Close()
40-
41+
4142
if err != nil {
4243
return fmt.Errorf("load engine: %w", err)
4344
}

main.go

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,77 @@
11
package main
22

33
import (
4+
"context"
5+
"io"
6+
"io/ioutil"
7+
"log"
48
"os"
9+
"path/filepath"
10+
"strings"
511

12+
"github.com/open-policy-agent/conftest/downloader"
613
"github.com/policy-hub/policy-hub-cli/internal/commands"
14+
"github.com/policy-hub/policy-hub-cli/pkg/helpers"
715
)
816

17+
func init() {
18+
checkCreateDir()
19+
checkCreateRegistriesList()
20+
checkCreateRegistriesMetadata()
21+
}
22+
923
func main() {
1024
if err := commands.NewRootCommand().Execute(); err != nil {
1125
os.Exit(1)
1226
}
1327
}
28+
29+
func checkCreateRegistriesMetadata() {
30+
metadataPath := helpers.MetadataConfigPath()
31+
_, err := os.Stat(metadataPath)
32+
if os.IsNotExist(err) {
33+
34+
registriesListPath := filepath.ToSlash(
35+
filepath.Join(helpers.ConfigPath(), helpers.PolicyRegistryFilename))
36+
content, err := ioutil.ReadFile(registriesListPath)
37+
if err != nil {
38+
log.Panic("could not read registries list file: %w", err)
39+
}
40+
41+
lines := strings.Split(string(content), "\n")
42+
err = downloader.Download(context.Background(), metadataPath, lines)
43+
if err != nil {
44+
log.Panic("could not fetch metadata file: %w", err)
45+
}
46+
}
47+
}
48+
49+
func checkCreateRegistriesList() {
50+
configPath := helpers.ConfigPath()
51+
registriesListPath := filepath.ToSlash(
52+
filepath.Join(configPath, helpers.PolicyRegistryFilename))
53+
54+
_, err := os.Stat(registriesListPath)
55+
if os.IsNotExist(err) {
56+
file, err := os.Create(registriesListPath)
57+
defer file.Close()
58+
if err != nil {
59+
log.Panic("could not create file: %w", err)
60+
}
61+
62+
_, err = io.WriteString(file, helpers.RegistryListDefault)
63+
if err != nil {
64+
log.Panic("could not write to file: %w", err)
65+
}
66+
67+
file.Sync()
68+
}
69+
}
70+
71+
func checkCreateDir() {
72+
configPath := helpers.ConfigPath()
73+
_, err := os.Stat(configPath)
74+
if os.IsNotExist(err) {
75+
os.MkdirAll(configPath, os.ModePerm)
76+
}
77+
}

main_test.go

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,13 @@ import (
44
"bytes"
55
"os"
66
"os/exec"
7+
"path/filepath"
78
"testing"
89
"time"
910

1011
"github.com/onsi/gomega"
1112
"github.com/onsi/gomega/gexec"
13+
"github.com/policy-hub/policy-hub-cli/pkg/helpers"
1214
"github.com/stretchr/testify/assert"
1315
)
1416

@@ -17,9 +19,11 @@ func TestMainCLI(t *testing.T) {
1719
pathToMainCLI, err := gexec.Build("main.go")
1820
assert.NoError(t, err, "Error creating binary")
1921
defer gexec.CleanupBuildArtifacts()
22+
defer os.RemoveAll(helpers.IndexPath())
23+
defer os.RemoveAll(helpers.ConfigPath())
2024

2125
t.Run("we can search registries", func(t *testing.T) {
22-
command := exec.Command(pathToMainCLI, "search", "k8s", "-r", "./metadata/registries.yml")
26+
command := exec.Command(pathToMainCLI, "search", "k8s")
2327
session, err := gexec.Start(command, os.Stdout, os.Stdout)
2428
session.Wait()
2529
assert.NoError(t, err, "Error running search command")
@@ -37,4 +41,28 @@ func TestMainCLI(t *testing.T) {
3741
_, err = os.Stat(policyPackageName)
3842
assert.False(t, os.IsNotExist(err), "could not find the directory of policies")
3943
})
44+
45+
t.Run("cli should create registry information", func(t *testing.T) {
46+
configPath := helpers.ConfigPath()
47+
os.RemoveAll(configPath)
48+
defer os.RemoveAll(configPath)
49+
command := exec.Command(pathToMainCLI, "help")
50+
session, _ := gexec.Start(command, os.Stdout, os.Stdout)
51+
session.Wait(10 * time.Second)
52+
53+
t.Run("should create the config directory", func(t *testing.T) {
54+
_, err := os.Stat(configPath)
55+
assert.False(t, os.IsNotExist(err), "could not find the directory config directory")
56+
})
57+
58+
t.Run("should create the registries list", func(t *testing.T) {
59+
_, err = os.Stat(filepath.ToSlash(filepath.Join(helpers.ConfigPath(), helpers.PolicyRegistryFilename)))
60+
assert.False(t, os.IsNotExist(err), "could not find the registries list file")
61+
})
62+
63+
t.Run("should create the registries file from the list", func(t *testing.T) {
64+
_, err = os.Stat(helpers.MetadataConfigPath())
65+
assert.False(t, os.IsNotExist(err), "could not find the registries metadata files")
66+
})
67+
})
4068
}

pkg/helpers/configpath.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package helpers
2+
3+
import (
4+
"os"
5+
"path/filepath"
6+
)
7+
8+
const PolicyIndexDirName = ".policy-hub-index"
9+
const PolicyDirName = ".policy-hub"
10+
const PolicyRegistryFilename = "registries.list"
11+
const RegistryMetadataDir = "metadata"
12+
const DefaultRegistriesFilename = "registries.yml"
13+
const RegistryListDefault = "https://raw.githubusercontent.com/policy-hub/policy-hub-cli/main/metadata/" + DefaultRegistriesFilename
14+
15+
//DefaultMetaDataFile Returns the path to the default registries yaml for the current system
16+
func DefaultMetaDataFile() string {
17+
return filepath.ToSlash(filepath.Join(
18+
MetadataConfigPath(), DefaultRegistriesFilename))
19+
}
20+
21+
//MetadataConfigPath Returns the path to the metadata directory for the current system
22+
func MetadataConfigPath() string {
23+
directory := filepath.ToSlash(filepath.Join(ConfigPath(), RegistryMetadataDir))
24+
return directory
25+
}
26+
27+
//ConfigPath Returns the path to the config directory for the current system
28+
func ConfigPath() string {
29+
homeDir, _ := os.UserHomeDir()
30+
directory := filepath.ToSlash(filepath.Join(homeDir, PolicyDirName))
31+
return directory
32+
}
33+
34+
//IndexPath Returns the path to the search index directory for the current system
35+
func IndexPath() string {
36+
homeDir, _ := os.UserHomeDir()
37+
directory := filepath.ToSlash(filepath.Join(homeDir, PolicyIndexDirName))
38+
return directory
39+
}

pkg/search/index.go

Lines changed: 7 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,14 @@ import (
1010

1111
"github.com/blevesearch/bleve"
1212
"github.com/olekukonko/tablewriter"
13+
"github.com/policy-hub/policy-hub-cli/pkg/helpers"
1314
"github.com/policy-hub/policy-hub-cli/pkg/metaconfig"
1415
)
1516

1617
// IndexVersion indicates the version of the search index.
1718
// This is used to migrate between index versions.
1819
const IndexVersion = "v1"
1920

20-
2121
type Engine struct {
2222
index bleve.Index
2323
}
@@ -81,7 +81,7 @@ func (e *Engine) Close() error {
8181

8282
// constructIndex builds a search index
8383
func constructIndex() (bleve.Index, error) {
84-
cacheDir := cacheDirectory()
84+
cacheDir := helpers.IndexPath()
8585
if _, err := os.Stat(cacheDir); os.IsNotExist(err) {
8686
return setupIndexDirectory()
8787
}
@@ -93,7 +93,7 @@ func constructIndex() (bleve.Index, error) {
9393
func loadIndex() (bleve.Index, error) {
9494
index, err := bleve.Open(indexDirectory())
9595
if err == bleve.ErrorIndexPathDoesNotExist {
96-
index, err := constructIndex();
96+
index, err := constructIndex()
9797
if err != nil {
9898
return nil, fmt.Errorf("construct index: %w", err)
9999
}
@@ -108,7 +108,7 @@ func loadIndex() (bleve.Index, error) {
108108

109109
// setupIndexDirectory setups the index directory
110110
func setupIndexDirectory() (bleve.Index, error) {
111-
cacheDir := cacheDirectory()
111+
cacheDir := helpers.IndexPath()
112112
if err := os.MkdirAll(cacheDir, os.ModePerm); err != nil {
113113
return nil, fmt.Errorf("make search dir: %w", err)
114114
}
@@ -117,7 +117,7 @@ func setupIndexDirectory() (bleve.Index, error) {
117117
if err != nil {
118118
return nil, fmt.Errorf("create version file: %w", err)
119119
}
120-
120+
121121
mapping := bleve.NewIndexMapping()
122122
index, err := bleve.New(indexDirectory(), mapping)
123123
if err != nil {
@@ -127,19 +127,7 @@ func setupIndexDirectory() (bleve.Index, error) {
127127
return index, nil
128128
}
129129

130-
// cacheDirectory returns the directory to cache policy-cli configs
131-
func cacheDirectory() string {
132-
const cacheDir = ".policy-hub"
133-
134-
homeDir, _ := os.UserHomeDir()
135-
136-
directory := filepath.Join(homeDir, cacheDir)
137-
directory = filepath.ToSlash(directory)
138-
139-
return directory
140-
}
141-
142130
// indexDirectory returns the directory to store the search index in
143131
func indexDirectory() string {
144-
return filepath.Join(cacheDirectory(), "index")
145-
}
132+
return filepath.Join(helpers.IndexPath(), "index")
133+
}

0 commit comments

Comments
 (0)