Skip to content

Commit

Permalink
Linting.
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielRailean committed Feb 17, 2023
1 parent d225b21 commit d1c561b
Show file tree
Hide file tree
Showing 6 changed files with 83 additions and 56 deletions.
60 changes: 29 additions & 31 deletions cmd/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,24 +40,24 @@ const (
modeKongEnterprise
)

type summary struct
{
type summary struct {
Creating int32 `json:"creating"`
Updating int32 `json:"updating"`
Deleting int32 `json:"deleting"`
Total int32 `json:"total"`
Total int32 `json:"total"`
}

type jsonOutputObject struct
{
Changes diff.EntityChanges `json:"changes"`
Summary summary `json:"summary"`
Warnings []string `json:"warnings"`
Errors []string `json:"errors"`
type jsonOutputObject struct {
Changes diff.EntityChanges `json:"changes"`
Summary summary `json:"summary"`
Warnings []string `json:"warnings"`
Errors []string `json:"errors"`
}

var jsonOutput jsonOutputObject
var isJsonOutput bool
var (
jsonOutput jsonOutputObject
isJSONOutput bool
)

func getMode(targetContent *file.Content) mode {
if inKonnectMode(targetContent) {
Expand Down Expand Up @@ -94,23 +94,23 @@ func workspaceExists(ctx context.Context, config utils.KongClientConfig, workspa
func getWorkspaceName(workspaceFlag string, targetContent *file.Content) string {
if workspaceFlag != targetContent.Workspace && workspaceFlag != "" {
warning := fmt.Sprintf("Workspace '%v' specified via --workspace flag is "+
"different from workspace '%v' found in state file(s).", workspaceFlag, targetContent.Workspace)
if(isJsonOutput){
"different from workspace '%v' found in state file(s).", workspaceFlag, targetContent.Workspace)
if isJSONOutput {
jsonOutput.Warnings = append(jsonOutput.Warnings, warning)
}else{
cprint.DeletePrintf("Warning: "+warning+"\n")
} else {
cprint.DeletePrintf("Warning: " + warning + "\n")
}
return workspaceFlag
}
return targetContent.Workspace
}

func syncMain(ctx context.Context, filenames []string, dry bool, parallelism,
delay int, workspace string, enableJsonOutput bool,
delay int, workspace string, enableJSONOutput bool,
) error {
// read target file
if(enableJsonOutput){
isJsonOutput = true
if enableJSONOutput {
isJSONOutput = true
jsonOutput.Errors = []string{}
jsonOutput.Warnings = []string{}
jsonOutput.Changes = diff.EntityChanges{
Expand Down Expand Up @@ -240,13 +240,13 @@ func syncMain(ctx context.Context, filenames []string, dry bool, parallelism,
return err
}

if(enableJsonOutput){
if enableJSONOutput {
workspace := diff.EntityState{
Name: wsConfig.Workspace,
Type: "Workspace",
}
jsonOutput.Changes.Creating = append(jsonOutput.Changes.Creating, workspace)
}else{
} else {
cprint.CreatePrintln("Creating workspace", wsConfig.Workspace)
}
if !dry {
Expand Down Expand Up @@ -276,27 +276,25 @@ func syncMain(ctx context.Context, filenames []string, dry bool, parallelism,
totalOps, err := performDiff(
ctx, currentState, targetState, dry, parallelism, delay, kongClient, mode == modeKonnect)
if err != nil {

if(isJsonOutput){
if errs, ok := err.(utils.ErrArray)
ok {
if isJSONOutput {
if errs, ok := err.(utils.ErrArray); ok {
jsonOutput.Errors = append(jsonOutput.Errors, errs.ErrorList()...)
} else {
jsonOutput.Errors = append(jsonOutput.Errors, fmt.Sprintf("%v", err))
}
}else{
} else {
return err
}
}
if diffCmdNonZeroExitCode && totalOps > 0 {
os.Exit(exitCodeDiffDetection)
}
if(enableJsonOutput){
if enableJSONOutput {
jsonOutputStr, jsonErr := json.MarshalIndent(jsonOutput, "", " ")
if jsonErr != nil {
return err
}
cprint.CreatePrintf(string(jsonOutputStr)+"\n")
cprint.CreatePrintf(string(jsonOutputStr) + "\n")
}
return nil
}
Expand Down Expand Up @@ -352,17 +350,17 @@ func performDiff(ctx context.Context, currentState, targetState *state.KongState
return 0, err
}

stats, errs, changes := s.Solve(ctx, parallelism, dry, isJsonOutput)
stats, errs, changes := s.Solve(ctx, parallelism, dry, isJSONOutput)
// print stats before error to report completed operations
if(!isJsonOutput){
if !isJSONOutput {
printStats(stats)
}
if errs != nil {
return 0, utils.ErrArray{Errors: errs}
}
totalOps := stats.CreateOps.Count() + stats.UpdateOps.Count() + stats.DeleteOps.Count()

if(isJsonOutput) {
if isJSONOutput {
jsonOutput.Changes = diff.EntityChanges{
Creating: append(jsonOutput.Changes.Creating, changes.Creating...),
Updating: append(jsonOutput.Changes.Updating, changes.Updating...),
Expand All @@ -372,7 +370,7 @@ func performDiff(ctx context.Context, currentState, targetState *state.KongState
Creating: stats.CreateOps.Count(),
Updating: stats.UpdateOps.Count(),
Deleting: stats.DeleteOps.Count(),
Total: totalOps,
Total: totalOps,
}
}
return int(totalOps), nil
Expand Down
6 changes: 3 additions & 3 deletions cmd/diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ var (
diffCmdParallelism int
diffCmdNonZeroExitCode bool
diffWorkspace string
diffJsonOutput bool
diffJSONOutput bool
)

// newDiffCmd represents the diff command
Expand All @@ -28,7 +28,7 @@ that will be created, updated, or deleted.
Args: validateNoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return syncMain(cmd.Context(), diffCmdKongStateFile, true,
diffCmdParallelism, 0, diffWorkspace, diffJsonOutput)
diffCmdParallelism, 0, diffWorkspace, diffJSONOutput)
},
PreRunE: func(cmd *cobra.Command, args []string) error {
if len(diffCmdKongStateFile) == 0 {
Expand Down Expand Up @@ -66,7 +66,7 @@ that will be created, updated, or deleted.
"and exit code 1 if an error occurs.")
diffCmd.Flags().BoolVar(&dumpConfig.SkipCACerts, "skip-ca-certificates",
false, "do not diff CA certificates.")
diffCmd.Flags().BoolVar(&diffJsonOutput, "enable-json-output",
diffCmd.Flags().BoolVar(&diffJSONOutput, "enable-json-output",
false, "print execution results to stdout in a JSON format")
addSilenceEventsFlag(diffCmd.Flags())
return diffCmd
Expand Down
6 changes: 3 additions & 3 deletions cmd/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ var (
syncCmdParallelism int
syncCmdDBUpdateDelay int
syncWorkspace string
syncJsonOutput bool
syncJSONOutput bool
)

// newSyncCmd represents the sync command
Expand All @@ -25,7 +25,7 @@ to get Kong's state in sync with the input state.`,
Args: validateNoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return syncMain(cmd.Context(), syncCmdKongStateFile, false,
syncCmdParallelism, syncCmdDBUpdateDelay, syncWorkspace, syncJsonOutput)
syncCmdParallelism, syncCmdDBUpdateDelay, syncWorkspace, syncJSONOutput)
},
PreRunE: func(cmd *cobra.Command, args []string) error {
if len(syncCmdKongStateFile) == 0 {
Expand Down Expand Up @@ -63,7 +63,7 @@ to get Kong's state in sync with the input state.`,
"See `db_update_propagation` in kong.conf.")
syncCmd.Flags().BoolVar(&dumpConfig.SkipCACerts, "skip-ca-certificates",
false, "do not sync CA certificates.")
syncCmd.Flags().BoolVar(&syncJsonOutput, "enable-json-output",
syncCmd.Flags().BoolVar(&syncJSONOutput, "enable-json-output",
false, "provide JSON output to std out")
addSilenceEventsFlag(syncCmd.Flags())
return syncCmd
Expand Down
28 changes: 13 additions & 15 deletions diff/diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,18 @@ import (
"github.com/kong/go-kong/kong"
)

type EntityState struct
type entityState struct
{
Name string `json:"name"`
Type string `json:"type"`
OldState any `json:"oldState"`
NewState any `json:"newState"`
Name string
OldState any
NewState any
}

type EntityChanges struct
{
Creating []EntityState `json:"creating"`
Updating []EntityState `json:"updating"`
Deleting []EntityState `json:"deleting"`
Creating []entityState
Updating []entityState
Deleting []entityState
}

var errEnqueueFailed = errors.New("failed to queue event")
Expand Down Expand Up @@ -418,9 +417,9 @@ func (sc *Syncer) Solve(ctx context.Context, parallelism int, dry bool, isJsonOu
}

output := EntityChanges{
Creating: []EntityState{},
Updating: []EntityState{},
Deleting: []EntityState{},
Creating: []entityState{},
Updating: []entityState{},
Deleting: []entityState{},
}

errs := sc.Run(ctx, parallelism, func(e crud.Event) (crud.Arg, error) {
Expand All @@ -429,11 +428,10 @@ func (sc *Syncer) Solve(ctx context.Context, parallelism int, dry bool, isJsonOu

c := e.Obj.(state.ConsoleString)

item := EntityState{
OldState: e.OldObj,
NewState: e.Obj,
item := entityState{
OldState: e.Obj,
NewState: e.OldObj,
Name: c.Console(),
Type: string(e.Kind),
}
switch e.Op {
case crud.Create:
Expand Down
37 changes: 34 additions & 3 deletions tests/integration/diff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,39 @@ func Test_Diff_Workspace_OlderThan3x(t *testing.T) {

_, err := diff(tc.stateFile)
assert.NoError(t, err)
assert.Equal(t, out, expectedOutputUnMasked)
})
}
}

func Test_Diff_Workspace_Masked_OlderThan3x(t *testing.T) {
tests := []struct {
name string
stateFile string
expectedState utils.KongRawState
envVars map[string]string
}{
{
name: "diff with not existent workspace doesn't error out",
stateFile: "testdata/diff/001-not-existing-workspace/kong.yaml",
envVars: diffEnvVars,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
for k, v := range tc.envVars {
os.Setenv(k, v)
defer func(k string) {
os.Unsetenv(k)
}(k)
}
runWhen(t, "kong", "<3.0.0")
teardown := setup(t)
defer teardown(t)

out, err := diff(tc.stateFile)
assert.NoError(t, err)
assert.Equal(t, out, expectedOutputMasked)
})
}
}
Expand Down Expand Up @@ -120,9 +153,7 @@ func Test_Diff_Workspace_NewerThan3x(t *testing.T) {
}
}

// test scope:
// - 2.8.0
func Test_Diff_Masked_OlderThan3x(t *testing.T) {
func Test_Diff_Workspace_Masked_NewerThan3x(t *testing.T) {
tests := []struct {
name string
initialStateFile string
Expand Down
2 changes: 1 addition & 1 deletion utils/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ func (e ErrArray) ErrorList() []string {
errList := []string{}

for _, err := range e.Errors {
errList = append(errList, fmt.Sprintf("%v", err))
errList = append(errList, fmt.Sprintf("%v", err))
}
return errList
}
Expand Down

0 comments on commit d1c561b

Please sign in to comment.