Skip to content

feat: openfeature pull command #79

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*.dll
*.so
*.dylib
cli

# Test binary, built with `go test -c`
*.test
Expand All @@ -26,4 +27,7 @@ go.work.sum
dist

# openfeature cli config
.openfeature.yaml
.openfeature.yaml

# generated files from running the CLI
flags.json
8 changes: 4 additions & 4 deletions cmd/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
"strings"

"github.com/open-feature/cli/internal/config"
"github.com/open-feature/cli/internal/flagset"
"github.com/open-feature/cli/internal/generators"
"github.com/open-feature/cli/internal/generators/csharp"
"github.com/open-feature/cli/internal/generators/golang"
Expand All @@ -13,6 +12,7 @@
"github.com/open-feature/cli/internal/generators/python"
"github.com/open-feature/cli/internal/generators/react"
"github.com/open-feature/cli/internal/logger"
"github.com/open-feature/cli/internal/manifest"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -86,7 +86,7 @@
OutputPath: outputPath,
Custom: nodejs.Params{},
}
flagset, err := flagset.Load(manifestPath)
flagset, err := manifest.LoadFlagSet(manifestPath)
if err != nil {
return err
}
Expand Down Expand Up @@ -130,7 +130,7 @@
OutputPath: outputPath,
Custom: react.Params{},
}
flagset, err := flagset.Load(manifestPath)
flagset, err := manifest.LoadFlagSet(manifestPath)
if err != nil {
return err
}
Expand Down Expand Up @@ -170,7 +170,7 @@

logger.Default.GenerationStarted("NestJS")

flagset, err := flagset.Load(manifestPath)

Check failure on line 173 in cmd/generate.go

View workflow job for this annotation

GitHub Actions / lint

undefined: flagset

Check failure on line 173 in cmd/generate.go

View workflow job for this annotation

GitHub Actions / lint

undefined: flagset

Check failure on line 173 in cmd/generate.go

View workflow job for this annotation

GitHub Actions / lint

undefined: flagset

Check failure on line 173 in cmd/generate.go

View workflow job for this annotation

GitHub Actions / C# Generator Test

undefined: flagset

Check failure on line 173 in cmd/generate.go

View workflow job for this annotation

GitHub Actions / test

undefined: flagset

Check failure on line 173 in cmd/generate.go

View workflow job for this annotation

GitHub Actions / Validate docs

undefined: flagset
if err != nil {
return err
}
Expand Down Expand Up @@ -231,7 +231,7 @@
Namespace: namespace,
},
}
flagset, err := flagset.Load(manifestPath)

Check failure on line 234 in cmd/generate.go

View workflow job for this annotation

GitHub Actions / lint

undefined: flagset

Check failure on line 234 in cmd/generate.go

View workflow job for this annotation

GitHub Actions / lint

undefined: flagset

Check failure on line 234 in cmd/generate.go

View workflow job for this annotation

GitHub Actions / lint

undefined: flagset

Check failure on line 234 in cmd/generate.go

View workflow job for this annotation

GitHub Actions / C# Generator Test

undefined: flagset

Check failure on line 234 in cmd/generate.go

View workflow job for this annotation

GitHub Actions / test

undefined: flagset

Check failure on line 234 in cmd/generate.go

View workflow job for this annotation

GitHub Actions / Validate docs

undefined: flagset
if err != nil {
return err
}
Expand Down Expand Up @@ -282,7 +282,7 @@
},
}

flagset, err := flagset.Load(manifestPath)
flagset, err := manifest.LoadFlagSet(manifestPath)
if err != nil {
return err
}
Expand Down Expand Up @@ -326,7 +326,7 @@
OutputPath: outputPath,
Custom: python.Params{},
}
flagset, err := flagset.Load(manifestPath)

Check failure on line 329 in cmd/generate.go

View workflow job for this annotation

GitHub Actions / lint

undefined: flagset) (typecheck)

Check failure on line 329 in cmd/generate.go

View workflow job for this annotation

GitHub Actions / lint

undefined: flagset) (typecheck)

Check failure on line 329 in cmd/generate.go

View workflow job for this annotation

GitHub Actions / C# Generator Test

undefined: flagset

Check failure on line 329 in cmd/generate.go

View workflow job for this annotation

GitHub Actions / test

undefined: flagset

Check failure on line 329 in cmd/generate.go

View workflow job for this annotation

GitHub Actions / Validate docs

