diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 10237838..8f10e55c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -62,7 +62,7 @@ jobs: # Require: The version of golangci-lint to use. # When `install-mode` is `binary` (default) the value can be v1.2 or v1.2.3 or `latest` to use the latest version. # When `install-mode` is `goinstall` the value can be v1.2.3, `latest`, or the hash of a commit. - version: v2.9.0 + version: v2.15.0 check-license: name: License scan @@ -115,7 +115,7 @@ jobs: # either 'goreleaser' (default) or 'goreleaser-pro' distribution: goreleaser # 'latest', 'nightly', or a semver - version: v1.25.1 + version: v1.26.2 args: check test: @@ -187,7 +187,7 @@ jobs: # either 'goreleaser' (default) or 'goreleaser-pro' distribution: goreleaser # 'latest', 'nightly', or a semver - version: v1.25.1 + version: v1.26.2 args: release - name: Write latest version to file run: mkdir -p dist && printf '%s\n' "${TAG}" > dist/LATEST_VERSION diff --git a/.golangci.yml b/.golangci.yml index 8b9d40e8..b732deef 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -60,6 +60,10 @@ linters: allow-unused: true exclusions: generated: lax + rules: + - path: '(_test|test_helper)\.go$' + linters: + - goconst presets: - comments - common-false-positives diff --git a/cmd/context/context_save.go b/cmd/context/context_save.go index e05b28b0..a8708d35 100644 --- a/cmd/context/context_save.go +++ b/cmd/context/context_save.go @@ -12,7 +12,8 @@ import ( ) const ( - APIPathFlag = "api-path" + currentContextKey = "current-context" + APIPathFlag = "api-path" ) type SaveArgs struct { @@ -112,7 +113,7 @@ func RunContextSaveCommand(args *SaveArgs) func(cli *di.Deps, cmd *cobra.Command if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "current-context": cfg.CurrentContext, + currentContextKey: cfg.CurrentContext, "context": namedCtx.Context, }) } else { diff --git a/cmd/context/context_set.go b/cmd/context/context_set.go index 6ced7136..f89f0d74 100644 --- a/cmd/context/context_set.go +++ b/cmd/context/context_set.go @@ -47,7 +47,7 @@ func RunContextSetCommand(args *SetArgs, cli *di.Deps) func(cli *di.Deps, cmd *c if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "current-context": args.Name, + currentContextKey: args.Name, }) } else { cli.Printer.PrintLn(fmt.Sprintf("Current context set to %s", args.Name)) diff --git a/cmd/context/context_show.go b/cmd/context/context_show.go index d064b27b..601bc4bb 100644 --- a/cmd/context/context_show.go +++ b/cmd/context/context_show.go @@ -31,7 +31,7 @@ func RunContextShowCommand(cli *di.Deps, cmd *cobra.Command, cfg *config.Config) if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "current-context": ctx.Context, + currentContextKey: ctx.Context, "name": cfg.CurrentContext, }) } else { diff --git a/cmd/dashboard/dashboard_apply.go b/cmd/dashboard/dashboard_apply.go index a3128319..545c2d29 100644 --- a/cmd/dashboard/dashboard_apply.go +++ b/cmd/dashboard/dashboard_apply.go @@ -13,6 +13,10 @@ import ( "sigs.k8s.io/kustomize/kyaml/yaml" ) +const ( + dashboardKey = "dashboard" +) + // ApplyArgs contains arguments for dashboard apply command type ApplyArgs struct { File string @@ -93,7 +97,7 @@ func createDashboard(cli *di.Deps, api *stackstate_api.APIClient, fileBytes []by if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "dashboard": dashboard, + dashboardKey: dashboard, }) } else { cli.Printer.Success(fmt.Sprintf("Dashboard created successfully! ID: %d, Name: %s", dashboard.GetId(), dashboard.GetName())) @@ -118,7 +122,7 @@ func updateDashboard(cli *di.Deps, api *stackstate_api.APIClient, dashboardId st patchSchema.SetScope(*scope) } } - if dashboardContent, ok := dashboardData["dashboard"]; ok { + if dashboardContent, ok := dashboardData[dashboardKey]; ok { // Convert dashboard content to PersesDashboard dashboardBytes, err := yaml.Marshal(dashboardContent) if err == nil { @@ -137,7 +141,7 @@ func updateDashboard(cli *di.Deps, api *stackstate_api.APIClient, dashboardId st if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "dashboard": dashboard, + dashboardKey: dashboard, }) } else { cli.Printer.Success(fmt.Sprintf("Dashboard updated successfully! ID: %d, Name: %s", dashboard.GetId(), dashboard.GetName())) diff --git a/cmd/dashboard/dashboard_clone.go b/cmd/dashboard/dashboard_clone.go index 05209a37..156d015d 100644 --- a/cmd/dashboard/dashboard_clone.go +++ b/cmd/dashboard/dashboard_clone.go @@ -85,7 +85,7 @@ func RunDashboardCloneCommand(args *CloneArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "dashboard": clonedDashboard, + dashboardKey: clonedDashboard, }) } else { cli.Printer.Success(fmt.Sprintf("Dashboard cloned successfully! New dashboard ID: %d, Name: %s", clonedDashboard.GetId(), clonedDashboard.GetName())) diff --git a/cmd/dashboard/dashboard_edit.go b/cmd/dashboard/dashboard_edit.go index d3a71dd7..bc230b47 100644 --- a/cmd/dashboard/dashboard_edit.go +++ b/cmd/dashboard/dashboard_edit.go @@ -99,7 +99,7 @@ func RunDashboardEditCommand(args *EditArgs) di.CmdWithApiFn { patchSchema.SetScope(*scope) } } - if dashboardContent, ok := editedDashboard["dashboard"]; ok { + if dashboardContent, ok := editedDashboard[dashboardKey]; ok { // Convert dashboard content to PersesDashboard dashboardBytes, err := json.Marshal(dashboardContent) if err == nil { @@ -118,7 +118,7 @@ func RunDashboardEditCommand(args *EditArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "dashboard": updatedDashboard, + dashboardKey: updatedDashboard, }) } else { cli.Printer.Success(fmt.Sprintf("Dashboard updated successfully! ID: %d, Name: %s", updatedDashboard.GetId(), updatedDashboard.GetName())) diff --git a/cmd/health/health_status.go b/cmd/health/health_status.go index 7fe283ee..093a6508 100644 --- a/cmd/health/health_status.go +++ b/cmd/health/health_status.go @@ -11,6 +11,11 @@ import ( "github.com/stackvista/stackstate-cli/internal/printer" ) +const ( + metricsKey = "metrics" + errorsKey = "errors" +) + type StatusArgs struct { Urn string SubStream string @@ -105,8 +110,8 @@ func RunStreamStatus(cli *di.Deps, api *stackstate_api.APIClient, args *StatusAr if cli.IsJson() { json := map[string]interface{}{ "consistency-model": status.ConsistencyModel, - "metrics": streamMetricsToJson(status.AggregateMetrics), - "errors": streamErrorsToJson(status.GlobalErrors), + metricsKey: streamMetricsToJson(status.AggregateMetrics), + errorsKey: streamErrorsToJson(status.GlobalErrors), } if status.HasMainStreamStatus() { json["main-stream"] = subStreamStatusToJson(*status.MainStreamStatus) @@ -148,7 +153,7 @@ func streamMetricsToTable(metrics stackstate_api.HealthStreamMetrics) printer.Ta printer.MetricBucketToRow("updates per seconds", metrics.UpdatesPerSecond), printer.MetricBucketToRow("deletes per seconds", metrics.DeletesPerSecond), }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "metrics"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: metricsKey}, } } @@ -174,7 +179,7 @@ func streamErrorsToTable(errors []stackstate_api.HealthStreamError) printer.Tabl return printer.TableData{ Header: []string{"Message", "Count"}, Data: data, - MissingTableDataMsg: printer.NotFoundMsg{Types: "errors"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: errorsKey}, } } @@ -233,7 +238,7 @@ func streamConsistencyStateToTable(state stackstate_api.HealthSubStreamConsisten Data: [][]interface{}{ {repeatInterval, expiryInterval, snapshotRepeatInterval, snapshotExpiryInterval, checkpointOffset, checkpointBatchIndex}, }, - MissingTableDataMsg: printer.NotFoundMsg{Types: "errors"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: errorsKey}, } } @@ -251,8 +256,8 @@ func subStreamStatusToJson(status stackstate_api.HealthSubStreamStatus) map[stri return map[string]interface{}{ "check-state-count": status.CheckStateCount, "consistency-state": streamConsistencyStateToJson(status.SubStreamState), - "metrics": streamMetricsToJson(status.Metrics), - "errors": streamErrorsToJson(status.Errors), + metricsKey: streamMetricsToJson(status.Metrics), + errorsKey: streamErrorsToJson(status.Errors), } } diff --git a/cmd/license/common.go b/cmd/license/common.go index b4f19184..99535dd2 100644 --- a/cmd/license/common.go +++ b/cmd/license/common.go @@ -5,18 +5,22 @@ import ( "github.com/stackvista/stackstate-cli/internal/printer" ) +const ( + stateKey = "state" +) + func subscriptionAsTable(subscription *stackstate_api.SubscriptionState) printer.TableData { var header []string data := make([][]interface{}, 0) switch l := subscription.GetActualInstance().(type) { case *stackstate_api.ExpiredSubscription: - header = []string{"state", "tenant", "expiration", "plan"} + header = []string{stateKey, "tenant", "expiration", "plan"} data = append(data, []interface{}{"expired", l.Subscription.Tenant, expiration(l.Subscription.ExpiryTimestampMs), l.Subscription.Plan}) case *stackstate_api.LicensedSubscription: - header = []string{"state", "tenant", "expiration", "plan"} + header = []string{stateKey, "tenant", "expiration", "plan"} data = append(data, []interface{}{"valid", l.Subscription.Tenant, expiration(l.Subscription.ExpiryTimestampMs), l.Subscription.Plan}) case *stackstate_api.UnlicensedSubscription: - header = []string{"state", "reason"} + header = []string{stateKey, "reason"} data = append(data, []interface{}{"unlicensed", l.Reason}) } diff --git a/cmd/monitor/monitor_apply.go b/cmd/monitor/monitor_apply.go index 8e1ea99c..cd72ec52 100644 --- a/cmd/monitor/monitor_apply.go +++ b/cmd/monitor/monitor_apply.go @@ -11,6 +11,16 @@ import ( "github.com/stackvista/stackstate-cli/internal/printer" ) +const ( + statusColumn = "Status" +) + +const ( + nameKey = "Name" + nodesKey = "nodes" + identifierKey = "Identifier" +) + type ApplyArgs struct { File string } @@ -45,7 +55,7 @@ func RunMonitorApplyCommand(args *ApplyArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "nodes": nodes, + nodesKey: nodes, }) } else { if len(nodes) == 0 { @@ -61,7 +71,7 @@ func RunMonitorApplyCommand(args *ApplyArgs) di.CmdWithApiFn { cli.Printer.Success(fmt.Sprintf("Applied %d monitor(s).", len(nodes))) if len(nodes) > 0 { cli.Printer.Table(printer.TableData{ - Header: []string{"Type", "Id", "Status", "Identifier", "Name"}, + Header: []string{"Type", "Id", statusColumn, identifierKey, nameKey}, Data: tableData, }) } diff --git a/cmd/monitor/monitor_clone.go b/cmd/monitor/monitor_clone.go index cfbc71e3..bec35d07 100644 --- a/cmd/monitor/monitor_clone.go +++ b/cmd/monitor/monitor_clone.go @@ -10,6 +10,10 @@ import ( "github.com/stackvista/stackstate-cli/internal/di" ) +const ( + monitorKey = "monitor" +) + type CloneArgs struct { IdArgs NewName string @@ -53,7 +57,7 @@ func RunMonitorCloneCommand(args *CloneArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "monitor": clonedMonitor, + monitorKey: clonedMonitor, }) } else { cli.Printer.Success(fmt.Sprintf("Monitor %d has been created", clonedMonitor.GetId())) diff --git a/cmd/monitor/monitor_disable.go b/cmd/monitor/monitor_disable.go index d0c762ab..ba439974 100644 --- a/cmd/monitor/monitor_disable.go +++ b/cmd/monitor/monitor_disable.go @@ -48,7 +48,7 @@ func RunMonitorDisableCommand(args *IdArgs, status *sts.MonitorStatusValue) di.C if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "monitor": monitorPatchResult, + monitorKey: monitorPatchResult, }) } else { cli.Printer.Success(fmt.Sprintf("Monitor %s has been disabled", identifier)) diff --git a/cmd/monitor/monitor_edit.go b/cmd/monitor/monitor_edit.go index 722faf9a..b96f6127 100644 --- a/cmd/monitor/monitor_edit.go +++ b/cmd/monitor/monitor_edit.go @@ -97,7 +97,7 @@ func RunMonitorEditCommand(args *EditArgs) di.CmdWithApiFn { if strings.Compare(orig, string(c)) == 0 { if cli.IsJson() { - cli.Printer.PrintJson(map[string]interface{}{"nodes": []string{}, "message": "No changes made"}) + cli.Printer.PrintJson(map[string]interface{}{nodesKey: []string{}, "message": "No changes made"}) } else { cli.Printer.PrintWarn("No changes made") } @@ -119,7 +119,7 @@ func RunMonitorEditCommand(args *EditArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "nodes": nodes, + nodesKey: nodes, }) } else { tableData := make([][]interface{}, 0) @@ -130,7 +130,7 @@ func RunMonitorEditCommand(args *EditArgs) di.CmdWithApiFn { cli.Printer.Success(fmt.Sprintf("Updated %d monitor(s).", len(nodes))) if len(nodes) > 0 { cli.Printer.Table(printer.TableData{ - Header: []string{"Type", "Id", "Status", "Identifier", "Name"}, + Header: []string{"Type", "Id", statusColumn, identifierKey, nameKey}, Data: tableData, }) } diff --git a/cmd/monitor/monitor_enable.go b/cmd/monitor/monitor_enable.go index 69db2cda..f4dcabd8 100644 --- a/cmd/monitor/monitor_enable.go +++ b/cmd/monitor/monitor_enable.go @@ -47,7 +47,7 @@ func RunMonitorEnableCommand(args *IdArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "monitor": monitorPatchResult, + monitorKey: monitorPatchResult, }) } else { cli.Printer.Success(fmt.Sprintf("Monitor %s has been enabled", identifier)) diff --git a/cmd/monitor/monitor_list.go b/cmd/monitor/monitor_list.go index 1ee374ed..98e6384c 100644 --- a/cmd/monitor/monitor_list.go +++ b/cmd/monitor/monitor_list.go @@ -50,7 +50,7 @@ func RunMonitorListCommand( tableData = append(tableData, []interface{}{monitor.Id, monitor.Status, *monitor.Identifier, monitor.Name, monitor.FunctionId, monitor.Tags}) } cli.Printer.Table(printer.TableData{ - Header: []string{"Id", "Status", "Identifier", "Name", "Function Id", "Tags"}, + Header: []string{"Id", statusColumn, identifierKey, nameKey, "Function Id", "Tags"}, Data: tableData, MissingTableDataMsg: printer.NotFoundMsg{Types: "monitors"}, }) diff --git a/cmd/rbac/rbac_describe_permissions.go b/cmd/rbac/rbac_describe_permissions.go index 8631f1f3..a8dd3b57 100644 --- a/cmd/rbac/rbac_describe_permissions.go +++ b/cmd/rbac/rbac_describe_permissions.go @@ -13,6 +13,10 @@ import ( "github.com/stackvista/stackstate-cli/pkg/pflags" ) +const ( + permissionsKey = "permissions" +) + type DescribePermissionsArgs struct { Subject string Permission string @@ -69,14 +73,14 @@ func RunDescribePermissionsCommand(args *DescribePermissionsArgs) di.CmdWithApiF if cli.IsJson() { if sourceStrings != nil { cli.Printer.PrintJson(map[string]interface{}{ - "subject": description.SubjectHandle, - "permissions": description.Permissions, - "sources": sourceStrings, + Subject: description.SubjectHandle, + permissionsKey: description.Permissions, + "sources": sourceStrings, }) } else { cli.Printer.PrintJson(map[string]interface{}{ - "subject": description.SubjectHandle, - "permissions": description.Permissions, + Subject: description.SubjectHandle, + permissionsKey: description.Permissions, }) } } else { diff --git a/cmd/rbac/rbac_grant.go b/cmd/rbac/rbac_grant.go index b0877718..880a4137 100644 --- a/cmd/rbac/rbac_grant.go +++ b/cmd/rbac/rbac_grant.go @@ -62,8 +62,8 @@ func RunGrantPermissionsCommand(args *GrantPermissionsArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "subject": description.SubjectHandle, - "permissions": description.Permissions, + Subject: description.SubjectHandle, + permissionsKey: description.Permissions, }) } else { cli.Printer.Successf("Granted permission '%s' on '%s' to subject '%s'", args.Permission, args.Resource, args.Subject) diff --git a/cmd/rbac/rbac_list_permissions.go b/cmd/rbac/rbac_list_permissions.go index 7bd88162..722f563e 100644 --- a/cmd/rbac/rbac_list_permissions.go +++ b/cmd/rbac/rbac_list_permissions.go @@ -31,7 +31,7 @@ func RunListPermissionsCommand(cmd *cobra.Command, cli *di.Deps, api *stackstate if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "permissions": permissions.Permissions, + permissionsKey: permissions.Permissions, }) } else { cli.Printer.Successf("Available permissions: %s", strings.Join(permissions.Permissions, ", ")) diff --git a/cmd/rbac/rbac_revoke.go b/cmd/rbac/rbac_revoke.go index c8b135ef..aa5270a1 100644 --- a/cmd/rbac/rbac_revoke.go +++ b/cmd/rbac/rbac_revoke.go @@ -62,8 +62,8 @@ func RunRevokePermissionsCommand(args *RevokePermissionsArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "subject": description.SubjectHandle, - "permissions": description.Permissions, + Subject: description.SubjectHandle, + permissionsKey: description.Permissions, }) } else { cli.Printer.Successf("Revoked permission '%s' on '%s' from subject '%s'", args.Permission, args.Resource, args.Subject) diff --git a/cmd/settings/settings_apply.go b/cmd/settings/settings_apply.go index 7f26f6da..4da77b08 100644 --- a/cmd/settings/settings_apply.go +++ b/cmd/settings/settings_apply.go @@ -13,6 +13,12 @@ import ( "github.com/stackvista/stackstate-cli/pkg/pflags" ) +const ( + typeKey = "Type" + nameKey = "Name" + identifierColumn = "Identifier" +) + var ( UnlockedStrategyChoices = []string{"fail", "skip", "overwrite"} LockedStrategyChoices = []string{"fail", "skip", "overwrite"} @@ -89,7 +95,7 @@ func RunSettingsApplyCommand(args *ApplyArgs) di.CmdWithApiFn { cli.Printer.Success(fmt.Sprintf("Applied %d setting node(s).\n", len(nodes))) if len(nodes) > 0 { cli.Printer.Table(printer.TableData{ - Header: []string{"Type", "Id", "Identifier", "Name"}, + Header: []string{typeKey, "Id", identifierColumn, nameKey}, Data: tableData, }) } diff --git a/cmd/settings/settings_edit.go b/cmd/settings/settings_edit.go index cf816077..b4af1f31 100644 --- a/cmd/settings/settings_edit.go +++ b/cmd/settings/settings_edit.go @@ -114,7 +114,7 @@ func RunSettingsEditCommand(args *EditArgs) di.CmdWithApiFn { cli.Printer.Success(fmt.Sprintf("Updated %d setting node(s).\n", len(nodes))) if len(nodes) > 0 { cli.Printer.Table(printer.TableData{ - Header: []string{"Type", "Id", "Identifier", "Name"}, + Header: []string{typeKey, "Id", identifierColumn, nameKey}, Data: tableData, }) } diff --git a/cmd/settings/settings_list.go b/cmd/settings/settings_list.go index a5d23298..cee87346 100644 --- a/cmd/settings/settings_list.go +++ b/cmd/settings/settings_list.go @@ -82,7 +82,7 @@ func RunSettingsListCommand(args *ListArgs) di.CmdWithApiFn { }) } cli.Printer.Table(printer.TableData{ - Header: []string{"Type", "Id", "Identifier", "Name", "owned by", "last updated"}, + Header: []string{typeKey, "Id", identifierColumn, nameKey, "owned by", "last updated"}, Data: data, MissingTableDataMsg: printer.NotFoundMsg{Types: fmt.Sprintf("settings of type \"%s\"", args.TypeName)}, }) diff --git a/cmd/stackpack/common.go b/cmd/stackpack/common.go index c9901340..25d83a72 100644 --- a/cmd/stackpack/common.go +++ b/cmd/stackpack/common.go @@ -14,6 +14,10 @@ import ( ) const ( + stackpackKey = "stackpack" + statusKey = "status" + versionKey = "version" + lastUpdatedColumn = "last updated" // StackPack configuration status constants for wait operations StatusInstalled = "INSTALLED" // Configuration is successfully installed StatusProvisioning = "PROVISIONING" // Configuration is still being processed @@ -147,8 +151,8 @@ func waitAndDisplayResult(cli *di.Deps, api *stackstate_api.APIClient, stackPack if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "stackpack": finalStackPack, - "status": "completed", + stackpackKey: finalStackPack, + statusKey: "completed", "current-version": finalStackPack.GetVersion(), }) } else { @@ -167,7 +171,7 @@ func waitAndDisplayResult(cli *di.Deps, api *stackstate_api.APIClient, stackPack } cli.Printer.Table(printer.TableData{ - Header: []string{"id", "name", "status", "version", "last updated"}, + Header: []string{"id", NameFlag, statusKey, versionKey, lastUpdatedColumn}, Data: data, MissingTableDataMsg: printer.NotFoundMsg{Types: "configurations for " + stackPackName}, }) diff --git a/cmd/stackpack/stackpack_confirm_manual_steps.go b/cmd/stackpack/stackpack_confirm_manual_steps.go index d7c5a76e..de1a3c6e 100644 --- a/cmd/stackpack/stackpack_confirm_manual_steps.go +++ b/cmd/stackpack/stackpack_confirm_manual_steps.go @@ -9,6 +9,10 @@ import ( "github.com/stackvista/stackstate-cli/internal/di" ) +const ( + successKey = "success" +) + type ManualStepsArgs struct { TypeName string ID int64 @@ -42,7 +46,7 @@ func RunStackpackConfirmManualStepsCommand(args *ManualStepsArgs) di.CmdWithApiF } if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "success": true, + successKey: true, "stackpack-name": args.TypeName, "stackpack-instance-id": args.ID, }) diff --git a/cmd/stackpack/stackpack_describe.go b/cmd/stackpack/stackpack_describe.go index ab0c2f68..2fea10e9 100644 --- a/cmd/stackpack/stackpack_describe.go +++ b/cmd/stackpack/stackpack_describe.go @@ -12,8 +12,9 @@ import ( ) const ( - Name = "name" - NameUsage = "StackPack name" + displayNameColumn = "display name" + Name = "name" + NameUsage = "StackPack name" ) type DescribeArgs struct { @@ -52,7 +53,7 @@ func RunStackpackDescribeCommand(args *DescribeArgs) di.CmdWithApiFn { if stackpack.Name == args.Name { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "stackpack": stackpack, + stackpackKey: stackpack, }) } else { cli.Printer.PrintLn(fmt.Sprintf("StackPack %s v%s (latest available is v%s)", stackpack.DisplayName, stackpack.Version, stackpack.LatestVersion.Version)) @@ -71,14 +72,14 @@ func RunStackpackDescribeCommand(args *DescribeArgs) di.CmdWithApiFn { if len(stackpack.Steps) > 0 { cli.Printer.PrintLn("\nInstance configuration parameters:") cli.Printer.Table(printer.TableData{ - Header: []string{"name", "display name", "type"}, + Header: []string{NameFlag, displayNameColumn, "type"}, Data: formatParametersTable(stackpack), MissingTableDataMsg: printer.NotFoundMsg{Types: "instance parameters"}, }) } cli.Printer.PrintLn("\nInstalled instances:") cli.Printer.Table(printer.TableData{ - Header: []string{"id", "status", "version", "last updated"}, + Header: []string{"id", statusKey, versionKey, lastUpdatedColumn}, Data: formatInstancesTable(stackpack), MissingTableDataMsg: printer.NotFoundMsg{Types: "installed StackPack instances"}, }) diff --git a/cmd/stackpack/stackpack_downgrade.go b/cmd/stackpack/stackpack_downgrade.go index 3fb2c885..d6c7413b 100644 --- a/cmd/stackpack/stackpack_downgrade.go +++ b/cmd/stackpack/stackpack_downgrade.go @@ -61,7 +61,7 @@ func RunStackpackDowngradeCommand(args *DowngradeArgs) di.CmdWithApiFn { } else { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "success": true, + successKey: true, "target-version": args.Version, }) } else { diff --git a/cmd/stackpack/stackpack_install.go b/cmd/stackpack/stackpack_install.go index 69b4e4f8..0dfe9d7e 100644 --- a/cmd/stackpack/stackpack_install.go +++ b/cmd/stackpack/stackpack_install.go @@ -13,6 +13,10 @@ import ( "github.com/stackvista/stackstate-cli/pkg/pflags" ) +const ( + failKey = "fail" +) + type InstallArgs struct { Name string UnlockedStrategy string @@ -43,7 +47,7 @@ sts stackpack install --name example --stackpack-version 1.2.3 -p "full_name=Fir common.AddRequiredNameFlagVar(cmd, &args.Name, "Name of the StackPack") pflags.EnumVar(cmd.Flags(), &args.UnlockedStrategy, UnlockedStrategyFlag, - "fail", + failKey, UnlockedStrategyChoices, "Strategy use to upgrade StackPack instance"+ fmt.Sprintf(" (must be { %s })", strings.Join(UnlockedStrategyChoices, " | ")), @@ -103,8 +107,8 @@ func RunStackpackInstallCommand(args *InstallArgs) di.CmdWithApiFn { // Display final status if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "stackpack": finalStackPack, - "status": "completed", + stackpackKey: finalStackPack, + statusKey: "completed", }) } else { cli.Printer.Success("StackPack installation completed successfully") @@ -124,7 +128,7 @@ func RunStackpackInstallCommand(args *InstallArgs) di.CmdWithApiFn { cli.Printer.Table( printer.TableData{ - Header: []string{"id", "name", "status", "version", "last updated"}, + Header: []string{"id", NameFlag, statusKey, versionKey, lastUpdatedColumn}, Data: data, MissingTableDataMsg: printer.NotFoundMsg{Types: "configurations for " + args.Name}, }, @@ -141,7 +145,7 @@ func RunStackpackInstallCommand(args *InstallArgs) di.CmdWithApiFn { cli.Printer.Success("StackPack instance installation triggered") cli.Printer.Table( printer.TableData{ - Header: []string{"id", "name", "status", "version", "last updated"}, + Header: []string{"id", NameFlag, statusKey, versionKey, lastUpdatedColumn}, Data: [][]interface{}{{instance.Id, instance.Name, instance.Status, instance.StackPackVersion, lastUpdateTime}}, MissingTableDataMsg: printer.NotFoundMsg{Types: "provision details of " + args.Name}, }, diff --git a/cmd/stackpack/stackpack_list.go b/cmd/stackpack/stackpack_list.go index 15d47f2e..e19c76f5 100644 --- a/cmd/stackpack/stackpack_list.go +++ b/cmd/stackpack/stackpack_list.go @@ -66,7 +66,7 @@ func RunStackpackListCommand(args *ListArgs) di.CmdWithApiFn { }) } else { cli.Printer.Table(printer.TableData{ - Header: []string{"name", "display name", "installed version", "next version", "latest version", "instance count"}, + Header: []string{NameFlag, displayNameColumn, "installed version", "next version", "latest version", "instance count"}, Data: data, MissingTableDataMsg: printer.NotFoundMsg{Types: "StackPacks"}, }) diff --git a/cmd/stackpack/stackpack_list_instances.go b/cmd/stackpack/stackpack_list_instances.go index 6a9d3243..7486aa10 100644 --- a/cmd/stackpack/stackpack_list_instances.go +++ b/cmd/stackpack/stackpack_list_instances.go @@ -85,7 +85,7 @@ func RunStackpackListInstanceCommand(args *ListPropertiesArgs) di.CmdWithApiFn { }) } else { cli.Printer.Table(printer.TableData{ - Header: []string{"id", "status", "version", "last updated"}, + Header: []string{"id", statusKey, versionKey, lastUpdatedColumn}, Data: data, MissingTableDataMsg: printer.NotFoundMsg{Types: "installed StackPack instances"}, }) diff --git a/cmd/stackpack/stackpack_list_parameters.go b/cmd/stackpack/stackpack_list_parameters.go index 5a66af6e..ca48d364 100644 --- a/cmd/stackpack/stackpack_list_parameters.go +++ b/cmd/stackpack/stackpack_list_parameters.go @@ -78,7 +78,7 @@ func RunStackpackListParameterCommand(args *ListPropertiesArgs) di.CmdWithApiFn }) } else { cli.Printer.Table(printer.TableData{ - Header: []string{"name", "display name", "type"}, + Header: []string{NameFlag, displayNameColumn, "type"}, Data: data, MissingTableDataMsg: printer.NotFoundMsg{Types: fmt.Sprintf("StackPack \"%s\"", args.Name)}, }) diff --git a/cmd/stackpack/stackpack_list_versions.go b/cmd/stackpack/stackpack_list_versions.go index ff99c336..171a163a 100644 --- a/cmd/stackpack/stackpack_list_versions.go +++ b/cmd/stackpack/stackpack_list_versions.go @@ -61,7 +61,7 @@ func RunStackpackListVersionsCommand(args *ListVersionsArgs) di.CmdWithApiFn { }) } cli.Printer.Table(printer.TableData{ - Header: []string{"version", "dev", "in use"}, + Header: []string{versionKey, "dev", "in use"}, Data: data, MissingTableDataMsg: printer.NotFoundMsg{Types: "versions"}, }) diff --git a/cmd/stackpack/stackpack_package.go b/cmd/stackpack/stackpack_package.go index 85d69ec7..984baf8e 100644 --- a/cmd/stackpack/stackpack_package.go +++ b/cmd/stackpack/stackpack_package.go @@ -182,7 +182,7 @@ func RunStackpackPackageCommand(args *PackageArgs) func(cli *di.Deps, cmd *cobra if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "success": true, + successKey: true, "stackpack_name": stackpackInfo.Name, "stackpack_version": stackpackInfo.Version, "zip_file": args.ArchiveFile, diff --git a/cmd/stackpack/stackpack_scaffold.go b/cmd/stackpack/stackpack_scaffold.go index 90da66ad..d52f8e76 100644 --- a/cmd/stackpack/stackpack_scaffold.go +++ b/cmd/stackpack/stackpack_scaffold.go @@ -70,13 +70,13 @@ sts stackpack scaffold --template-github-repo stackvista/my-templates --name my- // Common flags cmd.Flags().StringVar(&args.DestinationDir, "destination-dir", "", "Target directory where scaffolded files will be created. If not specified, creates a directory with the stackpack name in the current working directory") - cmd.Flags().StringVar(&args.Name, "name", "", "Name of the stackpack (required). Must start with [a-z] and contain only lowercase letters, digits, and hyphens") + cmd.Flags().StringVar(&args.Name, NameFlag, "", "Name of the stackpack (required). Must start with [a-z] and contain only lowercase letters, digits, and hyphens") cmd.Flags().StringVar(&args.DisplayName, "display-name", "", "Name that's displayed on both the StackPack listing page and on the title of the StackPack page. If not provided, the value of --name will be used") cmd.Flags().StringVar(&args.TemplateName, "template-name", defaultTemplateName, fmt.Sprintf("Name of the template subdirectory to use (default: %s)", defaultTemplateName)) cmd.Flags().BoolVar(&args.Force, "force", false, "Overwrite existing files without prompting") // Mark required flags - cmd.MarkFlagRequired("name") //nolint:errcheck + cmd.MarkFlagRequired(NameFlag) //nolint:errcheck // Template sources are mutually exclusive but not required (will use default GitHub repo if none specified) stscobra.MarkMutexFlags(cmd, []string{"template-local-dir", "template-github-repo"}, "template-source", false) @@ -145,10 +145,10 @@ func RunStackpackScaffoldCommand(args *ScaffoldArgs) func(cli *di.Deps, cmd *cob if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "success": result.Success, + successKey: result.Success, "source": result.Source, "destination": result.Destination, - "name": result.Name, + NameFlag: result.Name, "template": result.Template, "files_count": result.FilesCount, "files": result.Files, diff --git a/cmd/stackpack/stackpack_test_deploy.go b/cmd/stackpack/stackpack_test_deploy.go index dd9ba478..7c616ea9 100644 --- a/cmd/stackpack/stackpack_test_deploy.go +++ b/cmd/stackpack/stackpack_test_deploy.go @@ -147,7 +147,7 @@ func RunStackpackTestDeployCommand(args *TestDeployArgs) di.CmdWithApiFn { } }() - tempStackpackDir := filepath.Join(tempDir, "stackpack") + tempStackpackDir := filepath.Join(tempDir, stackpackKey) if err := copyDirectory(args.StackpackDir, tempStackpackDir); err != nil { return common.NewRuntimeError(fmt.Errorf("failed to copy stackpack to temporary directory: %w", err)) } @@ -205,7 +205,7 @@ func RunStackpackTestDeployCommand(args *TestDeployArgs) di.CmdWithApiFn { if installedVersion != "" { upgradeArgs := &UpgradeArgs{ TypeName: originalInfo.Name, - UnlockedStrategy: "fail", + UnlockedStrategy: failKey, Wait: true, Timeout: DefaultTimeout, } @@ -217,7 +217,7 @@ func RunStackpackTestDeployCommand(args *TestDeployArgs) di.CmdWithApiFn { } else { installArgs := &InstallArgs{ Name: originalInfo.Name, - UnlockedStrategy: "fail", + UnlockedStrategy: failKey, Params: args.Params, Wait: true, Timeout: DefaultTimeout, @@ -237,8 +237,8 @@ func RunStackpackTestDeployCommand(args *TestDeployArgs) di.CmdWithApiFn { printMsg(cli, fmt.Sprintf("Note: Could not clean up .sts file %s: %v", packageArgs.ArchiveFile, err)) } else if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "stackpack": originalInfo.Name, - "version": newVersion, + stackpackKey: originalInfo.Name, + versionKey: newVersion, }) } diff --git a/cmd/stackpack/stackpack_uninstall.go b/cmd/stackpack/stackpack_uninstall.go index 81de70e2..683459c9 100644 --- a/cmd/stackpack/stackpack_uninstall.go +++ b/cmd/stackpack/stackpack_uninstall.go @@ -44,8 +44,8 @@ func RunStackpackUninstallCommand(args *UninstallArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "success": true, - "result": result, + successKey: true, + "result": result, }) } else { cli.Printer.Success(fmt.Sprintf("Successfully uninstalled StackPack: name=%s id=%d", args.Name, args.Id)) diff --git a/cmd/stackpack/stackpack_upgrade.go b/cmd/stackpack/stackpack_upgrade.go index e504a71a..572931ff 100644 --- a/cmd/stackpack/stackpack_upgrade.go +++ b/cmd/stackpack/stackpack_upgrade.go @@ -14,7 +14,7 @@ import ( ) var ( - UnlockedStrategyChoices = []string{"fail", "skip", "overwrite"} + UnlockedStrategyChoices = []string{failKey, "skip", "overwrite"} ) type UpgradeArgs struct { @@ -40,7 +40,7 @@ sts stackpack upgrade --name kubernetes --wait`, common.AddRequiredNameFlagVar(cmd, &args.TypeName, "Name of the StackPack") pflags.EnumVar(cmd.Flags(), &args.UnlockedStrategy, UnlockedStrategyFlag, - "fail", + failKey, UnlockedStrategyChoices, "Strategy use to upgrade StackPack instance"+ fmt.Sprintf(" (must be { %s })", strings.Join(UnlockedStrategyChoices, " | ")), @@ -79,7 +79,7 @@ func RunStackpackUpgradeCommand(args *UpgradeArgs) di.CmdWithApiFn { } else { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "success": true, + successKey: true, "current-version": stack.GetVersion(), "next-version": stack.NextVersion.GetVersion(), }) diff --git a/cmd/stackpack/stackpack_upload.go b/cmd/stackpack/stackpack_upload.go index 0731642d..4f10782f 100644 --- a/cmd/stackpack/stackpack_upload.go +++ b/cmd/stackpack/stackpack_upload.go @@ -55,7 +55,7 @@ func RunStackpackUploadCommand(args *UploadArgs) di.CmdWithApiFn { } else { cli.Printer.Success(fmt.Sprintf("uploaded StackPack: %s", args.FilePath)) cli.Printer.Table(printer.TableData{ - Header: []string{"name", "display name", "version"}, + Header: []string{NameFlag, displayNameColumn, versionKey}, Data: [][]interface{}{{stackpack.Name, stackpack.DisplayName, stackpack.Version}}, }) } diff --git a/cmd/stackpack/stackpack_validate.go b/cmd/stackpack/stackpack_validate.go index 5924c398..58c9ff13 100644 --- a/cmd/stackpack/stackpack_validate.go +++ b/cmd/stackpack/stackpack_validate.go @@ -84,8 +84,8 @@ func RunStackpackValidateCommand(args *ValidateArgs) di.CmdWithApiFn { if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "success": true, - "result": result, + successKey: true, + "result": result, }) } else { cli.Printer.Success("Stackpack validation successful!") diff --git a/cmd/topology/topology_inspect.go b/cmd/topology/topology_inspect.go index 46979240..21ffd87a 100644 --- a/cmd/topology/topology_inspect.go +++ b/cmd/topology/topology_inspect.go @@ -13,6 +13,13 @@ import ( "github.com/stackvista/stackstate-cli/internal/printer" ) +const ( + identifierKey = "identifier" + componentsKey = "components" + viewSnapshotType = "ViewSnapshot" + nameKey = "name" +) + const UNKNOWN = "unknown" type InspectArgs struct { @@ -56,7 +63,7 @@ sts topology inspect --type "otel service instance" -o json`, cmd.Flags().StringVar(&args.ComponentType, "type", "", "Component type (required)") cmd.MarkFlagRequired("type") //nolint:errcheck cmd.Flags().StringSliceVar(&args.Tags, "tag", []string{}, "Filter by tags in format 'tag-name:tag-value' (multiple allowed, ANDed together)") - cmd.Flags().StringSliceVar(&args.Identifiers, "identifier", []string{}, "Filter by component identifiers (multiple allowed, ANDed together)") + cmd.Flags().StringSliceVar(&args.Identifiers, identifierKey, []string{}, "Filter by component identifiers (multiple allowed, ANDed together)") cmd.Flags().IntVar(&args.Limit, "limit", 0, "Maximum number of components to output (must be positive)") return cmd @@ -118,7 +125,7 @@ func RunInspectCommand( if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "components": components, + componentsKey: components, }) return nil } else { @@ -231,7 +238,7 @@ func parseSnapshotResponse( // Note: the `View` prefix on response type comes from the existing (Scala) DTO types // If it's not a ViewSnapshot, it's an error type - return empty components and let error handler deal with it - if respType != "ViewSnapshot" { + if respType != viewSnapshotType { return nil, fmt.Errorf("response is an error type: %s", respType) } @@ -239,7 +246,7 @@ func parseSnapshotResponse( // Parse components from the already-unmarshalled components field var components []Component - if componentsSlice, ok := respMap["components"].([]interface{}); ok { + if componentsSlice, ok := respMap[componentsKey].([]interface{}); ok { for _, comp := range componentsSlice { if compMap, ok := comp.(map[string]interface{}); ok { components = append(components, parseComponentFromMap(compMap, metadata, baseURL)) @@ -300,8 +307,8 @@ func parseMetadataByIdentifier(metadataValue interface{}) map[string]string { for _, item := range items { if itemMap, ok := item.(map[string]interface{}); ok { - identifier, idOk := itemMap["identifier"].(string) - name, nameOk := itemMap["name"].(string) + identifier, idOk := itemMap[identifierKey].(string) + name, nameOk := itemMap[nameKey].(string) if idOk && nameOk { result[identifier] = name } @@ -322,7 +329,7 @@ func parseComponentFromMap(compMap map[string]interface{}, metadata ComponentMet if id, ok := compMap["id"].(float64); ok { comp.ID = int64(id) } - if name, ok := compMap["name"].(string); ok { + if name, ok := compMap[nameKey].(string); ok { comp.Name = name } @@ -380,8 +387,8 @@ func parseComponentReference(compMap map[string]interface{}, identifierFieldName refName = name } return map[string]interface{}{ - "identifier": refIdentifier, - "name": refName, + identifierKey: refIdentifier, + nameKey: refName, } } return nil @@ -409,6 +416,6 @@ func printTableOutput( cli.Printer.Table(printer.TableData{ Header: []string{"Name", "Type", "Identifiers"}, Data: tableData, - MissingTableDataMsg: printer.NotFoundMsg{Types: "components"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: componentsKey}, }) } diff --git a/cmd/topology/topology_state.go b/cmd/topology/topology_state.go index dcda10f6..3ef74452 100644 --- a/cmd/topology/topology_state.go +++ b/cmd/topology/topology_state.go @@ -51,7 +51,7 @@ sts topology state --type "otel service instance" -o json`, cmd.Flags().StringVar(&args.ComponentType, "type", "", "Component type") cmd.Flags().StringSliceVar(&args.Tags, "tag", []string{}, "Filter by tags in format 'tag-name:tag-value' (multiple allowed, ANDed together)") - cmd.Flags().StringSliceVar(&args.Identifiers, "identifier", []string{}, "Filter by component identifiers (multiple allowed, ANDed together)") + cmd.Flags().StringSliceVar(&args.Identifiers, identifierKey, []string{}, "Filter by component identifiers (multiple allowed, ANDed together)") cmd.Flags().IntVar(&args.Limit, "limit", 0, "Maximum number of components to output (must be positive)") return cmd @@ -111,7 +111,7 @@ func RunStateCommand( if cli.IsJson() { cli.Printer.PrintJson(map[string]interface{}{ - "components": componentStates, + componentsKey: componentStates, }) return nil } else { @@ -141,14 +141,14 @@ func parseStateResponse(result *stackstate_api.QuerySnapshotResult) ([]Component return nil, fmt.Errorf("response has no _type discriminator") } - if respType != "ViewSnapshot" { + if respType != viewSnapshotType { return nil, fmt.Errorf("response is an error type: %s", respType) } metadata := parseMetadata(respMap) var componentStates []ComponentState - if componentsSlice, ok := respMap["components"].([]interface{}); ok { + if componentsSlice, ok := respMap[componentsKey].([]interface{}); ok { for _, comp := range componentsSlice { if compMap, ok := comp.(map[string]interface{}); ok { componentStates = append(componentStates, parseComponentStateFromMap(compMap, metadata)) @@ -169,7 +169,7 @@ func parseComponentStateFromMap(compMap map[string]interface{}, metadata Compone if id, ok := compMap["id"].(float64); ok { cs.ID = int64(id) } - if name, ok := compMap["name"].(string); ok { + if name, ok := compMap[nameKey].(string); ok { cs.Name = name } @@ -216,6 +216,6 @@ func printStateTableOutput(cli *di.Deps, componentStates []ComponentState) { cli.Printer.Table(printer.TableData{ Header: []string{"Name", "Type", "Health State", "Identifiers"}, Data: tableData, - MissingTableDataMsg: printer.NotFoundMsg{Types: "components"}, + MissingTableDataMsg: printer.NotFoundMsg{Types: componentsKey}, }) } diff --git a/internal/printer/printer.go b/internal/printer/printer.go index 23fecdb8..6cb1aed3 100644 --- a/internal/printer/printer.go +++ b/internal/printer/printer.go @@ -45,9 +45,7 @@ type TableData struct { MissingTableDataMsg MissingTableDataMsg } -const ( - YamlIndent = 2 -) +const YamlIndent = 2 type StopPrinterFn func() diff --git a/internal/util/string_util.go b/internal/util/string_util.go index cf672e69..a4023794 100644 --- a/internal/util/string_util.go +++ b/internal/util/string_util.go @@ -69,7 +69,7 @@ func ToString(x interface{}) string { k := r.Kind() // this is the only way to check whether `x == nill`, because nil is specific to the type in Golang :( - isPointer := k == reflect.Chan || k == reflect.Func || k == reflect.Map || k == reflect.Ptr || + isPointer := k == reflect.Chan || k == reflect.Func || k == reflect.Map || k == reflect.Pointer || k == reflect.UnsafePointer || k == reflect.Slice || k == reflect.Interface if k == reflect.Invalid || (isPointer && r.IsNil()) { return "-"