Skip to content

Commit

Permalink
feat(ext): determinism in exporting and declarative formats
Browse files Browse the repository at this point in the history
  • Loading branch information
devumesh committed Sep 30, 2024
1 parent 4343b36 commit ad2a6f8
Show file tree
Hide file tree
Showing 9 changed files with 1,505 additions and 4 deletions.
10 changes: 9 additions & 1 deletion cmd/flipt/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ type exportCommand struct {
token string
namespaces string // comma delimited list of namespaces
allNamespaces bool
sortByKey bool
}

func newExportCommand() *cobra.Command {
Expand Down Expand Up @@ -72,6 +73,13 @@ func newExportCommand() *cobra.Command {
"export all namespaces. (mutually exclusive with --namespaces)",
)

cmd.Flags().BoolVar(
&export.sortByKey,
"sort-by-key",
false,
"sort exported resources by key",
)

cmd.Flags().StringVar(&providedConfigFile, "config", "", "path to config file")

cmd.MarkFlagsMutuallyExclusive("all-namespaces", "namespaces", "namespace")
Expand Down Expand Up @@ -139,5 +147,5 @@ func (c *exportCommand) run(cmd *cobra.Command, _ []string) error {
}

func (c *exportCommand) export(ctx context.Context, enc ext.Encoding, dst io.Writer, lister ext.Lister) error {
return ext.NewExporter(lister, c.namespaces, c.allNamespaces).Export(ctx, enc, dst)
return ext.NewExporter(lister, c.namespaces, c.allNamespaces, c.sortByKey).Export(ctx, enc, dst)
}
16 changes: 15 additions & 1 deletion internal/ext/exporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"io"
"sort"
"strings"

"github.com/blang/semver/v4"
Expand Down Expand Up @@ -44,16 +45,18 @@ type Exporter struct {
batchSize int32
namespaceKeys []string
allNamespaces bool
sortByKey bool
}

func NewExporter(store Lister, namespaces string, allNamespaces bool) *Exporter {
func NewExporter(store Lister, namespaces string, allNamespaces, sortByKey bool) *Exporter {
ns := strings.Split(namespaces, ",")

return &Exporter{
store: store,
batchSize: defaultBatchSize,
namespaceKeys: ns,
allNamespaces: allNamespaces,
sortByKey: sortByKey,
}
}

Expand Down Expand Up @@ -316,6 +319,17 @@ func (e *Exporter) Export(ctx context.Context, encoding Encoding, w io.Writer) e
}
}

// sort flags and segments by key if sorting is enabled
if e.sortByKey {
sort.SliceStable(doc.Flags, func(i, j int) bool {
return doc.Flags[i].Key < doc.Flags[j].Key
})

sort.SliceStable(doc.Segments, func(i, j int) bool {
return doc.Segments[i].Key < doc.Segments[j].Key
})
}

if err := enc.Encode(doc); err != nil {
return fmt.Errorf("marshaling document: %w", err)
}
Expand Down
Loading

0 comments on commit ad2a6f8

Please sign in to comment.