undefined: flagset
if err != nil {
return err
}
Expand Down
20 changes: 20 additions & 0 deletions cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ func GetInitCmd() *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
manifestPath := config.GetManifestPath(cmd)
override := config.GetOverride(cmd)
flagSourceUrl := config.GetFlagSourceUrl(cmd)

manifestExists, _ := filesystem.Exists(manifestPath)
if manifestExists && !override {
Expand All @@ -45,6 +46,25 @@ func GetInitCmd() *cobra.Command {
return err
}

configFileExists, _ := filesystem.Exists(".openfeature.yaml")
if !configFileExists {
err = filesystem.WriteFile(".openfeature.yaml", []byte(""))
if err != nil {
return err
}
}

if flagSourceUrl != "" {
pterm.Info.Println("Writing flag source URL to .openfeature.yaml", pterm.LightWhite(flagSourceUrl))
err = filesystem.WriteFile(".openfeature.yaml", []byte("flagSourceUrl: " + flagSourceUrl))
if err != nil {
return err
}
}

pterm.Info.Printfln("Manifest created at %s", pterm.LightWhite(manifestPath))
pterm.Success.Println("Project initialized.")

logger.Default.FileCreated(manifestPath)
logger.Default.Success("Project initialized.")
return nil
Expand Down
125 changes: 125 additions & 0 deletions cmd/pull.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package cmd

import (
"errors"
"fmt"
"strconv"
"strings"

"github.com/open-feature/cli/internal/config"
"github.com/open-feature/cli/internal/filesystem"
"github.com/open-feature/cli/internal/flagset"
"github.com/open-feature/cli/internal/manifest"
"github.com/open-feature/cli/internal/requests"
"github.com/pterm/pterm"
"github.com/spf13/cobra"
)

func promptForDefaultValue(flag *flagset.Flag) (any) {
var prompt string
switch flag.Type {
case flagset.BoolType:
var options []string = []string{"false", "true"}
prompt = fmt.Sprintf("Enter default value for flag '%s' (%s)", flag.Key, flag.Type)
boolStr, _ := pterm.DefaultInteractiveSelect.WithOptions(options).WithFilter(false).Show(prompt)
boolValue, _ := strconv.ParseBool(boolStr)
return boolValue
case flagset.IntType:
var err error = errors.New("Input a valid integer")
prompt = fmt.Sprintf("Enter default value for flag '%s' (%s)", flag.Key, flag.Type)
var defaultValue int
for err != nil {
defaultValueString, _ := pterm.DefaultInteractiveTextInput.WithDefaultText("0").Show(prompt)
defaultValue, err = strconv.Atoi(defaultValueString)
}
return defaultValue
case flagset.FloatType:
var err error = errors.New("Input a valid float")
prompt = fmt.Sprintf("Enter default value for flag '%s' (%s)", flag.Key, flag.Type)
var defaultValue float64
for err != nil {
defaultValueString, _ := pterm.DefaultInteractiveTextInput.WithDefaultText("0.0").Show(prompt)
defaultValue, err = strconv.ParseFloat(defaultValueString, 64)
if err != nil {
pterm.Error.Println("Input a valid float")
}
}
return defaultValue
case flagset.StringType:
prompt = fmt.Sprintf("Enter default value for flag '%s' (%s)", flag.Key, flag.Type)
defaultValue, _ := pterm.DefaultInteractiveTextInput.WithDefaultText("").Show(prompt)
return defaultValue
// TODO: Add proper support for object type
case flagset.ObjectType:
return map[string]any{}
default:
return nil
}
}

func GetPullCmd() *cobra.Command {
pullCmd := &cobra.Command{
Use: "pull",
Short: "Pull a flag manifest from a remote source",
Long: "Pull a flag manifest from a remote source.",
PreRunE: func(cmd *cobra.Command, args []string) error {
return initializeConfig(cmd, "pull")
},
RunE: func(cmd *cobra.Command, args []string) error {
flagSourceUrl := config.GetFlagSourceUrl(cmd)
manifestPath := config.GetManifestPath(cmd)
authToken := config.GetAuthToken(cmd)

var err error
if flagSourceUrl == "" {
return fmt.Errorf("flagSourceUrl not set in config")
}

flags := flagset.Flagset{}
// fetch the flags from the remote source
// Check if the URL is a local file path
if strings.HasPrefix(flagSourceUrl, "file://") {
localPath := strings.TrimPrefix(flagSourceUrl, "file://")
var data, err = filesystem.ReadFile(localPath)
if err != nil {
return fmt.Errorf("error reading local flags file: %w", err)
}
loadedFlags, err := flagset.LoadFromSourceFlags(data)
if err != nil {
return fmt.Errorf("error loading flags from local file: %w", err)
}
flags.Flags = *loadedFlags
} else if strings.HasPrefix(flagSourceUrl, "http://") && !strings.HasPrefix(flagSourceUrl, "https://") {
flags, err = requests.FetchFlags(flagSourceUrl, authToken)
if err != nil {
return fmt.Errorf("error reading local flags file: %w", err)
}
return nil
}

if err != nil {
return fmt.Errorf("error fetching flags: %w", err)
}

// Check each flag for null defaultValue
for index, flag := range flags.Flags {
if flag.DefaultValue == nil {
defaultValue := promptForDefaultValue(&flag)
flags.Flags[index].DefaultValue = defaultValue
}
}

pterm.Success.Printf("Successfully fetched flags from %s", flagSourceUrl)
err = manifest.Write(manifestPath, flags)
if err != nil {
return fmt.Errorf("error writing manifest: %w", err)
}

return nil
},
}

config.AddPullFlags(pullCmd)

return pullCmd
}
117 changes: 117 additions & 0 deletions cmd/pull_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package cmd

import (
"encoding/json"
"testing"

"github.com/h2non/gock"
"github.com/open-feature/cli/internal/config"
"github.com/open-feature/cli/internal/filesystem"

"github.com/spf13/afero"

"github.com/stretchr/testify/assert"
)

func setupTest(t *testing.T) (afero.Fs) {
fs := afero.NewMemMapFs()
filesystem.SetFileSystem(fs)
readOsFileAndWriteToMemMap(t, "testdata/empty_manifest.golden", "manifest/path.json", fs)
return fs
}

func TestPull(t *testing.T) {
t.Run("pull no flag source url", func(t *testing.T) {
setupTest(t)
cmd := GetPullCmd()

// Prepare command arguments
args := []string{
"pull",
}

cmd.SetArgs(args)

// Run command
err := cmd.Execute()
assert.Error(t, err)
assert.Contains(t, err.Error(), "flagSourceUrl not set in config")
})

t.Run("pull with flag source url", func(t *testing.T) {
fs := setupTest(t)
defer gock.Off()

flags := []map[string]any{
{"key": "testFlag", "type": "boolean", "defaultValue": true},
{"key": "testFlag2", "type": "string", "defaultValue": "string value"},
}

gock.New("https://example.com/flags").
Get("/").
Reply(200).
JSON(flags)

cmd := GetPullCmd()

// global flag exists on root only.
config.AddRootFlags(cmd)

// Prepare command arguments
args := []string{
"pull",
"--flag-source-url", "https://example.com/flags",
"--manifest", "manifest/path.json",
}

cmd.SetArgs(args)


// Run command
err := cmd.Execute()
assert.NoError(t, err)

// check if the file content is correct
content, err := afero.ReadFile(fs, "manifest/path.json")
assert.NoError(t, err)

var manifestFlags map[string]interface{}
err = json.Unmarshal(content, &manifestFlags)
assert.NoError(t, err)

// Compare actual content with expected flags
for _, flag := range flags {
flagKey := flag["key"].(string)
_, exists := manifestFlags["flags"].(map[string]interface{})[flagKey]
assert.True(t, exists, "Flag %s should exist in manifest", flagKey)
}
})

t.Run("error when endpoint returns error", func(t *testing.T) {
setupTest(t)
defer gock.Off()

gock.New("https://example.com/flags").
Get("/").
Reply(404)

cmd := GetPullCmd()

// global flag exists on root only.
config.AddRootFlags(cmd)

// Prepare command arguments
args := []string{
"pull",
"--flag-source-url", "https://example.com/flags",
"--manifest", "manifest/path.json",
}

cmd.SetArgs(args)

// Run command
err := cmd.Execute()
assert.Error(t, err)
assert.Contains(t, err.Error(), "Received error response from flag source")
})
}
1 change: 1 addition & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ func GetRootCmd() *cobra.Command {
rootCmd.AddCommand(GetVersionCmd())
rootCmd.AddCommand(GetInitCmd())
rootCmd.AddCommand(GetGenerateCmd())
rootCmd.AddCommand(GetPullCmd())

// Add a custom error handler after the command is created
rootCmd.SetFlagErrorFunc(func(cmd *cobra.Command, err error) error {
Expand Down
3 changes: 3 additions & 0 deletions cmd/testdata/empty_manifest.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"flags": {}
}
Loading
Loading